Synch with Gnus.
[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 ;; * Gero Treuner's gpg-2comp script is supported, and data which is is
43 ;;   compatible with PGP 2.6.3 is generated.
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 
111   (require 'cl))
112
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-2comp"))
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\"
232 for `gpg-2comp' if you don't have this script, but you'll lose PGP
233 2.6.x compatibility."
234   :tag "GnuPG programs"
235   :type 'gpg-command-alist
236   :group 'gpg-options)
237
238 (defcustom gpg-command-flag-textmode "--textmode"
239   "The flag to indicate canonical text mode to GnuPG."
240   :tag "Text mode flag"
241   :type 'string
242   :group 'gpg-options)
243
244 (defcustom gpg-command-flag-armor "--armor"
245   "The flag to request ASCII-armoring output from GnuPG."
246   :tag "Armor flag"
247   :type 'string
248   :group 'gpg-options)
249
250 (defcustom gpg-command-flag-sign-with-key '("--local-user=" sign-with-key)
251   "String to include to specify the signing key ID.
252 The elements are concatenated (without spaces) to form a command line
253 option."
254   :tag "Sign with key flag"
255   :type '(repeat :tag "Argument parts"
256           (choice :format "%[Type%] %v"
257            (const :tag "Start next argument." :value next-argument)
258            (const :tag "Insert signing key ID here." :value sign-with-key)
259            (string)))
260   :group 'gpg-options)
261
262 (defcustom gpg-command-flag-recipient
263   '(nil . ("-r" next-argument recipient next-argument))
264   "Format of a recipient specification.
265 The elements are concatenated (without spaces) to form a command line
266 option.  The second part is repeated for each recipient."
267   :tag "Recipients Flag"
268   :type '(cons
269           (repeat :tag "Common prefix"
270            (choice :format "%[Type%] %v"
271             (const :tag "Start next argument." :value next-argument)
272             (string)))
273           (repeat :tag "For each recipient"
274            (choice :format "%[Type%] %v"
275             (const :tag "Start next argument." :value next-argument)
276             (const :tag "Insert recipient key ID here." :value recipient)
277             (string))))
278   :group 'gpg-options)
279
280 (defcustom gpg-command-passphrase-env
281   nil
282   "Environment variable to set when a passphrase is required, or nil.
283 If an operation is invoked which requires a passphrase, this
284 environment variable is set before calling the external program to
285 indicate that it should read the passphrase from standard input."
286   :tag "Passphrase environment"
287   :type '(choice
288           (const :tag "Disabled" :value nil)
289           (cons
290            (string :tag "Variable")
291            (string :tag "Value")))
292   :group 'gpg-options)
293
294 ;;; Customization: Variables: GnuPG Commands:
295
296 (defcustom gpg-command-verify
297   '(gpg . ("--batch" "--verbose" "--verify" signature-file message-file))
298   "Command to verify a detached signature.
299 The invoked program has to read the signed message and the signature
300 from the given files.  It should write human-readable information to
301 standard output and/or standard error.  The program shall not convert
302 charsets or line endings; the input data shall be treated as binary."
303   :tag "Verify Command"
304   :type '(cons 
305           gpg-command-program
306           (repeat 
307            :tag "Arguments"
308            (choice 
309             :format "%[Type%] %v"
310             (const :tag "Insert name of file containing the message here." 
311                    :value message-file)
312             (const :tag "Insert name of file containing the signature here."
313                    :value signature-file)
314             (string :format "%v"))))
315   :group 'gpg-commands)
316
317 (defcustom gpg-command-verify-cleartext
318   '(gpg . ("--batch" "--verbose" "--verify" message-file))
319   "Command to verify a message.
320 The invoked program has to read the signed message from the given
321 file.  It should write human-readable information to standard output
322 and/or standard error.  The program shall not convert charsets or line
323 endings; the input data shall be treated as binary."
324   :tag "Cleartext Verify Command"
325   :type '(cons 
326           gpg-command-program
327           (repeat 
328            :tag "Arguments"
329            (choice 
330             :format "%[Type%] %v"
331             (const :tag "Insert name of file containing the message here." 
332                    :value message-file)
333             (string :format "%v"))))
334   :group 'gpg-commands)
335
336 (defcustom gpg-command-decrypt
337   '(gpg . ("--decrypt" "--batch" "--passphrase-fd=0"))
338   "Command to decrypt a message.
339 The invoked program has to read the passphrase from standard
340 input, followed by the encrypted message.  It writes the decrypted
341 message to standard output, and human-readable diagnostic messages to
342 standard error."
343   :tag "Decrypt Command"
344   :type '(cons
345           gpg-command-program
346           (repeat
347            :tag "Arguments"
348            (choice 
349             :format "%[Type%] %v"
350             (const :tag "Insert name of file containing the message here." 
351                    :value message-file)
352             (string :format "%v"))))
353   :group 'gpg-commands)
354
355 (defcustom gpg-command-sign-cleartext
356   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
357                  armor textmode  "--clearsign"
358                  sign-with-key))
359   "Command to create a create a \"clearsign\" text file.  
360 The invoked program has to read the passphrase from standard input,
361 followed by the message to sign.  It should write the ASCII-amored
362 signed text message to standard output, and diagnostic messages to
363 standard error."
364   :tag "Clearsign Command"
365   :type 'gpg-command-sign-options
366   :group 'gpg-commands)
367
368 (defcustom gpg-command-sign-detached
369   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
370                  armor textmode "--detach-sign" 
371                  sign-with-key))
372   "Command to create a create a detached signature. 
373 The invoked program has to read the passphrase from standard input,
374 followed by the message to sign.  It should write the ASCII-amored
375 detached signature to standard output, and diagnostic messages to
376 standard error.  The program shall not convert charsets or line
377 endings; the input data shall be treated as binary."
378   :tag "Sign Detached Command"
379   :type 'gpg-command-sign-options
380   :group 'gpg-commands)
381
382 (defcustom gpg-command-sign-encrypt
383   '(gpg-2comp . ("--batch" "--passphrase-fd=0" "--output=-"
384                  armor textmode  "--always-trust" sign-with-key recipients
385                   "--sign" "--encrypt" plaintext-file))
386   "Command to sign and encrypt a file.
387 The invoked program has to read the passphrase from standard input,
388 followed by the message to sign and encrypt if there is no
389 `plaintext-file' placeholder.  It should write the ASCII-amored
390 encrypted message to standard output, and diagnostic messages to
391 standard error."
392   :tag "Sign And Encrypt Command"
393   :type '(cons 
394           gpg-command-program
395           (repeat 
396            :tag "Arguments"
397            (choice 
398             :format "%[Type%] %v"
399             (const :tag "Insert the `sign with key' option here if necessary."
400                    :value sign-with-key)
401             (const :tag "Insert list of recipients here."
402                    :value recipients)
403             (const :tag "Insert here name of file with plaintext."
404                    :value plaintext-file)
405             (string :format "%v"))))
406   :group 'gpg-commands)
407
408 (defcustom gpg-command-encrypt
409   '(gpg-2comp . ("--batch" "--output=-" armor textmode "--always-trust" 
410                  "--encrypt" recipients plaintext-file))
411   "Command to encrypt a file.  
412 The invoked program has to read the message to encrypt from standard
413 input or from the plaintext file (if the `plaintext-file' placeholder
414 is present).  It should write the ASCII-amored encrypted message to
415 standard output, and diagnostic messages to standard error."
416   :type '(cons 
417           gpg-command-program
418           (repeat 
419            :tag "Arguments"
420            (choice 
421             :format "%[Type%] %v"
422             (const :tag "Insert list of recipients here."
423                    :value recipients)
424             (const :tag "Insert here name of file with plaintext."
425                    :value plaintext-file)
426             (string :format "%v"))))
427   :group 'gpg-commands)
428
429 ;;; Customization: Variables: Key Management Commands:
430
431 (defcustom gpg-command-key-import
432   '(gpg . ("--import" "--verbose" message-file))
433   "Command to import a public key from a file."
434   :tag "Import Command"
435   :type '(cons 
436           gpg-command-program
437           (repeat 
438            :tag "Arguments"
439            (choice 
440             :format "%[Type%] %v"
441             (const :tag "Insert name of file containing the key here." 
442                    :value message-file)
443             (string :format "%v"))))
444   :group 'gpg-commands-key)
445
446 (defcustom gpg-command-key-export
447   '(gpg . ("--no-verbose" "--armor" "--export" key-id))
448   "Command to export a public key from the key ring.
449 The key should be written to standard output using ASCII armor."
450   :tag "Export Command"
451   :type 'gpg-command-key-options
452   :group 'gpg-commands-key)
453
454 (defcustom gpg-command-key-verify
455   '(gpg . ("--no-verbose" "--batch" "--fingerprint" "--check-sigs" key-id))
456   "Command to verify a public key."
457   :tag "Verification Command"
458   :type 'gpg-command-key-options
459   :group 'gpg-commands-key)
460
461 (defcustom gpg-command-key-public-ring
462   '(gpg . ("--no-verbose" "--batch" "--with-colons" "--list-keys" key-id))
463   "Command to list the contents of the public key ring."
464   :tag "List Public Key Ring Command"
465   :type 'gpg-command-key-options
466   :group 'gpg-commands-key)
467
468 (defcustom gpg-command-key-secret-ring
469   '(gpg . ("--no-verbose" "--batch" "--with-colons" 
470            "--list-secret-keys" key-id))
471   "Command to list the contents of the secret key ring."
472   :tag "List Secret Key Ring Command"
473   :type 'gpg-command-key-options
474   :group 'gpg-commands-key)
475
476 (defcustom gpg-command-key-retrieve 
477   '(gpg . ("--batch" "--recv-keys" key-id))
478   "Command to retrieve public keys."
479   :tag "Retrieve Keys Command"
480   :type 'gpg-command-key-options
481   :group 'gpg-commands-key)
482
483 \f
484 ;;;; Helper functions for GnuPG invocation:
485
486 ;;; Build the GnuPG command line:
487
488 (defun gpg-build-argument (template substitutions &optional pass-start)
489   "Build command line argument(s) by substituting placeholders.
490 TEMPLATE is a list of strings and symbols.  The placeholder symbols in
491 it are replaced by SUBSTITUTIONS, the elements between
492 `next-argument' symbols are concatenated without spaces and are
493 returned in a list.
494
495 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either
496 a string (which is inserted literally), a list of strings (which are
497 inserted as well), or nil, which means to insert nothing.
498
499 If PASS-START is t, `next-argument' is also inserted into the result,
500 and symbols without a proper substitution are retained in the output,
501 otherwise, an untranslated symbol results in an error.
502
503 This function does not handle empty arguments reliably."
504   (let ((current-arg "")
505         (arglist nil))
506     (while template
507       (let* ((templ (pop template))
508              (repl (assoc templ substitutions))
509              (new (if repl (cdr repl) templ)))
510         (cond
511          ((eq templ 'next-argument)
512           ;; If the current argument is not empty, start a new one.
513           (unless (equal current-arg "")
514             (setq arglist (nconc arglist 
515                                  (if pass-start
516                                      (list current-arg 'next-argument)
517                                    (list current-arg))))
518             (setq current-arg "")))
519          ((null new) nil)               ; Drop it.
520          ((and (not (stringp templ)) (null repl))
521           ;; Retain an untranslated symbol in the output if
522           ;; `pass-start' is true.
523           (unless pass-start
524             (error "No replacement for `%s'" templ))
525           (setq arglist (nconc arglist (list current-arg templ)))
526           (setq current-arg ""))
527          (t
528           (unless (listp new)
529             (setq new (list new)))
530           (setq current-arg (concat current-arg 
531                                     (apply 'concat new)))))))
532     (unless (equal current-arg "")
533       (setq arglist (nconc arglist (list current-arg))))
534     arglist))
535
536 (defun gpg-build-arg-list (template substitutions)
537   "Build command line by substituting placeholders.
538 TEMPLATE is a list of strings and symbols.  The placeholder symbols in
539 it are replaced by SUBSTITUTIONS.
540
541 SUBSTITIONS is a list of (SYMBOL . SEXP) pairs, where SEXP is either a
542 string (which is inserted literally), a list of strings (which are
543 inserted as well), or nil, which means to insert nothing."
544   (let (arglist)
545     (while template
546       (let* ((templ (pop template))
547              (repl (assoc templ substitutions))
548              (new (if repl (cdr repl) templ)))
549         (cond
550          ((and (symbolp templ) (null repl))
551           (error "No replacement for `%s'" templ))
552          ((null new) nil)               ; Drop it.
553          (t
554           (unless (listp new)
555             (setq new (list new)))
556           (setq arglist (nconc arglist new))))))
557     arglist))
558
559 (defun gpg-build-flag-recipients-one (recipient)
560   "Build argument for one RECIPIENT."
561   (gpg-build-argument (cdr gpg-command-flag-recipient)
562                       `((recipient . ,recipient)) t))
563
564 (defun gpg-build-flag-recipients (recipients)
565   "Build list of RECIPIENTS using `gpg-command-flag-recipient'."
566   (gpg-build-argument
567    (apply 'append (car gpg-command-flag-recipient)
568                   (mapcar 'gpg-build-flag-recipients-one
569                           recipients))
570    nil))
571
572 (defun gpg-read-recipients ()
573   "Query the user for several recipients."
574   (let ((go t) 
575         recipients r)
576     (while go
577       (setq r (read-string "Enter recipient ID [RET when no more]: "))
578       (if (equal r "")
579           (setq go nil)
580         (setq recipients (nconc recipients (list r)))))
581     recipients))
582     
583 (defun gpg-build-flag-sign-with-key (key)
584   "Build sign with key flag using `gpg-command-flag-sign-with-key'."
585   (let ((k (if key key 
586              (if gpg-default-key-id gpg-default-key-id
587                nil))))
588     (if k
589         (gpg-build-argument gpg-command-flag-sign-with-key
590                             (list (cons 'sign-with-key k)))
591       nil)))
592
593 (defmacro gpg-with-passphrase-env (&rest body)
594   "Adjust the process environment and evaluate BODY.
595 During the evaluation of the body forms, the process environment is
596 adjust according to `gpg-command-passphrase-env'."
597   (let ((env-value (make-symbol "env-value")))
598     `(let ((,env-value))
599        (unwind-protect
600            (progn
601              (when gpg-command-passphrase-env
602                (setq ,env-value (getenv (car gpg-command-passphrase-env)))
603                (setenv (car gpg-command-passphrase-env) 
604                        (cdr gpg-command-passphrase-env)))
605              ,@body)
606          (when gpg-command-passphrase-env
607            ;; This will clear the variable if it wasn't set before.
608            (setenv (car gpg-command-passphrase-env) ,env-value))))))
609 (put 'gpg-with-passphrase-env 'lisp-indent-function 0)
610 (put 'gpg-with-passphrase-env 'edebug-form-spec '(body))
611
612 ;;; Temporary files:
613
614 (defun gpg-make-temp-file ()
615   "Create a temporary file in a safe way"
616   (let ((name  ;; User may use "~/"
617          (expand-file-name "gnupg" gpg-temp-directory)))
618     (if (fboundp 'make-temp-file)
619         ;; If we've got make-temp-file, we are on the save side.
620         (make-temp-file name)
621       ;; make-temp-name doesn't create the file, and an ordinary
622       ;; write-file operation is prone to nasty symlink attacks if the
623       ;; temporary file resides in a world-writable directory.
624       (unless (or (memq system-type '(windows-nt cygwin32 win32 w32 mswindows))
625                   (eq (file-modes gpg-temp-directory) 448)) ; mode 0700
626         (error "Directory for temporary files must have mode 0700."))
627       (setq name (make-temp-name name))
628       (let ((mode (default-file-modes)))
629         (unwind-protect
630             (progn
631               (set-default-file-modes 384) ; mode 0600
632               (with-temp-file name))
633           (set-default-file-modes mode)))
634       name)))
635
636 (defvar gpg-temp-files nil
637   "List of temporary files used by the GnuPG interface.
638 Do not set this variable.  Call `gpg-with-temp-files' if you need
639 temporary files.")
640
641 (defun gpg-with-temp-files-create (count)
642   "Do not call this function.  Used internally by `gpg-with-temp-files'."
643   (while (> count 0)
644     (setq gpg-temp-files (cons (gpg-make-temp-file) gpg-temp-files))
645     (setq count (1- count))))
646
647 (defun gpg-with-temp-files-delete ()
648   "Do not call this function.  Used internally by `gpg-with-temp-files'."
649   (while gpg-temp-files
650     (let ((file (pop gpg-temp-files)))
651       (condition-case nil
652           (delete-file file)
653         (error nil)))))
654
655 (defmacro gpg-with-temp-files (count &rest body)
656   "Create COUNT temporary files, USE them, and delete them.
657 The function USE is called with the names of all temporary files as
658 arguments."
659   `(let ((gpg-temp-files))
660       (unwind-protect
661           (progn
662             ;; Create the temporary files.
663             (gpg-with-temp-files-create ,count)
664             ,@body)
665         (gpg-with-temp-files-delete))))
666 (put 'gpg-with-temp-files 'lisp-indent-function 1)
667 (put 'gpg-with-temp-files 'edebug-form-spec '(body))
668
669 ;;;  Making subprocesses:
670
671 (defun gpg-exec-path (option)
672   "Return the program name for OPTION.
673 OPTION is of the form (PROGRAM . ARGLIST).  This functions returns
674 PROGRAM, but takes default values into account."
675   (let* ((prg (car option))
676          (path (assq prg gpg-command-default-alist)))
677     (cond
678      (path (if (null (cdr path))
679                (error "Command `%s' is not available" prg)
680              (cdr path)))
681      ((null prg) (error "Command is disabled"))
682      (t prg))))
683
684 (defun gpg-call-process (cmd args stdin stdout stderr &optional passphrase)
685   "Invoke external program CMD with ARGS on buffer STDIN.
686 Standard output is insert before point in STDOUT, standard error in
687 STDERR.  If PASSPHRASE is given, send it before STDIN.  PASSPHRASE
688 should not end with a line feed (\"\\n\").
689
690 If `stdin-file' is present in ARGS, it is replaced by the name of a
691 temporary file.  Before invoking CMD, the contents of STDIN is written
692 to this file."
693   (gpg-with-temp-files 2
694    (let* ((coding-system-for-read 'no-conversion)
695           (coding-system-for-write 'no-conversion)
696           (have-stdin-file (memq 'stdin-file args))
697           (stdin-file (nth 0 gpg-temp-files))
698           (stderr-file (nth 1 gpg-temp-files))
699           (cpr-args `(,cmd 
700                       nil               ; don't delete
701                       (,stdout ,stderr-file)
702                       nil               ; don't display
703                       ;; Replace `stdin-file'.
704                       ,@(gpg-build-arg-list 
705                           args (list (cons 'stdin-file stdin-file)))))
706           res)
707      (when have-stdin-file
708        (with-temp-file stdin-file
709          (buffer-disable-undo)
710          (insert-buffer-substring stdin)))
711      (setq res
712            (if passphrase
713                (with-temp-buffer
714                  (buffer-disable-undo)
715                  (insert passphrase "\n")
716                  (unless have-stdin-file
717                    (apply 'insert-buffer-substring 
718                           (if (listp stdin) stdin (list stdin))))
719                  (apply 'call-process-region (point-min) (point-max) cpr-args)
720                  ;; Wipe out passphrase.
721                  (goto-char (point-min))
722                  (translate-region (point) (gpg-point-at-eol)
723                                    (make-string 256 ? )))
724              (if (listp stdin)
725                  (with-current-buffer (car stdin)
726                    (apply 'call-process-region 
727                           (cadr stdin)
728                           (if have-stdin-file (cadr stdin) (caddr stdin))
729                           cpr-args))
730                (with-current-buffer stdin
731                  (apply 'call-process-region 
732                         (point-min) 
733                         (if have-stdin-file (point-min) (point-max))
734                         cpr-args)))))
735      (with-current-buffer stderr
736        (insert-file-contents-literally stderr-file))
737      (if (or (stringp res) (> res 0))
738          ;; Signal or abnormal exit.
739          (with-current-buffer stderr
740            (goto-char (point-max))
741            (insert (format "\nCommand exit status: %s\n" res))
742            nil)
743        t))))
744
745 (defvar gpg-result-buffer nil
746   "The result of a GnuPG operation is stored in this buffer.
747 Never set this variable directly, use `gpg-show-result' instead.")
748
749 (defun gpg-show-result-buffer (always-show result)
750   "Called by `gpg-show-results' to actually show the buffer."
751   (with-current-buffer gpg-result-buffer
752     ;; Only proceed if the buffer is non-empty.
753     (when (and (/= (point-min) (point-max))
754                (or always-show (not result)))
755       (save-window-excursion
756         (display-buffer (current-buffer))
757         (unless (y-or-n-p "Continue? ")
758           (error "GnuPG operation aborted."))))))
759
760 (defmacro gpg-show-result (always-show &rest body)
761   "Show GnuPG result to user for confirmation.
762 This macro binds `gpg-result-buffer' to a temporary buffer and
763 evaluates BODY, like `progn'.  If BODY evaluates to `nil' (or
764 `always-show' is not nil), the user is asked for confirmation."
765   `(let ((gpg-result-buffer (get-buffer-create 
766                          (generate-new-buffer-name "*GnuPG Output*"))))
767      (unwind-protect
768          (gpg-show-result-buffer ,always-show (progn ,@body))
769        (kill-buffer gpg-result-buffer))))
770 (put 'gpg-show-result 'lisp-indent-function 1)
771 (put 'gpg-show-result 'edebug-form-spec '(body))
772
773 ;;; Passphrase handling:
774
775 (defvar gpg-passphrase-timer
776   (timer-create)
777   "This timer will clear the passphrase cache periodically.")
778
779 (defvar gpg-passphrase
780   nil
781   "The (unencrypted) passphrase cache.")
782
783 (defun gpg-passphrase-clear-string (str)
784   "Erases STR by overwriting all characters."
785   (let ((pos 0)
786         (len (length str)))
787     (while (< pos len)
788       (aset str pos ? )
789       (incf pos))))
790
791 ;;;###autoload
792 (defun gpg-passphrase-forget ()
793   "Forget stored passphrase."
794   (interactive)
795   (cancel-timer gpg-passphrase-timer)
796   (gpg-passphrase-clear-string gpg-passphrase)
797   (setq gpg-passphrase nil))
798
799 (defun gpg-passphrase-store (passphrase)
800   "Store PASSPHRASE in cache.
801 Updates the timeout for clearing the cache to `gpg-passphrase-timeout'."
802   (unless (equal gpg-passphrase-timeout 0)
803     (timer-set-time gpg-passphrase-timer 
804                     (timer-relative-time (current-time) 
805                                          gpg-passphrase-timeout))
806     (timer-set-function gpg-passphrase-timer 'gpg-passphrase-forget)
807     (unless (and (fboundp 'itimer-live-p)
808                  (itimer-live-p gpg-passphrase-timer))
809       (timer-activate gpg-passphrase-timer))
810     (setq gpg-passphrase passphrase))
811   passphrase)
812
813 (defun gpg-passphrase-read ()
814   "Read a passphrase and remember it for some time."
815   (interactive)
816   (if gpg-passphrase
817       ;; This reinitializes the timer.
818       (gpg-passphrase-store gpg-passphrase)
819     (let ((pp (read-passwd "Enter passphrase: ")))
820       (gpg-passphrase-store pp))))
821
822 \f
823 ;;;; Main operations:
824
825 ;;;###autoload
826 (defun gpg-verify (message signature result)
827   "Verify buffer MESSAGE against detached SIGNATURE buffer.
828 Returns t if everything worked out well, nil otherwise.  Consult
829 buffer RESULT for details."
830   (interactive "bBuffer containing message: \nbBuffer containing signature: \nbBuffor for result: ")
831   (gpg-with-temp-files 2
832     (let* ((sig-file    (nth 0 gpg-temp-files))
833            (msg-file    (nth 1 gpg-temp-files))
834            (cmd (gpg-exec-path gpg-command-verify))
835            (args (gpg-build-arg-list (cdr gpg-command-verify)
836                                      `((signature-file . ,sig-file)
837                                        (message-file . ,msg-file))))
838            res)
839       (with-temp-file sig-file 
840         (buffer-disable-undo)
841         (apply 'insert-buffer-substring (if (listp signature)
842                                             signature
843                                           (list signature))))
844       (with-temp-file msg-file 
845         (buffer-disable-undo)
846         (apply 'insert-buffer-substring (if (listp message)
847                                             message
848                                           (list message))))
849       (setq res (apply 'call-process-region 
850                        (point-min) (point-min) ; no data
851                        cmd
852                        nil              ; don't delete
853                        result
854                        nil              ; don't display
855                        args))
856       (if (or (stringp res) (> res 0))
857           ;; Signal or abnormal exit.
858           (with-current-buffer result
859             (insert (format "\nCommand exit status: %s\n" res))
860             nil)
861         t))))
862
863 ;;;###autoload
864 (defun gpg-verify-cleartext (message result)
865   "Verify message in buffer MESSAGE.
866 Returns t if everything worked out well, nil otherwise.  Consult
867 buffer RESULT for details.
868
869 NOTE: Use of this function is deprecated."
870   (interactive "bBuffer containing message: \nbBuffor for result: ")
871   (gpg-with-temp-files 1
872     (let* ((msg-file    (nth 0 gpg-temp-files))
873            (cmd (gpg-exec-path gpg-command-verify-cleartext))
874            (args (gpg-build-arg-list (cdr gpg-command-verify-cleartext)
875                                      `((message-file . ,msg-file))))
876            res)
877       (with-temp-file msg-file 
878         (buffer-disable-undo)
879         (apply 'insert-buffer-substring (if (listp message)
880                                             message
881                                           (list message))))
882       (setq res (apply 'call-process-region
883                        (point-min) (point-min) ; no data
884                        cmd
885                        nil              ; don't delete
886                        result
887                        nil              ; don't display
888                        args))
889       (if (or (stringp res) (> res 0))
890           ;; Signal or abnormal exit.
891           (with-current-buffer result
892             (insert (format "\nCommand exit status: %s\n" res))
893             nil)
894         t))))
895
896 ;;;###autoload
897 (defun gpg-decrypt (ciphertext plaintext result &optional passphrase)
898   "Decrypt buffer CIPHERTEXT to buffer PLAINTEXT.
899 Returns t if everything worked out well, nil otherwise.  Consult
900 buffer RESULT for details.  Reads a missing PASSPHRASE using
901 `gpg-passphrase-read'."
902   (interactive "bBuffer containing ciphertext: \nbBuffer for plaintext: \nbBuffor for decryption status: ")
903   (gpg-call-process (gpg-exec-path gpg-command-decrypt)
904                     (gpg-build-arg-list (cdr gpg-command-decrypt) nil)
905                     ciphertext plaintext result
906                     (if passphrase passphrase (gpg-passphrase-read)))
907   (when passphrase
908     (gpg-passphrase-clear-string passphrase)))
909
910 ;;;###autoload
911 (defun gpg-sign-cleartext
912   (plaintext signed-text result &optional passphrase sign-with-key)
913   "Sign buffer PLAINTEXT, and store PLAINTEXT with signature in
914 SIGNED-TEXT.
915 Reads a missing PASSPHRASE using `gpg-passphrase-read'.  Uses key ID
916 SIGN-WITH-KEY if given, otherwise the default key ID.  Returns t if
917 everything worked out well, nil otherwise.  Consult buffer RESULT for
918 details.
919
920 NOTE: Use of this function is deprecated."
921   (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
922   (let ((subst (list (cons 'sign-with-key 
923                            (gpg-build-flag-sign-with-key sign-with-key))
924                      (cons 'armor gpg-command-flag-armor)
925                      (cons 'textmode gpg-command-flag-textmode))))
926     (gpg-call-process (gpg-exec-path gpg-command-sign-cleartext)
927                       (gpg-build-arg-list (cdr gpg-command-sign-cleartext) 
928                                           subst)
929                       plaintext signed-text result
930                       (if passphrase passphrase (gpg-passphrase-read))))
931   (when passphrase
932     (gpg-passphrase-clear-string passphrase)))
933
934 ;;;###autoload
935 (defun gpg-sign-detached
936   (plaintext signature result &optional passphrase sign-with-key
937    armor textmode)
938   "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
939 Reads a missing PASSPHRASE using `gpg-passphrase-read'.  Uses key ID
940 SIGN-WITH-KEY if given, otherwise the default key ID.  Returns t if
941 everything worked out well, nil otherwise.  Consult buffer RESULT for
942 details.  ARMOR the result and activate canonical TEXTMODE if
943 requested."
944   (interactive "bBuffer containing plaintext: \nbBuffer for text with signature: \nbBuffer for status information: ")
945   (let ((subst (list (cons 'sign-with-key 
946                            (gpg-build-flag-sign-with-key sign-with-key))
947                      (cons 'armor (if armor gpg-command-flag-armor))
948                      (cons 'textmode (if armor gpg-command-flag-textmode)))))
949     (gpg-call-process (gpg-exec-path gpg-command-sign-detached)
950                       (gpg-build-arg-list (cdr gpg-command-sign-detached)
951                                           subst)
952                       plaintext signature result
953                       (if passphrase passphrase (gpg-passphrase-read))))
954   (when passphrase
955     (gpg-passphrase-clear-string passphrase)))
956
957
958 ;;;###autoload
959 (defun gpg-sign-encrypt
960   (plaintext ciphertext result recipients &optional passphrase sign-with-key
961    armor textmode)
962   "Sign buffer PLAINTEXT, and store SIGNATURE in that buffer.
963 RECIPIENTS is a list of key IDs used for encryption.  This function
964 reads a missing PASSPHRASE using `gpg-passphrase-read', and uses key
965 ID SIGN-WITH-KEY for the signature if given, otherwise the default key
966 ID.  Returns t if everything worked out well, nil otherwise.  Consult
967 buffer RESULT for details.  ARMOR the result and activate canonical
968 TEXTMODE if requested."
969   (interactive (list
970                 (read-buffer "Buffer containing plaintext: " nil t)
971                 (read-buffer "Buffer for ciphertext: " nil t)
972                 (read-buffer "Buffer for status informationt: " nil t)
973                 (gpg-read-recipients)))
974     (let ((subst `((sign-with-key . ,(gpg-build-flag-sign-with-key 
975                                       sign-with-key))
976                    (plaintext-file . stdin-file)
977                    (recipients . ,(gpg-build-flag-recipients recipients))
978                    (armor ,(if armor gpg-command-flag-armor))
979                    (textmode ,(if armor gpg-command-flag-textmode)))))
980       (gpg-call-process (gpg-exec-path gpg-command-sign-encrypt)
981                         (gpg-build-arg-list (cdr gpg-command-sign-encrypt) 
982                                             subst)
983                         plaintext ciphertext result
984                         (if passphrase passphrase (gpg-passphrase-read))))
985   (when passphrase
986     (gpg-passphrase-clear-string passphrase)))
987
988
989 ;;;###autoload
990 (defun gpg-encrypt
991   (plaintext ciphertext result recipients &optional passphrase armor textmode)
992   "Encrypt buffer PLAINTEXT, and store CIPHERTEXT in that buffer.
993 RECIPIENTS is a list of key IDs used for encryption.  Returns t if
994 everything worked out well, nil otherwise.  Consult buffer RESULT for
995 details.  ARMOR the result and activate canonical
996 TEXTMODE if requested."
997   (interactive (list
998                 (read-buffer "Buffer containing plaintext: " nil t)
999                 (read-buffer "Buffer for ciphertext: " nil t)
1000                 (read-buffer "Buffer for status informationt: " nil t)
1001                 (gpg-read-recipients)))
1002   (let ((subst `((plaintext-file . stdin-file)
1003                  (recipients . ,(gpg-build-flag-recipients recipients))
1004                  (armor ,(if armor gpg-command-flag-armor))
1005                  (textmode ,(if armor gpg-command-flag-textmode)))))
1006     (gpg-call-process (gpg-exec-path gpg-command-encrypt)
1007                       (gpg-build-arg-list (cdr gpg-command-encrypt) subst)
1008                       plaintext ciphertext result nil))
1009   (when passphrase
1010     (gpg-passphrase-clear-string passphrase)))
1011
1012 \f
1013 ;;;; Key management
1014
1015 ;;; ADT: OpenPGP Key
1016
1017 (defun gpg-key-make (user-id key-id unique-id length algorithm
1018                      creation-date expire-date validity trust)
1019   "Create a new key object (for internal use only)."
1020   (vector 
1021         ;;  0   1      2         3      4        
1022         user-id key-id unique-id length algorithm
1023         ;; 5          6           7        8
1024         creation-date expire-date validity trust))
1025
1026
1027 (defun gpg-key-p (key)
1028   "Return t if KEY is a key specification."
1029   (and (arrayp key) (equal (length key) 9) key))
1030
1031 (defmacro gpg-key-primary-user-id (key)
1032   "The primary user ID for KEY (human-readable).
1033 DO NOT USE this ID for selecting recipients.  It is probably not
1034 unique."
1035   (list 'car (list 'aref key 0)))
1036
1037 (defmacro gpg-key-user-ids (key)
1038   "A list of additional user IDs for KEY (human-readable).
1039 DO NOT USE these IDs for selecting recipients.  They are probably not
1040 unique."
1041   (list 'cdr (list 'aref key 0)))
1042
1043 (defmacro gpg-key-id (key)
1044   "The key ID of KEY.
1045 DO NOT USE this ID for selecting recipients.  It is not guaranteed to
1046 be unique."
1047   (list 'aref key 1))
1048
1049 (defun gpg-short-key-id (key)
1050   "The short key ID of KEY."
1051   (let* ((id (gpg-key-id key))
1052          (len (length id)))
1053     (if (> len 8)
1054         (substring id (- len 8))
1055       id)))
1056
1057 (defmacro gpg-key-unique-id (key)
1058   "A non-standard ID of KEY which is only valid locally.
1059 This ID can be used to specify recipients in a safe manner.  Note,
1060 even this ID might not be unique unless GnuPG is used."
1061   (list 'aref key 2))
1062
1063 (defmacro gpg-key-unique-id-list (key-list)
1064   "Like `gpg-key-unique-id', but operate on a list."
1065   `(mapcar (lambda (key) (gpg-key-unique-id key)) 
1066            ,key-list))
1067
1068 (defmacro gpg-key-length (key)
1069   "Returns the key length."
1070   (list 'aref key 3))
1071
1072 (defmacro gpg-key-algorithm (key)
1073   "The encryption algorithm used by KEY.
1074 One of the symbols `rsa', `rsa-encrypt', `rsa-sign', `elgamal',
1075 `elgamal-encrypt', `dsa'."
1076   (list 'aref key 4))
1077
1078 (defmacro gpg-key-creation-date (key)
1079   "A string with the creation date of KEY in ISO format."
1080   (list 'aref key 5))
1081
1082 (defmacro gpg-key-expire-date (key)
1083   "A string with the expiration date of KEY in ISO format."
1084   (list 'aref key 6))
1085
1086 (defmacro gpg-key-validity (key)
1087   "The calculated validity of KEY.  
1088 One of the symbols `not-known', `disabled', `revoked', `expired',
1089 `undefined', `trust-none', `trust-marginal', `trust-full',
1090 `trust-ultimate' (see the GnuPG documentation for details)."
1091  (list 'aref key 7))
1092
1093 (defmacro gpg-key-trust (key)
1094   "The assigned trust for KEY.  
1095 One of the symbols `not-known', `undefined', `trust-none',
1096 `trust-marginal', `trust-full' (see the GnuPG
1097 documentation for details)."
1098   (list 'aref key 8))
1099
1100 (defun gpg-key-lessp (a b)
1101   "Returns t if primary user ID of A is less than B."
1102   (string-lessp (gpg-key-primary-user-id a) (gpg-key-primary-user-id b) ))
1103
1104 ;;; Accessing the key database:
1105
1106 ;; Internal functions:
1107
1108 (defmacro gpg-key-list-keys-skip-field ()
1109   '(search-forward ":" eol 'move))
1110
1111 (defmacro gpg-key-list-keys-get-field ()
1112   '(buffer-substring (point) (if (gpg-key-list-keys-skip-field) 
1113                                  (1- (point)) 
1114                                eol)))
1115 (defmacro gpg-key-list-keys-string-field ()
1116   '(gpg-key-list-keys-get-field))
1117
1118 (defmacro gpg-key-list-keys-read-field ()
1119   (let ((field (make-symbol "field")))
1120     `(let ((,field (gpg-key-list-keys-get-field)))
1121        (if (equal (length ,field) 0)
1122            nil
1123          (read ,field)))))
1124
1125 (defun gpg-key-list-keys-parse-line ()
1126   "Parse the line in the current buffer and return a vector of fields."
1127   (let* ((eol (gpg-point-at-eol))
1128          (v (if (eolp)
1129                 nil
1130               (vector
1131                (gpg-key-list-keys-read-field) ; type
1132                (gpg-key-list-keys-get-field) ; trust
1133                (gpg-key-list-keys-read-field) ; key length
1134                (gpg-key-list-keys-read-field) ; algorithm
1135                (gpg-key-list-keys-get-field) ; key ID
1136                (gpg-key-list-keys-get-field) ; creation data
1137                (gpg-key-list-keys-get-field) ; expire
1138                (gpg-key-list-keys-get-field) ; unique (local) ID
1139                (gpg-key-list-keys-get-field) ; ownertrust
1140                (gpg-key-list-keys-string-field) ; user ID
1141                ))))
1142     (if (eolp)
1143         (when v
1144           (forward-char 1))
1145       (error "Too many fields in GnuPG key database"))
1146     v))
1147
1148 (defconst gpg-pubkey-algo-alist
1149   '((1 . rsa)
1150     (2 . rsa-encrypt-only)
1151     (3 . rsa-sign-only)
1152     (16 . elgamal-encrypt-only)
1153     (17 . dsa)
1154     (20 . elgamal))
1155   "Alist mapping OpenPGP public key algorithm numbers to symbols.")
1156
1157 (defconst gpg-trust-alist
1158   '((?- . not-known)
1159     (?o . not-known)
1160     (?d . disabled)
1161     (?r . revoked)
1162     (?e . expired)
1163     (?q . trust-undefined)
1164     (?n . trust-none)
1165     (?m . trust-marginal)
1166     (?f . trust-full)
1167     (?u . trust-ultimate))
1168   "Alist mapping GnuPG trust value short forms to long symbols.")
1169
1170 (defmacro gpg-key-list-keys-in-buffer-store ()
1171   '(when primary-user-id
1172      (sort user-id 'string-lessp)
1173      (push (gpg-key-make (cons primary-user-id  user-id)
1174                          key-id unique-id key-length
1175                          algorithm creation-date 
1176                          expire-date validity trust)
1177            key-list)))
1178
1179 (defun gpg-key-list-keys-in-buffer (&optional buffer)
1180   "Return a list of keys for BUFFER.
1181 If BUFFER is omitted, use current buffer."
1182   (with-current-buffer (if buffer buffer (current-buffer))
1183     (goto-char (point-min))
1184     ;; Skip key ring filename written by GnuPG.
1185     (search-forward "\n---------------------------\n" nil t)
1186     ;; Loop over all lines in buffer and analyze them.
1187     (let (primary-user-id user-id key-id unique-id ; current key components
1188           key-length algorithm creation-date expire-date validity trust
1189           line                          ; fields in current line
1190           key-list)                     ; keys gather so far
1191     
1192       (while (setq line (gpg-key-list-keys-parse-line))
1193         (cond
1194          ;; Public or secret key.
1195          ((memq (aref line 0) '(pub sec))
1196           ;; Store previous key, if any.
1197           (gpg-key-list-keys-in-buffer-store)
1198           ;; Record field values.
1199           (setq primary-user-id (aref line 9))
1200           (setq user-id nil)
1201           (setq key-id (aref line 4)) 
1202           ;; We use the key ID if no unique ID is available.
1203           (setq unique-id (if (> (length (aref line 7)) 0)
1204                               (concat "#" (aref line 7))
1205                             (concat "0x" key-id)))
1206           (setq key-length (aref line 2))
1207           (setq algorithm (assq (aref line 3) gpg-pubkey-algo-alist))
1208           (if algorithm
1209               (setq algorithm (cdr algorithm))
1210             (error "Unknown algorithm %s" (aref line 3)))
1211           (setq creation-date (if (> (length (aref line 5)) 0)
1212                                   (aref line 5)))
1213           (setq expire-date (if (> (length (aref line 6)) 0)
1214                                 (aref line 6)))
1215           (setq validity (assq (aref (aref line 1) 0) gpg-trust-alist))
1216           (if validity
1217               (setq validity (cdr validity))
1218             (error "Unknown validity specification %S" (aref line 1)))
1219           (setq trust (assq (aref (aref line 8) 0) gpg-trust-alist))
1220           (if trust
1221               (setq trust (cdr trust))
1222             (error "Unknown trust specification %S" (aref line 8))))
1223         
1224          ;; Additional user ID
1225          ((eq 'uid (aref line 0))
1226           (setq user-id (cons (aref line 9) user-id)))
1227          
1228          ;; Subkeys are ignored for now.
1229          ((memq (aref line 0) '(sub ssb))
1230           t)
1231          (t (error "Unknown record type %S" (aref line 0)))))
1232
1233       ;; Store the key retrieved last.
1234       (gpg-key-list-keys-in-buffer-store)
1235       ;; Sort the keys according to the primary user ID.
1236       (sort key-list 'gpg-key-lessp))))
1237
1238 (defun gpg-key-list-keyspec (command &optional keyspec stderr ignore-error)
1239   "Insert the output of COMMAND before point in current buffer."
1240   (let* ((cmd (gpg-exec-path command))
1241          (key (if (equal keyspec "") nil keyspec))
1242          (args (gpg-build-arg-list (cdr command) `((key-id . ,key))))
1243          exit-status)
1244     (setq exit-status 
1245           (apply 'call-process-region 
1246                  (point-min) (point-min) ; no data
1247                  cmd
1248                  nil                    ; don't delete
1249                  (if stderr t '(t nil))
1250                  nil                    ; don't display
1251                  args))
1252     (unless (or ignore-error (equal exit-status 0))
1253       (error "GnuPG command exited unsuccessfully"))))
1254   
1255   
1256 (defun gpg-key-list-keyspec-parse (command &optional keyspec)
1257   "Return a list of keys matching KEYSPEC.
1258 COMMAND is used to obtain the key list.  The usual substring search
1259 for keys is performed."
1260   (with-temp-buffer 
1261     (buffer-disable-undo)
1262     (gpg-key-list-keyspec command keyspec)
1263     (gpg-key-list-keys-in-buffer)))
1264
1265 ;;;###autoload
1266 (defun gpg-key-list-keys (&optional keyspec)
1267   "A list of public keys matching KEYSPEC.
1268 The usual substring search for keys is performed."
1269   (gpg-key-list-keyspec-parse gpg-command-key-public-ring keyspec))
1270
1271 ;;;###autoload
1272 (defun gpg-key-list-secret-keys (&optional keyspec)
1273   "A list of secret keys matching KEYSPEC.
1274 The usual substring search for keys is performed."
1275   (gpg-key-list-keyspec-parse gpg-command-key-secret-ring keyspec))
1276
1277 ;;;###autoload
1278 (defun gpg-key-insert-public-key (key)
1279   "Inserts the public key(s) matching KEYSPEC.
1280 The ASCII-armored key is inserted before point into current buffer."
1281   (gpg-key-list-keyspec gpg-command-key-export key))
1282
1283 ;;;###autoload
1284 (defun gpg-key-insert-information (key)
1285   "Insert human-readable information (including fingerprint) on KEY.
1286 Insertion takes place in current buffer before point."
1287   (gpg-key-list-keyspec gpg-command-key-verify key))
1288
1289 ;;;###autoload
1290 (defun gpg-key-retrieve (key)
1291   "Fetch KEY from default key server.
1292 KEY is a key ID or a list of key IDs.  Status information about this
1293 operation is inserted into the current buffer before point."
1294   (gpg-key-list-keyspec gpg-command-key-retrieve key t t))
1295
1296 ;;;###autoload
1297 (defun gpg-key-add-to-ring (key result)
1298   "Adds key in buffer KEY to the GnuPG key ring.
1299 Human-readable information on the RESULT is stored in buffer RESULT
1300 before point.")
1301
1302 (provide 'gpg)
1303
1304 ;;; gpg.el ends here