]> err.no Git - pwstore/blob - pws
Fix up GROUP_PATTERN support so it allows multiple access items on a line
[pwstore] / pws
1 #!/usr/bin/ruby
2
3 # password store management tool
4
5 # Copyright (c) 2008, 2009 Peter Palfrader <peter@palfrader.org>
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining
8 # a copy of this software and associated documentation files (the
9 # "Software"), to deal in the Software without restriction, including
10 # without limitation the rights to use, copy, modify, merge, publish,
11 # distribute, sublicense, and/or sell copies of the Software, and to
12 # permit persons to whom the Software is furnished to do so, subject to
13 # the following conditions:
14 #
15 # The above copyright notice and this permission notice shall be
16 # included in all copies or substantial portions of the Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25
26 require 'optparse'
27 require 'thread'
28 require 'tempfile'
29
30 require 'yaml'
31 Thread.abort_on_exception = true
32
33 GNUPG = "/usr/bin/gpg"
34 GROUP_PATTERN = "@[a-zA-Z0-9-]+"
35 USER_PATTERN = "[a-zA-Z0-9:-]+"
36 $program_name = File.basename($0, '.*')
37
38 $editor = ENV['EDITOR']
39 if $editor == nil
40   %w{/usr/bin/sensible-editor /usr/bin/editor /usr/bin/vi}.each do |editor|
41     if FileTest.executable?(editor)
42       $editor = editor
43       break
44     end
45   end
46 end
47
48 class GnuPG
49   @@my_keys = nil
50   @@my_fprs = nil
51   @@keyid_fpr_mapping = {}
52
53   def GnuPG.readwrite3(intxt, infd, stdoutfd, stderrfd, statusfd)
54     outtxt, stderrtxt, statustxt = ''
55     thread_in = Thread.new {
56       infd.print intxt
57       infd.close
58     }
59     thread_out = Thread.new {
60       outtxt = stdoutfd.read
61       stdoutfd.close
62     }
63     thread_err = Thread.new {
64       errtxt = stderrfd.read
65       stderrfd.close
66     }
67     thread_status = Thread.new {
68       statustxt = statusfd.read
69       statusfd.close
70     } if (statusfd)
71
72     thread_in.join
73     thread_out.join
74     thread_err.join
75     thread_status.join if thread_status
76
77     return outtxt, stderrtxt, statustxt
78   end
79
80   def GnuPG.gpgcall(intxt, args, require_success = false)
81     inR, inW = IO.pipe
82     outR, outW = IO.pipe
83     errR, errW = IO.pipe
84     statR, statW = IO.pipe
85
86     pid = Kernel.fork do
87       inW.close
88       outR.close
89       errR.close
90       statR.close
91       STDIN.reopen(inR)
92       STDOUT.reopen(outW)
93       STDERR.reopen(errW)
94       begin
95         exec(GNUPG, "--status-fd=#{statW.fileno}",  *args)
96       rescue Exception => e
97         outW.puts("[PWSEXECERROR]: #{e}")
98         exit(1)
99       end
100       raise ("Calling gnupg failed")
101     end
102     inR.close
103     outW.close
104     errW.close
105     statW.close
106     (outtxt, stderrtxt, statustxt) = readwrite3(intxt, inW, outR, errR, statR);
107     wpid, status = Process.waitpid2 pid
108     throw "Unexpected pid: #{pid} vs #{wpid}" unless pid == wpid
109     throw "Process has not exited!?" unless status.exited?
110     throw "gpg call did not exit sucessfully" if (require_success and status.exitstatus != 0)
111     if m=/^\[PWSEXECERROR\]: (.*)/.match(outtxt) then
112       STDERR.puts "Could not run GnuPG: #{m[1]}"
113       exit(1)
114     end
115     return outtxt, stderrtxt, statustxt, status.exitstatus
116   end
117
118   def GnuPG.init_keys()
119     return if @@my_keys
120     (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', %w{--fast-list-mode --with-colons --with-fingerprint --list-secret-keys}, true)
121     @@my_keys = []
122     @@my_fprs = []
123     outtxt.split("\n").each do |line|
124       parts = line.split(':')
125       if (parts[0] == "ssb" or parts[0] == "sec")
126         @@my_keys.push parts[4]
127       elsif (parts[0] == "fpr")
128         @@my_fprs.push parts[9]
129       end
130     end
131   end
132   # This is for my private keys, so we can tell if a file is encrypted to us
133   def GnuPG.get_my_keys()
134     init_keys
135     @@my_keys
136   end
137   # And this is for my private keys also, so we can tell if we are encrypting to ourselves
138   def GnuPG.get_my_fprs()
139     init_keys
140     @@my_fprs
141   end
142
143   # This maps public keyids to fingerprints, so we can figure
144   # out if a file that is encrypted to a bunch of keys is
145   # encrypted to the fingerprints it should be encrypted to
146   def GnuPG.get_fpr_from_keyid(keyid)
147     fpr = @@keyid_fpr_mapping[keyid]
148     # this can be null, if we tried to find the fpr but failed to find the key in our keyring
149     unless fpr
150       STDERR.puts "Warning: No key found for keyid #{keyid}"
151     end
152     return fpr
153   end
154   def GnuPG.get_fprs_from_keyids(keyids)
155     learn_fingerprints_from_keyids(keyids)
156     return keyids.collect{ |k| get_fpr_from_keyid(k) or "unknown" }
157   end
158
159   # this is to load the keys we will soon be asking about into
160   # our keyid-fpr-mapping hash
161   def GnuPG.learn_fingerprints_from_keyids(keyids)
162     need_to_learn = keyids.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }
163     if need_to_learn.size > 0
164       # we can't use --fast-list-mode here because GnuPG is broken
165       # and does not show elmo's fingerprint in a call like
166       # gpg --with-colons --fast-list-mode --with-fingerprint --list-key D7C3F131AB2A91F5
167       args = %w{--with-colons --with-fingerprint --list-keys}
168       args.concat need_to_learn
169       (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', args, true)
170
171       pub = nil
172       fpr = nil
173       outtxt.split("\n").each do |line|
174         parts = line.split(':')
175         if (parts[0] == "pub")
176           pub = parts[4]
177         elsif (parts[0] == "fpr")
178           fpr = parts[9]
179           @@keyid_fpr_mapping[pub] = fpr
180         elsif (parts[0] == "sub")
181           @@keyid_fpr_mapping[parts[4]] = fpr
182         end
183       end
184     end
185     need_to_learn.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }.each { |k| @@keyid_fpr_mapping[k] = nil }
186   end
187 end
188
189 def read_input(query, default_yes=true)
190   if default_yes
191     append = '[Y/n]'
192   else
193     append = '[y/N]'
194   end
195
196   while true
197     print "#{query} #{append} "
198     begin
199       i = STDIN.readline.chomp.downcase
200     rescue EOFError
201       return default_yes
202     end
203     if i==""
204       return default_yes
205     elsif i=="y"
206       return true
207     elsif i=="n"
208       return false
209     end
210   end
211 end
212
213 class GroupConfig
214   def initialize
215     parse_file
216     expand_groups
217   end
218
219   def verify(content)
220     begin
221       f = File.open(ENV['HOME']+'/.pws-trusted-users')
222     rescue Exception => e
223       STDERR.puts e
224       exit(1)
225     end
226
227     trusted = []
228     f.readlines.each do |line|
229       line.chomp!
230       next if line =~ /^$/
231       next if line =~ /^#/
232
233       trusted.push line
234     end
235
236     args = []
237     args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
238     (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
239     goodsig = false
240     validsig = nil
241     statustxt.split("\n").each do |line|
242       if m = /^\[GNUPG:\] GOODSIG/.match(line)
243         goodsig = true
244       elsif m = /^\[GNUPG:\] VALIDSIG \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([0-9A-F]+)/.match(line)
245         validsig = m[1]
246       end
247     end
248
249     if not goodsig
250       STDERR.puts ".users file is not signed properly.  GnuPG said on stdout:"
251       STDERR.puts outtxt
252       STDERR.puts "and on stderr:"
253       STDERR.puts stderrtxt
254       STDERR.puts "and via statusfd:"
255       STDERR.puts statustxt
256       exit(1)
257     end
258
259     if not trusted.include?(validsig)
260       STDERR.puts ".users file is signed by #{validsig} which is not in ~/.pws-trusted-users"
261       exit(1)
262     end
263
264     if not exitstatus==0
265       STDERR.puts "gpg verify failed for .users file"
266       exit(1)
267     end
268
269     return outtxt
270   end
271
272   def parse_file
273     begin
274       f = File.open('.users')
275     rescue Exception => e
276       STDERR.puts e
277       exit(1)
278     end
279
280     users = f.read
281     f.close
282
283     users = verify(users)
284
285     @users = {}
286     @groups = {}
287
288     lno = 0
289     users.split("\n").each do |line|
290       lno = lno+1
291       next if line =~ /^$/
292       next if line =~ /^#/
293       if (m = /^(#{USER_PATTERN})\s*=\s*([0-9A-Fa-f]{40})\s*$/.match line)
294         user = m[1]
295         fpr = m[2]
296         if @users.has_key?(user)
297           STDERR.puts "User #{user} redefined at line #{lno}!"
298           exit(1)
299         end
300         @users[user] = fpr
301       elsif (m = /^(#{GROUP_PATTERN})\s*=\s*(.*)$/.match line)
302         group = m[1]
303         members = m[2].strip
304         if @groups.has_key?(group)
305           STDERR.puts "Group #{group} redefined at line #{lno}!"
306           exit(1)
307         end
308         members = members.split(/[\t ,]+/)
309         @groups[group] = { "members" => members }
310       end
311     end
312   end
313
314   def is_group(name)
315     return (name =~ /^@/)
316   end
317   def check_exists(x, whence, fatal=true)
318     ok=true
319     if is_group(x)
320       ok=false unless (@groups.has_key?(x))
321     else
322       ok=false unless @users.has_key?(x)
323     end
324     unless ok
325       STDERR.puts( (fatal ? "Error: " : "Warning: ") + "#{whence} contains unknown member #{x}")
326       exit(1) if fatal
327     end
328     return ok
329   end
330   def expand_groups
331     @groups.each_pair do |groupname, group|
332       group['members'].each do |member|
333         check_exists(member, "Group #{groupname}")
334       end
335       group['members_to_do'] = group['members'].clone
336     end
337
338     while true
339       had_progress = false
340       all_expanded = true
341       @groups.each_pair do |groupname, group|
342         group['keys'] = [] unless group['keys'] 
343
344         still_contains_groups = false
345         group['members_to_do'].clone.each do |member|
346           if is_group(member)
347             if @groups[member]['members_to_do'].size == 0
348               group['keys'].concat @groups[member]['keys']
349               group['members_to_do'].delete(member)
350               had_progress = true
351             else
352               still_contains_groups = true
353             end
354           else
355             group['keys'].push @users[member]
356             group['members_to_do'].delete(member)
357             had_progress = true
358           end
359         end
360         all_expanded = false if still_contains_groups
361       end
362       break if all_expanded
363       unless had_progress
364         cyclic_groups = @groups.keys.reject{|name| @groups[name]['members_to_do'].size == 0}.join(", ")
365         STDERR.puts "Cyclic group memberships in #{cyclic_groups}?"
366         exit(1)
367       end
368     end
369   end
370
371   def expand_targets(targets)
372     fprs = []
373     ok = true
374     targets.each do |t|
375       unless check_exists(t, "access line", false)
376         ok = false
377         next
378       end
379       if is_group(t)
380         fprs.concat @groups[t]['keys']
381       else
382         fprs.push @users[t]
383       end
384     end
385     return ok, fprs.uniq
386   end
387
388   def get_users()
389     return @users
390   end
391 end
392
393 class EncryptedFile
394   attr_reader :accessible, :encrypted, :readable, :readers
395
396   def EncryptedFile.determine_readable(readers)
397     GnuPG.get_my_keys.each do |keyid|
398       return true if readers.include?(keyid)
399     end
400     return false
401   end
402
403   def EncryptedFile.list_readers(statustxt)
404     readers = []
405     statustxt.split("\n").each do |line|
406       m = /^\[GNUPG:\] ENC_TO ([0-9A-F]+)/.match line
407       next unless m
408       readers.push m[1]
409     end
410     return readers
411   end
412
413   def EncryptedFile.targets(text)
414     text.split("\n").each do |line|
415       if /^#/.match line
416         next
417       end
418       m = /^access: "?((?:(?:#{GROUP_PATTERN}|#{USER_PATTERN}),?\s*)+)"?/.match line
419       return [] unless m
420       return m[1].strip.split(/[\t ,]+/)
421     end
422   end
423
424
425   def initialize(filename, new=false)
426     @groupconfig = GroupConfig.new
427     @new = new
428     if @new
429       @readers = []
430     end
431
432     @filename = filename
433     unless FileTest.readable?(filename)
434       @accessible = false
435       return
436     end
437     @accessible = true
438     @encrypted_content = File.read(filename)
439     (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall(@encrypted_content, %w{--with-colons --no-options --no-default-keyring --secret-keyring=/dev/null --keyring=/dev/null})
440     @encrypted = !(statustxt =~ /\[GNUPG:\] NODATA/)
441     if @encrypted
442       @readers = EncryptedFile.list_readers(statustxt)
443       @readable = EncryptedFile.determine_readable(@readers)
444     end
445   end
446
447   def decrypt
448     (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(@encrypted_content, %w{--decrypt})
449     if !@new and exitstatus != 0
450       proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when decrypting #{@filename}.  Proceed?", false)
451       exit(0) unless proceed
452     elsif !@new and outtxt.length == 0
453       proceed = read_input("Warning: #{@filename} decrypted to an empty file.  Proceed?")
454       exit(0) unless proceed
455     end
456
457     return outtxt
458   end
459
460   def encrypt(content, recipients)
461     args = recipients.collect{ |r| "--recipient=#{r}"}
462     args.push "--trust-model=always"
463     args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
464     args.push "--armor"
465     args.push "--encrypt"
466     (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
467
468     invalid = []
469     statustxt.split("\n").each do |line|
470       m = /^\[GNUPG:\] INV_RECP \S+ ([0-9A-F]+)/.match line
471       next unless m
472       invalid.push m[1]
473     end
474     if invalid.size > 0
475       again = read_input("Warning: the following recipients are invalid: #{invalid.join(", ")}. Try again (or proceed)?")
476       return false if again
477     end
478     if outtxt.length == 0
479       tryagain = read_input("Error: #{@filename} encrypted to an empty file.  Edit again (or exit)?")
480       return false if tryagain
481       exit(0)
482     end
483     if exitstatus != 0
484       proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when encrypting #{@filename}. Said:\n#{stderrtxt}\n#{statustxt}\n\nProceed (or try again)?")
485       return false unless proceed
486     end
487
488     return true, outtxt
489   end
490
491
492   def determine_encryption_targets(content)
493     targets = EncryptedFile.targets(content)
494     if targets.size == 0
495       tryagain = read_input("Warning: Did not find targets to encrypt to in header.  Try again (or exit)?", true)
496       return false if tryagain
497       exit(0)
498     end
499
500     ok, expanded = @groupconfig.expand_targets(targets)
501     if (expanded.size == 0)
502       tryagain = read_input("Errors in access header.  Edit again (or exit)?", true)
503       return false if tryagain
504       exit(0)
505     elsif (not ok)
506       tryagain = read_input("Warnings in access header.  Edit again (or continue)?", true)
507       return false if tryagain
508     end
509
510     to_me = false
511     GnuPG.get_my_fprs.each do |fpr|
512       if expanded.include?(fpr)
513         to_me = true
514         break
515       end
516     end
517     unless to_me
518       tryagain = read_input("File is not being encrypted to you.  Edit again (or continue)?", true)
519       return false if tryagain
520     end
521
522     return true, expanded
523   end
524
525   def write_back(content, targets)
526     ok, encrypted = encrypt(content, targets)
527     return false unless ok
528
529     File.open(@filename,"w").write(encrypted)
530     return true
531   end
532 end
533
534 class Ls
535   def help(parser, code=0, io=STDOUT)
536     io.puts "Usage: #{$program_name} ls [<directory> ...]"
537     io.puts parser.summarize
538     io.puts "Lists the contents of the given directory/directories, or the current"
539     io.puts "directory if none is given.  For each file show whether it is PGP-encrypted"
540     io.puts "file, and if yes whether we can read it."
541     exit(code)
542   end
543
544   def ls_dir(dirname)
545     begin
546       dir = Dir.open(dirname)
547     rescue Exception => e
548       STDERR.puts e
549       return
550     end
551     puts "#{dirname}:"
552     Dir.chdir(dirname) do
553       unless FileTest.exists?(".users")
554         STDERR.puts "The .users file does not exists here.  This is not a password store, is it?"
555         exit(1)
556       end
557       dir.sort.each do |filename|
558         next if (filename =~ /^\./) and not (@all >= 3)
559         stat = File::Stat.new(filename)
560         if stat.symlink?
561           puts "(sym)      #{filename}" if (@all >= 2)
562         elsif stat.directory?
563           puts "(dir)      #{filename}" if (@all >= 2)
564         elsif !stat.file?
565           puts "(other)    #{filename}" if (@all >= 2)
566         else
567           f = EncryptedFile.new(filename)
568           if !f.accessible
569             puts "(!perm)    #{filename}"
570           elsif !f.encrypted
571             puts "(file)     #{filename}" if (@all >= 2)
572           elsif f.readable
573             puts "(ok)       #{filename}"
574           else
575             puts "(locked)   #{filename}" if (@all >= 1)
576           end
577         end
578       end
579     end
580   end
581
582   def initialize()
583     @all = 0
584     ARGV.options do |opts|
585       opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
586       opts.on_tail("-a", "--all" , "Show all files (use up to 3 times to show even more than all)") { @all = @all+1 }
587       opts.parse!
588     end
589
590     dirs = ARGV
591     dirs.push('.') unless dirs.size > 0
592     dirs.each { |dir| ls_dir(dir) }
593   end
594 end
595
596 class Ed
597   def help(parser, code=0, io=STDOUT)
598     io.puts "Usage: #{$program_name} ed <filename>"
599     io.puts parser.summarize
600     io.puts "Decrypts the file, spawns an editor, and encrypts it again"
601     exit(code)
602   end
603
604   def edit(filename)
605     encrypted_file = EncryptedFile.new(filename, @new)
606     if !@new and !encrypted_file.readable && !@force
607       STDERR.puts "#{filename} is probably not readable"
608       exit(1)
609     end
610
611     encrypted_to = GnuPG.get_fprs_from_keyids(encrypted_file.readers).sort
612
613     content = encrypted_file.decrypt
614     original_content = content
615     while true
616       oldsize = content.length
617       tempfile = Tempfile.open('pws')
618       tempfile.puts content
619       tempfile.flush
620       system($editor, tempfile.path)
621       status = $?
622       throw "Process has not exited!?" unless status.exited?
623       unless status.exitstatus == 0
624         proceed = read_input("Warning: Editor did not exit successfully (exit code #{status.exitstatus}.  Proceed?")
625         exit(0) unless proceed
626       end
627
628       # some editors do not write new content in place, but instead
629       # make a new file and more it in the old file's place.
630       begin
631         reopened = File.open(tempfile.path, "r+")
632       rescue Exception => e
633         STDERR.puts e
634         exit(1)
635       end
636       content = reopened.read
637
638       # zero the file, well, both of them.
639       newsize = content.length
640       clearsize = (newsize > oldsize) ? newsize : oldsize
641
642       [tempfile, reopened].each do |f|
643         f.seek(0, IO::SEEK_SET)
644         f.print "\0"*clearsize
645         f.fsync
646       end
647       reopened.close
648       tempfile.close(true)
649
650       if content.length == 0
651         proceed = read_input("Warning: Content is now empty.  Proceed?")
652         exit(0) unless proceed
653       end
654
655       ok, targets = encrypted_file.determine_encryption_targets(content)
656       next unless ok
657
658       if (original_content == content)
659         if (targets.sort == encrypted_to)
660           proceed = read_input("Nothing changed.  Re-encrypt anyway?", false)
661           exit(0) unless proceed
662         else
663           STDERR.puts("Info: Content not changed but re-encrypting anyway because the list of keys changed")
664         end
665       end
666
667       success = encrypted_file.write_back(content, targets)
668       break if success
669     end
670   end
671
672   def initialize()
673     ARGV.options do |opts|
674       opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
675       opts.on_tail("-n", "--new" , "Edit new file") { |new| @new=new }
676       opts.on_tail("-f", "--force" , "Spawn an editor even if the file is probably not readable") { |force| @force=force }
677       opts.parse!
678     end
679     help(ARGV.options, 1, STDERR) if ARGV.length != 1
680     filename = ARGV.shift
681
682     if @new
683       if FileTest.exists?(filename)
684         STDERR.puts "#{filename} does exist"
685         exit(1)
686       end
687     else
688       if !FileTest.exists?(filename)
689         STDERR.puts "#{filename} does not exist"
690         exit(1)
691       elsif !FileTest.file?(filename)
692         STDERR.puts "#{filename} is not a regular file"
693         exit(1)
694       elsif !FileTest.readable?(filename)
695         STDERR.puts "#{filename} is not accessible (unix perms)"
696         exit(1)
697       end
698     end
699
700     dirname = File.dirname(filename)
701     basename = File.basename(filename)
702     Dir.chdir(dirname) {
703       edit(basename)
704     }
705   end
706 end
707
708 class Get
709   def help(parser, code=0, io=STDOUT)
710     io.puts "Usage: #{$program_name} get <filename> <query>"
711     io.puts parser.summarize
712     io.puts "Decrypts the file, fetches a key and outputs it to stdout."
713     io.puts "The file must be in YAML format."
714     io.puts "query is a query, formatted like /host/users/root"
715     exit(code)
716   end
717
718   def get(filename, what)
719     encrypted_file = EncryptedFile.new(filename, @new)
720     if !encrypted_file.readable
721       STDERR.puts "#{filename} is probably not readable"
722       exit(1)
723     end
724
725     begin
726       yaml = YAML::load(encrypted_file.decrypt)
727     rescue Psych::SyntaxError, ArgumentError => e
728       STDERR.puts "Could not parse YAML: #{e.message}"
729       exit(1)
730     end
731
732     require 'pp'
733
734     a = what.split("/")[1..-1]
735     hit = yaml
736     if a.nil?
737       # q = /, so print top level keys
738       puts "Keys:"
739       hit.keys.each do |k|
740         puts "- #{k}"
741       end
742       return
743     end
744     a.each do |k|
745       hit = hit[k]
746     end
747     if hit.nil?
748       STDERR.puts("No such key or invalid lookup expression")
749     elsif hit.respond_to?(:keys)
750       puts "Keys:"
751       hit.keys.each do |k|
752         puts "- #{k}"
753       end
754     else
755         puts hit
756     end
757   end
758
759   def initialize()
760     ARGV.options do |opts|
761       opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
762       opts.parse!
763     end
764     help(ARGV.options, 1, STDERR) if ARGV.length != 2
765     filename = ARGV.shift
766     what = ARGV.shift
767
768     if !FileTest.exists?(filename)
769       STDERR.puts "#{filename} does not exist"
770       exit(1)
771     elsif !FileTest.file?(filename)
772       STDERR.puts "#{filename} is not a regular file"
773       exit(1)
774     elsif !FileTest.readable?(filename)
775       STDERR.puts "#{filename} is not accessible (unix perms)"
776       exit(1)
777     end
778
779     dirname = File.dirname(filename)
780     basename = File.basename(filename)
781     Dir.chdir(dirname) {
782       get(basename, what)
783     }
784   end
785 end
786
787 class KeyringUpdater
788   def help(parser, code=0, io=STDOUT)
789     io.puts "Usage: #{$program_name} update-keyring [<keyserver>]"
790     io.puts parser.summarize
791     io.puts "Updates the local .keyring file"
792     exit(code)
793   end
794
795   def initialize()
796     ARGV.options do |opts|
797       opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
798       opts.parse!
799     end
800     help(ARGV.options, 1, STDERR) if ARGV.length > 1
801     keyserver = ARGV.shift
802     keyserver = 'keys.gnupg.net' unless keyserver
803
804     groupconfig = GroupConfig.new
805     users = groupconfig.get_users()
806     args = %w{--with-colons --no-options --no-default-keyring --keyring=./.keyring}
807
808     system('touch', '.keyring')
809     users.each_pair() do |uid, keyid|
810       cmd = args.clone()
811       cmd << "--keyserver=#{keyserver}"
812       cmd << "--recv-keys"
813       cmd << keyid
814       puts "Fetching key for #{uid}"
815       (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', cmd)
816       unless (statustxt =~ /^\[GNUPG:\] IMPORT_OK /)
817         STDERR.puts "Warning: did not find IMPORT_OK token in status output"
818         STDERR.puts "gpg exited with exit code #{ecode})"
819         STDERR.puts "Command was gpg #{cmd.join(' ')}"
820         STDERR.puts "stdout was #{outtxt}"
821         STDERR.puts "stderr was #{stderrtxt}"
822         STDERR.puts "statustxt was #{statustxt}"
823       end
824
825       cmd = args.clone()
826       cmd << '--batch' << '--edit' << keyid << 'minimize' << 'save'
827       (outtxt, stderrtxt, statustxt, ecode) = GnuPG.gpgcall('', cmd)
828     end
829
830
831   end
832 end
833
834 def help(code=0, io=STDOUT)
835   io.puts "Usage: #{$program_name} ed"
836   io.puts "       #{$program_name} ls"
837   io.puts "       #{$program_name} update-keyring"
838   io.puts "       #{$program_name} help"
839   io.puts "Call #{$program_name} <command> --help for additional options/parameters"
840   exit(code)
841 end
842
843
844 def parse_command
845   case ARGV.shift
846     when 'ls' then Ls.new
847     when 'ed' then Ed.new
848     when 'get' then Get.new
849     when 'update-keyring' then KeyringUpdater.new
850     when 'help' then
851       case ARGV.length
852         when 0 then help
853         when 1 then
854           ARGV.push "--help"
855           parse_command
856         else help(1, STDERR)
857       end
858     else
859       help(1, STDERR)
860   end
861 end
862
863 parse_command
864
865 # vim:set shiftwidth=2:
866 # vim:set et:
867 # vim:set ts=2: