Fixed error messages.
[elisp/epg.git] / epg.el
1 ;;; epg.el --- the EasyPG Library
2 ;; Copyright (C) 1999, 2000, 2002, 2003, 2004,
3 ;;   2005, 2006 Free Software Foundation, Inc.
4 ;; Copyright (C) 2006 Daiki Ueno
5
6 ;; Author: Daiki Ueno <ueno@unixuser.org>
7 ;; Keywords: PGP, GnuPG
8
9 ;; This file is part of EasyPG.
10
11 ;; This program is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; This program is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25
26 ;;; Code:
27
28 (defgroup epg ()
29   "The EasyPG Library")
30
31 (defcustom epg-gpg-program "gpg"
32   "The `gpg' executable."
33   :group 'epg
34   :type 'string)
35
36 (defvar epg-user-id nil
37   "GnuPG ID of your default identity.")
38
39 (defvar epg-user-id-alist nil
40   "An alist mapping from key ID to user ID.")
41
42 (defvar epg-read-point nil)
43 (defvar epg-pending-status-list nil)
44 (defvar epg-key-id nil)
45 (defvar epg-context nil)
46 (defvar epg-debug nil)
47
48 ;; from gnupg/include/cipher.h
49 (defconst epg-cipher-algorithm-alist
50   '((0 . "NONE")
51     (1 . "IDEA")
52     (2 . "3DES")
53     (3 . "CAST5")
54     (4 . "BLOWFISH")
55     (7 . "AES")
56     (8 . "AES192")
57     (9 . "AES256")
58     (10 . "TWOFISH")
59     (110 . "DUMMY")))
60
61 ;; from gnupg/include/cipher.h
62 (defconst epg-pubkey-algorithm-alist
63   '((1 . "RSA")
64     (2 . "RSA_E")
65     (3 . "RSA_S")
66     (16 . "ELGAMAL_E")
67     (17 . "DSA")
68     (20 . "ELGAMAL")))
69
70 ;; from gnupg/include/cipher.h
71 (defconst epg-digest-algorithm-alist
72   '((1 . "MD5")
73     (2 . "SHA1")
74     (3 . "RMD160")
75     (8 . "SHA256")
76     (9 . "SHA384")
77     (10 . "SHA512")))
78
79 ;; from gnupg/include/cipher.h
80 (defconst epg-compress-algorithm-alist
81   '((0 . "NONE")
82     (1 . "ZIP")
83     (2 . "ZLIB")
84     (3 . "BZIP2")))
85
86 (defconst epg-invalid-recipients-alist
87   '((0 . "No specific reason given")
88     (1 . "Not Found")
89     (2 . "Ambigious specification")
90     (3 . "Wrong key usage")
91     (4 . "Key revoked")
92     (5 . "Key expired")
93     (6 . "No CRL known")
94     (7 . "CRL too old")
95     (8 . "Policy mismatch")
96     (9 . "Not a secret key")
97     (10 . "Key not trusted")))
98
99 (defvar epg-key-validity-alist
100   '((?o . unknown)
101     (?i . invalid)
102     (?d . disabled)
103     (?r . revoked)
104     (?e . expired)
105     (?- . none)
106     (?q . undefined)
107     (?n . never)
108     (?m . marginal)
109     (?f . full)
110     (?u . ultimate)))
111
112 (defvar epg-key-capablity-alist
113   '((?e . encrypt)
114     (?s . sign)
115     (?c . certify)
116     (?a . authentication)))
117
118 (defvar epg-prompt-alist nil)
119
120 (defun epg-make-data-from-file (file)
121   "Make a data object from FILE."
122   (vector file nil))
123
124 (defun epg-make-data-from-string (string)
125   "Make a data object from STRING."
126   (vector nil string))
127
128 (defun epg-data-file (data)
129   "Return the file of DATA."
130   (aref data 0))
131
132 (defun epg-data-string (data)
133   "Return the string of DATA."
134   (aref data 1))
135
136 (defun epg-make-context (&optional protocol armor textmode include-certs)
137   "Return a context object."
138   (vector protocol armor textmode include-certs
139           #'epg-passphrase-callback-function
140           #'epg-progress-callback-function
141           nil nil nil nil))
142
143 (defun epg-context-protocol (context)
144   "Return the protocol used within the context."
145   (aref context 0))
146
147 (defun epg-context-armor (context)
148   "Return t if the output shouled be ASCII armored in the CONTEXT context."
149   (aref context 1))
150
151 (defun epg-context-textmode (context)
152   "Return t if canonical text mode should be used in the CONTEXT context."
153   (aref context 2))
154
155 (defun epg-context-include-certs (context)
156   "Return how many certificates should be included in an S/MIME signed
157 message."
158   (aref context 3))
159
160 (defun epg-context-passphrase-callback (context)
161   "Return the function used to query passphrase."
162   (aref context 4))
163
164 (defun epg-context-progress-callback (context)
165   "Return the function which handles progress update."
166   (aref context 5))
167
168 (defun epg-context-signers (context)
169   "Return the list of key-id for singning."
170   (aref context 6))
171
172 (defun epg-context-process (context)
173   "Return the process object of `epg-gpg-program'.
174 This function is for internal use only."
175   (aref context 7))
176
177 (defun epg-context-output-file (context)
178   "Return the output file of `epg-gpg-program'.
179 This function is for internal use only."
180   (aref context 8))
181
182 (defun epg-context-result (context)
183   "Return the result of the previous cryptographic operation."
184   (aref context 9))
185
186 (defun epg-context-set-protocol (context protocol)
187   "Set the protocol used within the context."
188   (aset context 0 protocol))
189
190 (defun epg-context-set-armor (context armor)
191   "Specify if the output shouled be ASCII armored in the CONTEXT context."
192   (aset context 1 armor))
193
194 (defun epg-context-set-textmode (context textmode)
195   "Specify if canonical text mode should be used in the CONTEXT context."
196   (aset context 2 textmode))
197
198 (defun epg-context-set-include-certs (context include-certs)
199  "Set how many certificates should be included in an S/MIME signed message."
200   (aset context 3 include-certs))
201
202 (defun epg-context-set-passphrase-callback (context
203                                                  passphrase-callback)
204   "Set the function used to query passphrase."
205   (aset context 4 passphrase-callback))
206
207 (defun epg-context-set-progress-callback (context progress-callback)
208   "Set the function which handles progress update."
209   (aset context 5 progress-callback))
210
211 (defun epg-context-set-signers (context signers)
212  "Set the list of key-id for singning."
213   (aset context 6 signers))
214
215 (defun epg-context-set-process (context process)
216   "Set the process object of `epg-gpg-program'.
217 This function is for internal use only."
218   (aset context 7 process))
219
220 (defun epg-context-set-output-file (context output-file)
221   "Set the output file of `epg-gpg-program'.
222 This function is for internal use only."
223   (aset context 8 output-file))
224
225 (defun epg-context-set-result (context result)
226   "Set the result of the previous cryptographic operation."
227   (aset context 9 result))
228
229 (defun epg-make-signature (status key-id user-id)
230   "Return a signature object."
231   (vector status key-id user-id nil nil))
232
233 (defun epg-signature-status (signature)
234   "Return the status code of SIGNATURE."
235   (aref signature 0))
236
237 (defun epg-signature-key-id (signature)
238   "Return the key-id of SIGNATURE."
239   (aref signature 1))
240
241 (defun epg-signature-user-id (signature)
242   "Return the user-id of SIGNATURE."
243   (aref signature 2))
244   
245 (defun epg-signature-validity (signature)
246   "Return the validity of SIGNATURE."
247   (aref signature 3))
248
249 (defun epg-signature-fingerprint (signature)
250   "Return the fingerprint of SIGNATURE."
251   (aref signature 4))
252
253 (defun epg-signature-set-status (signature status)
254  "Set the status code of SIGNATURE."
255   (aset signature 0 status))
256
257 (defun epg-signature-set-key-id (signature key-id)
258  "Set the key-id of SIGNATURE."
259   (aset signature 1 key-id))
260
261 (defun epg-signature-set-user-id (signature user-id)
262  "Set the user-id of SIGNATURE."
263   (aset signature 2 user-id))
264   
265 (defun epg-signature-set-validity (signature validity)
266  "Set the validity of SIGNATURE."
267   (aset signature 3 validity))
268
269 (defun epg-signature-set-fingerprint (signature fingerprint)
270  "Set the fingerprint of SIGNATURE."
271   (aset signature 4 fingerprint))
272
273 (defun epg-make-key (owner-trust)
274   "Return a key object."
275   (vector owner-trust nil nil))
276
277 (defun epg-key-owner-trust (key)
278   "Return the owner trust of KEY."
279   (aref key 0))
280
281 (defun epg-key-sub-key-list (key)
282   "Return the sub key list of KEY."
283   (aref key 1))
284
285 (defun epg-key-user-id-list (key)
286   "Return the user ID list of KEY."
287   (aref key 2))
288
289 (defun epg-key-set-sub-key-list (key sub-key-list)
290   "Set the sub key list of KEY."
291   (aset key 1 sub-key-list))
292
293 (defun epg-key-set-user-id-list (key user-id-list)
294   "Set the user ID list of KEY."
295   (aset key 2 user-id-list))
296
297 (defun epg-make-sub-key (validity capability secret algorithm length id
298                                   creation-time expiration-time)
299   "Return a sub key object."
300   (vector validity capability secret algorithm length id creation-time
301           expiration-time nil))
302
303 (defun epg-sub-key-validity (sub-key)
304   "Return the validity of SUB-KEY."
305   (aref sub-key 0))
306
307 (defun epg-sub-key-capability (sub-key)
308   "Return the capability of SUB-KEY."
309   (aref sub-key 1))
310
311 (defun epg-sub-key-secret (sub-key)
312   "Return non-nil if SUB-KEY is a secret key."
313   (aref sub-key 2))
314
315 (defun epg-sub-key-algorithm (sub-key)
316   "Return the algorithm of SUB-KEY."
317   (aref sub-key 3))
318
319 (defun epg-sub-key-length (sub-key)
320   "Return the length of SUB-KEY."
321   (aref sub-key 4))
322
323 (defun epg-sub-key-id (sub-key)
324   "Return the ID of SUB-KEY."
325   (aref sub-key 5))
326
327 (defun epg-sub-key-creation-time (sub-key)
328   "Return the creation time of SUB-KEY."
329   (aref sub-key 6))
330
331 (defun epg-sub-key-expiration-time (sub-key)
332   "Return the expiration time of SUB-KEY."
333   (aref sub-key 7))
334
335 (defun epg-sub-key-fingerprint (sub-key)
336   "Return the fingerprint of SUB-KEY."
337   (aref sub-key 8))
338
339 (defun epg-sub-key-set-fingerprint (sub-key fingerprint)
340   "Set the fingerprint of SUB-KEY.
341 This function is for internal use only."
342   (aset sub-key 8 fingerprint))
343
344 (defun epg-make-user-id (validity name)
345   "Return a user ID object."
346   (vector validity name nil))
347
348 (defun epg-user-id-validity (user-id)
349   "Return the validity of USER-ID."
350   (aref user-id 0))
351
352 (defun epg-user-id-name (user-id)
353   "Return the name of USER-ID."
354   (aref user-id 1))
355
356 (defun epg-user-id-signature-list (user-id)
357   "Return the signature list of USER-ID."
358   (aref user-id 2))
359
360 (defun epg-user-id-set-signature-list (user-id signature-list)
361   "Set the signature list of USER-ID."
362   (aset user-id 2 signature-list))
363
364 (defun epg-context-result-for (context name)
365   (cdr (assq name (epg-context-result context))))
366
367 (defun epg-context-set-result-for (context name value)
368   (let* ((result (epg-context-result context))
369          (entry (assq name result)))
370     (if entry
371         (setcdr entry value)
372       (epg-context-set-result context (cons (cons name value) result)))))
373
374 (defun epg-start (context args)
375   "Start `epg-gpg-program' in a subprocess with given ARGS."
376   (let* ((args (append (list "--no-tty"
377                              "--status-fd" "1"
378                              "--command-fd" "0")
379                        (if (epg-context-armor context) '("--armor"))
380                        (if (epg-context-textmode context) '("--textmode"))
381                        (if (epg-context-output-file context)
382                            (list "--output" (epg-context-output-file context)))
383                        args))
384          (coding-system-for-write 'binary)
385          process-connection-type
386          (orig-mode (default-file-modes))
387          (buffer (generate-new-buffer " *epg*"))
388          process)
389     (with-current-buffer buffer
390       (make-local-variable 'epg-read-point)
391       (setq epg-read-point (point-min))
392       (make-local-variable 'epg-pending-status-list)
393       (setq epg-pending-status-list nil)
394       (make-local-variable 'epg-key-id)
395       (setq epg-key-id nil)
396       (make-local-variable 'epg-context)
397       (setq epg-context context))
398     (unwind-protect
399         (progn
400           (set-default-file-modes 448)
401           (setq process
402                 (apply #'start-process "epg" buffer epg-gpg-program args)))
403       (set-default-file-modes orig-mode))
404     (set-process-filter process #'epg-process-filter)
405     (epg-context-set-process context process)))
406
407 (defun epg-process-filter (process input)
408   (if epg-debug
409       (save-excursion
410         (set-buffer (get-buffer-create  " *epg-debug*"))
411         (goto-char (point-max))
412         (insert input)))
413   (if (buffer-live-p (process-buffer process))
414       (save-excursion
415         (set-buffer (process-buffer process))
416         (goto-char (point-max))
417         (insert input)
418         (goto-char epg-read-point)
419         (beginning-of-line)
420         (while (looking-at ".*\n")      ;the input line is finished
421           (save-excursion
422             (if (looking-at "\\[GNUPG:] \\([A-Z_]+\\) ?\\(.*\\)")
423                 (let* ((status (match-string 1))
424                        (string (match-string 2))
425                        (symbol (intern-soft (concat "epg-status-" status))))
426                   (if (member status epg-pending-status-list)
427                       (setq epg-pending-status-list nil))
428                   (if (and symbol
429                            (fboundp symbol))
430                       (funcall symbol process string)))))
431           (forward-line))
432         (setq epg-read-point (point)))))
433
434 (defun epg-read-output (context)
435   (with-temp-buffer
436     (if (fboundp 'set-buffer-multibyte)
437         (set-buffer-multibyte nil))
438     (if (file-exists-p (epg-context-output-file context))
439         (let ((coding-system-for-read (if (epg-context-textmode context)
440                                           'raw-text
441                                         'binary)))
442           (insert-file-contents (epg-context-output-file context))
443           (buffer-string)))))
444
445 (defun epg-wait-for-status (context status-list)
446   (with-current-buffer (process-buffer (epg-context-process context))
447     (setq epg-pending-status-list status-list)
448     (while (and (eq (process-status (epg-context-process context)) 'run)
449                 epg-pending-status-list)
450       (accept-process-output (epg-context-process context) 1))))
451
452 (defun epg-wait-for-completion (context)
453   (if (eq (process-status (epg-context-process context)) 'run)
454       (process-send-eof (epg-context-process context)))
455   (while (eq (process-status (epg-context-process context)) 'run)
456     ;; We can't use accept-process-output instead of sit-for here
457     ;; because it may cause an interrupt during the sentinel execution.
458     (sit-for 0.1)))
459
460 (defun epg-reset (context)
461   (if (and (epg-context-process context)
462            (buffer-live-p (process-buffer (epg-context-process context))))
463       (kill-buffer (process-buffer (epg-context-process context))))
464   (epg-context-set-process context nil))
465
466 (defun epg-delete-output-file (context)
467   (if (and (epg-context-output-file context)
468            (file-exists-p (epg-context-output-file context)))
469       (delete-file (epg-context-output-file context))))
470
471 (defun epg-status-USERID_HINT (process string)
472   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
473       (let* ((key-id (match-string 1 string))
474              (user-id (match-string 2 string))
475              (entry (assoc key-id epg-user-id-alist)))
476         (if entry
477             (setcdr entry user-id)
478           (setq epg-user-id-alist (cons (cons key-id user-id)
479                                         epg-user-id-alist))))))
480
481 (defun epg-status-NEED_PASSPHRASE (process string)
482   (if (string-match "\\`\\([^ ]+\\)" string)
483       (setq epg-key-id (match-string 1 string))))
484
485 (defun epg-status-NEED_PASSPHRASE_SYM (process string)
486   (setq epg-key-id 'SYM))
487
488 (defun epg-status-NEED_PASSPHRASE_PIN (process string)
489   (setq epg-key-id 'PIN))
490
491 (defun epg-status-GET_HIDDEN (process string)
492   (let ((passphrase
493          (funcall (if (consp (epg-context-passphrase-callback epg-context))
494                       (car (epg-context-passphrase-callback epg-context))
495                     (epg-context-passphrase-callback epg-context))
496                   epg-key-id
497                   (if (consp (epg-context-passphrase-callback epg-context))
498                       (cdr (epg-context-passphrase-callback epg-context)))))
499         string)
500     (if passphrase
501         (unwind-protect
502             (progn
503               (setq string (concat passphrase "\n"))
504               (fillarray passphrase 0)
505               (setq passphrase nil)
506               (process-send-string process string))
507           (if string
508               (fillarray string 0))))))
509
510 (defun epg-status-GET_BOOL (process string)
511   (let ((entry (assoc string epg-prompt-alist)))
512     (if (y-or-n-p (if entry (cdr entry) (concat string "? ")))
513         (process-send-string process "y\n")
514       (process-send-string process "n\n"))))
515
516 (defun epg-status-GET_LINE (process string)
517   (let* ((entry (assoc string epg-prompt-alist))
518          (string (read-string (if entry (cdr entry) (concat string ": ")))))
519     (process-send-string process (concat string "\n"))))
520
521 (defun epg-status-GOODSIG (process string)
522   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
523       (epg-context-set-result-for
524        epg-context
525        'verify
526        (cons (epg-make-signature 'good
527                                  (match-string 1 string)
528                                  (match-string 2 string))
529              (epg-context-result-for epg-context 'verify)))))
530
531 (defun epg-status-EXPSIG (process string)
532   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
533       (epg-context-set-result-for
534        epg-context
535        'verify
536        (cons (epg-make-signature 'expired
537                                  (match-string 1 string)
538                                  (match-string 2 string))
539              (epg-context-result-for epg-context 'verify)))))
540
541 (defun epg-status-EXPKEYSIG (process string)
542   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
543       (epg-context-set-result-for
544        epg-context
545        'verify
546        (cons (epg-make-signature 'expired-key
547                                  (match-string 1 string)
548                                  (match-string 2 string))
549              (epg-context-result-for epg-context 'verify)))))
550
551 (defun epg-status-REVKEYSIG (process string)
552   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
553       (epg-context-set-result-for
554        epg-context
555        'verify
556        (cons (epg-make-signature 'revoked-key
557                                  (match-string 1 string)
558                                  (match-string 2 string))
559              (epg-context-result-for epg-context 'verify)))))
560
561 (defun epg-status-BADSIG (process string)
562   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
563       (epg-context-set-result-for
564        epg-context
565        'verify
566        (cons (epg-make-signature 'bad
567                                  (match-string 1 string)
568                                  (match-string 2 string))
569              (epg-context-result-for epg-context 'verify)))))
570
571 (defun epg-status-VALIDSIG (process string)
572   (let ((signature (car (epg-context-result-for epg-context 'verify))))
573     (if (and signature
574              (eq (epg-signature-status signature) 'good)
575              (string-match "\\`\\([^ ]+\\) " string))
576         (epg-signature-set-fingerprint signature (match-string 1 string)))))
577
578 (defun epg-status-TRUST_UNDEFINED (process string)
579   (let ((signature (car (epg-context-result-for epg-context 'verify))))
580     (if (and signature
581              (eq (epg-signature-status signature) 'good))
582         (epg-signature-set-validity signature 'undefined))))
583
584 (defun epg-status-TRUST_NEVER (process string)
585   (let ((signature (car (epg-context-result-for epg-context 'verify))))
586     (if (and signature
587              (eq (epg-signature-status signature) 'good))
588         (epg-signature-set-validity signature 'never))))
589
590 (defun epg-status-TRUST_MARGINAL (process string)
591   (let ((signature (car (epg-context-result-for epg-context 'verify))))
592     (if (and signature
593              (eq (epg-signature-status signature) 'marginal))
594         (epg-signature-set-validity signature 'marginal))))
595
596 (defun epg-status-TRUST_FULLY (process string)
597   (let ((signature (car (epg-context-result-for epg-context 'verify))))
598     (if (and signature
599              (eq (epg-signature-status signature) 'good))
600         (epg-signature-set-validity signature 'full))))
601
602 (defun epg-status-TRUST_ULTIMATE (process string)
603   (let ((signature (car (epg-context-result-for epg-context 'verify))))
604     (if (and signature
605              (eq (epg-signature-status signature) 'good))
606         (epg-signature-set-validity signature 'ultimate))))
607
608 (defun epg-status-PROGRESS (process string)
609   (if (string-match "\\`\\([^ ]+\\) \\([^ ]\\) \\([0-9]+\\) \\([0-9]+\\)"
610                     string)
611       (funcall (if (consp (epg-context-progress-callback epg-context))
612                    (car (epg-context-progress-callback epg-context))
613                  (epg-context-progress-callback epg-context))
614                (match-string 1 string)
615                (match-string 2 string)
616                (string-to-number (match-string 3 string))
617                (string-to-number (match-string 4 string))
618                (if (consp (epg-context-progress-callback epg-context))
619                    (cdr (epg-context-progress-callback epg-context))))))
620
621 (defun epg-status-DECRYPTION_FAILED (process string)
622   (epg-context-set-result-for
623    epg-context 'error
624    (cons 'decryption-failed
625          (epg-context-result-for epg-context 'error))))
626
627 (defun epg-status-NODATA (process string)
628   (epg-context-set-result-for
629    epg-context 'error
630    (cons (cons 'no-data (string-to-number string))
631          (epg-context-result-for epg-context 'error))))
632
633 (defun epg-status-UNEXPECTED (process string)
634   (epg-context-set-result-for
635    epg-context 'error
636    (cons (cons 'unexpected (string-to-number string))
637          (epg-context-result-for epg-context 'error))))
638
639 (defun epg-status-KEYEXPIRED (process string)
640   (epg-context-set-result-for
641    epg-context 'error
642    (cons (cons 'key-expired string)
643          (epg-context-result-for epg-context 'error))))
644
645 (defun epg-status-KEYREVOKED (process string)
646   (epg-context-set-result-for
647    epg-context 'error
648    (cons 'key-revoked
649          (epg-context-result-for epg-context 'error))))
650
651 (defun epg-status-BADARMOR (process string)
652   (epg-context-set-result-for
653    epg-context 'error
654    (cons 'bad-armor
655          (epg-context-result-for epg-context 'error))))
656
657 (defun epg-status-INV_RECP (process string)
658   (if (string-match "\\`\\([0-9]+\\) \\(.*\\)" string)
659       (epg-context-set-result-for
660        epg-context 'error
661        (cons (cons 'invalid-recipient
662                    (string-to-number (match-string 1 string)))
663              (epg-context-result-for epg-context 'error)))))
664
665 (defun epg-status-NO_RECP (process string)
666   (epg-context-set-result-for
667    epg-context 'error
668    (cons 'no-recipients
669          (epg-context-result-for epg-context 'error))))
670
671 (defun epg-passphrase-callback-function (key-id handback)
672   (read-passwd
673    (if (eq key-id 'SYM)
674        "Passphrase for symmetric encryption: "
675      (if (eq key-id 'PIN)
676          "Passphrase for PIN: "
677        (let ((entry (assoc key-id epg-user-id-alist)))
678          (if entry
679              (format "Passphrase for %s %s: " key-id (cdr entry))
680            (format "Passphrase for %s: " key-id)))))))
681
682 (defun epg-progress-callback-function (what char current total handback)
683   (message "%s: %d%%/%d%%" what current total))
684
685 (defun epg-configuration ()
686   "Return a list of internal configuration parameters of `epg-gpg-program'."
687   (let (config type)
688     (with-temp-buffer
689       (apply #'call-process epg-gpg-program nil (list t nil) nil
690              '("--with-colons" "--list-config"))
691       (goto-char (point-min))
692       (while (re-search-forward "^cfg:\\([^:]+\\):\\(.*\\)" nil t)
693         (setq type (intern (match-string 1))
694               config (cons (cons type
695                                  (if (memq type
696                                            '(pubkey cipher digest compress))
697                                      (mapcar #'string-to-number
698                                              (delete "" (split-string
699                                                          (match-string 2)
700                                                          ";")))
701                                    (match-string 2)))
702                            config))))
703     config))
704
705 (defun epg-list-keys-1 (name mode)
706   (let ((args (append (list "--with-colons" "--no-greeting" "--batch"
707                             "--fixed-list-mode" "--with-fingerprint"
708                             "--with-fingerprint"
709                             (if mode "--list-secret-keys" "--list-keys"))
710                       (if name (list name))))
711         keys string field index)
712     (with-temp-buffer
713       (apply #'call-process epg-gpg-program nil (list t nil) nil args)
714       (goto-char (point-min))
715       (while (re-search-forward "^[a-z][a-z][a-z]:.*" nil t)
716         (setq keys (cons (make-vector 15 nil) keys)
717               string (match-string 0)
718               index 0
719               field 0)
720         (while (eq index
721                    (string-match "\\([^:]+\\)?:" string index))
722           (setq index (match-end 0))
723           (aset (car keys) field (match-string 1 string))
724           (setq field (1+ field))))
725       (nreverse keys))))
726
727 (defun epg-make-sub-key-1 (line)
728   (epg-make-sub-key
729    (cdr (assq (string-to-char (aref line 1)) epg-key-validity-alist))
730    (delq nil
731          (mapcar (lambda (char) (cdr (assq char epg-key-capablity-alist)))
732                  (aref line 11)))
733    (member (aref line 0) '("sec" "ssb"))
734    (string-to-number (aref line 3))
735    (string-to-number (aref line 2))
736    (aref line 4)
737    (aref line 5)
738    (aref line 6)))
739
740 (defun epg-list-keys (&optional name mode)
741   (let ((lines (epg-list-keys-1 name mode))
742         keys)
743     (while lines
744       (cond
745        ((member (aref (car lines) 0) '("pub" "sec"))
746         (when (car keys)
747           (epg-key-set-sub-key-list
748            (car keys)
749            (nreverse (epg-key-sub-key-list (car keys))))
750           (epg-key-set-user-id-list
751            (car keys)
752            (nreverse (epg-key-user-id-list (car keys)))))
753         (setq keys (cons (epg-make-key
754                           (cdr (assq (string-to-char (aref (car lines) 8))
755                                      epg-key-validity-alist)))
756                          keys))
757         (epg-key-set-sub-key-list
758          (car keys)
759          (cons (epg-make-sub-key-1 (car lines))
760                (epg-key-sub-key-list (car keys)))))
761        ((member (aref (car lines) 0) '("sub" "ssb"))
762         (epg-key-set-sub-key-list
763          (car keys)
764          (cons (epg-make-sub-key-1 (car lines))
765                (epg-key-sub-key-list (car keys)))))
766        ((equal (aref (car lines) 0) "uid")
767         (epg-key-set-user-id-list
768          (car keys)
769          (cons (epg-make-user-id
770                 (cdr (assq (string-to-char (aref (car lines) 1))
771                            epg-key-validity-alist))
772                 (aref (car lines) 9))
773                (epg-key-user-id-list (car keys)))))
774        ((equal (aref (car lines) 0) "fpr")
775         (epg-sub-key-set-fingerprint (car (epg-key-sub-key-list (car keys)))
776                                      (aref (car lines) 9))))
777       (setq lines (cdr lines)))
778     (nreverse keys)))
779
780 (if (fboundp 'make-temp-file)
781     (defalias 'epg-make-temp-file 'make-temp-file)
782   ;; stolen from poe.el.
783   (defun epg-make-temp-file (prefix)
784     "Create a temporary file.
785 The returned file name (created by appending some random characters at the end
786 of PREFIX, and expanding against `temporary-file-directory' if necessary),
787 is guaranteed to point to a newly created empty file.
788 You can then use `write-region' to write new data into the file."
789     (let (tempdir tempfile)
790       (unwind-protect
791           (let (file)
792             ;; First, create a temporary directory.
793             (while (condition-case ()
794                        (progn
795                          (setq tempdir (make-temp-name
796                                         (concat
797                                          (file-name-directory prefix)
798                                          "DIR")))
799                          ;; return nil or signal an error.
800                          (make-directory tempdir))
801                      ;; let's try again.
802                      (file-already-exists t)))
803             (set-file-modes tempdir 448)
804             ;; Second, create a temporary file in the tempdir.
805             ;; There *is* a race condition between `make-temp-name'
806             ;; and `write-region', but we don't care it since we are
807             ;; in a private directory now.
808             (setq tempfile (make-temp-name (concat tempdir "/EMU")))
809             (write-region "" nil tempfile nil 'silent)
810             (set-file-modes tempfile 384)
811             ;; Finally, make a hard-link from the tempfile.
812             (while (condition-case ()
813                        (progn
814                          (setq file (make-temp-name prefix))
815                          ;; return nil or signal an error.
816                          (add-name-to-file tempfile file))
817                      ;; let's try again.
818                      (file-already-exists t)))
819             file)
820         ;; Cleanup the tempfile.
821         (and tempfile
822              (file-exists-p tempfile)
823              (delete-file tempfile))
824         ;; Cleanup the tempdir.
825         (and tempdir
826              (file-directory-p tempdir)
827              (delete-directory tempdir))))))
828
829 ;;;###autoload
830 (defun epg-start-decrypt (context cipher)
831   "Initiate a decrypt operation on CIPHER.
832 CIPHER is a data object.
833
834 If you use this function, you will need to wait for the completion of
835 `epg-gpg-program' by using `epg-wait-for-completion' and call
836 `epg-reset' to clear a temporaly output file.
837 If you are unsure, use synchronous version of this function
838 `epg-decrypt-file' or `epg-decrypt-string' instead."
839   (unless (epg-data-file cipher)
840     (error "Not a file"))
841   (epg-context-set-result context nil)
842   (epg-start context (list "--decrypt" (epg-data-file cipher)))
843   (epg-wait-for-status context '("BEGIN_DECRYPTION")))
844
845 ;;;###autoload
846 (defun epg-decrypt-file (context cipher plain)
847   "Decrypt a file CIPHER and store the result to a file PLAIN.
848 If PLAIN is nil, it returns the result as a string."
849   (unwind-protect
850       (progn
851         (if plain
852             (epg-context-set-output-file context plain)
853           (epg-context-set-output-file context
854                                        (epg-make-temp-file "epg-output")))
855         (epg-start-decrypt context (epg-make-data-from-file cipher))
856         (epg-wait-for-completion context)
857         (if (epg-context-result-for context 'error)
858             (error "Decrypt failed: %S"
859                    (epg-context-result-for context 'error)))
860         (unless plain
861           (epg-read-output context)))
862     (unless plain
863       (epg-delete-output-file context))
864     (epg-reset context)))
865
866 ;;;###autoload
867 (defun epg-decrypt-string (context cipher)
868   "Decrypt a string CIPHER and return the plain text."
869   (let ((input-file (epg-make-temp-file "epg-input"))
870         (coding-system-for-write 'binary))
871     (unwind-protect
872         (progn
873           (write-region cipher nil input-file)
874           (epg-context-set-output-file context
875                                        (epg-make-temp-file "epg-output"))
876           (epg-start-decrypt context (epg-make-data-from-file input-file))
877           (epg-wait-for-completion context)
878           (if (epg-context-result-for context 'error)
879               (error "Decrypt failed: %S"
880                      (epg-context-result-for context 'error)))
881           (epg-read-output context))
882       (epg-delete-output-file context)
883       (if (file-exists-p input-file)
884           (delete-file input-file))
885       (epg-reset context))))
886
887 ;;;###autoload
888 (defun epg-start-verify (context signature &optional signed-text)
889   "Initiate a verify operation on SIGNATURE.
890 SIGNATURE and SIGNED-TEXT are a data object if they are specified.
891
892 For a detached signature, both SIGNATURE and SIGNED-TEXT should be set.
893 For a normal or a clear text signature, SIGNED-TEXT should be nil.
894
895 If you use this function, you will need to wait for the completion of
896 `epg-gpg-program' by using `epg-wait-for-completion' and call
897 `epg-reset' to clear a temporaly output file.
898 If you are unsure, use synchronous version of this function
899 `epg-verify-file' or `epg-verify-string' instead."
900   (epg-context-set-result context nil)
901   (if signed-text
902       ;; Detached signature.
903       (if (epg-data-file signed-text)
904           (epg-start context (list "--verify" (epg-data-file signature)
905                                    (epg-data-file signed-text)))
906         (epg-start context (list "--verify" (epg-data-file signature) "-"))
907         (if (eq (process-status (epg-context-process context)) 'run)
908             (process-send-string (epg-context-process context)
909                                  (epg-data-string signed-text))))
910     ;; Normal (or cleartext) signature.
911     (if (epg-data-file signature)
912         (epg-start context (list "--verify" (epg-data-file signature)))
913       (epg-start context (list "--verify"))
914       (if (eq (process-status (epg-context-process context)) 'run)
915           (process-send-string (epg-context-process context)
916                                (epg-data-string signature))))))
917
918 ;;;###autoload
919 (defun epg-verify-file (context signature &optional signed-text plain)
920   "Verify a file SIGNATURE.
921 SIGNED-TEXT and PLAIN are also a file if they are specified.
922
923 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
924 For a normal or a clear text signature, SIGNED-TEXT should be nil."
925   (unwind-protect
926       (progn
927         (if plain
928             (epg-context-set-output-file context plain)
929           (epg-context-set-output-file context
930                                        (epg-make-temp-file "epg-output")))
931         (if signed-text
932             (epg-start-verify context
933                               (epg-make-data-from-file signature)
934                               (epg-make-data-from-file signed-text))
935           (epg-start-verify context
936                             (epg-make-data-from-file signature)))
937         (epg-wait-for-completion context)
938         (unless plain
939           (epg-read-output context)))
940     (unless plain
941       (epg-delete-output-file context))
942     (epg-reset context)))
943
944 ;;;###autoload
945 (defun epg-verify-string (context signature &optional signed-text)
946   "Verify a string SIGNATURE.
947 SIGNED-TEXT is a string if it is specified.
948
949 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
950 For a normal or a clear text signature, SIGNED-TEXT should be nil."
951   (let ((coding-system-for-write 'binary)
952         input-file)
953     (unwind-protect
954         (progn
955           (epg-context-set-output-file context
956                                        (epg-make-temp-file "epg-output"))
957           (if signed-text
958               (progn
959                 (setq input-file (epg-make-temp-file "epg-signature"))
960                 (write-region signature nil input-file)
961                 (epg-start-verify context
962                                   (epg-make-data-from-file input-file)
963                                   (epg-make-data-from-string signed-text)))
964             (epg-start-verify context (epg-make-data-from-string signature)))
965           (epg-wait-for-completion context)
966           (epg-read-output context))
967       (epg-delete-output-file context)
968       (if (and input-file
969                (file-exists-p input-file))
970           (delete-file input-file))
971       (epg-reset context))))
972
973 ;;;###autoload
974 (defun epg-start-sign (context plain &optional mode)
975   "Initiate a sign operation on PLAIN.
976 PLAIN is a data object.
977
978 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
979 If MODE is t or 'detached, it makes a detached signature.
980 Otherwise, it makes a normal signature.
981
982 If you use this function, you will need to wait for the completion of
983 `epg-gpg-program' by using `epg-wait-for-completion' and call
984 `epg-reset' to clear a temporaly output file.
985 If you are unsure, use synchronous version of this function
986 `epg-sign-file' or `epg-sign-string' instead."
987   (epg-context-set-result context nil)
988   (epg-start context
989              (append (list (if (eq mode 'clearsign)
990                                "--clearsign"
991                              (if (or (eq mode t) (eq mode 'detached))
992                                  "--detach-sign"
993                                "--sign")))
994                      (apply #'nconc
995                             (mapcar (lambda (signer)
996                                       (list "-u" signer))
997                                     (epg-context-signers context)))
998                      (if (epg-data-file plain)
999                          (list (epg-data-file plain)))))
1000   (epg-wait-for-status context '("BEGIN_SIGNING"))
1001   (if (and (epg-data-string plain)
1002            (eq (process-status (epg-context-process context)) 'run))
1003       (process-send-string (epg-context-process context)
1004                            (epg-data-string plain))))
1005
1006 ;;;###autoload
1007 (defun epg-sign-file (context plain signature &optional mode)
1008   "Sign a file PLAIN and store the result to a file SIGNATURE.
1009 If SIGNATURE is nil, it returns the result as a string.
1010 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
1011 If MODE is t or 'detached, it makes a detached signature.
1012 Otherwise, it makes a normal signature."
1013   (unwind-protect
1014       (progn
1015         (if signature
1016             (epg-context-set-output-file context signature)
1017           (epg-context-set-output-file context
1018                                        (epg-make-temp-file "epg-output")))
1019         (epg-start-sign context (epg-make-data-from-file plain) mode)
1020         (epg-wait-for-completion context)
1021         (if (epg-context-result-for context 'error)
1022             (error "Sign failed: %S"
1023                    (epg-context-result-for context 'error)))
1024         (unless signature
1025           (epg-read-output context)))
1026     (unless signature
1027       (epg-delete-output-file context))
1028     (epg-reset context)))
1029
1030 ;;;###autoload
1031 (defun epg-sign-string (context plain &optional mode)
1032   "Sign a string PLAIN and return the output as string.
1033 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
1034 If MODE is t or 'detached, it makes a detached signature.
1035 Otherwise, it makes a normal signature."
1036   (unwind-protect
1037       (progn
1038         (epg-context-set-output-file context
1039                                      (epg-make-temp-file "epg-output"))
1040         (epg-start-sign context (epg-make-data-from-string plain) mode)
1041         (epg-wait-for-completion context)
1042         (if (epg-context-result-for context 'error)
1043             (error "Sign failed: %S"
1044                    (epg-context-result-for context 'error)))
1045         (epg-read-output context))
1046     (epg-delete-output-file context)
1047     (epg-reset context)))
1048
1049 ;;;###autoload
1050 (defun epg-start-encrypt (context plain recipients
1051                                   &optional sign always-trust)
1052   "Initiate an encrypt operation on PLAIN.
1053 PLAIN is a data object.
1054 If RECIPIENTS is nil, it performs symmetric encryption.
1055
1056 If you use this function, you will need to wait for the completion of
1057 `epg-gpg-program' by using `epg-wait-for-completion' and call
1058 `epg-reset' to clear a temporaly output file.
1059 If you are unsure, use synchronous version of this function
1060 `epg-encrypt-file' or `epg-encrypt-string' instead."
1061   (epg-context-set-result context nil)
1062   (epg-start context
1063              (append (if always-trust '("--always-trust"))
1064                      (if recipients '("--encrypt") '("--symmetric"))
1065                      (if sign
1066                          (cons "--sign"
1067                                (apply #'nconc
1068                                       (mapcar (lambda (signer)
1069                                                 (list "-u" signer))
1070                                               (epg-context-signers context)))))
1071                      (apply #'nconc
1072                             (mapcar (lambda (recipient)
1073                                       (list "-r" recipient))
1074                                     recipients))
1075                      (if (epg-data-file plain)
1076                          (list (epg-data-file plain)))))
1077   (if sign
1078       (epg-wait-for-status context '("BEGIN_SIGNING"))
1079     (if (null recipients)
1080         (epg-wait-for-status context '("BEGIN_ENCRYPTION"))))
1081   (if (and (epg-data-string plain)
1082            (eq (process-status (epg-context-process context)) 'run))
1083       (process-send-string (epg-context-process context)
1084                            (epg-data-string plain))))
1085
1086 ;;;###autoload
1087 (defun epg-encrypt-file (context plain recipients
1088                                  cipher &optional sign always-trust)
1089   "Encrypt a file PLAIN and store the result to a file CIPHER.
1090 If CIPHER is nil, it returns the result as a string.
1091 If RECIPIENTS is nil, it performs symmetric encryption."
1092   (unwind-protect
1093       (progn
1094         (if cipher
1095             (epg-context-set-output-file context cipher)
1096           (epg-context-set-output-file context
1097                                        (epg-make-temp-file "epg-output")))
1098         (epg-start-encrypt context (epg-make-data-from-file plain)
1099                            recipients sign always-trust)
1100         (epg-wait-for-completion context)
1101         (if (epg-context-result-for context 'error)
1102             (error "Encrypt failed: %S"
1103                    (epg-context-result-for context 'error)))
1104         (unless cipher
1105           (epg-read-output context)))
1106     (unless cipher
1107       (epg-delete-output-file context))
1108     (epg-reset context)))
1109
1110 ;;;###autoload
1111 (defun epg-encrypt-string (context plain recipients
1112                                    &optional sign always-trust)
1113   "Encrypt a string PLAIN.
1114 If RECIPIENTS is nil, it performs symmetric encryption."
1115   (unwind-protect
1116       (progn
1117         (epg-context-set-output-file context
1118                                      (epg-make-temp-file "epg-output"))
1119         (epg-start-encrypt context (epg-make-data-from-string plain)
1120                            recipients sign always-trust)
1121         (epg-wait-for-completion context)
1122         (if (epg-context-result-for context 'error)
1123             (error "Encrypt failed: %S"
1124                    (epg-context-result-for context 'error)))
1125         (epg-read-output context))
1126     (epg-delete-output-file context)
1127     (epg-reset context)))
1128
1129 ;;;###autoload
1130 (defun epg-start-export-keys (context pattern)
1131   "Initiate an export keys operation.
1132
1133 If you use this function, you will need to wait for the completion of
1134 `epg-gpg-program' by using `epg-wait-for-completion' and call
1135 `epg-reset' to clear a temporaly output file.
1136 If you are unsure, use synchronous version of this function
1137 `epg-export-keys' instead."
1138   (epg-context-set-result context nil)
1139   (epg-context-set-output-file context (epg-make-temp-file "epg-output"))
1140   (epg-start context (list "--export" pattern)))
1141
1142 ;;;###autoload
1143 (defun epg-export-keys (context pattern)
1144   "Extract public keys matched with PATTERN and return them."
1145   (unwind-protect
1146       (progn
1147         (epg-start-export-keys context pattern)
1148         (epg-wait-for-completion context)
1149         (if (epg-context-result-for context 'error)
1150             (error "Export keys failed"))
1151         (epg-read-output context))
1152     (epg-reset context)))
1153
1154 ;;;###autoload
1155 (defun epg-start-import-keys (context keys)
1156   "Initiate an import keys operation.
1157 KEYS is a data object.
1158
1159 If you use this function, you will need to wait for the completion of
1160 `epg-gpg-program' by using `epg-wait-for-completion' and call
1161 `epg-reset' to clear a temporaly output file.
1162 If you are unsure, use synchronous version of this function
1163 `epg-import-keys-from-file' or `epg-import-keys-from-string' instead."
1164   (epg-context-set-result context nil)
1165   (epg-context-set-output-file context (epg-make-temp-file "epg-output"))
1166   (epg-start context (append (list "--import") (epg-data-file keys)))
1167   (if (and (epg-data-string keys)
1168            (eq (process-status (epg-context-process context)) 'run))
1169       (process-send-string (epg-context-process context)
1170                            (epg-data-string keys))))
1171   
1172 (defun epg-import-keys-1 (context keys)
1173   (unwind-protect
1174       (progn
1175         (epg-start-import-keys context keys)
1176         (epg-wait-for-completion context)
1177         (if (epg-context-result-for context 'error)
1178             (error "Import keys failed"))
1179         (epg-read-output context))
1180     (epg-reset context)))
1181
1182 ;;;###autoload
1183 (defun epg-import-keys-from-file (context keys)
1184   "Add keys from a file KEYS."
1185   (epg-import-keys-1 context (epg-make-data-from-file keys)))
1186
1187 ;;;###autoload
1188 (defun epg-import-keys-from-string (context keys)
1189   "Add keys from a string KEYS."
1190   (epg-import-keys-1 context (epg-make-data-from-string keys)))
1191
1192 (provide 'epg)
1193
1194 ;;; epg.el ends here