-
Notifications
You must be signed in to change notification settings - Fork 2
/
admin.wsgi
1819 lines (1549 loc) · 72.9 KB
/
admin.wsgi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
AdminTool: Web app for IF Archive administration.
See tinyapp/app.py for how the underlying web app framework works.
This file (admin.wsgi) is installed as /var/ifarchive/wsgi-bin/admin.wsgi.
It can also be run to perform some command-line operations:
python3 /var/ifarchive/wsgi-bin/admin.wsgi
"""
import sys
import time
import os, os.path
import hashlib
import urllib.request, urllib.error
import configparser
import shutil
import subprocess
import logging, logging.handlers
import threading
from tinyapp.constants import PLAINTEXT, BINARY
from tinyapp.handler import before, beforeall
from tinyapp.excepts import HTTPError, HTTPRedirectPost, HTTPRawResponse
from tinyapp.util import random_bytes, time_now
from adminlib.admapp import AdminApp, AdminHandler
from adminlib.session import User, Session
from adminlib.session import require_user, require_role
from adminlib.util import bad_filename, in_user_time, clean_newlines
from adminlib.util import zip_compress
from adminlib.util import find_unused_filename
from adminlib.util import urlencode
from adminlib.util import canon_archivedir, FileConsistency
from adminlib.util import sortcanon
from adminlib.util import log_files_tail
from adminlib.info import FileEntry, DirEntry, SymlinkEntry, IndexOnlyEntry, UploadEntry
from adminlib.info import get_dir_entries, dir_is_empty
from adminlib.index import IndexDir, update_file_entries
# URL handlers...
class han_Home(AdminHandler):
renderparams = { 'navtab':'top' }
def add_renderparams(self, req, map):
cookiename = req.app.cookieprefix+'username'
if cookiename in req.cookies:
map['username'] = req.cookies[cookiename].value
return map
def do_get(self, req):
if not req._user:
return self.render('login.html', req)
incount = len([ ent for ent in os.scandir(self.app.incoming_dir) if ent.is_file() ])
# Sorry about the special case.
unproccount = len([ ent for ent in os.scandir(self.app.unprocessed_dir) if ent.is_file() and ent.name != '.listing' ])
locktime = self.app.get_locktime()
buildtime, builddesc = self.app.get_buildinfo(user=req._user)
diskuse = shutil.disk_usage(self.app.archive_dir)
return self.render('front.html', req,
incount=incount, unproccount=unproccount,
locktime=locktime,
buildtime=buildtime, builddesc=builddesc,
diskuse=diskuse)
def do_post(self, req):
formname = req.get_input_field('name')
formpw = req.get_input_field('password')
if not (formname and formpw):
return self.render('login.html', req,
formerror='You must supply name and password.')
curs = self.app.getdb().cursor()
if '@' in formname:
res = curs.execute('SELECT name, pw, pwsalt, roles FROM users WHERE email = ?', (formname,))
else:
res = curs.execute('SELECT name, pw, pwsalt, roles FROM users WHERE name = ?', (formname,))
tup = res.fetchone()
if not tup:
return self.render('login.html', req,
formerror='The name and password do not match.')
name, pw, pwsalt, roles = tup
formsalted = pwsalt + b':' + formpw.encode()
formcrypted = hashlib.sha1(formsalted).hexdigest()
if formcrypted != pw:
return self.render('login.html', req,
formerror='The name and password do not match.')
sessionid = random_bytes(20)
req.set_cookie(self.app.cookieprefix+'sessionid', sessionid, maxage=self.app.max_session_age, httponly=True)
req.set_cookie(self.app.cookieprefix+'username', name, httponly=True)
now = time_now()
ipaddr = req.env.get('REMOTE_ADDR', '?')
curs = self.app.getdb().cursor()
curs.execute('INSERT INTO sessions VALUES (?, ?, ?, ?, ?)', (name, sessionid, ipaddr, now, now))
req.loginfo('Logged in: user=%s, roles=%s', name, roles)
raise HTTPRedirectPost(self.app.approot)
class han_LogOut(AdminHandler):
def do_get(self, req):
if req._user:
curs = self.app.getdb().cursor()
curs.execute('DELETE FROM sessions WHERE sessionid = ?', (req._user.sessionid,))
# Could clear the sessionid cookie here but I can't seem to make that work
raise HTTPRedirectPost(self.app.approot)
@beforeall(require_user)
class han_UserProfile(AdminHandler):
def do_get(self, req):
return self.render('user.html', req)
@beforeall(require_user)
class han_ChangePW(AdminHandler):
def do_get(self, req):
return self.render('changepw.html', req)
def do_post(self, req):
oldpw = req.get_input_field('oldpassword')
newpw = req.get_input_field('newpassword')
duppw = req.get_input_field('duppassword')
if not newpw:
return self.render('changepw.html', req,
formerror='You must supply a new password.')
curs = self.app.getdb().cursor()
res = curs.execute('SELECT pw, pwsalt FROM users WHERE name = ?', (req._user.name,))
tup = res.fetchone()
if not tup:
return self.render('changepw.html', req,
formerror='Cannot locate user record.')
pw, pwsalt = tup
formsalted = pwsalt + b':' + oldpw.encode()
formcrypted = hashlib.sha1(formsalted).hexdigest()
if formcrypted != pw:
return self.render('changepw.html', req,
formerror='Old password does not match.')
if newpw != duppw:
return self.render('changepw.html', req,
formerror='New password does not match.')
pwsalt = random_bytes(8).encode()
salted = pwsalt + b':' + newpw.encode()
crypted = hashlib.sha1(salted).hexdigest()
curs.execute('UPDATE users SET pw = ?, pwsalt = ? WHERE name = ?', (crypted, pwsalt, req._user.name))
req.loginfo('Changed password')
return self.render('changepwdone.html', req)
@beforeall(require_user)
class han_ChangeTZ(AdminHandler):
def do_get(self, req):
return self.render('changetz.html', req)
def do_post(self, req):
tzname = req.get_input_field('tz_field')
curs = self.app.getdb().cursor()
curs.execute('UPDATE users SET tzname = ? WHERE name = ?', (tzname, req._user.name))
req.loginfo('Changed timezone to %s', tzname)
raise HTTPRedirectPost(self.app.approot+'/user')
@beforeall(require_role('admin'))
class han_AdminAdmin(AdminHandler):
renderparams = { 'navtab':'admin' }
def do_get(self, req):
return self.render('admin.html', req)
@beforeall(require_role('admin'))
class han_AllUsers(AdminHandler):
renderparams = { 'navtab':'admin' }
def do_get(self, req):
curs = self.app.getdb().cursor()
res = curs.execute('SELECT name, email, roles FROM users')
userlist = [ User(name, email, roles=roles) for name, email, roles in res.fetchall() ]
return self.render('allusers.html', req,
users=userlist)
@beforeall(require_role('admin'))
class han_AllSessions(AdminHandler):
renderparams = { 'navtab':'admin' }
def do_get(self, req):
curs = self.app.getdb().cursor()
res = curs.execute('SELECT name, ipaddr, starttime, refreshtime FROM sessions')
sessionlist = [ Session(tup, user=req._user, maxage=self.app.max_session_age) for tup in res.fetchall() ]
return self.render('allsessions.html', req,
sessions=sessionlist)
@beforeall(require_role('admin'))
class han_HashCache(AdminHandler):
renderparams = { 'navtab':'admin' }
def do_get(self, req):
cachels = self.app.hasher.dump()
pid = os.getpid()
return self.render('hashcache.html', req,
cachels=cachels, pid=pid)
class base_DirectoryPage(AdminHandler):
"""Base class for all handlers that display a file list.
This will have subclasses for each directory that has special
handling. (Incoming, Trash, etc.)
This is rather long and messy because it also handles all the
buttons that can appear under a file name: Move, Rename, Delete,
and so on.
"""
# Should we load UploadEntry info for files in this directory?
# (Subclasses may override this to be true.)
autoload_uploadinfo = False
def get_dirpath(self, req):
"""Return the (full) filesystem path of the directory that this
subclass will operate on. (E.g. "/var/ifarchive/incoming" or
"/var/ifarchive/htdocs/if-archive/unprocessed".)
Subclasses must customize this.
"""
raise NotImplementedError('%s: get_dirpath not implemented' % (self.__class__.__name__,))
def get_dirname(self, req):
"""Return the printable name of the directory that this
subclass will operate on. (E.g. "incoming" or "unprocessed".)
Subclasses must customize this.
"""
raise NotImplementedError('%s: get_dirname not implemented' % (self.__class__.__name__,))
def check_fileops(self, req):
"""Add a req._fileops field, containing file operations valid for
the current user in this directory.
Subclasses should customize get_fileops(), not this method.
"""
req._fileops = set()
if req._user:
ops = self.get_fileops(req)
if ops:
req._fileops.update(ops)
def get_fileops(self, req):
"""Return the operations which are available for files in this
directory. This should be limited to what the req._user's roles
allow.
(You can assume that req._user is set when this is called.)
Subclasses should customize this to permit appropriate operations.
"""
return None
def get_file(self, filename, req):
"""Get one FileEntry from our directory, or None if the file
does not exist.
"""
if bad_filename(filename):
return None
pathname = os.path.join(self.get_dirpath(req), filename)
if not os.path.exists(pathname):
return None
if not os.path.isfile(pathname):
return None
stat = os.stat(pathname)
return FileEntry(filename, stat, user=req._user)
def get_dirent(self, filename, req):
"""Same as above, but for subdirectories.
"""
if bad_filename(filename):
return None
pathname = os.path.join(self.get_dirpath(req), filename)
if not os.path.exists(pathname):
return None
if not os.path.isdir(pathname):
return None
stat = os.stat(pathname)
return DirEntry(filename, stat, user=req._user)
def get_symlink(self, filename, req):
"""Same as above, but for symlinks.
"""
if bad_filename(filename):
return None
pathname = os.path.join(self.get_dirpath(req), filename)
if not os.path.islink(pathname):
return None
target = os.readlink(pathname)
path = os.path.realpath(pathname)
if path.startswith(self.app.archive_dir+'/') and os.path.exists(path):
relpath = path[ len(self.app.archive_dir)+1 : ]
if os.path.isfile(path):
stat = os.stat(path)
return SymlinkEntry(filename, target, stat, realpath=relpath, isdir=False, user=req._user)
elif os.path.isdir(path):
stat = os.stat(path)
return SymlinkEntry(filename, target, stat, realpath=relpath, isdir=True, user=req._user)
else:
return None
else:
# Gotta use the link's own stat
stat = os.lstat(pathname)
return SymlinkEntry(filename, target, stat, isdir=False, broken=True, user=req._user)
def get_filelist(self, req, dirs=False, shortdate=False, sort=None):
"""Get a list of FileEntries from our directory.
See get_dir_entries().
Optionally sort by date or filename.
"""
filelist = get_dir_entries(self.get_dirpath(req), self.app.archive_dir, dirs=dirs, user=req._user, shortdate=shortdate)
if self.autoload_uploadinfo:
# Optionally load up the uploadinfo for the files in the list.
for file in filelist:
if isinstance(file, FileEntry):
(uploads, size) = self.get_uploadinfo(req, file.name)
if uploads:
file.uploads = uploads
if sort == 'date':
filelist.sort(key=lambda file:file.date)
elif sort == 'name':
filelist.sort(key=lambda file:sortcanon(file.name))
return filelist
def get_uploadinfo(self, req, filename):
"""Return a list of UploadEntry records and the file size for a file.
If the file doesn't exist or is not readable, return (None, None).
"""
if bad_filename(filename):
return (None, None)
pathname = os.path.join(self.get_dirpath(req), filename)
if not os.path.isfile(pathname):
return (None, None)
try:
stat = os.stat(pathname)
filesize = stat.st_size
except Exception as ex:
return (None, None)
if not filesize:
# No point in checking the upload history for zero-length
# uploads.
uploads = []
else:
hashval = self.app.hasher.get_md5(pathname)
curs = self.app.getdb().cursor()
res = curs.execute('SELECT * FROM uploads WHERE md5 = ? ORDER BY uploadtime', (hashval,))
uploads = [ UploadEntry(tup, user=req._user) for tup in res.fetchall() ]
for obj in uploads:
obj.checksuggested(self.app)
return (uploads, filesize)
def do_get(self, req):
"""The GET case has to handle download and "show info" links,
as well as the basic file list.
"""
self.check_fileops(req)
view = req.get_query_field('view')
if view:
# In this case there will be a "filename" field in the query
# string. (Not form field -- this is GET, not POST.)
filename = req.get_query_field('filename')
if view == 'info':
return self.do_get_info(req, filename)
if view == 'dl':
return self.do_get_download(req, filename)
raise HTTPError('404 Not Found', 'View "%s" not found: %s' % (view, filename,))
# Show the list of files and their buttons.
return self.render(self.template, req)
def do_get_download(self, req, filename):
"""Handler to download a file within a directory.
"""
if bad_filename(filename):
msg = 'Not found: %s' % (filename,)
raise HTTPError('404 Not Found', msg)
dirpath = self.get_dirpath(req)
pathname = os.path.join(dirpath, filename)
if not os.path.isfile(pathname):
msg = 'Not a file: %s' % (pathname,)
raise HTTPError('400 Not Readable', msg)
try:
stat = os.stat(pathname)
filesize = stat.st_size
except Exception as ex:
msg = 'Unable to stat: %s %s' % (pathname, ex,)
raise HTTPError('400 Not Readable', msg)
fl = None
try:
fl = open(pathname, 'rb')
except Exception as ex:
msg = 'Unable to read: %s %s' % (pathname, ex,)
raise HTTPError('400 Not Readable', msg)
response_headers = [
('Content-Type', BINARY),
('Content-Length', str(filesize)),
]
# The filename has to be encoded according to RFC 5987. But if
# that's no change, we use the plain version. (Note this takes care
# of quotes as well as Unicode.)
encname = urlencode(filename)
if encname == filename:
val = 'filename="%s"' % (encname,)
else:
# Note no added quotes for this form.
val = 'filename*=UTF-8\'\'%s' % (encname,)
response_headers.append( ('Content-Disposition', 'attachment; '+val) )
def resp():
while True:
val = fl.read(8192)
if not val:
break
yield val
fl.close()
return
raise HTTPRawResponse('200 OK', response_headers, resp())
def do_get_info(self, req, filename):
"""Handler to show upload info for a file within a directory.
"""
(uploads, filesize) = self.get_uploadinfo(req, filename)
if uploads is None or filesize is None:
msg = 'Not found: %s' % (filename,)
raise HTTPError('404 Not Found', msg)
return self.render('uploadinfo.html', req, filename=filename, filesize=filesize, uploads=uploads)
def do_post(self, req):
"""The POST case has to handle showing the "confirm/cancel" buttons
after an operation is selected, and *also* the confirmed operation
itself.
"""
self.check_fileops(req)
view = req.get_query_field('view')
if view:
# In this case there will be a "filename" field in the query
# string. (Not form field.)
filename = req.get_query_field('filename')
if view == 'info':
return self.do_post_info(req, filename)
raise HTTPError('404 Not Found', 'View "%s" not found: %s' % (view, filename,))
# The operation may be defined by an "op" hidden field or by the
# button just pressed. (Depending on what stage we're at.)
if req.get_input_field('op'):
op = req.get_input_field('op')
else:
op = None
for val in req._fileops:
if req.get_input_field(val):
op = val
break
if not op or op not in req._fileops:
return self.render(self.template, req,
formerror='Invalid operation: %s' % (op,))
dirpath = self.get_dirpath(req)
filename = req.get_input_field('filename')
if filename == '.':
ent = None # directory operation
else:
if op == 'dellink':
ent = self.get_symlink(filename, req)
elif op == 'linkto':
ent = self.get_file(filename, req)
if ent is None:
ent = self.get_dirent(filename, req)
elif op == 'rename':
ent = self.get_file(filename, req)
if ent is None:
ent = self.get_symlink(filename, req)
else:
ent = self.get_file(filename, req)
if not ent:
return self.render(self.template, req,
formerror='File not found: "%s"' % (filename,))
# ent is not actually used after this point, though. It was just a check.
# On any Cancel button, we redirect back to the GET for this page.
if req.get_input_field('cancel'):
raise HTTPRedirectPost(self.app.approot+req.path_info+'#list_'+urlencode(filename))
# If neither "confirm" nor "cancel" was pressed, we're at the
# stage of showing those buttons. (And also the "rename" input
# field, etc.) Render the template with those controls showing.
# "opfile" will be the highlighted file.
if not req.get_input_field('confirm'):
# These args are only meaningful for the "move" op.
movedestorig = None
movedestgood = None
delparentdir = None
delchilddir = None
ziptoo = None
if op == 'move' and self.get_dirname(req) == 'unprocessed':
# This is messy, but the plan is to look up the
# "suggested" dir for this file and then check whether
# it's a valid Archive dir. Set movedestorig to the suggested
# value; set movedestgood to the fill value (minus "arch")
# if it's valid.
try:
origpath = os.path.join(dirpath, filename)
origmd5 = self.app.hasher.get_md5(origpath)
curs = self.app.getdb().cursor()
res = curs.execute('SELECT * FROM uploads where md5 = ?', (origmd5,))
tup = res.fetchone()
if tup:
ent = UploadEntry(tup)
movedestorig = ent.suggestdir
ent.checksuggested(self.app)
if ent.suggestdiruri and ent.suggestdiruri.startswith('arch/'):
movedestgood = ent.suggestdiruri[5:]
except:
pass
if op == 'deldir':
# More mess; we need to split the dirname into parent
# and child. This should always we possible, as we only
# permit deletion of dirs second-level and deeper.
val = self.get_dirname(req)
delparentdir, _, delchilddir = val.rpartition('/')
if op == 'uncache':
# Check the filename for zip-ness.
ziptoo = filename.lower().endswith('.zip')
return self.render(self.template, req,
op=op, opfile=filename,
movedestorig=movedestorig,
movedestgood=movedestgood,
delparentdir=delparentdir,
delchilddir=delchilddir,
ziptoo=ziptoo)
# The "confirm" button was pressed, so it's time to perform the
# action.
if op == 'delete':
return self.do_post_delete(req, dirpath, filename)
elif op == 'dellink':
return self.do_post_dellink(req, dirpath, filename)
elif op == 'linkto':
return self.do_post_linkto(req, dirpath, filename)
elif op == 'move':
return self.do_post_move(req, dirpath, filename)
elif op == 'rename':
return self.do_post_rename(req, dirpath, filename)
elif op == 'zip':
return self.do_post_zip(req, dirpath, filename)
elif op == 'uncache':
return self.do_post_uncache(req, dirpath, filename)
elif op == 'csubdir':
return self.do_post_csubdir(req, dirpath)
elif op == 'deldir':
subdirname = req.get_input_field('subdirname')
return self.do_post_deldir(req, dirpath, subdirname)
else:
return self.render(self.template, req,
formerror='Operation not implemented: %s' % (op,))
def do_post_info(self, req, filename):
"""Like do_post(), but for the ?view=info case.
This duplicates the structure of do_post(), which is annoyingly
redundant. But it also avoids a bunch of fiddly special cases.
"""
(uploads, filesize) = self.get_uploadinfo(req, filename)
if uploads is None or filesize is None:
msg = 'Not found: %s' % (filename,)
raise HTTPError('404 Not Found', msg)
# Note that we do not check fileops! The "Add Note" button does
# not require a role check; it's always available.
# On any Cancel button, we redirect back to the GET for this page.
if req.get_input_field('cancel'):
raise HTTPRedirectPost(self.app.approot+req.path_info+'?view=info&filename='+urlencode(filename))
if req.get_input_field('op'):
op = req.get_input_field('op')
else:
op = None
if req.get_input_field('addusernote'):
op = 'addusernote'
elif req.get_input_field('notifyifdb'):
op = 'notifyifdb'
if not op:
return self.render('uploadinfo.html', req, filename=filename, filesize=filesize, uploads=uploads,
formerror='Invalid operation: %s' % (op,))
# If neither "confirm" nor "cancel" was pressed, we're at the
# stage of showing those buttons.
if not req.get_input_field('confirm'):
return self.render('uploadinfo.html', req,
op=op,
filename=filename, filesize=filesize, uploads=uploads)
# The "confirm" button was pressed, so it's time to perform the
# action.
if op == 'addusernote':
return self.do_post_addusernote(req, filename, uploads, filesize)
elif op == 'notifyifdb':
return self.do_post_notifyifdb(req, filename, uploads, filesize)
else:
return self.render('uploadinfo.html', req,
op=op,
filename=filename, filesize=filesize, uploads=uploads,
formerror='Operation not implemented: %s' % (op,))
def do_post_delete(self, req, dirpath, filename):
"""Handle a delete operation (which is really "move to trash").
"""
op = 'delete'
if dirpath == self.app.trash_dir:
raise Exception('delete op cannot be used in the trash')
newname = find_unused_filename(filename, self.app.trash_dir)
origpath = os.path.join(dirpath, filename)
newpath = os.path.join(self.app.trash_dir, newname)
if not os.path.isfile(origpath):
raise Exception('delete op requires a file')
shutil.move(origpath, newpath)
os.utime(newpath)
# See if we need to delete an Index entry as well.
dirname = self.get_dirname(req)
indexdir = IndexDir(dirname, rootdir=self.app.archive_dir, orblank=True)
ient = indexdir.getmap().get(filename)
if ient:
indexdir.delete(filename)
self.app.rewrite_indexdir(indexdir)
req.loginfo('Deleted "%s" from /%s', filename, self.get_dirname(req))
return self.render(self.template, req,
diddelete=filename, didnewname=newname,
didindextoo=bool(ient))
def do_post_dellink(self, req, dirpath, filename):
"""Handle a delete-symlink operation (which really is delete; we
don't put symlinks in the trash).
"""
op = 'dellink'
origpath = os.path.join(dirpath, filename)
if not os.path.islink(origpath):
raise Exception('dellink op requires a symlink')
os.remove(origpath)
# See if we need to delete an Index entry as well.
dirname = self.get_dirname(req)
indexdir = IndexDir(dirname, rootdir=self.app.archive_dir, orblank=True)
ient = indexdir.getmap().get(filename)
if ient:
indexdir.delete(filename)
self.app.rewrite_indexdir(indexdir)
req.loginfo('Deleted symlink "%s" from /%s', filename, self.get_dirname(req))
return self.render(self.template, req,
diddellink=filename,
didindextoo=bool(ient))
def do_post_linkto(self, req, dirpath, filename):
"""Handle a create-symlink operation.
"""
op = 'linkto'
destdir = req.get_input_field('destination')
if not destdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You must select a directory.')
newdir = destdir
if newdir.startswith('/'):
newdir = newdir[ 1 : ]
if newdir.startswith('if-archive/'):
newdir = newdir[ 11 : ]
try:
newdir = canon_archivedir(newdir, archivedir=req.app.archive_dir)
except FileConsistency as ex:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Not an Archive directory: %s' % (newdir,))
if not newdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You cannot create symlinks in the Archive root.')
if newdir == 'unprocessed':
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You cannot create symlinks in /unprocessed.')
dirname = self.get_dirname(req)
if newdir == dirname:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You are already in %s!' % (newdir,))
origpath = os.path.join(dirpath, filename)
if os.path.islink(origpath):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You cannot link to a link!')
origtype = '???'
if os.path.isfile(origpath):
origtype = 'file'
if os.path.isdir(origpath):
origtype = 'subdir'
newpath = os.path.join(self.app.archive_dir, newdir, filename)
if os.path.exists(newpath):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='The %s directory already contains %s.' % (newdir, filename))
relpath = os.path.relpath(origpath, start=os.path.join(self.app.archive_dir, newdir))
os.symlink(relpath, newpath)
# See if we need to clone an Index entry.
indexdir = IndexDir(dirname, rootdir=self.app.archive_dir, orblank=True)
ient = indexdir.getmap().get(filename)
if ient:
indexdir2 = IndexDir(newdir, rootdir=self.app.archive_dir, orblank=True)
indexdir2.add(ient)
self.app.rewrite_indexdir(indexdir2)
req.loginfo('Created symlink to %s "%s" from /%s to /%s', origtype, filename, self.get_dirname(req), newdir)
return self.render(self.template, req,
didlinkto=filename, didnewdir=newdir, didnewuri='arch/'+newdir,
didindextoo=bool(ient))
def do_post_move(self, req, dirpath, filename):
"""Handle a move operation. This checks the radio buttons and
input field to see where you want to move the file.
"""
op = 'move'
destopt = req.get_input_field('destopt')
destdir = req.get_input_field('destination')
if (not destopt or destopt == 'other') and not destdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You must select a destination.')
if destopt == 'inc' and destdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You selected both /incoming and %s; which is it?' % (destdir,))
if destopt == 'unp' and destdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You selected both /unprocessed and %s; which is it?' % (destdir,))
if destopt and destopt.startswith('dir_') and destdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You selected both %s and %s; which is it?' % (destopt[4:], destdir,))
if destopt == 'inc':
# This isn't in the Archive tree, so handle it as a special case.
# Note that we auto-rename if necessary. (The user might not
# know what's in /incoming.)
newname = find_unused_filename(filename, self.app.incoming_dir)
origpath = os.path.join(dirpath, filename)
newpath = os.path.join(self.app.incoming_dir, newname)
shutil.move(origpath, newpath)
req.loginfo('Moved "%s" from /%s to /incoming', filename, self.get_dirname(req))
return self.render(self.template, req,
didmove=filename, didnewdir='incoming', didnewuri='incoming', didnewname=newname)
if destopt == 'unp':
newdir = 'unprocessed'
elif destopt and destopt.startswith('dir_'):
dirname = self.get_dirname(req)
newdir = os.path.join(dirname, destopt[4:])
try:
newdir = canon_archivedir(newdir, archivedir=req.app.archive_dir)
except FileConsistency as ex:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Not an Archive directory: %s' % (newdir,))
else:
newdir = destdir
if newdir.startswith('/'):
newdir = newdir[ 1 : ]
if newdir.startswith('if-archive/'):
newdir = newdir[ 11 : ]
try:
newdir = canon_archivedir(newdir, archivedir=req.app.archive_dir)
except FileConsistency as ex:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Not an Archive directory: %s' % (newdir,))
if not newdir:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You cannot move files to the Archive root.')
dirname = self.get_dirname(req)
if newdir == dirname:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You are already in %s!' % (newdir,))
origpath = os.path.join(dirpath, filename)
newpath = os.path.join(self.app.archive_dir, newdir, filename)
if os.path.exists(newpath):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='A file named %s already exists in %s.' % (filename, newdir,))
shutil.move(origpath, newpath)
# See if we need to move an Index entry as well.
indexdir = IndexDir(dirname, rootdir=self.app.archive_dir, orblank=True)
ient = indexdir.getmap().get(filename)
if ient:
indexdir2 = IndexDir(newdir, rootdir=self.app.archive_dir, orblank=True)
indexdir2.add(ient)
indexdir.delete(filename)
self.app.rewrite_indexdir(indexdir2)
self.app.rewrite_indexdir(indexdir)
req.loginfo('Moved "%s" from /%s to /%s', filename, self.get_dirname(req), newdir)
return self.render(self.template, req,
didmove=filename, didnewdir=newdir, didnewuri='arch/'+newdir,
didindextoo=bool(ient))
def do_post_rename(self, req, dirpath, filename):
"""Handle a rename operation. This checks the input field to see
what you want to rename the file to.
"""
op = 'rename'
newname = req.get_input_field('newname')
if newname is not None:
newname = newname.strip()
if not newname:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='You must supply a filename.')
if bad_filename(newname):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Invalid filename: "%s"' % (newname,))
if newname in FileEntry.specialnames:
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Cannot use reserved filename: "%s"' % (newname,))
origpath = os.path.join(dirpath, filename)
newpath = os.path.join(dirpath, newname)
if os.path.exists(newpath):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='Filename already in use: "%s"' % (newname,))
shutil.move(origpath, newpath)
# See if we need to rename an Index entry as well.
dirname = self.get_dirname(req)
indexdir = IndexDir(dirname, rootdir=self.app.archive_dir, orblank=True)
ient = indexdir.getmap().get(filename)
if ient:
ient.filename = newname
self.app.rewrite_indexdir(indexdir)
req.loginfo('Renamed "%s" to "%s" in /%s', filename, newname, self.get_dirname(req))
return self.render(self.template, req,
didrename=filename, didnewname=newname,
didindextoo=bool(ient))
def do_post_zip(self, req, dirpath, filename):
"""Handle a zip-up-file operation.
"""
op = 'zip'
newname, newsuffix = os.path.splitext(filename)
newname += '.zip'
origpath = os.path.join(dirpath, filename)
newpath = os.path.join(dirpath, newname)
if os.path.exists(newpath):
return self.render(self.template, req,
op=op, opfile=filename,
selecterror='File already exists: "%s"' % (newname,))
origmd5 = self.app.hasher.get_md5(origpath)
zip_compress(origpath, newpath)
# Now move the original to the trash.
if dirpath != 'trash':
trashname = find_unused_filename(filename, self.app.trash_dir)
trashpath = os.path.join(self.app.trash_dir, trashname)
shutil.move(origpath, trashpath)
os.utime(trashpath)
# Now create a new upload entry with the new md5.
newmd5, newsize = self.app.hasher.get_md5_size(newpath)
curs = self.app.getdb().cursor()
res = curs.execute('SELECT * FROM uploads where md5 = ?', (origmd5,))
for tup in list(res.fetchall()):
ent = UploadEntry(tup)
curs.execute('INSERT INTO uploads (uploadtime, md5, size, filename, origfilename, donorname, donoremail, donorip, donoruseragent, permission, suggestdir, ifdbid, about, usernotes, tuid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', (ent.uploadtime, newmd5, newsize, newname, ent.origfilename, ent.donorname, ent.donoremail, ent.donorip, ent.donoruseragent, ent.permission, ent.suggestdir, ent.ifdbid, ent.about, ent.usernotes, ent.tuid))
req.loginfo('Zipped "%s" to "%s" in /%s', filename, newname, self.get_dirname(req))
return self.render(self.template, req,
didzip=filename, didnewname=newname)
def do_post_uncache(self, req, dirpath, filename):
"""Handle a cache-purge operation.
"""
op = 'uncache'
dirname = self.get_dirname(req)
ziptoo = filename.lower().endswith('.zip')
try:
args = [ self.app.uncache_script_path ]
if ziptoo:
args.append('--zip')
args.append('if-archive/%s/%s' % (dirname, filename,))
if self.app.secure_site:
args.insert(0, '/usr/bin/sudo')
subprocess.run(args, check=True, text=True, capture_output=True)
except subprocess.CalledProcessError as ex:
errortext = ''
if ex.stdout:
errortext += ex.stdout
if ex.stderr:
errortext += ex.stderr
return self.render(self.template, req,
op=op, opfile=filename,
ziptoo=ziptoo,
selecterror='Error: %s\n%s' % (ex, errortext))
except Exception as ex:
return self.render(self.template, req,
op=op, opfile=filename,
ziptoo=ziptoo,
selecterror='Error: %s' % (ex,))
req.loginfo('Cache-wiped "%s" in /%s', filename, self.get_dirname(req))
return self.render(self.template, req,
diduncache=filename, ziptoo=ziptoo)
def do_post_csubdir(self, req, dirpath):
"""Handle a create-subdir operation.
"""
op = 'csubdir'
newname = req.get_input_field('newname')
if newname is not None:
newname = newname.strip()
if not newname:
return self.render(self.template, req,
op=op, opfile='.',
selecterror='You must supply a directory name.')
if bad_filename(newname):
return self.render(self.template, req,
op=op, opfile='.',
selecterror='Invalid dirname: "%s"' % (newname,))
if newname in FileEntry.specialnames:
return self.render(self.template, req,
op=op, opfile='.',
selecterror='Cannot use reserved filename: "%s"' % (newname,))
newpath = os.path.join(dirpath, newname)
if os.path.exists(newpath):
return self.render(self.template, req,
op=op, opfile='.',
selecterror='Filename already in use: "%s"' % (newname,))
os.mkdir(newpath)
req.loginfo('Created subdirectory "%s" in /%s', newname, self.get_dirname(req))
return self.render(self.template, req,
didcsubdir='.', didnewname=newname)