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 (list 'invalid-recipient
662                    (string-to-number (match-string 1 string))
663                    (match-string 2 string))
664              (epg-context-result-for epg-context 'error)))))
665
666 (defun epg-status-NO_RECP (process string)
667   (epg-context-set-result-for
668    epg-context 'error
669    (cons 'no-recipients
670          (epg-context-result-for epg-context 'error))))
671
672 (defun epg-passphrase-callback-function (key-id handback)
673   (read-passwd
674    (if (eq key-id 'SYM)
675        "Passphrase for symmetric encryption: "
676      (if (eq key-id 'PIN)
677          "Passphrase for PIN: "
678        (let ((entry (assoc key-id epg-user-id-alist)))
679          (if entry
680              (format "Passphrase for %s %s: " key-id (cdr entry))
681            (format "Passphrase for %s: " key-id)))))))
682
683 (defun epg-progress-callback-function (what char current total handback)
684   (message "%s: %d%%/%d%%" what current total))
685
686 (defun epg-configuration ()
687   "Return a list of internal configuration parameters of `epg-gpg-program'."
688   (let (config type)
689     (with-temp-buffer
690       (apply #'call-process epg-gpg-program nil (list t nil) nil
691              '("--with-colons" "--list-config"))
692       (goto-char (point-min))
693       (while (re-search-forward "^cfg:\\([^:]+\\):\\(.*\\)" nil t)
694         (setq type (intern (match-string 1))
695               config (cons (cons type
696                                  (if (memq type
697                                            '(pubkey cipher digest compress))
698                                      (mapcar #'string-to-number
699                                              (delete "" (split-string
700                                                          (match-string 2)
701                                                          ";")))
702                                    (match-string 2)))
703                            config))))
704     config))
705
706 (defun epg-list-keys-1 (name mode)
707   (let ((args (append (list "--with-colons" "--no-greeting" "--batch"
708                             "--fixed-list-mode" "--with-fingerprint"
709                             "--with-fingerprint"
710                             (if mode "--list-secret-keys" "--list-keys"))
711                       (if name (list name))))
712         keys string field index)
713     (with-temp-buffer
714       (apply #'call-process epg-gpg-program nil (list t nil) nil args)
715       (goto-char (point-min))
716       (while (re-search-forward "^[a-z][a-z][a-z]:.*" nil t)
717         (setq keys (cons (make-vector 15 nil) keys)
718               string (match-string 0)
719               index 0
720               field 0)
721         (while (eq index
722                    (string-match "\\([^:]+\\)?:" string index))
723           (setq index (match-end 0))
724           (aset (car keys) field (match-string 1 string))
725           (setq field (1+ field))))
726       (nreverse keys))))
727
728 (defun epg-make-sub-key-1 (line)
729   (epg-make-sub-key
730    (cdr (assq (string-to-char (aref line 1)) epg-key-validity-alist))
731    (delq nil
732          (mapcar (lambda (char) (cdr (assq char epg-key-capablity-alist)))
733                  (aref line 11)))
734    (member (aref line 0) '("sec" "ssb"))
735    (string-to-number (aref line 3))
736    (string-to-number (aref line 2))
737    (aref line 4)
738    (aref line 5)
739    (aref line 6)))
740
741 (defun epg-list-keys (&optional name mode)
742   (let ((lines (epg-list-keys-1 name mode))
743         keys)
744     (while lines
745       (cond
746        ((member (aref (car lines) 0) '("pub" "sec"))
747         (when (car keys)
748           (epg-key-set-sub-key-list
749            (car keys)
750            (nreverse (epg-key-sub-key-list (car keys))))
751           (epg-key-set-user-id-list
752            (car keys)
753            (nreverse (epg-key-user-id-list (car keys)))))
754         (setq keys (cons (epg-make-key
755                           (cdr (assq (string-to-char (aref (car lines) 8))
756                                      epg-key-validity-alist)))
757                          keys))
758         (epg-key-set-sub-key-list
759          (car keys)
760          (cons (epg-make-sub-key-1 (car lines))
761                (epg-key-sub-key-list (car keys)))))
762        ((member (aref (car lines) 0) '("sub" "ssb"))
763         (epg-key-set-sub-key-list
764          (car keys)
765          (cons (epg-make-sub-key-1 (car lines))
766                (epg-key-sub-key-list (car keys)))))
767        ((equal (aref (car lines) 0) "uid")
768         (epg-key-set-user-id-list
769          (car keys)
770          (cons (epg-make-user-id
771                 (cdr (assq (string-to-char (aref (car lines) 1))
772                            epg-key-validity-alist))
773                 (aref (car lines) 9))
774                (epg-key-user-id-list (car keys)))))
775        ((equal (aref (car lines) 0) "fpr")
776         (epg-sub-key-set-fingerprint (car (epg-key-sub-key-list (car keys)))
777                                      (aref (car lines) 9))))
778       (setq lines (cdr lines)))
779     (nreverse keys)))
780
781 (if (fboundp 'make-temp-file)
782     (defalias 'epg-make-temp-file 'make-temp-file)
783   ;; stolen from poe.el.
784   (defun epg-make-temp-file (prefix)
785     "Create a temporary file.
786 The returned file name (created by appending some random characters at the end
787 of PREFIX, and expanding against `temporary-file-directory' if necessary),
788 is guaranteed to point to a newly created empty file.
789 You can then use `write-region' to write new data into the file."
790     (let (tempdir tempfile)
791       (unwind-protect
792           (let (file)
793             ;; First, create a temporary directory.
794             (while (condition-case ()
795                        (progn
796                          (setq tempdir (make-temp-name
797                                         (concat
798                                          (file-name-directory prefix)
799                                          "DIR")))
800                          ;; return nil or signal an error.
801                          (make-directory tempdir))
802                      ;; let's try again.
803                      (file-already-exists t)))
804             (set-file-modes tempdir 448)
805             ;; Second, create a temporary file in the tempdir.
806             ;; There *is* a race condition between `make-temp-name'
807             ;; and `write-region', but we don't care it since we are
808             ;; in a private directory now.
809             (setq tempfile (make-temp-name (concat tempdir "/EMU")))
810             (write-region "" nil tempfile nil 'silent)
811             (set-file-modes tempfile 384)
812             ;; Finally, make a hard-link from the tempfile.
813             (while (condition-case ()
814                        (progn
815                          (setq file (make-temp-name prefix))
816                          ;; return nil or signal an error.
817                          (add-name-to-file tempfile file))
818                      ;; let's try again.
819                      (file-already-exists t)))
820             file)
821         ;; Cleanup the tempfile.
822         (and tempfile
823              (file-exists-p tempfile)
824              (delete-file tempfile))
825         ;; Cleanup the tempdir.
826         (and tempdir
827              (file-directory-p tempdir)
828              (delete-directory tempdir))))))
829
830 ;;;###autoload
831 (defun epg-start-decrypt (context cipher)
832   "Initiate a decrypt operation on CIPHER.
833 CIPHER is a data object.
834
835 If you use this function, you will need to wait for the completion of
836 `epg-gpg-program' by using `epg-wait-for-completion' and call
837 `epg-reset' to clear a temporaly output file.
838 If you are unsure, use synchronous version of this function
839 `epg-decrypt-file' or `epg-decrypt-string' instead."
840   (unless (epg-data-file cipher)
841     (error "Not a file"))
842   (epg-context-set-result context nil)
843   (epg-start context (list "--decrypt" (epg-data-file cipher)))
844   (epg-wait-for-status context '("BEGIN_DECRYPTION")))
845
846 ;;;###autoload
847 (defun epg-decrypt-file (context cipher plain)
848   "Decrypt a file CIPHER and store the result to a file PLAIN.
849 If PLAIN is nil, it returns the result as a string."
850   (unwind-protect
851       (progn
852         (if plain
853             (epg-context-set-output-file context plain)
854           (epg-context-set-output-file context
855                                        (epg-make-temp-file "epg-output")))
856         (epg-start-decrypt context (epg-make-data-from-file cipher))
857         (epg-wait-for-completion context)
858         (if (epg-context-result-for context 'error)
859             (error "Decrypt failed: %S"
860                    (epg-context-result-for context 'error)))
861         (unless plain
862           (epg-read-output context)))
863     (unless plain
864       (epg-delete-output-file context))
865     (epg-reset context)))
866
867 ;;;###autoload
868 (defun epg-decrypt-string (context cipher)
869   "Decrypt a string CIPHER and return the plain text."
870   (let ((input-file (epg-make-temp-file "epg-input"))
871         (coding-system-for-write 'binary))
872     (unwind-protect
873         (progn
874           (write-region cipher nil input-file)
875           (epg-context-set-output-file context
876                                        (epg-make-temp-file "epg-output"))
877           (epg-start-decrypt context (epg-make-data-from-file input-file))
878           (epg-wait-for-completion context)
879           (if (epg-context-result-for context 'error)
880               (error "Decrypt failed: %S"
881                      (epg-context-result-for context 'error)))
882           (epg-read-output context))
883       (epg-delete-output-file context)
884       (if (file-exists-p input-file)
885           (delete-file input-file))
886       (epg-reset context))))
887
888 ;;;###autoload
889 (defun epg-start-verify (context signature &optional signed-text)
890   "Initiate a verify operation on SIGNATURE.
891 SIGNATURE and SIGNED-TEXT are a data object if they are specified.
892
893 For a detached signature, both SIGNATURE and SIGNED-TEXT should be set.
894 For a normal or a clear text signature, SIGNED-TEXT should be nil.
895
896 If you use this function, you will need to wait for the completion of
897 `epg-gpg-program' by using `epg-wait-for-completion' and call
898 `epg-reset' to clear a temporaly output file.
899 If you are unsure, use synchronous version of this function
900 `epg-verify-file' or `epg-verify-string' instead."
901   (epg-context-set-result context nil)
902   (if signed-text
903       ;; Detached signature.
904       (if (epg-data-file signed-text)
905           (epg-start context (list "--verify" (epg-data-file signature)
906                                    (epg-data-file signed-text)))
907         (epg-start context (list "--verify" (epg-data-file signature) "-"))
908         (if (eq (process-status (epg-context-process context)) 'run)
909             (process-send-string (epg-context-process context)
910                                  (epg-data-string signed-text))))
911     ;; Normal (or cleartext) signature.
912     (if (epg-data-file signature)
913         (epg-start context (list "--verify" (epg-data-file signature)))
914       (epg-start context (list "--verify"))
915       (if (eq (process-status (epg-context-process context)) 'run)
916           (process-send-string (epg-context-process context)
917                                (epg-data-string signature))))))
918
919 ;;;###autoload
920 (defun epg-verify-file (context signature &optional signed-text plain)
921   "Verify a file SIGNATURE.
922 SIGNED-TEXT and PLAIN are also a file if they are specified.
923
924 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
925 For a normal or a clear text signature, SIGNED-TEXT should be nil."
926   (unwind-protect
927       (progn
928         (if plain
929             (epg-context-set-output-file context plain)
930           (epg-context-set-output-file context
931                                        (epg-make-temp-file "epg-output")))
932         (if signed-text
933             (epg-start-verify context
934                               (epg-make-data-from-file signature)
935                               (epg-make-data-from-file signed-text))
936           (epg-start-verify context
937                             (epg-make-data-from-file signature)))
938         (epg-wait-for-completion context)
939         (unless plain
940           (epg-read-output context)))
941     (unless plain
942       (epg-delete-output-file context))
943     (epg-reset context)))
944
945 ;;;###autoload
946 (defun epg-verify-string (context signature &optional signed-text)
947   "Verify a string SIGNATURE.
948 SIGNED-TEXT is a string if it is specified.
949
950 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
951 For a normal or a clear text signature, SIGNED-TEXT should be nil."
952   (let ((coding-system-for-write 'binary)
953         input-file)
954     (unwind-protect
955         (progn
956           (epg-context-set-output-file context
957                                        (epg-make-temp-file "epg-output"))
958           (if signed-text
959               (progn
960                 (setq input-file (epg-make-temp-file "epg-signature"))
961                 (write-region signature nil input-file)
962                 (epg-start-verify context
963                                   (epg-make-data-from-file input-file)
964                                   (epg-make-data-from-string signed-text)))
965             (epg-start-verify context (epg-make-data-from-string signature)))
966           (epg-wait-for-completion context)
967           (epg-read-output context))
968       (epg-delete-output-file context)
969       (if (and input-file
970                (file-exists-p input-file))
971           (delete-file input-file))
972       (epg-reset context))))
973
974 ;;;###autoload
975 (defun epg-start-sign (context plain &optional mode)
976   "Initiate a sign operation on PLAIN.
977 PLAIN is a data object.
978
979 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
980 If MODE is t or 'detached, it makes a detached signature.
981 Otherwise, it makes a normal signature.
982
983 If you use this function, you will need to wait for the completion of
984 `epg-gpg-program' by using `epg-wait-for-completion' and call
985 `epg-reset' to clear a temporaly output file.
986 If you are unsure, use synchronous version of this function
987 `epg-sign-file' or `epg-sign-string' instead."
988   (epg-context-set-result context nil)
989   (epg-start context
990              (append (list (if (eq mode 'clearsign)
991                                "--clearsign"
992                              (if (or (eq mode t) (eq mode 'detached))
993                                  "--detach-sign"
994                                "--sign")))
995                      (apply #'nconc
996                             (mapcar (lambda (signer)
997                                       (list "-u" signer))
998                                     (epg-context-signers context)))
999                      (if (epg-data-file plain)
1000                          (list (epg-data-file plain)))))
1001   (epg-wait-for-status context '("BEGIN_SIGNING"))
1002   (if (and (epg-data-string plain)
1003            (eq (process-status (epg-context-process context)) 'run))
1004       (process-send-string (epg-context-process context)
1005                            (epg-data-string plain))))
1006
1007 ;;;###autoload
1008 (defun epg-sign-file (context plain signature &optional mode)
1009   "Sign a file PLAIN and store the result to a file SIGNATURE.
1010 If SIGNATURE is nil, it returns the result as a string.
1011 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
1012 If MODE is t or 'detached, it makes a detached signature.
1013 Otherwise, it makes a normal signature."
1014   (unwind-protect
1015       (progn
1016         (if signature
1017             (epg-context-set-output-file context signature)
1018           (epg-context-set-output-file context
1019                                        (epg-make-temp-file "epg-output")))
1020         (epg-start-sign context (epg-make-data-from-file plain) mode)
1021         (epg-wait-for-completion context)
1022         (if (epg-context-result-for context 'error)
1023             (error "Sign failed: %S"
1024                    (epg-context-result-for context 'error)))
1025         (unless signature
1026           (epg-read-output context)))
1027     (unless signature
1028       (epg-delete-output-file context))
1029     (epg-reset context)))
1030
1031 ;;;###autoload
1032 (defun epg-sign-string (context plain &optional mode)
1033   "Sign a string PLAIN and return the output as string.
1034 If optional 3rd argument MODE is 'clearsign, it makes a clear text signature.
1035 If MODE is t or 'detached, it makes a detached signature.
1036 Otherwise, it makes a normal signature."
1037   (unwind-protect
1038       (progn
1039         (epg-context-set-output-file context
1040                                      (epg-make-temp-file "epg-output"))
1041         (epg-start-sign context (epg-make-data-from-string plain) mode)
1042         (epg-wait-for-completion context)
1043         (if (epg-context-result-for context 'error)
1044             (error "Sign failed: %S"
1045                    (epg-context-result-for context 'error)))
1046         (epg-read-output context))
1047     (epg-delete-output-file context)
1048     (epg-reset context)))
1049
1050 ;;;###autoload
1051 (defun epg-start-encrypt (context plain recipients
1052                                   &optional sign always-trust)
1053   "Initiate an encrypt operation on PLAIN.
1054 PLAIN is a data object.
1055 If RECIPIENTS is nil, it performs symmetric encryption.
1056
1057 If you use this function, you will need to wait for the completion of
1058 `epg-gpg-program' by using `epg-wait-for-completion' and call
1059 `epg-reset' to clear a temporaly output file.
1060 If you are unsure, use synchronous version of this function
1061 `epg-encrypt-file' or `epg-encrypt-string' instead."
1062   (epg-context-set-result context nil)
1063   (epg-start context
1064              (append (if always-trust '("--always-trust"))
1065                      (if recipients '("--encrypt") '("--symmetric"))
1066                      (if sign
1067                          (cons "--sign"
1068                                (apply #'nconc
1069                                       (mapcar (lambda (signer)
1070                                                 (list "-u" signer))
1071                                               (epg-context-signers context)))))
1072                      (apply #'nconc
1073                             (mapcar (lambda (recipient)
1074                                       (list "-r" recipient))
1075                                     recipients))
1076                      (if (epg-data-file plain)
1077                          (list (epg-data-file plain)))))
1078   (if sign
1079       (epg-wait-for-status context '("BEGIN_SIGNING"))
1080     (if (null recipients)
1081         (epg-wait-for-status context '("BEGIN_ENCRYPTION"))))
1082   (if (and (epg-data-string plain)
1083            (eq (process-status (epg-context-process context)) 'run))
1084       (process-send-string (epg-context-process context)
1085                            (epg-data-string plain))))
1086
1087 ;;;###autoload
1088 (defun epg-encrypt-file (context plain recipients
1089                                  cipher &optional sign always-trust)
1090   "Encrypt a file PLAIN and store the result to a file CIPHER.
1091 If CIPHER is nil, it returns the result as a string.
1092 If RECIPIENTS is nil, it performs symmetric encryption."
1093   (unwind-protect
1094       (progn
1095         (if cipher
1096             (epg-context-set-output-file context cipher)
1097           (epg-context-set-output-file context
1098                                        (epg-make-temp-file "epg-output")))
1099         (epg-start-encrypt context (epg-make-data-from-file plain)
1100                            recipients sign always-trust)
1101         (epg-wait-for-completion context)
1102         (if (epg-context-result-for context 'error)
1103             (error "Encrypt failed: %S"
1104                    (epg-context-result-for context 'error)))
1105         (unless cipher
1106           (epg-read-output context)))
1107     (unless cipher
1108       (epg-delete-output-file context))
1109     (epg-reset context)))
1110
1111 ;;;###autoload
1112 (defun epg-encrypt-string (context plain recipients
1113                                    &optional sign always-trust)
1114   "Encrypt a string PLAIN.
1115 If RECIPIENTS is nil, it performs symmetric encryption."
1116   (unwind-protect
1117       (progn
1118         (epg-context-set-output-file context
1119                                      (epg-make-temp-file "epg-output"))
1120         (epg-start-encrypt context (epg-make-data-from-string plain)
1121                            recipients sign always-trust)
1122         (epg-wait-for-completion context)
1123         (if (epg-context-result-for context 'error)
1124             (error "Encrypt failed: %S"
1125                    (epg-context-result-for context 'error)))
1126         (epg-read-output context))
1127     (epg-delete-output-file context)
1128     (epg-reset context)))
1129
1130 ;;;###autoload
1131 (defun epg-start-export-keys (context pattern)
1132   "Initiate an export keys operation.
1133
1134 If you use this function, you will need to wait for the completion of
1135 `epg-gpg-program' by using `epg-wait-for-completion' and call
1136 `epg-reset' to clear a temporaly output file.
1137 If you are unsure, use synchronous version of this function
1138 `epg-export-keys' instead."
1139   (epg-context-set-result context nil)
1140   (epg-context-set-output-file context (epg-make-temp-file "epg-output"))
1141   (epg-start context (list "--export" pattern)))
1142
1143 ;;;###autoload
1144 (defun epg-export-keys (context pattern)
1145   "Extract public keys matched with PATTERN and return them."
1146   (unwind-protect
1147       (progn
1148         (epg-start-export-keys context pattern)
1149         (epg-wait-for-completion context)
1150         (if (epg-context-result-for context 'error)
1151             (error "Export keys failed"))
1152         (epg-read-output context))
1153     (epg-reset context)))
1154
1155 ;;;###autoload
1156 (defun epg-start-import-keys (context keys)
1157   "Initiate an import keys operation.
1158 KEYS is a data object.
1159
1160 If you use this function, you will need to wait for the completion of
1161 `epg-gpg-program' by using `epg-wait-for-completion' and call
1162 `epg-reset' to clear a temporaly output file.
1163 If you are unsure, use synchronous version of this function
1164 `epg-import-keys-from-file' or `epg-import-keys-from-string' instead."
1165   (epg-context-set-result context nil)
1166   (epg-context-set-output-file context (epg-make-temp-file "epg-output"))
1167   (epg-start context (append (list "--import") (epg-data-file keys)))
1168   (if (and (epg-data-string keys)
1169            (eq (process-status (epg-context-process context)) 'run))
1170       (process-send-string (epg-context-process context)
1171                            (epg-data-string keys))))
1172   
1173 (defun epg-import-keys-1 (context keys)
1174   (unwind-protect
1175       (progn
1176         (epg-start-import-keys context keys)
1177         (epg-wait-for-completion context)
1178         (if (epg-context-result-for context 'error)
1179             (error "Import keys failed"))
1180         (epg-read-output context))
1181     (epg-reset context)))
1182
1183 ;;;###autoload
1184 (defun epg-import-keys-from-file (context keys)
1185   "Add keys from a file KEYS."
1186   (epg-import-keys-1 context (epg-make-data-from-file keys)))
1187
1188 ;;;###autoload
1189 (defun epg-import-keys-from-string (context keys)
1190   "Add keys from a string KEYS."
1191   (epg-import-keys-1 context (epg-make-data-from-string keys)))
1192
1193 (provide 'epg)
1194
1195 ;;; epg.el ends here