c87dc64fb3a416a0c7dc464f91212a793fc8e522
[elisp/gnus.git-] / contrib / gpg.el
1 ;;; gpg.el --- Interface to GNU Privacy Guard
2
3 ;; Copyright (C) 2000 RUS-CERT, University Of Stuttgart
4
5 ;; Author: Florian Weimer <Florian.Weimer@RUS.Uni-Stuttgart.DE>
6 ;; Maintainer: Florian Weimer <Florian.Weimer@RUS.Uni-Stuttgart.DE>
7 ;; Keywords: crypto
8 ;; Created: 2000-04-15
9
10 ;; This file is NOT (yet?) part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
30 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
31 ;;
32 ;; This code is not well-tested.  BE CAREFUL!
33 ;; 
34 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
35 ;; ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA ALPHA
36
37 ;; Implemented features which can be tested:
38 ;;
39 ;; * Customization for all flavors of PGP is possible.
40 ;; * The main operations (verify, decrypt, sign, encrypt, sign &
41 ;;   encrypt) are implemented.
42 ;; * Optionally, Gero Treuner's gpg-2comp script is supported, 
43 ;;   to generate data which is compatible with PGP 2.6.3.
44
45 ;; Customizing external programs 
46 ;; =============================
47
48 ;; The customization are very similar to those of others programs,
49 ;; only the C-ish "%" constructs have been replaced by more Lisp-like
50 ;; syntax.
51 ;;
52 ;; First, you have to adjust the default executable paths
53 ;; (`gpg-command-default-alist', customization group `gpg-options',
54 ;; "Controlling GnuPG invocation.").  After that, you should
55 ;; change the configuration options which control how specific
56 ;; command line flags are built (`gpg-command-flag-sign-with-key',
57 ;; (`gpg-command-flag-recipient').  The elements of these lists are
58 ;; concatenated without spaces, and a new argument is only started
59 ;; where indicated.  The `gpg-command-flag-recipient' list is special:
60 ;; it consists of two parts, the first one remains at the beginning
61 ;; of the argument, the second one is repeated for each recipient.
62 ;; Finally, `gpg-command-passphrase-env' has to be changed if there's
63 ;; no command line flag to force the external program to read the data
64 ;; from standard input before the message.
65 ;;
66 ;; In customization group `gpg-commands', "Controlling GnuPG
67 ;; invocation.", you have to supply the actual syntax for external
68 ;; program calls.  Each variable consists of a pair of a program
69 ;; specification (if a Lisp symbol is given here, it is translated
70 ;; via `gpg-command-default-alist') and a list of program arguments
71 ;; with placeholders.  Please read the documentation of each variable
72 ;; before making your adjustments and try to match the given
73 ;; requirements as closely as possible!
74 ;;
75 ;; The `gpg-commands-key' group, "GnuPG Key Management Commands.",
76 ;; specifies key management commands.  The syntax of these variables
77 ;; is like those in the `gpg-commands' group.  Note that the output
78 ;; format of some of these external programs has to match very close
79 ;; that of GnuPG.  Additional tools (Thomas Roessler's "pgpring.c")
80 ;; are available if your favorite implementation of OpenPGP cannot
81 ;; output the this format.
82
83 ;; Security considerations 
84 ;; =======================
85
86 ;; On a typical multiuser UNIX system, the memory image of the
87 ;; Emacs process is not locked, therefore it can be swapped to disk
88 ;; at any time.  As a result, the passphrase might show up in the
89 ;; swap space (even if you don't use the passphrase cache, i.e. if
90 ;; `gpg-passphrase-timeout' is 0).  If someone is able to run `gdb' or
91 ;; another debugger on your Emacs process, he might be able to recover
92 ;; the passphrase as well.  Unfortunately, nothing can be done in
93 ;; order to prevent this at the moment.
94 ;;
95 ;; BE CAREFUL: If you use the passphrase cache feature, the passphrase
96 ;; is stored in the variable `gpg-passphrase' -- and it is NOT
97 ;; encrypted in any way.  (This is a conceptual problem because the
98 ;; nature of the passphrase cache requires that Emacs is able to
99 ;; decrypt automatically, so only a very weak protection could be
100 ;; applied anyway.)
101 ;;
102 ;; In addition, if you use an unpatched Emacs 20 (and earlier
103 ;; versions), passwords show up in the output of the `view-lossage'
104 ;; function (bound to `C-h l' by default).
105
106 \f
107 ;;; Code:
108
109 (require 'timer)
110 (eval-when-compile (require 'cl))
111
112 (eval-and-compile 
113   (defalias 'gpg-point-at-eol
114     (if (fboundp 'point-at-eol)
115         'point-at-eol
116       'line-end-position)))
117
118 ;;;; Customization:
119
120 ;;; Customization: Groups:
121
122 (defgroup gpg nil
123   "GNU Privacy Guard interface."
124   :tag "GnuPG"
125   :group 'processes)
126
127 (defgroup gpg-options nil
128   "Controlling GnuPG invocation."
129   :tag "GnuPG Options"
130   :group 'gpg)
131
132 (defgroup gpg-commands nil
133   "Primary GnuPG Operations."
134   :tag "GnuPG Commands"
135   :group 'gpg)
136
137 (defgroup gpg-commands-key nil
138   "Commands for GnuPG key management."
139   :tag "GnuPG Key Commands"
140   :group 'gpg-commands)
141
142 ;;; Customization: Widgets:
143
144 (if (get 'alist 'widget-type)
145     (define-widget 'gpg-command-alist 'alist
146       "An association list for GnuPG command names."
147       :key-type '(symbol :tag   "Abbreviation")
148       :value-type '(string :tag "Program name")
149       :convert-widget 'widget-alist-convert-widget
150       :tag "Alist")
151     (define-widget 'gpg-command-alist 'repeat
152       "An association list for GnuPG command names."
153       :args '((cons :format "%v"
154                     (symbol :tag   "Abbreviation")
155                     (string :tag "Program name")))
156       :tag "Alist"))
157
158 (define-widget 'gpg-command-program 'choice
159   "Widget for entering the name of a program (mostly the GnuPG binary)."
160   :tag "Program"
161   :args '((const :tag "Default GnuPG program."
162                  :value gpg)
163           (const :tag "GnuPG compatibility wrapper."
164                  :value gpg-2comp)
165           (const :tag "Disabled"
166                  :value nil)
167           (string :tag "Custom program" :format "%v")))
168
169 (define-widget 'gpg-command-sign-options 'cons
170   "Widget for entering signing options."
171   :args '(gpg-command-program
172           (repeat 
173            :tag "Arguments"
174            (choice 
175             :format "%[Type%] %v"
176             (const :tag "Insert armor option here if necessary."
177                    :value armor)
178             (const :tag "Insert text mode option here if necessary."
179                    :value textmode)
180             (const :tag "Insert the sign with key option here if necessary."
181                    :value sign-with-key)
182             (string :format "%v")))))
183
184 (define-widget 'gpg-command-key-options 'cons
185   "Widget for entering key command options."
186   :args '(gpg-command-program
187           (repeat 
188            :tag "Arguments"
189            (choice 
190             :format "%[Type%] %v"
191             (const :tag "Insert key ID here." 
192                    :value key-id)
193             (string :format "%v")))))
194
195 ;;; Customization: Variables:
196
197 ;;; Customization: Variables: Paths and Flags:
198
199 (defcustom gpg-passphrase-timeout
200   0
201   "Timeout (in seconds) for the passphrase cache.
202 The passphrase cache is cleared after is hasn't been used for this
203 many seconds.  The values 0 means that the passphrase is not cached at
204 all."
205   :tag "Passphrase Timeout"
206   :type 'number
207   :group 'gpg-options)
208
209 (defcustom gpg-default-key-id
210   nil
211   "Default key/user ID used for signatures."
212   :tag "Default Key ID"
213   :type '(choice
214           (const :tag "Use GnuPG default." :value nil)
215           (string))
216   :group 'gpg-options)
217
218 (defcustom gpg-temp-directory 
219   (expand-file-name "~/tmp")
220   "Directory for temporary files.
221 If you are running Emacs 20, this directory must have mode 0700."
222   :tag "Temp directory"
223   :type 'string
224   :group 'gpg-options)
225
226 (defcustom gpg-command-default-alist 
227   '((gpg . "gpg")
228     (gpg-2comp . "gpg"))
229   "Default paths for some GnuPG-related programs.
230 Modify this variable if you have to change the paths to the
231 executables required by the GnuPG interface.  You can enter \"gpg-2comp\"
232 for `gpg-2comp' if you have obtained this script, in order to gain
233 PGP 2.6.x compatibility."
234   :tag "GnuPG programs"
235   :type 'gpg-command-alist
236   :group 'gpg-options)
237
238 (defcustom gpg-command-all-arglist
239   nil
240   "List of arguments to add to all GPG commands."
241   :tag "All command args"
242   :group 'gpg-options)
243
244 (defcustom gpg-command-flag-textmode "--textmode"
245   "The flag to indicate canonical text mode to GnuPG."
246   :tag "Text mode flag"
247   :type 'string
248   :group 'gpg-options)
249
250 (defcustom gpg-command-flag-armor "--armor"
251   "The flag to request ASCII-armoring output from GnuPG."
252   :tag "Armor flag"
253   :type 'string
254   :group 'gpg-options)
255
256 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
257   "String to include to specify the signing key ID.
258 The elements are concatenated (without spaces) to form a command line
259 option."
260   :tag "Sign with key flag"
261   :type '(repeat :tag "Argument parts"
262           (choice :format "%[Type%] %v"
263            (const :tag "Start next argument." :value next-argument)
264            (const :tag "Insert signing key ID here." :value sign-with-key)
265            (string)))
266   :group 'gpg-options)
267
268 (defcustom gpg-command-flag-recipient
269   '(nil . ("-r" next-argument recipient next-argument))
270   "Format of a recipient specification.
271 The elements are concatenated (without spaces) to form a command line
272 option.  The second part is repeated for each recipient."
273   :tag "Recipients Flag"
274   :type '(cons
275           (repeat :tag "Common prefix"
276            (choice :format "%[Type%] %v"
277             (const :tag "Start next argument." :value next-argument)
278             (string)))
279           (repeat :tag "For each recipient"
280            (choice :format "%[Type%] %v"
281             (const :tag "Start next argument." :value next-argument)
282             (const :tag "Insert recipient key ID here." :value recipient)
283             (string))))
284   :group 'gpg-options)
285
286 (defcustom gpg-command-passphrase-env
287   nil
288   "Environment variable to set when a passphrase is required, or nil.
289 If an operation is invoked which requires a passphrase, this
290 environment variable is set before calling the external program to
291 indicate that it should read the passphrase from standard input."
292   :tag "Passphrase environment"
293   :type '(choice
294           (const :tag "Disabled" :value nil)
295           (cons
296            (string :tag "Variable")
297            (string :tag "Value")))
298   :group 'gpg-options)
299
300 ;;; Customization: Variables: GnuPG Commands:
301
302 (defcustom gpg-command-verify
303   '(gpg . ("--status-fd" "1" "--batch" "--verbose" "--verify" signature-file message-file))
304   "Command to verify a detached signature.
305 The invoked program has to read the signed message and the signature
306 from the given files.  It should write human-readable information to
307 standard output and/or standard error.  The program shall not convert
308 charsets or line endings; the input data shall be treated as binary."
309   :tag "Verify Command"
310   :type '(cons 
311           gpg-command-program
312           (repeat 
313            :tag "Arguments"
314            (choice 
315             :format "%[Type%] %v"
316             (const :tag "Insert name of file containing the message here." 
317                    :value message-file)
318             (const :tag "Insert name of file containing the signature here."
319                    :value signature-file)
320             (string :format "%v"))))
321   :group 'gpg-commands)
322
323 (defcustom gpg-command-verify-cleartext
324   '(gpg . ("--status-fd" "1" "--batch" "--verbose" "--verify" message-file))
325   "Command to verify a message.
326 The invoked program has to read the signed message from the given
327 file.  It should write human-readable information to standard output
328 and/or standard error.  The program shall not convert charsets or line
329 endings; the input data shall be treated as binary."
330   :tag "Cleartext Verify Command"
331   :type '(cons 
332           gpg-command-program
333           (repeat 
334            :tag "Arguments"
335            (choice 
336             :format "%[Type%] %v"
337             (const :tag "Insert name of file containing the message here." 
338                    :value message-file)
339             (string :format "%v"))))
340   :group 'gpg-commands)
341
342 (defcustom gpg-command-decrypt
343   '(gpg . ("--decrypt" "--batch" "--passphrase-fd=0"))
344   "Command to decrypt a message.
345 The invoked program has to read the passphrase from standard
346 input, followed by the encrypted message.  It writes the decrypted
347 message to standard output, and human-readable diagnostic messages to
348 standard error."
349   :tag "Decrypt Command"
350   :type '(cons
351           gpg-command-program
352           (repeat
353            :tag "Arguments"
354            (choice 
355             :format "%[Type%] %v"
356             (const :tag "Insert name of file containing the message here." 
357                    :value message-file)
358             (string :format "%v"))))
359   :group 'gpg-commands)
360
361 (defcustom gpg-command-sign-cleartext
362   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
363                  armor textmode  "--clearsign"
364                  sign-with-key))
365   "Command to create a \"clearsign\" text file.  
366 The invoked program has to read the passphrase from standard input,
367 followed by the message to sign.  It should write the ASCII-amored
368 signed text message to standard output, and diagnostic messages to
369 standard error."
370   :tag "Clearsign Command"
371   :type 'gpg-command-sign-options
372   :group 'gpg-commands)
373
374 (defcustom gpg-command-sign-detached
375   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
376                  armor textmode "--detach-sign" 
377                  sign-with-key))
378   "Command to create a detached signature. 
379 The invoked program has to read the passphrase from standard input,
380 followed by the message to sign.  It should write the ASCII-amored
381 detached signature to standard output, and diagnostic messages to
382 standard error.  The program shall not convert charsets or line
383 endings; the input data shall be treated as binary."
384   :tag "Sign Detached Command"
385   :type 'gpg-command-sign-options
386   :group 'gpg-commands)
387
388 (defcustom gpg-command-sign-encrypt
389   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
390                  armor textmode  "--always-trust" sign-with-key recipients
391                   "--sign" "--encrypt" plaintext-file))
392   "Command to sign and encrypt a file.
393 The invoked program has to read the passphrase from standard input,
394 followed by the message to sign and encrypt if there is no
395 `plaintext-file' placeholder.  It should write the ASCII-amored
396 encrypted message to standard output, and diagnostic messages to
397 standard error."
398   :tag "Sign And Encrypt Command"
399   :type '(cons 
400           gpg-command-program
401           (repeat 
402            :tag "Arguments"
403            (choice 
404             :format "%[Type%] %v"
405             (const :tag "Insert the `sign with key' option here if necessary."
406                    :value sign-with-key)
407             (const :tag "Insert list of recipients here."
408                    :value recipients)
409             (const :tag "Insert here name of file with plaintext."
410                    :value plaintext-file)
411             (string :format "%v"))))
412   :group 'gpg-commands)
413
414 (defcustom gpg-command-encrypt
415   '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust" 
416                  "--encrypt" recipients plaintext-file))
417   "Command to encrypt a file.  
418 The invoked program has to read the message to encrypt from standard
419 input or from the plaintext file (if the `plaintext-file' placeholder
420 is present).  It should write the ASCII-amored encrypted message to
421 standard output, and diagnostic messages to standard error."
422   :type '(cons 
423           gpg-command-program
424           (repeat 
425            :tag "Arguments"
426            (choice 
427             :format "%[Type%] %v"
428             (const :tag "Insert list of recipients here."
429                    :value recipients)
430             (const :tag "Insert here name of file with plaintext."
431                    :value plaintext-file)
432             (string :format "%v"))))
433   :group 'gpg-commands)
434
435 ;;; Customization: Variables: Key Management Commands:
436
437 (defcustom gpg-command-key-import
438   '(gpg . ("--import" "--verbose" message-file))
439   "Command to import a public key from a file."
440   :tag "Import Command"
441   :type '(cons 
442           gpg-command-program
443           (repeat 
444            :tag "Arguments"
445            (choice 
446             :format "%[Type%] %v"
447             (const :tag "Insert name of file containing the key here." 
448                    :value message-file)
449             (string :format "%v"))))
450   :group 'gpg-commands-key)
451
452 (defcustom gpg-command-key-export
453   '(gpg . ("--no-verbose" "--armor" "--export" key-id))
454   "Command to export a public key from the key ring.
455 The key should be written to standard output using ASCII armor."
456   :tag "Export Command"
457   :type 'gpg-command-key-options
458   :group 'gpg-commands-key)
459
460 (defcustom gpg-command-key-verify
461   '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
462   "Command to verify a public key."
463   :tag "Verification Command"
464   :type 'gpg-command-key-options
465   :group 'gpg-commands-key)
466
467 (defcustom gpg-command-key-public-ring
468   '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
469   "Command to list the contents of the public key ring."
470   :tag "List Public Key Ring Command"
471   :type 'gpg-command-key-options
472   :group 'gpg-commands-key)
473
474 (defcustom gpg-command-key-secret-ring
475   '(gpg . ("--no-verbose" "--batch" "--with-colons" 
476            "--list-secret-keys" key-id))
477   "Command to list the contents of the secret key ring."
478   :tag "List Secret Key Ring Command"
479   :type 'gpg-command-key-options
480   :group 'gpg-commands-key)
481
482 (defcustom gpg-command-key-retrieve 
483   '(gpg . ("--batch" "--recv-keys" key-id))
484   "Command to retrieve public keys."
485   :tag "Retrieve Keys Command"
486   :type 'gpg-command-key-options
487   :group 'gpg-commands-key)
488
489 \f
490 ;;;; Helper functions for GnuPG invocation:
491
492 ;;; Build the GnuPG command line:
493
494 (defun gpg-build-argument (template substitutions &optional pass-start)
495   "Build command line argument(s) by substituting placeholders.
496 TEMPLATE is a list of strings and symbols.  The placeholder symbols in
497 it are replaced by SUBSTITUTIONS, the elements between
498 `next-argument' symbols are concatenated without spaces and are
499 returned in a list.
500
501 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
502 a string (which is inserted literally), a list of strings (which are
503 inserted as well), or nil, which means to insert nothing.
504
505 If PASS-START is t, `next-argument' is also inserted into the result,
506 and symbols without a proper substitution are retained in the output,
507 otherwise, an untranslated symbol results in an error.
508
509 This function does not handle empty arguments reliably."
510   (let ((current-arg "")
511         (arglist nil))
512     (while template
513       (let* ((templ (pop template))
514              (repl (assoc templ substitutions))
515              (new (if repl (cdr repl) templ)))
516         (cond
517          ((eq templ 'next-argument)
518           ;; If the current argument is not empty, start a new one.
519           (unless (equal current-arg "")
520             (setq arglist (nconc arglist 
521                                  (if pass-start
522                                      (list current-arg 'next-argument)
523                                    (list current-arg))))
524             (setq current-arg "")))
525          ((null new) nil)               ; Drop it.
526          ((and (not (stringp templ)) (null repl))
527           ;; Retain an untranslated symbol in the output if
528           ;; `pass-start' is true.
529           (unless pass-start
530             (error "No replacement for `%s'" templ))
531           (setq arglist (nconc arglist (list current-arg templ)))
532           (setq current-arg ""))
533          (t
534           (unless (listp new)
535             (setq new (list new)))
536           (setq current-arg (concat current-arg 
537                                     (apply 'concat new)))))))
538     (unless (equal current-arg "")
539       (setq arglist (nconc arglist (list current-arg))))
540     arglist))
541
542 (defun gpg-build-arg-list (template substitutions)
543   "Build command line by substituting placeholders.
544 TEMPLATE is a list of strings and symbols.  The placeholder symbols in
545 it are replaced by SUBSTITUTIONS.
546
547 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
548 string (which is inserted literally), a list of strings (which are
549 inserted as well), or nil, which means to insert nothing."
550   (let ((arglist (copy-sequence gpg-command-all-arglist)))
551     (while template
552       (let* ((templ (pop template))
553              (repl (assoc templ substitutions))
554              (new (if repl (cdr repl) templ)))
555         (cond
556          ((and (symbolp templ) (null repl))
557           (error "No replacement for `%s'" templ))
558          ((null new) nil)               ; Drop it.
559          (t
560           (unless (listp new)
561             (setq new (list new)))
562           (setq arglist (nconc arglist new))))))
563     arglist))
564
565 (defun gpg-build-flag-recipients-one (recipient)
566   "Build argument for one RECIPIENT."
567   (gpg-build-argument (cdr gpg-command-flag-recipient)
568                       `((recipient . ,recipient)) t))
569
570 (defun gpg-build-flag-recipients (recipients)
571   "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
572   (gpg-build-argument
573    (apply 'append (car gpg-command-flag-recipient)
574                   (mapcar 'gpg-build-flag-recipients-one
575                           recipients))
576    nil))
577
578 (defun gpg-read-recipients ()
579   "Query the user for several recipients."
580   (let ((go t) 
581         recipients r)
582     (while go
583       (setq r (read-string "Enter recipient ID [RET when no more]: "))
584       (if (equal r "")
585           (setq go nil)
586         (setq recipients (nconc recipients (list r)))))
587     recipients))
588     
589 (defun gpg-build-flag-sign-with-key (key)
590   "Build sign with key flag using `gpg-command-flag-sign-with-key'."
591   (let ((k (if key key 
592              (if gpg-default-key-id gpg-default-key-id
593                nil))))
594     (if k
595         (gpg-build-argument gpg-command-flag-sign-with-key
596                             (list (cons 'sign-with-key k)))
597       nil)))
598
599 (defmacro gpg-with-passphrase-env (&rest body)
600   "Adjust the process environment and evaluate BODY.
601 During the evaluation of the body forms, the process environment is
602 adjust according to `gpg-command-passphrase-env'."
603   (let ((env-value (make-symbol "env-value")))
604     `(let ((,env-value))
605        (unwind-protect
606            (progn
607              (when gpg-command-passphrase-env
608                (setq ,env-value (getenv (car gpg-command-passphrase-env)))
609                (setenv (car gpg-command-passphrase-env) 
610                        (cdr gpg-command-passphrase-env)))
611              ,@body)
612          (when gpg-command-passphrase-env
613            ;; This will clear the variable if it wasn't set before.
614            (setenv (car gpg-command-passphrase-env) ,env-value))))))
615 (put 'gpg-with-passphrase-env 'lisp-indent-function 0)
616 (put 'gpg-with-passphrase-env 'edebug-form-spec '(body))
617
618 ;;; Temporary files:
619
620 (defun gpg-make-temp-file ()
621   "Create a temporary file in a safe way"
622   (let ((name  ;; User may use "~/"
623          (expand-file-name "gnupg" gpg-temp-directory)))
624     (if (fboundp 'make-temp-file)
625         ;; If we've got make-temp-file, we are on the save side.
626         (make-temp-file name)
627       ;; make-temp-name doesn't create the file, and an ordinary
628       ;; write-file operation is prone to nasty symlink attacks if the
629       ;; temporary file resides in a world-writable directory.
630       (unless (or (memq system-type '(windows-nt cygwin32 win32 w32 mswindows))
631                   (eq (file-modes gpg-temp-directory) 448)) ; mode 0700
632         (error "Directory for temporary files (%s) must have mode 0700" gpg-temp-directory))
633       (setq name (make-temp-name name))
634       (let ((mode (default-file-modes)))
635         (unwind-protect
636             (progn
637               (set-default-file-modes 384) ; mode 0600
638               (with-temp-file name))
639           (set-default-file-modes mode)))
640       name)))
641
642 (defvar gpg-temp-files nil
643   "List of temporary files used by the GnuPG interface.
644 Do not set this variable.  Call `gpg-with-temp-files' if you need
645 temporary files.")
646
647 (defun gpg-with-temp-files-create (count)
648   "Do not call this function.  Used internally by `gpg-with-temp-files'."
649   (while (> count 0)
650     (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
651     (setq count (1- count))))
652
653 (defun gpg-with-temp-files-delete ()
654   "Do not call this function.  Used internally by `gpg-with-temp-files'."
655   (while gpg-temp-files
656     (let ((file (pop gpg-temp-files)))
657       (condition-case nil
658           (delete-file file)
659         (error nil)))))
660
661 (defmacro gpg-with-temp-files (count &rest body)
662   "Create COUNT temporary files, USE them, and delete them.
663 The function USE is called with the names of all temporary files as
664 arguments."
665   `(let ((gpg-temp-files))
666       (unwind-protect
667           (progn
668             ;; Create the temporary files.
669             (gpg-with-temp-files-create ,count)
670             ,@body)
671         (gpg-with-temp-files-delete))))
672 (put 'gpg-with-temp-files 'lisp-indent-function 1)
673 (put 'gpg-with-temp-files 'edebug-form-spec '(body))
674
675 ;;;  Making subprocesses:
676
677 (defun gpg-exec-path (option)
678   "Return the program name for OPTION.
679 OPTION is of the form (PROGRAM . ARGLIST).  This functions returns
680 PROGRAM, but takes default values into account."
681   (let* ((prg (car option))
682          (path (assq prg gpg-command-default-alist)))
683     (cond
684      (path (if (null (cdr path))
685                (error "Command `%s' is not available" prg)
686              (cdr path)))
687      ((null prg) (error "Command is disabled"))
688      (t prg))))
689
690 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
691   "Invoke external program CMD with ARGS on buffer STDIN.
692 Standard output is insert before point in STDOUT, standard error in
693 STDERR.  If PASSPHRASE is given, send it before STDIN.  PASSPHRASE
694 should not end with a line feed (\"\\n\").
695
696 If `stdin-file' is present in ARGS, it is replaced by the name of a
697 temporary file.  Before invoking CMD, the contents of STDIN is written
698 to this file."
699   (gpg-with-temp-files 2
700    (let* ((coding-system-for-read 'no-conversion)
701           (coding-system-for-write 'no-conversion)
702           (have-stdin-file (memq 'stdin-file args))
703           (stdin-file (nth 0 gpg-temp-files))
704           (stderr-file (nth 1 gpg-temp-files))
705           (cpr-args `(,cmd 
706                       nil               ; don't delete
707                       (,stdout ,stderr-file)
708                       nil               ; don't display
709                       ;; Replace `stdin-file'.
710                       ,@(gpg-build-arg-list 
711                           args (list (cons 'stdin-file stdin-file)))))
712           res)
713      (when have-stdin-file
714        (with-temp-file stdin-file
715          (buffer-disable-undo)
716          (insert-buffer-substring stdin)))
717      (setq res
718            (if passphrase
719                (with-temp-buffer
720                  (buffer-disable-undo)
721                  (insert passphrase "\n")
722                  (unless have-stdin-file
723                    (apply 'insert-buffer-substring 
724                           (if (listp stdin) stdin (list stdin))))
725                  (apply 'call-process-region (point-min) (point-max) cpr-args)
726                  ;; Wipe out passphrase.
727                  (goto-char (point-min))
728                  (translate-region (point) (gpg-point-at-eol)
729                                    (make-string 256 ? )))
730              (if (listp stdin)
731                  (with-current-buffer (car stdin)
732                    (apply 'call-process-region 
733                           (cadr stdin)
734                           (if have-stdin-file (cadr stdin) (caddr stdin))
735                           cpr-args))
736                (with-current-buffer stdin
737                  (apply 'call-process-region 
738                         (point-min) 
739                         (if have-stdin-file (point-min) (point-max))
740                         cpr-args)))))
741      (with-current-buffer stderr
742        (insert-file-contents-literally stderr-file))
743      (if (or (stringp res) (> res 0))
744          ;; Signal or abnormal exit.
745          (with-current-buffer stderr
746            (goto-char (point-max))
747            (insert (format "\nCommand exit status: %s\n" res))
748            nil)
749        t))))
750
751 (defvar gpg-result-buffer nil
752   "The result of a GnuPG operation is stored in this buffer.
753 Never set this variable directly, use `gpg-show-result' instead.")
754
755 (defun gpg-show-result-buffer (always-show result)
756   "Called by `gpg-show-results' to actually show the buffer."
757   (with-current-buffer gpg-result-buffer
758     ;; Only proceed if the buffer is non-empty.
759     (when (and (/= (point-min) (point-max))
760                (or always-show (not result)))
761       (save-window-excursion
762         (display-buffer (current-buffer))
763         (unless (y-or-n-p "Continue? ")
764           (error "GnuPG operation aborted"))))))
765
766 (defmacro gpg-show-result (always-show &rest body)
767   "Show GnuPG result to user for confirmation.
768 This macro binds `gpg-result-buffer' to a temporary buffer and
769 evaluates BODY, like `progn'.  If BODY evaluates to `nil' (or
770 `always-show' is not nil), the user is asked for confirmation."
771   `(let ((gpg-result-buffer (get-buffer-create 
772                          (generate-new-buffer-name "*GnuPG Output*"))))
773      (unwind-protect
774          (gpg-show-result-buffer ,always-show (progn ,@body))
775        (kill-buffer gpg-result-buffer))))
776 (put 'gpg-show-result 'lisp-indent-function 1)
777 (put 'gpg-show-result 'edebug-form-spec '(body))
778
779 ;;; Passphrase handling:
780
781 (defvar gpg-passphrase-timer
782   (timer-create)
783   "This timer will clear the passphrase cache periodically.")
784
785 (defvar gpg-passphrase
786   nil
787   "The (unencrypted) passphrase cache.")
788
789 (defun gpg-passphrase-clear-string (str)
790   "Erases STR by overwriting all characters."
791   (let ((pos 0)
792         (len (length str)))
793     (while (< pos len)
794       (aset str pos ? )
795       (incf pos))))
796
797 ;;;###autoload
798 (defun gpg-passphrase-forget ()
799   "Forget stored passphrase."
800   (interactive)
801   (cancel-timer gpg-passphrase-timer)
802   (setq gpg-passphrase-timer nil)
803   (gpg-passphrase-clear-string gpg-passphrase)
804   (setq gpg-passphrase nil))
805
806 (defun gpg-passphrase-store (passphrase)
807   "Store PASSPHRASE in cache.
808 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
809   (unless (equal gpg-passphrase-timeout 0)
810     (if (null gpg-passphrase-timer)
811         (setq gpg-passphrase-timer (timer-create)))
812     (timer-set-time gpg-passphrase-timer 
813                     (timer-relative-time (current-time) 
814                                          gpg-passphrase-timeout))
815     (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
816     (unless (and (fboundp 'itimer-live-p)
817                  (itimer-live-p gpg-passphrase-timer))
818       (timer-activate gpg-passphrase-timer))
819     (setq gpg-passphrase passphrase))
820   passphrase)
821
822 (defun gpg-passphrase-read ()
823   "Read a passphrase and remember it for some time."
824   (interactive)
825   (if gpg-passphrase
826       ;; This reinitializes the timer.
827       (gpg-passphrase-store gpg-passphrase)
828     (let ((pp (read-passwd "Enter passphrase: ")))
829       (gpg-passphrase-store pp))))
830
831 \f
832 ;;;; Main operations:
833
834 ;;;###autoload
835 (defun gpg-verify (message signature result)
836   "Verify buffer MESSAGE against detached SIGNATURE buffer.
837 Returns t if everything worked out well, nil otherwise.  Consult
838 buffer RESULT for details."
839   (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
840   (gpg-with-temp-files 2
841     (let* ((sig-file    (nth 0 gpg-temp-files))
842            (msg-file    (nth 1 gpg-temp-files))
843            (cmd (gpg-exec-path gpg-command-verify))
844            (args (gpg-build-arg-list (cdr gpg-command-verify)
845                                      `((signature-file . ,sig-file)
846                                        (message-file . ,msg-file))))
847            res)
848       (with-temp-file sig-file 
849         (buffer-disable-undo)
850         (apply 'insert-buffer-substring (if (listp signature)
851                                             signature
852                                           (list signature))))
853       (with-temp-file msg-file 
854         (buffer-disable-undo)
855         (apply 'insert-buffer-substring (if (listp message)
856                                             message
857                                           (list message))))
858       (setq res (apply 'call-process-region 
859                        (point-min) (point-min) ; no data
860                        cmd
861                        nil              ; don't delete
862                        result
863                        nil              ; don't display
864                        args))
865       (if (or (stringp res) (> res 0))
866           ;; Signal or abnormal exit.
867           (with-current-buffer result
868             (insert (format "\nCommand exit status: %s\n" res))
869             nil)
870         t))))
871
872 ;;;###autoload
873 (defun gpg-verify-cleartext (message result)
874   "Verify message in buffer MESSAGE.
875 Returns t if everything worked out well, nil otherwise.  Consult
876 buffer RESULT for details.
877
878 NOTE: Use of this function is deprecated."
879   (interactive "bBuffer containing message: \nbBuffor for result: ")
880   (gpg-with-temp-files 1
881     (let* ((msg-file    (nth 0 gpg-temp-files))
882            (cmd (gpg-exec-path gpg-command-verify-cleartext))
883            (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext)
884                                      `((message-file . ,msg-file))))
885            res)
886       (with-temp-file msg-file 
887         (buffer-disable-undo)
888         (apply 'insert-buffer-substring (if (listp message)
889                                             message
890                                           (list message))))
891       (setq res (apply 'call-process-region
892                        (point-min) (point-min) ; no data
893                        cmd
894                        nil              ; don't delete
895                        result
896                        nil              ; don't display
897                        args))
898       (if (or (stringp res) (> res 0))
899           ;; Signal or abnormal exit.
900           (with-current-buffer result
901             (insert (format "\nCommand exit status: %s\n" res))
902             nil)
903         t))))
904
905 ;;;###autoload
906 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
907   "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
908 Returns t if everything worked out well, nil otherwise.  Consult
909 buffer RESULT for details.  Reads a missing PASSPHRASE using
910 `gpg-passphrase-read'."
911   (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
912   (gpg-call-process (gpg-exec-path gpg-command-decrypt)
913                     (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
914                     ciphertext plaintext result
915                     (if passphrase passphrase (gpg-passphrase-read)))
916   (when passphrase
917     (gpg-passphrase-clear-string passphrase)))
918
919 ;;;###autoload
920 (defun gpg-sign-cleartext
921   (plaintext signed-text result &optional passphrase sign-with-key)
922   "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
923 SIGNED-TEXT.
924 Reads a missing PASSPHRASE using `gpg-passphrase-read'.  Uses key ID
925 SIGN-WITH-KEY if given, otherwise the default key ID.  Returns t if
926 everything worked out well, nil otherwise.  Consult buffer RESULT for
927 details.
928
929 NOTE: Use of this function is deprecated."
930   (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
931   (let ((subst (list (cons 'sign-with-key 
932                            (gpg-build-flag-sign-with-key sign-with-key))
933                      (cons 'armor gpg-command-flag-armor)
934                      (cons 'textmode gpg-command-flag-textmode))))
935     (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
936                       (gpg-build-arg-list (cdr gpg-command-sign-cleartext) 
937                                           subst)
938                       plaintext signed-text result
939                       (if passphrase passphrase (gpg-passphrase-read))))
940   (when passphrase
941     (gpg-passphrase-clear-string passphrase)))
942
943 ;;;###autoload
944 (defun gpg-sign-detached
945   (plaintext signature result &optional passphrase sign-with-key
946    armor textmode)
947   "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
948 Reads a missing PASSPHRASE using `gpg-passphrase-read'.  Uses key ID
949 SIGN-WITH-KEY if given, otherwise the default key ID.  Returns t if
950 everything worked out well, nil otherwise.  Consult buffer RESULT for
951 details.  ARMOR the result and activate canonical TEXTMODE if
952 requested."
953   (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
954   (let ((subst (list (cons 'sign-with-key 
955                            (gpg-build-flag-sign-with-key sign-with-key))
956                      (cons 'armor (if armor gpg-command-flag-armor))
957                      (cons 'textmode (if armor gpg-command-flag-textmode)))))
958     (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
959                       (gpg-build-arg-list (cdr gpg-command-sign-detached)
960                                           subst)
961                       plaintext signature result
962                       (if passphrase passphrase (gpg-passphrase-read))))
963   (when passphrase
964     (gpg-passphrase-clear-string passphrase)))
965
966
967 ;;;###autoload
968 (defun gpg-sign-encrypt
969   (plaintext ciphertext result recipients &optional passphrase sign-with-key
970    armor textmode)
971   "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
972 RECIPIENTS is a list of key IDs used for encryption.  This function
973 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
974 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
975 ID.  Returns t if everything worked out well, nil otherwise.  Consult
976 buffer RESULT for details.  ARMOR the result and activate canonical
977 TEXTMODE if requested."
978   (interactive (list
979                 (read-buffer "Buffer containing plaintext: " nil t)
980                 (read-buffer "Buffer for ciphertext: " nil t)
981                 (read-buffer "Buffer for status informationt: " nil t)
982                 (gpg-read-recipients)))
983     (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key 
984                                       sign-with-key))
985                    (plaintext-file . stdin-file)
986                    (recipients . ,(gpg-build-flag-recipients recipients))
987                    (armor ,(if armor gpg-command-flag-armor))
988                    (textmode ,(if armor gpg-command-flag-textmode)))))
989       (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
990                         (gpg-build-arg-list (cdr gpg-command-sign-encrypt) 
991                                             subst)
992                         plaintext ciphertext result
993                         (if passphrase passphrase (gpg-passphrase-read))))
994   (when passphrase
995     (gpg-passphrase-clear-string passphrase)))
996
997
998 ;;;###autoload
999 (defun gpg-encrypt
1000   (plaintext ciphertext result recipients &optional passphrase armor textmode)
1001   "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
1002 RECIPIENTS is a list of key IDs used for encryption.  Returns t if
1003 everything worked out well, nil otherwise.  Consult buffer RESULT for
1004 details.  ARMOR the result and activate canonical
1005 TEXTMODE if requested."
1006   (interactive (list
1007                 (read-buffer "Buffer containing plaintext: " nil t)
1008                 (read-buffer "Buffer for ciphertext: " nil t)
1009                 (read-buffer "Buffer for status informationt: " nil t)
1010                 (gpg-read-recipients)))
1011   (let ((subst `((plaintext-file . stdin-file)
1012                  (recipients . ,(gpg-build-flag-recipients recipients))
1013                  (armor ,(if armor gpg-command-flag-armor))
1014                  (textmode ,(if armor gpg-command-flag-textmode)))))
1015     (gpg-call-process (gpg-exec-path gpg-command-encrypt)
1016                       (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
1017                       plaintext ciphertext result nil))
1018   (when passphrase
1019     (gpg-passphrase-clear-string passphrase)))
1020
1021 \f
1022 ;;;; Key management
1023
1024 ;;; ADT: OpenPGP Key
1025
1026 (defun gpg-key-make (user-id key-id unique-id length algorithm
1027                      creation-date expire-date validity trust)
1028   "Create a new key object (for internal use only)."
1029   (vector 
1030         ;;  0   1      2         3      4        
1031         user-id key-id unique-id length algorithm
1032         ;; 5          6           7        8
1033         creation-date expire-date validity trust))
1034
1035
1036 (defun gpg-key-p (key)
1037   "Return t if KEY is a key specification."
1038   (and (arrayp key) (equal (length key) 9) key))
1039
1040 (defmacro gpg-key-primary-user-id (key)
1041   "The primary user ID for KEY (human-readable).
1042 DO NOT USE this ID for selecting recipients.  It is probably not
1043 unique."
1044   (list 'car (list 'aref key 0)))
1045
1046 (defmacro gpg-key-user-ids (key)
1047   "A list of additional user IDs for KEY (human-readable).
1048 DO NOT USE these IDs for selecting recipients.  They are probably not
1049 unique."
1050   (list 'cdr (list 'aref key 0)))
1051
1052 (defmacro gpg-key-id (key)
1053   "The key ID of KEY.
1054 DO NOT USE this ID for selecting recipients.  It is not guaranteed to
1055 be unique."
1056   (list 'aref key 1))
1057
1058 (defun gpg-short-key-id (key)
1059   "The short key ID of KEY."
1060   (let* ((id (gpg-key-id key))
1061          (len (length id)))
1062     (if (> len 8)
1063         (substring id (- len 8))
1064       id)))
1065
1066 (defmacro gpg-key-unique-id (key)
1067   "A non-standard ID of KEY which is only valid locally.
1068 This ID can be used to specify recipients in a safe manner.  Note,
1069 even this ID might not be unique unless GnuPG is used."
1070   (list 'aref key 2))
1071
1072 (defmacro gpg-key-unique-id-list (key-list)
1073   "Like `gpg-key-unique-id', but operate on a list."
1074   `(mapcar (lambda (key) (gpg-key-unique-id key)) 
1075            ,key-list))
1076
1077 (defmacro gpg-key-length (key)
1078   "Returns the key length."
1079   (list 'aref key 3))
1080
1081 (defmacro gpg-key-algorithm (key)
1082   "The encryption algorithm used by KEY.
1083 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1084 `elgamal-encrypt', `dsa'."
1085   (list 'aref key 4))
1086
1087 (defmacro gpg-key-creation-date (key)
1088   "A string with the creation date of KEY in ISO format."
1089   (list 'aref key 5))
1090
1091 (defmacro gpg-key-expire-date (key)
1092   "A string with the expiration date of KEY in ISO format."
1093   (list 'aref key 6))
1094
1095 (defmacro gpg-key-validity (key)
1096   "The calculated validity of KEY.  
1097 One of the symbols `not-known', `disabled', `revoked', `expired',
1098 `undefined', `trust-none', `trust-marginal', `trust-full',
1099 `trust-ultimate' (see the GnuPG documentation for details)."
1100  (list 'aref key 7))
1101
1102 (defmacro gpg-key-trust (key)
1103   "The assigned trust for KEY.  
1104 One of the symbols `not-known', `undefined', `trust-none',
1105 `trust-marginal', `trust-full' (see the GnuPG
1106 documentation for details)."
1107   (list 'aref key 8))
1108
1109 (defun gpg-key-lessp (a b)
1110   "Returns t if primary user ID of A is less than B."
1111   (string-lessp (gpg-key-primary-user-id a) (gpg-key-primary-user-id b) ))
1112
1113 ;;; Accessing the key database:
1114
1115 ;; Internal functions:
1116
1117 (defmacro gpg-key-list-keys-skip-field ()
1118   '(search-forward ":" eol 'move))
1119
1120 (defmacro gpg-key-list-keys-get-field ()
1121   '(buffer-substring (point) (if (gpg-key-list-keys-skip-field) 
1122                                  (1- (point)) 
1123                                eol)))
1124 (defmacro gpg-key-list-keys-string-field ()
1125   '(gpg-key-list-keys-get-field))
1126
1127 (defmacro gpg-key-list-keys-read-field ()
1128   (let ((field (make-symbol "field")))
1129     `(let ((,field (gpg-key-list-keys-get-field)))
1130        (if (equal (length ,field) 0)
1131            nil
1132          (read ,field)))))
1133
1134 (defun gpg-key-list-keys-parse-line ()
1135   "Parse the line in the current buffer and return a vector of fields."
1136   (let* ((eol (gpg-point-at-eol))
1137          (v (if (eolp)
1138                 nil
1139               (vector
1140                (gpg-key-list-keys-read-field) ; type
1141                (gpg-key-list-keys-get-field) ; trust
1142                (gpg-key-list-keys-read-field) ; key length
1143                (gpg-key-list-keys-read-field) ; algorithm
1144                (gpg-key-list-keys-get-field) ; key ID
1145                (gpg-key-list-keys-get-field) ; creation data
1146                (gpg-key-list-keys-get-field) ; expire
1147                (gpg-key-list-keys-get-field) ; unique (local) ID
1148                (gpg-key-list-keys-get-field) ; ownertrust
1149                (gpg-key-list-keys-string-field) ; user ID
1150                ))))
1151     (if (eolp)
1152         (when v
1153           (forward-char 1))
1154       (error "Too many fields in GnuPG key database"))
1155     v))
1156
1157 (defconst gpg-pubkey-algo-alist
1158   '((1 . rsa)
1159     (2 . rsa-encrypt-only)
1160     (3 . rsa-sign-only)
1161     (16 . elgamal-encrypt-only)
1162     (17 . dsa)
1163     (20 . elgamal))
1164   "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1165
1166 (defconst gpg-trust-alist
1167   '((?- . not-known)
1168     (?o . not-known)
1169     (?d . disabled)
1170     (?r . revoked)
1171     (?e . expired)
1172     (?q . trust-undefined)
1173     (?n . trust-none)
1174     (?m . trust-marginal)
1175     (?f . trust-full)
1176     (?u . trust-ultimate))
1177   "Alist mapping GnuPG trust value short forms to long symbols.")
1178
1179 (defconst gpg-unabbrev-trust-alist
1180   '(("TRUST_UNDEFINED" . trust-undefined)
1181     ("TRUST_NEVER"     . trust-none)
1182     ("TRUST_MARGINAL"  . trust-marginal)
1183     ("TRUST_FULLY"     . trust-full)
1184     ("TRUST_ULTIMATE"  . trust-ultimate))
1185   "Alist mapping capitalized GnuPG trust values to long symbols.")
1186
1187 (defmacro gpg-key-list-keys-in-buffer-store ()
1188   '(when primary-user-id
1189      (sort user-id 'string-lessp)
1190      (push (gpg-key-make (cons primary-user-id  user-id)
1191                          key-id unique-id key-length
1192                          algorithm creation-date 
1193                          expire-date validity trust)
1194            key-list)))
1195
1196 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1197   "Return a list of keys for BUFFER.
1198 If BUFFER is omitted, use current buffer."
1199   (with-current-buffer (if buffer buffer (current-buffer))
1200     (goto-char (point-min))
1201     ;; Skip key ring filename written by GnuPG.
1202     (search-forward "\n---------------------------\n" nil t)
1203     ;; Loop over all lines in buffer and analyze them.
1204     (let (primary-user-id user-id key-id unique-id ; current key components
1205           key-length algorithm creation-date expire-date validity trust
1206           line                          ; fields in current line
1207           key-list)                     ; keys gather so far
1208     
1209       (while (setq line (gpg-key-list-keys-parse-line))
1210         (cond
1211          ;; Public or secret key.
1212          ((memq (aref line 0) '(pub sec))
1213           ;; Store previous key, if any.
1214           (gpg-key-list-keys-in-buffer-store)
1215           ;; Record field values.
1216           (setq primary-user-id (aref line 9))
1217           (setq user-id nil)
1218           (setq key-id (aref line 4)) 
1219           ;; We use the key ID if no unique ID is available.
1220           (setq unique-id (if (> (length (aref line 7)) 0)
1221                               (concat "#" (aref line 7))
1222                             (concat "0x" key-id)))
1223           (setq key-length (aref line 2))
1224           (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1225           (if algorithm
1226               (setq algorithm (cdr algorithm))
1227             (error "Unknown algorithm %s" (aref line 3)))
1228           (setq creation-date (if (> (length (aref line 5)) 0)
1229                                   (aref line 5)))
1230           (setq expire-date (if (> (length (aref line 6)) 0)
1231                                 (aref line 6)))
1232           (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1233           (if validity
1234               (setq validity (cdr validity))
1235             (error "Unknown validity specification %S" (aref line 1)))
1236           (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1237           (if trust
1238               (setq trust (cdr trust))
1239             (error "Unknown trust specification %S" (aref line 8))))
1240         
1241          ;; Additional user ID
1242          ((eq 'uid (aref line 0))
1243           (setq user-id (cons (aref line 9) user-id)))
1244          
1245          ;; Subkeys are ignored for now.
1246          ((memq (aref line 0) '(sub ssb))
1247           t)
1248          (t (error "Unknown record type %S" (aref line 0)))))
1249
1250       ;; Store the key retrieved last.
1251       (gpg-key-list-keys-in-buffer-store)
1252       ;; Sort the keys according to the primary user ID.
1253       (sort key-list 'gpg-key-lessp))))
1254
1255 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1256   "Insert the output of COMMAND before point in current buffer."
1257   (let* ((cmd (gpg-exec-path command))
1258          (key (if (equal keyspec "") nil keyspec))
1259          (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1260          exit-status)
1261     (setq exit-status 
1262           (apply 'call-process-region 
1263                  (point-min) (point-min) ; no data
1264                  cmd
1265                  nil                    ; don't delete
1266                  (if stderr t '(t nil))
1267                  nil                    ; don't display
1268                  args))
1269     (unless (or ignore-error (equal exit-status 0))
1270       (error "GnuPG command exited unsuccessfully"))))
1271   
1272   
1273 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1274   "Return a list of keys matching KEYSPEC.
1275 COMMAND is used to obtain the key list.  The usual substring search
1276 for keys is performed."
1277   (with-temp-buffer 
1278     (buffer-disable-undo)
1279     (gpg-key-list-keyspec command keyspec)
1280     (gpg-key-list-keys-in-buffer)))
1281
1282 ;;;###autoload
1283 (defun gpg-key-list-keys (&optional keyspec)
1284   "A list of public keys matching KEYSPEC.
1285 The usual substring search for keys is performed."
1286   (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1287
1288 ;;;###autoload
1289 (defun gpg-key-list-secret-keys (&optional keyspec)
1290   "A list of secret keys matching KEYSPEC.
1291 The usual substring search for keys is performed."
1292   (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1293
1294 ;;;###autoload
1295 (defun gpg-key-insert-public-key (key)
1296   "Inserts the public key(s) matching KEYSPEC.
1297 The ASCII-armored key is inserted before point into current buffer."
1298   (gpg-key-list-keyspec gpg-command-key-export key))
1299
1300 ;;;###autoload
1301 (defun gpg-key-insert-information (key)
1302   "Insert human-readable information (including fingerprint) on KEY.
1303 Insertion takes place in current buffer before point."
1304   (gpg-key-list-keyspec gpg-command-key-verify key))
1305
1306 ;;;###autoload
1307 (defun gpg-key-retrieve (key)
1308   "Fetch KEY from default key server.
1309 KEY is a key ID or a list of key IDs.  Status information about this
1310 operation is inserted into the current buffer before point."
1311   (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1312
1313 ;;;###autoload
1314 (defun gpg-key-add-to-ring (key result)
1315   "Adds key in buffer KEY to the GnuPG key ring.
1316 Human-readable information on the RESULT is stored in buffer RESULT
1317 before point.")
1318
1319 (provide 'gpg)
1320
1321 ;;; gpg.el ends here