-
Notifications
You must be signed in to change notification settings - Fork 4
/
give.py.in
executable file
·838 lines (777 loc) · 27.8 KB
/
give.py.in
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
#!/usr/bin/env python
##
# @file give.py
#
# give/take: securely offer files to another user
#
# 2010-05-20 Shawn Instenes <shawni@llnl.gov>
# last modified 2012-07 Dominic Manno <dmanno@lanl.gov>
#
# @author: Shawn Instenes
# @author: Trent D'Hooge
# @author: Jim Garlick
# @author: Jon Bringhurst
# @author: Dominic Manno
# @author: Ryan Day
#
#
# Work flow:
#
# Validate args: giver, taker, gt-<taker_uid>
#
# For give:
# Invoke give-assist <taker>- if it fails, we stop.
#
# Copy (with checking), filename from current directory to
# spool directory. Chmod destination file. Touch file (to update ctime).
#
# Opts to honor:
#
# -Vulhnrif
# V: version (use --version)
# u: ungive
# l: list
# n: compact list (not implmented in give 1.25a)
# r: recursive give (not imp. in give 1.25a)-- WE DO NOT YET IMPLEMENT
# i: interactive
# f: force overwrite
# h: help
#
# assume give- if named 'take' assume take.
#
# if invoked with no args, then list (have given, or to take).
#
# Python 2.3+
#==========================================================================
#
import sys, os, pwd, grp, time, subprocess
from optparse import OptionParser
try:
import readline
except:
pass
## STRICT will be set to 0 if non-strict checking was enabled at config time, or 1 by default (if non-strict checking wasn't enabled)
STRICT=@STRICT_CHECKS@
## SPOOL will be set to /usr/givedir at config time, unless ./config --enable-givedir=DIR is passed in at config time, then the SPOOL = DIR
SPOOL="@SPOOL@"
VERSION="%prog 3.1-5"
ASSIST="/usr/bin/give-assist"
COPY="/bin/cp"
TOUCH="/bin/touch"
assist_rec = {}
debug_mode = False
#==========================================================================
# Functions
#
##
# give-assist is ran here, it will use a c binary to elevate perms so that dirs can be made with the right perms safely
#
# this way giver can: give, ungive, list files given
# taker can: take and list files to take
#
# @param toname it is whomever is receiving the file
#
def run_assist(toname=None):
if toname == None:
return
if toname not in assist_rec:
assist_rec.setdefault(toname, True)
try:
ret = subprocess.call([ASSIST, toname])
if ret != 0:
#not going to output an error message here because give-assist SHOULD output it's own before exiting.
sys.exit(ret)
except:
print("Problem running %s." % ASSIST)
sys.exit(1)
##
# this will remove a file from the give spool
#
# it is called by run_copy if the copy fails to remove partially written files
#
# @param frompath the directory where the file being given is located (needed to get file name)
# @param topath the directory where the file will be copied (give spool)
# @param retcode from the os calls to see if the file exists and remove
#
def run_remove(frompath=None, topath=None):
retcode = 0
if (frompath == None or topath == None):
print("run_remove: bad args")
sys.exit(1)
filename = frompath.split('/').pop()
filepath = topath+"/"+filename
if debug_mode:
print("filepath is %s." % filepath)
if os.access(filepath, os.F_OK):
try:
print("Removing %s from give spool." % filepath)
retcode = os.unlink(filepath)
if retcode:
print("Failed to remove %s." % filepath)
except:
print("Problem running unlink.")
else:
print("No such file to remove: %s." % filepath)
retcode = 1
return retcode
##
# this will copy the file from 'frompath' to 'topath' (givedir)
#
# it makes sure the file exists in the frompath
# then copies.
#
# @param frompath the directory where the file being given is located
# @param topath the directory where the file will be copied to (givedir)
# @param preserve if this is true, the timestamp is preserved on the giver's local file
# @return retcode from os calls to see if the file exists and copy
#
def run_copy(frompath=None, topath=None, preserve=True):
retcode = 0
if (frompath == None or topath == None):
print("run_copy: bad args")
sys.exit(1)
if os.access(frompath, os.F_OK):
try:
if preserve:
retcode = subprocess.call([COPY, '-p', frompath, topath])
else:
retcode = subprocess.call([COPY, frompath, topath])
if retcode:
print("Copy of %s was unsuccessful." % frompath)
run_remove(frompath, topath)
except:
print("Problem running %s." % COPY)
sys.exit(1)
else:
print("No such file to copy: %s." % frompath)
retcode = 1 # signal a problem
return retcode
##
# this fixes perms on the file.
#
# it will use statbuf and chmod to change the perms, then it calls /bin/touch to update the new file's timestamp for the taker
#
# @param path the path of the file given (givedir/.....)
#
def fix_perms(path=None):
if (path == None):
print("Cannot fix permissions: no path")
sys.exit(1)
try:
statbuf = os.stat(path)
except:
print("No such file %s." % path)
sys.exit(1)
##
# mask out excessive world permissions if set by giver
# use "0774" instead of original "0777" -gap, Oct 2012
##
#py 2.6 allows for either 0777 or 0o777 for chmod
#anything before 2.6 likes 0777 and anything after
#wants 0o777, so we use a string and then an int with
#base=8 to convert for us...what a nightmare!
oldModeStr = "0777"
newModeStr = "0444"
oldmode = statbuf.st_mode & int(oldModeStr, base=8)
newmode = oldmode | int(newModeStr, base=8)
try:
os.chmod(path, newmode)
except:
print("Failed chmod on file %s." % path)
sys.exit(1)
try:
retcode = subprocess.call([TOUCH, path])
except:
print("Failed touch operation on file %s." % path)
sys.exit(1)
##
# this is ran if verbose option is used, it is interactive with the user
# it requires the user to type y or Y for yes, if anything else input
# it will take that as a no and return false
#
# this is only ran if the the verbose option is passed in, it creates the interactivity
#
# @param prompt this will be the question we are asking the user
# @return true if the user allows, false if not
#
def isokto(prompt=None):
if prompt == None:
prompt = "? "
yn = input(prompt)
if (yn[0:1] == "y" or yn[0:1] == "Y"):
return True
else:
return False
##
# we call run_assist to help give the file, check to see if the file exists in the dir, then give the file using run_copy, finally change perms using fix_perms
#
# @param fuid the givers's uid
# @param tuid the taker's uid
# @param path the location of the file the giver is giving
# @param prompt if prompt is true that means verbose was enabled, this will run isokto
#
def give_file(fuid=None, tuid=None, path=None, prompt=False):
retcode = 0
count = 1
if (tuid != None):
run_assist(tuid)
else:
print("Attempt to give file to <None>\n")
sys.exit(1)
if (fuid != None):
if prompt and not isokto("Give file %s to %s? " % (path, tuid)):
return 0
try:
if debug_mode:
print("copy ('%s','%s')" % (path, SPOOL+"/"+tuid+"/"+fuid))
if os.access(SPOOL+"/"+tuid+"/"+fuid+"/"+path, os.F_OK):
if opts.force:
retcode = run_copy(path, SPOOL+"/"+tuid+"/"+fuid, True)
if retcode == 0:
fix_perms(SPOOL+"/"+tuid+"/"+fuid+"/"+os.path.basename(path))
else:
print("File already given, won't overwrite without -f (force)")
count = 0
else:
retcode = run_copy(path, SPOOL+"/"+tuid+"/"+fuid, True)
if retcode == 0:
fix_perms(SPOOL+"/"+tuid+"/"+fuid+"/"+os.path.basename(path))
except Exception as em:
print("Error %s running %s.\n" % (em, COPY))
sys.exit(1)
if retcode:
count = 0
return count
else:
print("Attempt to give file <None>\n")
sys.exit(1)
##
# this is almost the same as give, but will 'un-give' the file.
# it uses os.unlink to delete the file in the givedir
#
# @param tuid takers uid
# @param fuid "un-giver's" uid
# @param path the name of the file to be deleted
# @param prompt if prompt is true that means verbose was enabled, this will run isokto, otherwise interactivity isn't enabled
# @return 1 for success
#
def ungive_file(fuid=None, tuid=None, path=None, prompt=False):
if (tuid != None and fuid != None and path != None):
if prompt and not isokto("Ungive file %s, given to %s? " % (path, tuid)):
return 0
try:
if debug_mode:
print("unlink('%s')" % (SPOOL+"/"+tuid+"/"+fuid+"/"+path))
if os.access(SPOOL+"/"+tuid+"/"+fuid+"/"+path, os.F_OK):
os.unlink(SPOOL+"/"+tuid+"/"+fuid+"/"+path)
else:
print("No such file to ungive: %s" % (path))
return 0
except Exception as em:
print("Error %s while unlinking.\n" % em)
return 0
return 1
else:
print("Attempt to use bad parameters to ungive_file\n")
sys.exit(1)
##
# this will take the file and copy it into the taker's current directory
# if the copy is successful, it will delete the file from the givedir using os.unlink
#
# @param fuid the giver's uid
# @param tuid the taker's uid
# @param path the file to be 'taken'
# @param prompt if prompt is true that means verbose was enabled, this will run isokto, otherwise intractivity isn't enabled
#
#
def take_file(fuid=None, tuid=None, path=None, prompt=False):
count = 1
retcode = 0
if (tuid == None):
print("Attempt to use bad parameters to take_file\n")
sys.exit(1)
if (path == None):
print("Attempt to use bad parameters to take_file\n")
sys.exit(1)
if (fuid != None):
if prompt and not isokto("Take file %s from %s? " % (path, fuid)):
return 0
try:
if debug_mode:
print("copy ('%s','%s')" % (SPOOL+"/"+tuid+"/"+fuid+"/"+path, "."))
if os.access("./"+path, os.F_OK):
if opts.force:
retcode = run_copy(SPOOL+"/"+tuid+"/"+fuid+"/"+path, ".", False)
else:
print("File %s already exists in local directory, won't overwrite without -f (force)" % (path))
retcode = 1
count = 0
else:
retcode = run_copy(SPOOL+"/"+tuid+"/"+fuid+"/"+path, ".", False)
except Exception as em:
print("Error %s running %s.\n" % (em, COPY))
sys.exit(1)
try:
if retcode == 0:
os.unlink(SPOOL+"/"+tuid+"/"+fuid+"/"+path)
else:
return 0
except Exception as em:
print("Error %s while unlinking.\n" % em)
sys.exit(1)
return count
else:
print("Attempt to use bad parameters to take_file\n")
sys.exit(1)
##
# this is used to generate the list of files in the directories, or enumerate the files to be listed
#
# @param f the giver usrname
# @param t the taker usrname
# @return dlist the list of files in the directory spool/taker/from
#
def enumerate_files(f=None, t=None):
if t == None:
return ()
if f == None:
try:
dirl = os.listdir(SPOOL+"/"+t)
except:
dirl = []
dlist = []
for d in dirl:
try:
sd = os.listdir(SPOOL+"/"+t+"/"+d)
dlist.append((d, sd))
except:
pass
return dlist
else:
try:
dlist = os.listdir(SPOOL+"/"+t+"/"+f)
except:
dlist = []
dlist.sort()
return dlist
##
# this is used to list a file, to do this os.path.basename is used on the path.
# if brief is true then the name of the file is listed, if brief is false then the
# size of the file is listed, along with the timestamp
#
# @param path the file to be listed, it includes the full path
# @param brief this is used to determine what info is printed.
#
def list_a_file(path=None, brief=False):
if path == None:
return
displayname = os.path.basename(path)
try:
if brief:
print("%s" % displayname)
else:
statbuf = os.stat(path)
fsize = statbuf.st_size
# love having bigints built-in to the language.
if (fsize // 2**80) > 0:
sc = "YB"; psize = fsize // 2**80
elif (fsize // 2**70) > 0:
sc = "ZB"; psize = fsize // 2**70
elif (fsize // 2**60) > 0:
sc = "EB"; psize = fsize // 2**60
elif (fsize // 2**50) > 0:
sc = "PB"; psize = fsize // 2**50
elif (fsize // 2**40) > 0:
sc = "TB"; psize = fsize // 2**40
elif (fsize // 2**30) > 0:
sc = "GB"; psize = fsize // 2**30
elif (fsize // 2**20) > 0:
sc = "MB"; psize = fsize // 2**20
elif (fsize // 2**10) > 0:
sc = "KB"; psize = fsize // 2**10
else:
sc = " B"; psize = fsize
ctime = time.strftime("%b %d %R", time.localtime(statbuf.st_ctime))
print("%6d %s %s %s" % (psize, sc, ctime, displayname))
except:
return
##
# this will list a directory which is path, it cals list_a_file to list the files in the path.
#
# @param path the directory that will be listed
# @param brief passed into list_a_file see that param section
# @param header this is printed above the files in the directory, it says (user has given:)
# @return the amount of files in the dir
#
def list_a_directory(path=None, brief=False, header=None):
try:
dlist = os.listdir(path)
if len(dlist) > 0:
dlist.sort()
if header != None:
print("%s" % header)
for fn in dlist:
list_a_file(path+"/"+fn, brief)
return len(dlist)
except:
return 0
##
#
# in the case we have no getpwnam() data for a giver, we
# attempt to fake it from data in the directory.
#
# @param giver giver's username
# @param taker taker's username
#
def get_giverpw_from_dir(giver=None, taker=None):
# in the case we have no getpwnam() data for a giver, we
# attempt to fake it from data in the directory.
dirname = SPOOL+"/"+taker+"/"+giver
try:
statbuf = os.stat(dirname)
except:
return None
return pwd.struct_passwd.__new__(pwd.struct_passwd, (giver, "x", statbuf.st_uid, statbuf.st_uid, giver, "/no_dir_exists", "/bin/false"))
##
# list the files you have given, this is invoked if give is ran w/o params.
# it uses os.listdir on spool, then sorts the subdirs and calls list_a_directory
# to list the files. It
#
# @param myuid this is the username of the invoking user
# @param theiruid this is the username of the person that was given the file
# @param brief this will determine if it tells the amount of files given
#
#
def list_files_given(myuid=None, theiruid=None, brief=False):
totalcount = 0
if myuid != None:
if theiruid == None:
dlist = os.listdir(SPOOL)
dlist.sort()
for pname in dlist:
if os.access(SPOOL+"/"+pname+"/"+myuid, os.F_OK):
dheader = " %s has been given:" % pname
dlen = list_a_directory(SPOOL+"/"+pname+"/"+myuid, brief, dheader)
totalcount += dlen
if not brief:
if dlen > 0:
print(" %d file(s)" % dlen)
if not brief:
if totalcount > 0:
print("You have given a total of %d file(s)." % totalcount)
else:
print("You have given no files.")
else:
dlen = list_a_directory(SPOOL+"/"+theiruid+"/"+myuid, brief, None)
totalcount += dlen
if not brief:
if totalcount > 0:
print("You have given %d file(s)." % totalcount)
else:
print("Attempt to use bad parameters to list_files_given\n")
sys.exit(1)
##
# list the files to take, it calls list a directory to assist with this, it is invoked if take is ran w/o params.
# it usees os.listdir on spool/myuid to be able to see what subdirs/files have been given, it prints the name, size, and
# who gave the file.
#
# @param myuid
# @param theiruid
# @param brief
#
def list_files_totake(myuid=None, theiruid=None, brief=False):
totalcount = 0
if myuid != None:
if theiruid == None:
try:
dlist = os.listdir(SPOOL+"/"+myuid)
except:
print("You have no files to take.")
return
dlist.sort()
for pname in dlist:
if os.access(SPOOL+"/"+myuid+"/"+pname, os.F_OK):
dheader = " %s has given:" % pname
dlen = list_a_directory(SPOOL+"/"+myuid+"/"+pname, brief, dheader)
totalcount += dlen
if not brief:
if dlen > 0:
print(" %d file(s)" % dlen)
if not brief:
if totalcount > 0:
print("You have %d file(s) to take." % totalcount)
else:
print("You have no files to take.")
else:
dheader = "%s has given:" % theiruid
dlen = list_a_directory(SPOOL+"/"+myuid+"/"+theiruid, brief, dheader)
totalcount += dlen
if not brief:
if totalcount > 0:
print("You have %d file(s) to take." % totalcount)
else:
print("Attempt to use bad parameters to list_files_totake\n")
sys.exit(1)
##
#
# We validate various things that should be true-.
#
# 1) taker/giver usernames map to available users (we can look them up)
#
# 2) if group "gt-<taker uid>" exists, then the giver is a member
#
# 3) taker's group exists, and the taker is the ONLY member
#
# @param giver_uname giver's username
# @param taker_uname taker's username
#
def validate_transaction (giver_uname, taker_uname):
isvalid = True
try:
g_ent = pwd.getpwnam(giver_uname)
t_ent = pwd.getpwnam(taker_uname)
except:
isvalid = False
# giver/taker can't be looked up? fail.
if not isvalid:
print("Both Giver and Taker must be valid in password database.")
return isvalid
try:
grp_ent = grp.getgrnam("gt-"+str(t_ent.pw_uid))
isvalid = False
for x in grp_ent.gr_mem:
if x == g_ent.pw_name:
isvalid = True # giver is in taker's gt-<uid> group
except:
isvalid = True
# giver is in taker's gt-<uid> group OR gt-<uid> group does not exist.
if not isvalid:
print("You are not authorized to give files to that user.")
return isvalid
try:
if(STRICT == 1):
grp_ent = grp.getgrgid(t_ent.pw_gid) #gets the default group, which should be equal to uid for LLNL
if g_ent.pw_uid != g_ent.pw_gid:
print("You are unathorized to give files...uid != gid")
isvalid = False
if t_ent.pw_uid != t_ent.pw_gid:
print("Taker is not authorized to receive files...uid != gid")
isvaild = False
else:
grp_ent = grp.getgrnam(t_ent.pw_name) #LANL doesn't require user == default gid, so we just get the 'user' group instead of default
for x in grp_ent.gr_mem:
if x != t_ent.pw_name:
isvalid = False # taker must be the only member of their user group
print("Taker's user group is not set up correctly, they must be the only member of their user group.") #changed *default --> user
return isvalid
except:
print("Can't obtain taker default group info")
isvalid = False # group must exist
return isvalid
##
#
# Send an email to the taker informing them of the given file
#
# @param giver_ent
# @param taker
# @param totalcount
# @param flist
#
def send_email (giver_ent, taker,totalcoutn, glist):
giver_gecos = giver_ent.pw_gecos
giver_name = giver_gecos.split(',')[0]
giver_id = giver_ent.pw_name
subj = '%s has given you %d file(s)' % (giver_name, totalcount)
body = '%s (%s) has given you %d file(s):\n' % (giver_name, giver_id, totalcount)
for fpath in glist:
body += "\n%s" % fpath.split('/').pop()
mail_cmd = 'echo "%s" | mail -s "%s" %s' % (body, subj, taker)
print("Sending email to %s." % taker)
os.system(mail_cmd)
#=================================================================
# Setup
progname = os.path.basename(sys.argv[0])
if progname[:4] == 'take':
give_mode = False
else:
give_mode = True
usagestr = "%prog [options] <user> [filename]"
parser = OptionParser(usage=usagestr, version=VERSION)
parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="suppress status messages")
parser.add_option("-i", "--interactive", action="store_true", dest="interact", default=False, help="prompt for confirmation for each file")
#
# Take care of different options of give and take.
#
if give_mode:
parser.add_option("-u", "--ungive", action="store_true", dest="ungive", default=False, help="ungive a file")
parser.add_option("-f", "--force", action="store_true", dest="force", default=False, help="force overwriting a file already given")
parser.add_option("-l", "--list", action="store_true", dest="list", default=False, help="list files you have given")
parser.add_option("-n", "--compact", action="store_true", dest="compact", default=False, help="brief list files you have given")
parser.add_option("-a", "--all", "--regive", action="store_true", dest="all", default=False, help="regive all files to user, with overwrite")
parser.add_option("-m", "--mail", action="store_true", dest="mail", default=False, help="send e-mail to recipient")
else:
parser.add_option("-l", "--list", action="store_true", dest="list", default=False, help="list files to take")
parser.add_option("-f", "--force", action="store_true", dest="force", default=False, help="force overwriting files")
parser.add_option("-n", "--compact", action="store_true", dest="compact", default=False, help="brief list files to take")
parser.add_option("-a", "--all", action="store_true", dest="all", default=False, help="all files")
(opts, args) = parser.parse_args()
#
# Sanity checking.
#
if len(args) > 0:
who = args[0]
args = args[1:]
else:
who = None # special token
if give_mode:
if opts.all:
opts.force = True
if give_mode:
if who == None:
if opts.all:
parser.error("--regive option requires a username.")
sys.exit(1)
else:
opts.list = True
else:
if not opts.all and not opts.ungive and len(args) == 0:
opts.list = True
else:
if who == None:
if not opts.all:
opts.list = True
if len(args) == 0:
opts.all = True
else:
if opts.all:
if give_mode:
parser.error("Cannot specify filenames AND --all or --regive.")
else:
parser.error("Cannot specify filenames AND --all.")
sys.exit(1)
if give_mode:
if len(args) == 0:
if not opts.compact and not opts.list and not opts.all:
if who != None:
opts.list = True
else:
parser.error("Need a username and filename.")
sys.exit(1)
if opts.compact:
opts.list = True
#=============================================================================
# Main
try:
if give_mode:
if who != None:
taker_ent = pwd.getpwnam(who)
else:
taker_ent = pwd.getpwuid(os.getuid())
except:
print("I cannot find account information for user %s." % who)
sys.exit(1)
if give_mode:
try:
giver_ent = pwd.getpwuid(os.getuid())
except:
print("I cannot find your account information.\n")
sys.exit(1)
else:
if who == None:
giver_ent = None
else:
try:
giver_ent = pwd.getpwnam(who)
except:
giver_ent = get_giverpw_from_dir(who, taker_ent.pw_name)
if giver_ent == None:
print("Cannot find giver's account information.\n")
sys.exit(1)
if give_mode:
if who != None:
if not validate_transaction(giver_ent.pw_name, who):
sys.exit(1)
#
# Giver, taker validated.
#
if opts.list:
if give_mode:
list_files_given(giver_ent.pw_name, who, opts.compact)
else:
list_files_totake(taker_ent.pw_name, who, opts.compact)
sys.exit(0)
totalcount = 0
if give_mode:
if opts.ungive:
if who == None:
parser.error("You must supply username for -u.")
sys.exit(1)
if opts.all:
flist = enumerate_files(giver_ent.pw_name, who)
else:
if len(args) == 0:
flist = enumerate_files(giver_ent.pw_name, who)
else:
flist = args
for fname in flist:
if opts.verbose:
print("Ungiving %s." % fname)
dlen = ungive_file(giver_ent.pw_name, who, fname, opts.interact)
totalcount += dlen
if totalcount > 0:
print("Ungave %d file(s)." % totalcount)
else:
print("No files ungiven.")
else:
if opts.all:
flist = enumerate_files(giver_ent.pw_name, who)
else:
flist = args
glist = []
for fname in flist:
if opts.verbose:
print("Giving %s." % fname)
dlen = give_file(giver_ent.pw_name, taker_ent.pw_name, fname, opts.interact)
if dlen > 0:
totalcount += dlen
glist.append(fname)
if totalcount > 0:
print("Gave %d file(s)." % totalcount)
if opts.mail:
send_email(giver_ent, taker_ent.pw_name, totalcount, glist)
else:
print("No files given.")
else:
if opts.all:
todo = enumerate_files(who, taker_ent.pw_name)
if who == None:
for (who,fnames) in todo:
for fname in fnames:
if opts.verbose:
print("Taking %s from %s." % (fname, who))
dlen = take_file(who, taker_ent.pw_name, fname, opts.interact)
totalcount += dlen
if totalcount > 0:
print("Taken %d file(s)." % totalcount)
else:
print("No files taken.")
else:
for fname in todo:
if opts.verbose:
print("Taking %s from %s." % (fname, who))
dlen = take_file(who, taker_ent.pw_name, fname, opts.interact)
totalcount += dlen
if totalcount > 0:
print("Taken %d file(s)." % totalcount)
else:
print("No files taken.")
else:
for fname in args:
if opts.verbose:
print("Taking %s." % fname)
dlen = take_file(giver_ent.pw_name, taker_ent.pw_name, fname, opts.interact)
totalcount += dlen
if totalcount > 0:
print("Taken %d file(s)." % totalcount)
else:
print("No files taken.")
sys.exit(0)