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