Fixed.
[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   :group 'emacs)
31
32 (defcustom epg-gpg-program "gpg"
33   "The `gpg' executable."
34   :group 'epg
35   :type 'string)
36
37 (defcustom epg-gpgsm-program "gpgsm"
38   "The `gpgsm' executable."
39   :group 'epg
40   :type 'string)
41
42 (defconst epg-version-number "0.0.4")
43
44 (defvar epg-user-id nil
45   "GnuPG ID of your default identity.")
46
47 (defvar epg-user-id-alist nil
48   "An alist mapping from key ID to user ID.")
49
50 (defvar epg-read-point nil)
51 (defvar epg-process-filter-running nil)
52 (defvar epg-pending-status-list nil)
53 (defvar epg-key-id nil)
54 (defvar epg-context nil)
55 (defvar epg-debug nil)
56 (defvar epg-debug-buffer nil)
57
58 ;; from gnupg/include/cipher.h
59 (defconst epg-cipher-algorithm-alist
60   '((0 . "NONE")
61     (1 . "IDEA")
62     (2 . "3DES")
63     (3 . "CAST5")
64     (4 . "BLOWFISH")
65     (7 . "AES")
66     (8 . "AES192")
67     (9 . "AES256")
68     (10 . "TWOFISH")
69     (110 . "DUMMY")))
70
71 ;; from gnupg/include/cipher.h
72 (defconst epg-pubkey-algorithm-alist
73   '((1 . "RSA")
74     (2 . "RSA_E")
75     (3 . "RSA_S")
76     (16 . "ELGAMAL_E")
77     (17 . "DSA")
78     (20 . "ELGAMAL")))
79
80 ;; from gnupg/include/cipher.h
81 (defconst epg-digest-algorithm-alist
82   '((1 . "MD5")
83     (2 . "SHA1")
84     (3 . "RMD160")
85     (8 . "SHA256")
86     (9 . "SHA384")
87     (10 . "SHA512")))
88
89 ;; from gnupg/include/cipher.h
90 (defconst epg-compress-algorithm-alist
91   '((0 . "NONE")
92     (1 . "ZIP")
93     (2 . "ZLIB")
94     (3 . "BZIP2")))
95
96 (defconst epg-invalid-recipients-reason-alist
97   '((0 . "No specific reason given")
98     (1 . "Not Found")
99     (2 . "Ambigious specification")
100     (3 . "Wrong key usage")
101     (4 . "Key revoked")
102     (5 . "Key expired")
103     (6 . "No CRL known")
104     (7 . "CRL too old")
105     (8 . "Policy mismatch")
106     (9 . "Not a secret key")
107     (10 . "Key not trusted")))
108
109 (defconst epg-delete-problem-reason-alist
110   '((1 . "No such key")
111     (2 . "Must delete secret key first")
112     (3 . "Ambigious specification")))
113
114 (defconst epg-import-ok-reason-alist
115   '((0 . "Not actually changed")
116     (1 . "Entirely new key")
117     (2 . "New user IDs")
118     (4 . "New signatures")
119     (8 . "New subkeys")
120     (16 . "Contains private key")))
121
122 (defconst epg-import-problem-reason-alist
123   '((0 . "No specific reason given")
124     (1 . "Invalid Certificate")
125     (2 . "Issuer Certificate missing")
126     (3 . "Certificate Chain too long")
127     (4 . "Error storing certificate")))
128
129 (defconst epg-no-data-reason-alist
130   '((1 . "No armored data")
131     (2 . "Expected a packet but did not found one")
132     (3 . "Invalid packet found, this may indicate a non OpenPGP message")
133     (4 . "Signature expected but not found")))
134
135 (defconst epg-unexpected-reason-alist nil)
136
137 (defvar epg-key-validity-alist
138   '((?o . unknown)
139     (?i . invalid)
140     (?d . disabled)
141     (?r . revoked)
142     (?e . expired)
143     (?- . none)
144     (?q . undefined)
145     (?n . never)
146     (?m . marginal)
147     (?f . full)
148     (?u . ultimate)))
149
150 (defvar epg-key-capablity-alist
151   '((?e . encrypt)
152     (?s . sign)
153     (?c . certify)
154     (?a . authentication)))
155
156 (defvar epg-new-signature-type-alist
157   '((?D . detached)
158     (?C . clear)
159     (?S . normal)))
160
161 (defvar epg-dn-type-alist
162   '(("1.2.840.113549.1.9.1" . "EMail")
163     ("2.5.4.12" . "T")
164     ("2.5.4.42" . "GN")
165     ("2.5.4.4" . "SN")
166     ("0.2.262.1.10.7.20" . "NameDistinguisher")
167     ("2.5.4.16" . "ADDR")
168     ("2.5.4.15" . "BC")
169     ("2.5.4.13" . "D")
170     ("2.5.4.17" . "PostalCode")
171     ("2.5.4.65" . "Pseudo")
172     ("2.5.4.5" . "SerialNumber")))
173
174 (defvar epg-prompt-alist nil)
175
176 (defun epg-make-data-from-file (file)
177   "Make a data object from FILE."
178   (cons 'epg-data (vector file nil)))
179
180 (defun epg-make-data-from-string (string)
181   "Make a data object from STRING."
182   (cons 'epg-data (vector nil string)))
183
184 (defun epg-data-file (data)
185   "Return the file of DATA."
186   (unless (eq (car data) 'epg-data)
187     (signal 'wrong-type-argument (list 'epg-data-p data)))
188   (aref (cdr data) 0))
189
190 (defun epg-data-string (data)
191   "Return the string of DATA."
192   (unless (eq (car data) 'epg-data)
193     (signal 'wrong-type-argument (list 'epg-data-p data)))
194   (aref (cdr data) 1))
195
196 (defun epg-make-context (&optional protocol armor textmode include-certs
197                                    cipher-algorithm digest-algorithm
198                                    compress-algorithm)
199   "Return a context object."
200   (cons 'epg-context
201         (vector (or protocol 'OpenPGP) armor textmode include-certs
202                 cipher-algorithm digest-algorithm compress-algorithm
203                 #'epg-passphrase-callback-function
204                 #'epg-progress-callback-function
205                 nil nil nil nil nil)))
206
207 (defun epg-context-protocol (context)
208   "Return the protocol used within CONTEXT."
209   (unless (eq (car context) 'epg-context)
210     (signal 'wrong-type-argument (list 'epg-context-p context)))
211   (aref (cdr context) 0))
212
213 (defun epg-context-armor (context)
214   "Return t if the output shouled be ASCII armored in CONTEXT."
215   (unless (eq (car context) 'epg-context)
216     (signal 'wrong-type-argument (list 'epg-context-p context)))
217   (aref (cdr context) 1))
218
219 (defun epg-context-textmode (context)
220   "Return t if canonical text mode should be used in CONTEXT."
221   (unless (eq (car context) 'epg-context)
222     (signal 'wrong-type-argument (list 'epg-context-p context)))
223   (aref (cdr context) 2))
224
225 (defun epg-context-include-certs (context)
226   "Return how many certificates should be included in an S/MIME signed
227 message."
228   (unless (eq (car context) 'epg-context)
229     (signal 'wrong-type-argument (list 'epg-context-p context)))
230   (aref (cdr context) 3))
231
232 (defun epg-context-cipher-algorithm (context)
233   "Return the cipher algorithm in CONTEXT."
234   (unless (eq (car context) 'epg-context)
235     (signal 'wrong-type-argument (list 'epg-context-p context)))
236   (aref (cdr context) 4))
237
238 (defun epg-context-digest-algorithm (context)
239   "Return the digest algorithm in CONTEXT."
240   (unless (eq (car context) 'epg-context)
241     (signal 'wrong-type-argument (list 'epg-context-p context)))
242   (aref (cdr context) 5))
243
244 (defun epg-context-compress-algorithm (context)
245   "Return the compress algorithm in CONTEXT."
246   (unless (eq (car context) 'epg-context)
247     (signal 'wrong-type-argument (list 'epg-context-p context)))
248   (aref (cdr context) 6))
249
250 (defun epg-context-passphrase-callback (context)
251   "Return the function used to query passphrase."
252   (unless (eq (car context) 'epg-context)
253     (signal 'wrong-type-argument (list 'epg-context-p context)))
254   (aref (cdr context) 7))
255
256 (defun epg-context-progress-callback (context)
257   "Return the function which handles progress update."
258   (unless (eq (car context) 'epg-context)
259     (signal 'wrong-type-argument (list 'epg-context-p context)))
260   (aref (cdr context) 8))
261
262 (defun epg-context-signers (context)
263   "Return the list of key-id for singning."
264   (unless (eq (car context) 'epg-context)
265     (signal 'wrong-type-argument (list 'epg-context-p context)))
266   (aref (cdr context) 9))
267
268 (defun epg-context-process (context)
269   "Return the process object of `epg-gpg-program'.
270 This function is for internal use only."
271   (unless (eq (car context) 'epg-context)
272     (signal 'wrong-type-argument (list 'epg-context-p context)))
273   (aref (cdr context) 10))
274
275 (defun epg-context-output-file (context)
276   "Return the output file of `epg-gpg-program'.
277 This function is for internal use only."
278   (unless (eq (car context) 'epg-context)
279     (signal 'wrong-type-argument (list 'epg-context-p context)))
280   (aref (cdr context) 11))
281
282 (defun epg-context-result (context)
283   "Return the result of the previous cryptographic operation."
284   (unless (eq (car context) 'epg-context)
285     (signal 'wrong-type-argument (list 'epg-context-p context)))
286   (aref (cdr context) 12))
287
288 (defun epg-context-operation (context)
289   "Return the name of the current cryptographic operation."
290   (unless (eq (car context) 'epg-context)
291     (signal 'wrong-type-argument (list 'epg-context-p context)))
292   (aref (cdr context) 13))
293
294 (defun epg-context-set-protocol (context protocol)
295   "Set the protocol used within CONTEXT."
296   (unless (eq (car context) 'epg-context)
297     (signal 'wrong-type-argument (list 'epg-context-p context)))
298   (aset (cdr context) 0 protocol))
299
300 (defun epg-context-set-armor (context armor)
301   "Specify if the output shouled be ASCII armored in CONTEXT."
302   (unless (eq (car context) 'epg-context)
303     (signal 'wrong-type-argument (list 'epg-context-p context)))
304   (aset (cdr context) 1 armor))
305
306 (defun epg-context-set-textmode (context textmode)
307   "Specify if canonical text mode should be used in CONTEXT."
308   (unless (eq (car context) 'epg-context)
309     (signal 'wrong-type-argument (list 'epg-context-p context)))
310   (aset (cdr context) 2 textmode))
311
312 (defun epg-context-set-include-certs (context include-certs)
313  "Set how many certificates should be included in an S/MIME signed message."
314   (unless (eq (car context) 'epg-context)
315     (signal 'wrong-type-argument (list 'epg-context-p context)))
316   (aset (cdr context) 3 include-certs))
317
318 (defun epg-context-set-cipher-algorithm (context cipher-algorithm)
319  "Set the cipher algorithm in CONTEXT."
320   (unless (eq (car context) 'epg-context)
321     (signal 'wrong-type-argument (list 'epg-context-p context)))
322   (aset (cdr context) 4 cipher-algorithm))
323
324 (defun epg-context-set-digest-algorithm (context digest-algorithm)
325  "Set the digest algorithm in CONTEXT."
326   (unless (eq (car context) 'epg-context)
327     (signal 'wrong-type-argument (list 'epg-context-p context)))
328   (aset (cdr context) 5 digest-algorithm))
329
330 (defun epg-context-set-compress-algorithm (context compress-algorithm)
331  "Set the compress algorithm in CONTEXT."
332   (unless (eq (car context) 'epg-context)
333     (signal 'wrong-type-argument (list 'epg-context-p context)))
334   (aset (cdr context) 6 compress-algorithm))
335
336 (defun epg-context-set-passphrase-callback (context
337                                                  passphrase-callback)
338   "Set the function used to query passphrase."
339   (unless (eq (car context) 'epg-context)
340     (signal 'wrong-type-argument (list 'epg-context-p context)))
341   (aset (cdr context) 7 passphrase-callback))
342
343 (defun epg-context-set-progress-callback (context progress-callback)
344   "Set the function which handles progress update."
345   (unless (eq (car context) 'epg-context)
346     (signal 'wrong-type-argument (list 'epg-context-p context)))
347   (aset (cdr context) 8 progress-callback))
348
349 (defun epg-context-set-signers (context signers)
350  "Set the list of key-id for singning."
351   (unless (eq (car context) 'epg-context)
352     (signal 'wrong-type-argument (list 'epg-context-p context)))
353   (aset (cdr context) 9 signers))
354
355 (defun epg-context-set-process (context process)
356   "Set the process object of `epg-gpg-program'.
357 This function is for internal use only."
358   (unless (eq (car context) 'epg-context)
359     (signal 'wrong-type-argument (list 'epg-context-p context)))
360   (aset (cdr context) 10 process))
361
362 (defun epg-context-set-output-file (context output-file)
363   "Set the output file of `epg-gpg-program'.
364 This function is for internal use only."
365   (unless (eq (car context) 'epg-context)
366     (signal 'wrong-type-argument (list 'epg-context-p context)))
367   (aset (cdr context) 11 output-file))
368
369 (defun epg-context-set-result (context result)
370   "Set the result of the previous cryptographic operation."
371   (unless (eq (car context) 'epg-context)
372     (signal 'wrong-type-argument (list 'epg-context-p context)))
373   (aset (cdr context) 12 result))
374
375 (defun epg-context-set-operation (context operation)
376   "Set the name of the current cryptographic operation."
377   (unless (eq (car context) 'epg-context)
378     (signal 'wrong-type-argument (list 'epg-context-p context)))
379   (aset (cdr context) 13 operation))
380
381 (defun epg-make-signature (status &optional key-id)
382   "Return a signature object."
383   (cons 'epg-signature (vector status key-id nil nil nil nil nil nil nil nil)))
384
385 (defun epg-signature-status (signature)
386   "Return the status code of SIGNATURE."
387   (unless (eq (car signature) 'epg-signature)
388     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
389   (aref (cdr signature) 0))
390
391 (defun epg-signature-key-id (signature)
392   "Return the key-id of SIGNATURE."
393   (unless (eq (car signature) 'epg-signature)
394     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
395   (aref (cdr signature) 1))
396
397 (defun epg-signature-validity (signature)
398   "Return the validity of SIGNATURE."
399   (unless (eq (car signature) 'epg-signature)
400     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
401   (aref (cdr signature) 2))
402
403 (defun epg-signature-fingerprint (signature)
404   "Return the fingerprint of SIGNATURE."
405   (unless (eq (car signature) 'epg-signature)
406     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
407   (aref (cdr signature) 3))
408
409 (defun epg-signature-creation-time (signature)
410   "Return the creation time of SIGNATURE."
411   (unless (eq (car signature) 'epg-signature)
412     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
413   (aref (cdr signature) 4))
414
415 (defun epg-signature-expiration-time (signature)
416   "Return the expiration time of SIGNATURE."
417   (unless (eq (car signature) 'epg-signature)
418     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
419   (aref (cdr signature) 5))
420
421 (defun epg-signature-pubkey-algorithm (signature)
422   "Return the public key algorithm of SIGNATURE."
423   (unless (eq (car signature) 'epg-signature)
424     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
425   (aref (cdr signature) 6))
426
427 (defun epg-signature-digest-algorithm (signature)
428   "Return the digest algorithm of SIGNATURE."
429   (unless (eq (car signature) 'epg-signature)
430     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
431   (aref (cdr signature) 7))
432
433 (defun epg-signature-class (signature)
434   "Return the class of SIGNATURE."
435   (unless (eq (car signature) 'epg-signature)
436     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
437   (aref (cdr signature) 8))
438
439 (defun epg-signature-version (signature)
440   "Return the version of SIGNATURE."
441   (unless (eq (car signature) 'epg-signature)
442     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
443   (aref (cdr signature) 9))
444
445 (defun epg-signature-set-status (signature status)
446  "Set the status code of SIGNATURE."
447   (unless (eq (car signature) 'epg-signature)
448     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
449   (aset (cdr signature) 0 status))
450
451 (defun epg-signature-set-key-id (signature key-id)
452  "Set the key-id of SIGNATURE."
453   (unless (eq (car signature) 'epg-signature)
454     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
455   (aset (cdr signature) 1 key-id))
456
457 (defun epg-signature-set-validity (signature validity)
458  "Set the validity of SIGNATURE."
459   (unless (eq (car signature) 'epg-signature)
460     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
461   (aset (cdr signature) 2 validity))
462
463 (defun epg-signature-set-fingerprint (signature fingerprint)
464  "Set the fingerprint of SIGNATURE."
465   (unless (eq (car signature) 'epg-signature)
466     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
467   (aset (cdr signature) 3 fingerprint))
468
469 (defun epg-signature-set-creation-time (signature creation-time)
470   "Set the creation time of SIGNATURE."
471   (unless (eq (car signature) 'epg-signature)
472     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
473   (aset (cdr signature) 4 creation-time))
474
475 (defun epg-signature-set-expiration-time (signature expiration-time)
476   "Set the expiration time of SIGNATURE."
477   (unless (eq (car signature) 'epg-signature)
478     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
479   (aset (cdr signature) 5 expiration-time))
480
481 (defun epg-signature-set-pubkey-algorithm (signature pubkey-algorithm)
482   "Set the public key algorithm of SIGNATURE."
483   (unless (eq (car signature) 'epg-signature)
484     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
485   (aset (cdr signature) 6 pubkey-algorithm))
486
487 (defun epg-signature-set-digest-algorithm (signature digest-algorithm)
488   "Set the digest algorithm of SIGNATURE."
489   (unless (eq (car signature) 'epg-signature)
490     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
491   (aset (cdr signature) 7 digest-algorithm))
492
493 (defun epg-signature-set-class (signature class)
494   "Set the class of SIGNATURE."
495   (unless (eq (car signature) 'epg-signature)
496     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
497   (aset (cdr signature) 8 class))
498
499 (defun epg-signature-set-version (signature version)
500   "Set the version of SIGNATURE."
501   (unless (eq (car signature) 'epg-signature)
502     (signal 'wrong-type-argument (list 'epg-signature-p signature)))
503   (aset (cdr signature) 9 version))
504
505 (defun epg-make-new-signature (type pubkey-algorithm digest-algorithm
506                                     class creation-time fingerprint)
507   "Return a new signature object."
508   (cons 'epg-new-signature (vector type pubkey-algorithm digest-algorithm
509                                    class creation-time fingerprint)))
510
511 (defun epg-new-signature-type (new-signature)
512   "Return the type of NEW-SIGNATURE."
513   (unless (eq (car new-signature) 'epg-new-signature)
514     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
515   (aref (cdr new-signature) 0))
516
517 (defun epg-new-signature-pubkey-algorithm (new-signature)
518   "Return the public key algorithm of NEW-SIGNATURE."
519   (unless (eq (car new-signature) 'epg-new-signature)
520     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
521   (aref (cdr new-signature) 1))
522
523 (defun epg-new-signature-digest-algorithm (new-signature)
524   "Return the digest algorithm of NEW-SIGNATURE."
525   (unless (eq (car new-signature) 'epg-new-signature)
526     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
527   (aref (cdr new-signature) 2))
528
529 (defun epg-new-signature-class (new-signature)
530   "Return the class of NEW-SIGNATURE."
531   (unless (eq (car new-signature) 'epg-new-signature)
532     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
533   (aref (cdr new-signature) 3))
534
535 (defun epg-new-signature-creation-time (new-signature)
536   "Return the creation time of NEW-SIGNATURE."
537   (unless (eq (car new-signature) 'epg-new-signature)
538     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
539   (aref (cdr new-signature) 4))
540
541 (defun epg-new-signature-fingerprint (new-signature)
542   "Return the fingerprint of NEW-SIGNATURE."
543   (unless (eq (car new-signature) 'epg-new-signature)
544     (signal 'wrong-type-argument (list 'epg-new-signature-p new-signature)))
545   (aref (cdr new-signature) 5))
546
547 (defun epg-make-key (owner-trust)
548   "Return a key object."
549   (cons 'epg-key (vector owner-trust nil nil)))
550
551 (defun epg-key-owner-trust (key)
552   "Return the owner trust of KEY."
553   (unless (eq (car key) 'epg-key)
554     (signal 'wrong-type-argument (list 'epg-key-p key)))
555   (aref (cdr key) 0))
556
557 (defun epg-key-sub-key-list (key)
558   "Return the sub key list of KEY."
559   (unless (eq (car key) 'epg-key)
560     (signal 'wrong-type-argument (list 'epg-key-p key)))
561   (aref (cdr key) 1))
562
563 (defun epg-key-user-id-list (key)
564   "Return the user ID list of KEY."
565   (unless (eq (car key) 'epg-key)
566     (signal 'wrong-type-argument (list 'epg-key-p key)))
567   (aref (cdr key) 2))
568
569 (defun epg-key-set-sub-key-list (key sub-key-list)
570   "Set the sub key list of KEY."
571   (unless (eq (car key) 'epg-key)
572     (signal 'wrong-type-argument (list 'epg-key-p key)))
573   (aset (cdr key) 1 sub-key-list))
574
575 (defun epg-key-set-user-id-list (key user-id-list)
576   "Set the user ID list of KEY."
577   (unless (eq (car key) 'epg-key)
578     (signal 'wrong-type-argument (list 'epg-key-p key)))
579   (aset (cdr key) 2 user-id-list))
580
581 (defun epg-make-sub-key (validity capability secret-p algorithm length id
582                                   creation-time expiration-time)
583   "Return a sub key object."
584   (cons 'epg-sub-key
585         (vector validity capability secret-p algorithm length id creation-time
586                 expiration-time nil)))
587
588 (defun epg-sub-key-validity (sub-key)
589   "Return the validity of SUB-KEY."
590   (unless (eq (car sub-key) 'epg-sub-key)
591     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
592   (aref (cdr sub-key) 0))
593
594 (defun epg-sub-key-capability (sub-key)
595   "Return the capability of SUB-KEY."
596   (unless (eq (car sub-key) 'epg-sub-key)
597     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
598   (aref (cdr sub-key) 1))
599
600 (defun epg-sub-key-secret-p (sub-key)
601   "Return non-nil if SUB-KEY is a secret key."
602   (unless (eq (car sub-key) 'epg-sub-key)
603     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
604   (aref (cdr sub-key) 2))
605
606 (defun epg-sub-key-algorithm (sub-key)
607   "Return the algorithm of SUB-KEY."
608   (unless (eq (car sub-key) 'epg-sub-key)
609     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
610   (aref (cdr sub-key) 3))
611
612 (defun epg-sub-key-length (sub-key)
613   "Return the length of SUB-KEY."
614   (unless (eq (car sub-key) 'epg-sub-key)
615     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
616   (aref (cdr sub-key) 4))
617
618 (defun epg-sub-key-id (sub-key)
619   "Return the ID of SUB-KEY."
620   (unless (eq (car sub-key) 'epg-sub-key)
621     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
622   (aref (cdr sub-key) 5))
623
624 (defun epg-sub-key-creation-time (sub-key)
625   "Return the creation time of SUB-KEY."
626   (unless (eq (car sub-key) 'epg-sub-key)
627     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
628   (aref (cdr sub-key) 6))
629
630 (defun epg-sub-key-expiration-time (sub-key)
631   "Return the expiration time of SUB-KEY."
632   (unless (eq (car sub-key) 'epg-sub-key)
633     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
634   (aref (cdr sub-key) 7))
635
636 (defun epg-sub-key-fingerprint (sub-key)
637   "Return the fingerprint of SUB-KEY."
638   (unless (eq (car sub-key) 'epg-sub-key)
639     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
640   (aref (cdr sub-key) 8))
641
642 (defun epg-sub-key-set-fingerprint (sub-key fingerprint)
643   "Set the fingerprint of SUB-KEY.
644 This function is for internal use only."
645   (unless (eq (car sub-key) 'epg-sub-key)
646     (signal 'wrong-type-argument (list 'epg-sub-key-p sub-key)))
647   (aset (cdr sub-key) 8 fingerprint))
648
649 (defun epg-make-user-id (validity string)
650   "Return a user ID object."
651   (cons 'epg-user-id (vector validity string nil)))
652
653 (defun epg-user-id-validity (user-id)
654   "Return the validity of USER-ID."
655   (unless (eq (car user-id) 'epg-user-id)
656     (signal 'wrong-type-argument (list 'epg-user-id-p user-id)))
657   (aref (cdr user-id) 0))
658
659 (defun epg-user-id-string (user-id)
660   "Return the name of USER-ID."
661   (unless (eq (car user-id) 'epg-user-id)
662     (signal 'wrong-type-argument (list 'epg-user-id-p user-id)))
663   (aref (cdr user-id) 1))
664
665 (defun epg-user-id-signature-list (user-id)
666   "Return the signature list of USER-ID."
667   (unless (eq (car user-id) 'epg-user-id)
668     (signal 'wrong-type-argument (list 'epg-user-id-p user-id)))
669   (aref (cdr user-id) 2))
670
671 (defun epg-user-id-set-signature-list (user-id signature-list)
672   "Set the signature list of USER-ID."
673   (unless (eq (car user-id) 'epg-user-id)
674     (signal 'wrong-type-argument (list 'epg-user-id-p user-id)))
675   (aset (cdr user-id) 2 signature-list))
676
677 (defun epg-make-key-signature (validity pubkey-algorithm key-id creation-time
678                                         expiration-time user-id class
679                                         exportable-p)
680   "Return a key signature object."
681   (cons 'epg-key-signature
682         (vector validity pubkey-algorithm key-id creation-time expiration-time
683                 user-id class exportable-p)))
684
685 (defun epg-key-signature-validity (key-signature)
686   "Return the validity of KEY-SIGNATURE."
687   (unless (eq (car key-signature) 'epg-key-signature)
688     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
689   (aref (cdr key-signature) 0))
690
691 (defun epg-key-signature-pubkey-algorithm (key-signature)
692   "Return the public key algorithm of KEY-SIGNATURE."
693   (unless (eq (car key-signature) 'epg-key-signature)
694     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
695   (aref (cdr key-signature) 1))
696
697 (defun epg-key-signature-key-id (key-signature)
698   "Return the key-id of KEY-SIGNATURE."
699   (unless (eq (car key-signature) 'epg-key-signature)
700     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
701   (aref (cdr key-signature) 2))
702
703 (defun epg-key-signature-creation-time (key-signature)
704   "Return the creation time of KEY-SIGNATURE."
705   (unless (eq (car key-signature) 'epg-key-signature)
706     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
707   (aref (cdr key-signature) 3))
708
709 (defun epg-key-signature-expiration-time (key-signature)
710   "Return the expiration time of KEY-SIGNATURE."
711   (unless (eq (car key-signature) 'epg-key-signature)
712     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
713   (aref (cdr key-signature) 4))
714
715 (defun epg-key-signature-user-id (key-signature)
716   "Return the user-id of KEY-SIGNATURE."
717   (unless (eq (car key-signature) 'epg-key-signature)
718     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
719   (aref (cdr key-signature) 5))
720
721 (defun epg-key-signature-class (key-signature)
722   "Return the class of KEY-SIGNATURE."
723   (unless (eq (car key-signature) 'epg-key-signature)
724     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
725   (aref (cdr key-signature) 6))
726
727 (defun epg-key-signature-exportable-p (key-signature)
728   "Return t if KEY-SIGNATURE is exportable."
729   (unless (eq (car key-signature) 'epg-key-signature)
730     (signal 'wrong-type-argument (list 'epg-key-signature-p key-signature)))
731   (aref (cdr key-signature) 7))
732
733 (defun epg-context-result-for (context name)
734   "Return the result of CONTEXT associated with NAME."
735   (cdr (assq name (epg-context-result context))))
736
737 (defun epg-context-set-result-for (context name value)
738   "Set the result of CONTEXT associated with NAME to VALUE."
739   (let* ((result (epg-context-result context))
740          (entry (assq name result)))
741     (if entry
742         (setcdr entry value)
743       (epg-context-set-result context (cons (cons name value) result)))))
744
745 (defun epg-signature-to-string (signature)
746   "Convert SIGNATURE to a human readable string."
747   (let ((user-id (cdr (assoc (epg-signature-key-id signature)
748                              epg-user-id-alist))))
749     (concat
750      (cond ((eq (epg-signature-status signature) 'good)
751             "Good signature from ")
752            ((eq (epg-signature-status signature) 'bad)
753             "Bad signature from ")
754            ((eq (epg-signature-status signature) 'expired)
755             "Expired signature from ")
756            ((eq (epg-signature-status signature) 'expired-key)
757             "Signature made by expired key ")
758            ((eq (epg-signature-status signature) 'revoked-key)
759             "Signature made by revoked key ")
760            ((eq (epg-signature-status signature) 'no-pubkey)
761             "No public key for "))
762      (epg-signature-key-id signature)
763      (if user-id
764          (concat " "
765                  (if (stringp user-id)
766                      user-id
767                    (epg-decode-dn user-id)))
768        "")
769      (if (epg-signature-validity signature)
770          (format " (trust %s)"  (epg-signature-validity signature))
771        ""))))
772
773 (defun epg-verify-result-to-string (verify-result)
774   "Convert VERIFY-RESULT to a human readable string."
775   (mapconcat #'epg-signature-to-string verify-result "\n"))
776
777 (defun epg-new-signature-to-string (new-signature)
778   "Convert NEW-SIGNATURE to a human readable string."
779   (concat
780    (cond ((eq (epg-new-signature-type new-signature) 'detached)
781           "Detached signature ")
782          ((eq (epg-new-signature-type new-signature) 'clear)
783           "Clear text signature ")
784          (t
785           "Signature "))
786    (cdr (assq (epg-new-signature-pubkey-algorithm new-signature)
787               epg-pubkey-algorithm-alist))
788    "/"
789    (cdr (assq (epg-new-signature-digest-algorithm new-signature)
790               epg-digest-algorithm-alist))
791    " "
792    (format "%02X " (epg-new-signature-class new-signature))
793    (epg-new-signature-fingerprint new-signature)))
794
795 (defun epg--start (context args)
796   "Start `epg-gpg-program' in a subprocess with given ARGS."
797   (if (and (epg-context-process context)
798            (eq (process-status (epg-context-process context)) 'run))
799       (error "%s is already running in this context"
800              (if (eq (epg-context-protocol context) 'CMS)
801                  epg-gpgsm-program
802                epg-gpg-program)))
803   (let* ((args (append (list "--no-tty"
804                              "--status-fd" "1"
805                              "--yes")
806                        (unless (eq (epg-context-protocol context) 'CMS)
807                          (list "--command-fd" "0"))
808                        (if (epg-context-armor context) '("--armor"))
809                        (if (epg-context-textmode context) '("--textmode"))
810                        (if (epg-context-output-file context)
811                            (list "--output" (epg-context-output-file context)))
812                        args))
813          (coding-system-for-write 'binary)
814          process-connection-type
815          (orig-mode (default-file-modes))
816          (buffer (generate-new-buffer " *epg*"))
817          process)
818     (if epg-debug
819         (save-excursion
820           (unless epg-debug-buffer
821             (setq epg-debug-buffer (generate-new-buffer " *epg-debug*")))
822           (set-buffer epg-debug-buffer)
823           (goto-char (point-max))
824           (insert (format "%s %s\n"
825                           (if (eq (epg-context-protocol context) 'CMS)
826                               epg-gpgsm-program
827                            epg-gpg-program)
828                           (mapconcat #'identity args " ")))))
829     (with-current-buffer buffer
830       (make-local-variable 'epg-read-point)
831       (setq epg-read-point (point-min))
832       (make-local-variable 'epg-process-filter-running)
833       (setq epg-process-filter-running nil)
834       (make-local-variable 'epg-pending-status-list)
835       (setq epg-pending-status-list nil)
836       (make-local-variable 'epg-key-id)
837       (setq epg-key-id nil)
838       (make-local-variable 'epg-context)
839       (setq epg-context context))
840     (unwind-protect
841         (progn
842           (set-default-file-modes 448)
843           (setq process
844                 (apply #'start-process "epg" buffer
845                        (if (eq (epg-context-protocol context) 'CMS)
846                            epg-gpgsm-program
847                          epg-gpg-program)
848                        args)))
849       (set-default-file-modes orig-mode))
850     (set-process-filter process #'epg--process-filter)
851     (epg-context-set-process context process)))
852
853 (defun epg--process-filter (process input)
854   (if epg-debug
855       (save-excursion
856         (unless epg-debug-buffer
857           (setq epg-debug-buffer (generate-new-buffer " *epg-debug*")))
858         (set-buffer epg-debug-buffer)
859         (goto-char (point-max))
860         (insert input)))
861   (if (buffer-live-p (process-buffer process))
862       (save-excursion
863         (set-buffer (process-buffer process))
864         (goto-char (point-max))
865         (insert input)
866         (unless epg-process-filter-running
867           (unwind-protect
868               (progn
869                 (setq epg-process-filter-running t)
870                 (goto-char epg-read-point)
871                 (beginning-of-line)
872                 (while (looking-at ".*\n") ;the input line finished
873                   (if (looking-at "\\[GNUPG:] \\([A-Z_]+\\) ?\\(.*\\)")
874                       (let* ((status (match-string 1))
875                              (string (match-string 2))
876                              (symbol (intern-soft (concat "epg--status-"
877                                                           status))))
878                         (if (member status epg-pending-status-list)
879                             (setq epg-pending-status-list nil))
880                         (if (and symbol
881                                  (fboundp symbol))
882                             (funcall symbol epg-context string))))
883                   (forward-line)
884                   (setq epg-read-point (point))))
885             (setq epg-process-filter-running nil))))))
886
887 (defun epg-read-output (context)
888   "Read the output file CONTEXT and return the content as a string."
889   (with-temp-buffer
890     (if (fboundp 'set-buffer-multibyte)
891         (set-buffer-multibyte nil))
892     (if (file-exists-p (epg-context-output-file context))
893         (let ((coding-system-for-read 'binary))
894           (insert-file-contents (epg-context-output-file context))
895           (buffer-string)))))
896
897 (defun epg-wait-for-status (context status-list)
898   "Wait until one of elements in STATUS-LIST arrives."
899   (with-current-buffer (process-buffer (epg-context-process context))
900     (setq epg-pending-status-list status-list)
901     (while (and (eq (process-status (epg-context-process context)) 'run)
902                 epg-pending-status-list)
903       (accept-process-output (epg-context-process context) 1))))
904
905 (defun epg-wait-for-completion (context)
906   "Wait until the `epg-gpg-program' process completes."
907   (while (eq (process-status (epg-context-process context)) 'run)
908     (accept-process-output (epg-context-process context) 1)))
909
910 (defun epg-reset (context)
911   "Reset the CONTEXT."
912   (if (and (epg-context-process context)
913            (buffer-live-p (process-buffer (epg-context-process context))))
914       (kill-buffer (process-buffer (epg-context-process context))))
915   (epg-context-set-process context nil))
916
917 (defun epg-delete-output-file (context)
918   "Delete the output file of CONTEXT."
919   (if (and (epg-context-output-file context)
920            (file-exists-p (epg-context-output-file context)))
921       (delete-file (epg-context-output-file context))))
922
923 (defun epg--status-USERID_HINT (context string)
924   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
925       (let* ((key-id (match-string 1 string))
926              (user-id (match-string 2 string))
927              (entry (assoc key-id epg-user-id-alist)))
928         (if entry
929             (setcdr entry user-id)
930           (setq epg-user-id-alist (cons (cons key-id user-id)
931                                         epg-user-id-alist))))))
932
933 (defun epg--status-NEED_PASSPHRASE (context string)
934   (if (string-match "\\`\\([^ ]+\\)" string)
935       (setq epg-key-id (match-string 1 string))))
936
937 (defun epg--status-NEED_PASSPHRASE_SYM (context string)
938   (setq epg-key-id 'SYM))
939
940 (defun epg--status-NEED_PASSPHRASE_PIN (context string)
941   (setq epg-key-id 'PIN))
942
943 (defun epg--status-GET_HIDDEN (context string)
944   (if (and epg-key-id
945            (string-match "\\`passphrase\\." string))
946       (let (inhibit-quit
947             passphrase
948             passphrase-with-new-line)
949         (unwind-protect
950             (condition-case nil
951                 (progn
952                   (setq passphrase
953                         (funcall
954                          (if (consp (epg-context-passphrase-callback context))
955                              (car (epg-context-passphrase-callback context))
956                            (epg-context-passphrase-callback context))
957                          context
958                          epg-key-id
959                          (if (consp (epg-context-passphrase-callback context))
960                              (cdr (epg-context-passphrase-callback context)))))
961                   (when passphrase
962                     (setq passphrase-with-new-line (concat passphrase "\n"))
963                     (fillarray passphrase 0)
964                     (setq passphrase nil)
965                     (process-send-string (epg-context-process context)
966                                          passphrase-with-new-line)))
967               (quit
968                (epg-context-set-result-for
969                 context 'error
970                 (cons '(quit)
971                       (epg-context-result-for context 'error)))
972                (delete-process (epg-context-process context))))
973           (if passphrase
974               (fillarray passphrase 0))
975           (if passphrase-with-new-line
976               (fillarray passphrase-with-new-line 0))))))
977
978 (defun epg--status-GET_BOOL (context string)
979   (let ((entry (assoc string epg-prompt-alist))
980         inhibit-quit)
981     (condition-case nil
982       (if (y-or-n-p (if entry (cdr entry) (concat string "? ")))
983           (process-send-string (epg-context-process context) "y\n")
984         (process-send-string (epg-context-process context) "n\n"))
985       (quit
986        (epg-context-set-result-for
987         context 'error
988         (cons '(quit)
989               (epg-context-result-for context 'error)))
990        (delete-process (epg-context-process context))))))
991
992 (defun epg--status-GET_LINE (context string)
993   (let ((entry (assoc string epg-prompt-alist))
994         inhibit-quit)
995     (condition-case nil
996         (process-send-string (epg-context-process context)
997                              (concat (read-string
998                                       (if entry
999                                           (cdr entry)
1000                                         (concat string ": ")))
1001                                      "\n"))
1002       (quit
1003        (epg-context-set-result-for
1004         context 'error
1005         (cons '(quit)
1006               (epg-context-result-for context 'error)))
1007        (delete-process (epg-context-process context))))))
1008
1009 (defun epg--status-*SIG (context status string)
1010   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
1011       (let* ((key-id (match-string 1 string))
1012              (user-id (match-string 2 string))
1013              (entry (assoc key-id epg-user-id-alist)))
1014         (epg-context-set-result-for
1015          context
1016          'verify
1017          (cons (epg-make-signature status key-id)
1018                (epg-context-result-for context 'verify)))
1019         (if (eq (epg-context-protocol context) 'CMS)
1020             (condition-case nil
1021                 (setq user-id (epg-dn-from-string user-id))
1022               (error)))
1023         (if entry
1024             (setcdr entry user-id)
1025           (setq epg-user-id-alist
1026                 (cons (cons key-id user-id) epg-user-id-alist))))
1027     (epg-context-set-result-for
1028      context
1029      'verify
1030      (cons (epg-make-signature status)
1031            (epg-context-result-for context 'verify)))))
1032
1033 (defun epg--status-GOODSIG (context string)
1034   (epg--status-*SIG context 'good string))
1035
1036 (defun epg--status-EXPSIG (context string)
1037   (epg--status-*SIG context 'expired string))
1038
1039 (defun epg--status-EXPKEYSIG (context string)
1040   (epg--status-*SIG context 'expired-key string))
1041
1042 (defun epg--status-REVKEYSIG (context string)
1043   (epg--status-*SIG context 'revoked-key string))
1044
1045 (defun epg--status-BADSIG (context string)
1046   (epg--status-*SIG context 'bad string))
1047
1048 (defun epg--status-NO_PUBKEY (context string)
1049   (let ((signature (car (epg-context-result-for context 'verify))))
1050     (if (and signature
1051              (eq (epg-signature-status signature) 'error)
1052              (equal (epg-signature-key-id signature) string))
1053         (epg-signature-set-status signature 'no-pubkey))))
1054
1055 (defun epg--time-from-seconds (seconds)
1056   (let ((number-seconds (string-to-number (concat seconds ".0"))))
1057     (cons (floor (/ number-seconds 65536))
1058           (floor (mod number-seconds 65536)))))
1059
1060 (defun epg--status-ERRSIG (context string)
1061   (if (string-match "\\`\\([^ ]+\\) \\([0-9]+\\) \\([0-9]+\\) \
1062 \\([0-9A-Fa-f][0-9A-Fa-f]\\) \\([^ ]+\\) \\([0-9]+\\)"
1063                     string)
1064       (let ((signature (epg-make-signature 'error)))
1065         (epg-context-set-result-for
1066          context
1067          'verify
1068          (cons signature
1069                (epg-context-result-for context 'verify)))
1070         (epg-signature-set-key-id
1071          signature
1072          (match-string 1 string))
1073         (epg-signature-set-pubkey-algorithm
1074          signature
1075          (string-to-number (match-string 2 string)))
1076         (epg-signature-set-digest-algorithm
1077          signature
1078          (string-to-number (match-string 3 string)))
1079         (epg-signature-set-class
1080          signature
1081          (string-to-number (match-string 4 string) 16))
1082         (epg-signature-set-creation-time
1083          signature
1084          (epg--time-from-seconds (match-string 5 string))))))
1085
1086 (defun epg--status-VALIDSIG (context string)
1087   (let ((signature (car (epg-context-result-for context 'verify))))
1088     (when (and signature
1089                (eq (epg-signature-status signature) 'good)
1090                (string-match "\\`\\([^ ]+\\) [^ ]+ \\([^ ]+\\) \\([^ ]+\\) \
1091 \\([0-9]+\\) [^ ]+ \\([0-9]+\\) \\([0-9]+\\) \\([0-9A-Fa-f][0-9A-Fa-f]\\) \
1092 \\(.*\\)"
1093                            string))
1094       (epg-signature-set-fingerprint
1095        signature
1096        (match-string 1 string))
1097       (epg-signature-set-creation-time
1098        signature
1099        (epg--time-from-seconds (match-string 2 string)))
1100       (epg-signature-set-expiration-time
1101        signature
1102        (epg--time-from-seconds (match-string 3 string)))
1103       (epg-signature-set-version
1104        signature
1105        (string-to-number (match-string 4 string)))
1106       (epg-signature-set-pubkey-algorithm
1107        signature 
1108        (string-to-number (match-string 5 string)))
1109       (epg-signature-set-digest-algorithm
1110        signature
1111        (string-to-number (match-string 6 string)))
1112       (epg-signature-set-class
1113        signature
1114        (string-to-number (match-string 7 string) 16)))))
1115
1116 (defun epg--status-TRUST_UNDEFINED (context string)
1117   (let ((signature (car (epg-context-result-for context 'verify))))
1118     (if (and signature
1119              (eq (epg-signature-status signature) 'good))
1120         (epg-signature-set-validity signature 'undefined))))
1121
1122 (defun epg--status-TRUST_NEVER (context string)
1123   (let ((signature (car (epg-context-result-for context 'verify))))
1124     (if (and signature
1125              (eq (epg-signature-status signature) 'good))
1126         (epg-signature-set-validity signature 'never))))
1127
1128 (defun epg--status-TRUST_MARGINAL (context string)
1129   (let ((signature (car (epg-context-result-for context 'verify))))
1130     (if (and signature
1131              (eq (epg-signature-status signature) 'marginal))
1132         (epg-signature-set-validity signature 'marginal))))
1133
1134 (defun epg--status-TRUST_FULLY (context string)
1135   (let ((signature (car (epg-context-result-for context 'verify))))
1136     (if (and signature
1137              (eq (epg-signature-status signature) 'good))
1138         (epg-signature-set-validity signature 'full))))
1139
1140 (defun epg--status-TRUST_ULTIMATE (context string)
1141   (let ((signature (car (epg-context-result-for context 'verify))))
1142     (if (and signature
1143              (eq (epg-signature-status signature) 'good))
1144         (epg-signature-set-validity signature 'ultimate))))
1145
1146 (defun epg--status-PROGRESS (context string)
1147   (if (string-match "\\`\\([^ ]+\\) \\([^ ]\\) \\([0-9]+\\) \\([0-9]+\\)"
1148                     string)
1149       (funcall (if (consp (epg-context-progress-callback context))
1150                    (car (epg-context-progress-callback context))
1151                  (epg-context-progress-callback context))
1152                context
1153                (match-string 1 string)
1154                (match-string 2 string)
1155                (string-to-number (match-string 3 string))
1156                (string-to-number (match-string 4 string))
1157                (if (consp (epg-context-progress-callback context))
1158                    (cdr (epg-context-progress-callback context))))))
1159
1160 (defun epg--status-DECRYPTION_FAILED (context string)
1161   (epg-context-set-result-for
1162    context 'error
1163    (cons '(decryption-failed)
1164          (epg-context-result-for context 'error))))
1165
1166 (defun epg--status-NODATA (context string)
1167   (epg-context-set-result-for
1168    context 'error
1169    (cons (list 'no-data (cons 'reason (string-to-number string)))
1170          (epg-context-result-for context 'error))))
1171
1172 (defun epg--status-UNEXPECTED (context string)
1173   (epg-context-set-result-for
1174    context 'error
1175    (cons (list 'unexpected (cons 'reason (string-to-number string)))
1176          (epg-context-result-for context 'error))))
1177
1178 (defun epg--status-KEYEXPIRED (context string)
1179   (epg-context-set-result-for
1180    context 'error
1181    (cons (list 'key-expired (cons 'expiration-time
1182                                   (epg--time-from-seconds string)))
1183          (epg-context-result-for context 'error))))
1184
1185 (defun epg--status-KEYREVOKED (context string)
1186   (epg-context-set-result-for
1187    context 'error
1188    (cons '(key-revoked)
1189          (epg-context-result-for context 'error))))
1190
1191 (defun epg--status-BADARMOR (context string)
1192   (epg-context-set-result-for
1193    context 'error
1194    (cons '(bad-armor)
1195          (epg-context-result-for context 'error))))
1196
1197 (defun epg--status-INV_RECP (context string)
1198   (if (string-match "\\`\\([0-9]+\\) \\(.*\\)" string)
1199       (epg-context-set-result-for
1200        context 'error
1201        (cons (list 'invalid-recipient
1202                    (cons 'reason
1203                          (string-to-number (match-string 1 string)))
1204                    (cons 'requested-recipient
1205                          (match-string 2 string)))
1206              (epg-context-result-for context 'error)))))
1207
1208 (defun epg--status-NO_RECP (context string)
1209   (epg-context-set-result-for
1210    context 'error
1211    (cons '(no-recipients)
1212          (epg-context-result-for context 'error))))
1213
1214 (defun epg--status-DELETE_PROBLEM (context string)
1215   (if (string-match "\\`\\([0-9]+\\)" string)
1216       (epg-context-set-result-for
1217        context 'error
1218        (cons (list 'delete-problem
1219                    (cons 'reason (string-to-number (match-string 1 string))))
1220              (epg-context-result-for context 'error)))))
1221
1222 (defun epg--status-SIG_CREATED (context string)
1223   (if (string-match "\\`\\([DCS]\\) \\([0-9]+\\) \\([0-9]+\\) \
1224 \\([0-9A-Fa-F][0-9A-Fa-F]\\) \\(.*\\) " string)
1225       (epg-context-set-result-for
1226        context 'sign
1227        (cons (epg-make-new-signature
1228               (cdr (assq (aref (match-string 1 string) 0)
1229                          epg-new-signature-type-alist))
1230               (string-to-number (match-string 2 string))
1231               (string-to-number (match-string 3 string))
1232               (string-to-number (match-string 4 string) 16)
1233               (epg--time-from-seconds (match-string 5 string))
1234               (substring string (match-end 0)))
1235              (epg-context-result-for context 'sign)))))
1236
1237 (defun epg--status-KEY_CREATED (context string)
1238   (if (string-match "\\`\\([BPS]\\) \\([^ ]+\\)" string)
1239       (epg-context-set-result-for
1240        context 'generate-key
1241        (cons (list (cons 'type (string-to-char (match-string 1 string)))
1242                    (cons 'fingerprint (match-string 2 string)))
1243              (epg-context-result-for context 'generate-key)))))
1244
1245 (defun epg--status-KEY_NOT_CREATED (context string)
1246   (epg-context-set-result-for
1247    context 'error
1248    (cons '(key-not-created)
1249          (epg-context-result-for context 'error))))
1250
1251 (defun epg--status-IMPORTED (context string)
1252   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
1253       (let* ((key-id (match-string 1 string))
1254              (user-id (match-string 2 string))
1255              (entry (assoc key-id epg-user-id-alist)))
1256         (if entry
1257             (setcdr entry user-id)
1258           (setq epg-user-id-alist (cons (cons key-id user-id)
1259                                         epg-user-id-alist)))
1260         (epg-context-set-result-for
1261          context 'import
1262          (cons (list (cons 'key-id key-id)
1263                      (cons 'user-id user-id))
1264                (epg-context-result-for context 'import))))))
1265
1266 (defun epg--status-IMPORT_OK (context string)
1267   (let ((result (epg-context-result-for context 'import)))
1268     (if (and result
1269              (string-match "\\`\\([0-9]+\\)\\( \\(.+\\)\\)?" string))
1270         (setcar result
1271                 (append (list (cons 'reason
1272                                     (string-to-number
1273                                      (match-string 1 string))))
1274                         (if (match-beginning 2)
1275                             (list (cons 'fingerprint
1276                                         (match-string 3 string))))
1277                         (car result))))))
1278
1279 (defun epg--status-IMPORT_PROBLEM (context string)
1280   (if (string-match "\\`\\([0-9]+\\)\\( \\(.+\\)\\)?" string)
1281       (epg-context-set-result-for
1282        context 'error
1283        (cons (cons 'import-problem
1284                    (append (list (cons 'reason
1285                                        (string-to-number
1286                                         (match-string 1 string))))
1287                            (if (match-beginning 2)
1288                                (list (cons 'fingerprint
1289                                            (match-string 3 string))))))
1290              (epg-context-result-for context 'error)))))
1291
1292 (defun epg-passphrase-callback-function (context key-id handback)
1293   (if (eq key-id 'SYM)
1294       (read-passwd "Passphrase for symmetric encryption: "
1295                    (eq (epg-context-operation context) 'encrypt))
1296     (read-passwd
1297      (if (eq key-id 'PIN)
1298         "Passphrase for PIN: "
1299        (let ((entry (assoc key-id epg-user-id-alist)))
1300          (if entry
1301              (format "Passphrase for %s %s: " key-id (cdr entry))
1302            (format "Passphrase for %s: " key-id)))))))
1303
1304 (defun epg-progress-callback-function (context what char current total
1305                                                handback)
1306   (message "%s: %d%%/%d%%" what current total))
1307
1308 ;;;###autoload
1309 (defun epg-configuration ()
1310   "Return a list of internal configuration parameters of `epg-gpg-program'."
1311   (let (config type)
1312     (with-temp-buffer
1313       (apply #'call-process epg-gpg-program nil (list t nil) nil
1314              '("--with-colons" "--list-config"))
1315       (goto-char (point-min))
1316       (while (re-search-forward "^cfg:\\([^:]+\\):\\(.*\\)" nil t)
1317         (setq type (intern (match-string 1))
1318               config (cons (cons type
1319                                  (if (memq type
1320                                            '(pubkey cipher digest compress))
1321                                      (mapcar #'string-to-number
1322                                              (delete "" (split-string
1323                                                          (match-string 2)
1324                                                          ";")))
1325                                    (match-string 2)))
1326                            config))))
1327     config))
1328
1329 ;;;###autoload
1330 (defun epg-check-configuration (configuration)
1331   "Verify that CONFIGURATION is sufficient."
1332   (let ((entry (assq 'version configuration))
1333         major minor teeny)
1334     (unless (and entry
1335                  (stringp (cdr entry))
1336                  (string-match "\\`\\([0-9]+\\)\\.\\([0-9]+\\)\\.\\([0-9]+\\)"
1337                                (cdr entry)))
1338       (error "Undetermined version: %S" entry))
1339     (setq major (string-to-number (match-string 1 (cdr entry)))
1340           minor (string-to-number (match-string 2 (cdr entry)))
1341           teeny (string-to-number (match-string 3 (cdr entry))))
1342     (unless (or (> major 1)
1343                 (and (= major 1)
1344                      (or (> minor 4)
1345                          (and (= minor 4)
1346                               (>= teeny 3)))))
1347       (error "Unsupported version: %s" (cdr entry)))))
1348
1349 (defun epg--list-keys-1 (context name mode)
1350   (let ((args (append (list "--with-colons" "--no-greeting" "--batch"
1351                             "--with-fingerprint"
1352                             "--with-fingerprint"
1353                             (if (memq mode '(t secret))
1354                                 "--list-secret-keys"
1355                               (if (memq mode '(nil public))
1356                                   "--list-keys"
1357                                 "--list-sigs")))
1358                       (unless (eq (epg-context-protocol context) 'CMS)
1359                         '("--fixed-list-mode"))
1360                       (if name (list name))))
1361         keys string field index)
1362     (with-temp-buffer
1363       (apply #'call-process
1364              (if (eq (epg-context-protocol context) 'CMS)
1365                  epg-gpgsm-program
1366                epg-gpg-program)
1367              nil (list t nil) nil args)
1368       (goto-char (point-min))
1369       (while (re-search-forward "^[a-z][a-z][a-z]:.*" nil t)
1370         (setq keys (cons (make-vector 15 nil) keys)
1371               string (match-string 0)
1372               index 0
1373               field 0)
1374         (while (eq index
1375                    (string-match "\\([^:]+\\)?:" string index))
1376           (setq index (match-end 0))
1377           (aset (car keys) field (match-string 1 string))
1378           (setq field (1+ field))))
1379       (nreverse keys))))
1380
1381 (defun epg--make-sub-key-1 (line)
1382   (epg-make-sub-key
1383    (if (aref line 1)
1384        (cdr (assq (string-to-char (aref line 1)) epg-key-validity-alist)))
1385    (delq nil
1386          (mapcar (lambda (char) (cdr (assq char epg-key-capablity-alist)))
1387                  (aref line 11)))
1388    (member (aref line 0) '("sec" "ssb"))
1389    (string-to-number (aref line 3))
1390    (string-to-number (aref line 2))
1391    (aref line 4)
1392    (epg--time-from-seconds (aref line 5))
1393    (epg--time-from-seconds (aref line 6))))
1394
1395 ;;;###autoload
1396 (defun epg-list-keys (context &optional name mode)
1397   "Return a list of epg-key objects matched with NAME.
1398 If MODE is nil or 'public, only public keyring should be searched.
1399 If MODE is t or 'secret, only secret keyring should be searched. 
1400 Otherwise, only public keyring should be searched and the key
1401 signatures should be included."
1402   (let ((lines (epg--list-keys-1 context name mode))
1403         keys cert pointer pointer-1)
1404     (while lines
1405       (cond
1406        ((member (aref (car lines) 0) '("pub" "sec" "crt" "crs"))
1407         (setq cert (member (aref (car lines) 0) '("crt" "crs"))
1408               keys (cons (epg-make-key
1409                           (if (aref (car lines) 8)
1410                               (cdr (assq (string-to-char (aref (car lines) 8))
1411                                          epg-key-validity-alist))))
1412                          keys))
1413         (epg-key-set-sub-key-list
1414          (car keys)
1415          (cons (epg--make-sub-key-1 (car lines))
1416                (epg-key-sub-key-list (car keys)))))
1417        ((member (aref (car lines) 0) '("sub" "ssb"))
1418         (epg-key-set-sub-key-list
1419          (car keys)
1420          (cons (epg--make-sub-key-1 (car lines))
1421                (epg-key-sub-key-list (car keys)))))
1422        ((equal (aref (car lines) 0) "uid")
1423         (epg-key-set-user-id-list
1424          (car keys)
1425          (cons (epg-make-user-id
1426                 (if (aref (car lines) 1)
1427                     (cdr (assq (string-to-char (aref (car lines) 1))
1428                                epg-key-validity-alist)))
1429                 (if cert
1430                     (condition-case nil
1431                         (epg-dn-from-string (aref (car lines) 9))
1432                       (error (aref (car lines) 9)))
1433                   (aref (car lines) 9)))
1434                (epg-key-user-id-list (car keys)))))
1435        ((equal (aref (car lines) 0) "fpr")
1436         (epg-sub-key-set-fingerprint (car (epg-key-sub-key-list (car keys)))
1437                                      (aref (car lines) 9)))
1438        ((equal (aref (car lines) 0) "sig")
1439         (epg-user-id-set-signature-list
1440          (car (epg-key-user-id-list (car keys)))
1441          (cons
1442           (epg-make-key-signature
1443            (if (aref (car lines) 1)
1444                (cdr (assq (string-to-char (aref (car lines) 1))
1445                           epg-key-validity-alist)))
1446            (string-to-number (aref (car lines) 3))
1447            (aref (car lines) 4)
1448            (epg--time-from-seconds (aref (car lines) 5))
1449            (epg--time-from-seconds (aref (car lines) 6))
1450            (aref (car lines) 9)
1451            (string-to-number (aref (car lines) 10) 16)
1452            (eq (aref (aref (car lines) 10) 2) ?x))
1453           (epg-user-id-signature-list
1454            (car (epg-key-user-id-list (car keys))))))))
1455       (setq lines (cdr lines)))
1456     (setq keys (nreverse keys)
1457           pointer keys)
1458     (while pointer
1459       (epg-key-set-sub-key-list
1460        (car pointer)
1461        (nreverse (epg-key-sub-key-list (car pointer))))
1462       (setq pointer-1 (epg-key-set-user-id-list
1463                           (car pointer)
1464                           (nreverse (epg-key-user-id-list (car pointer)))))
1465       (while pointer-1
1466         (epg-user-id-set-signature-list
1467          (car pointer-1)
1468          (nreverse (epg-user-id-signature-list (car pointer-1))))
1469         (setq pointer-1 (cdr pointer-1)))
1470       (setq pointer (cdr pointer)))
1471     keys))
1472
1473 (if (fboundp 'make-temp-file)
1474     (defalias 'epg--make-temp-file 'make-temp-file)
1475   (defvar temporary-file-directory)
1476   ;; stolen from poe.el.
1477   (defun epg--make-temp-file (prefix)
1478     "Create a temporary file.
1479 The returned file name (created by appending some random characters at the end
1480 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1481 is guaranteed to point to a newly created empty file.
1482 You can then use `write-region' to write new data into the file."
1483     (let (tempdir tempfile)
1484       (setq prefix (expand-file-name prefix
1485                                      (if (featurep 'xemacs)
1486                                          (temp-directory)
1487                                        temporary-file-directory)))
1488       (unwind-protect
1489           (let (file)
1490             ;; First, create a temporary directory.
1491             (while (condition-case ()
1492                        (progn
1493                          (setq tempdir (make-temp-name
1494                                         (concat
1495                                          (file-name-directory prefix)
1496                                          "DIR")))
1497                          ;; return nil or signal an error.
1498                          (make-directory tempdir))
1499                      ;; let's try again.
1500                      (file-already-exists t)))
1501             (set-file-modes tempdir 448)
1502             ;; Second, create a temporary file in the tempdir.
1503             ;; There *is* a race condition between `make-temp-name'
1504             ;; and `write-region', but we don't care it since we are
1505             ;; in a private directory now.
1506             (setq tempfile (make-temp-name (concat tempdir "/EMU")))
1507             (write-region "" nil tempfile nil 'silent)
1508             (set-file-modes tempfile 384)
1509             ;; Finally, make a hard-link from the tempfile.
1510             (while (condition-case ()
1511                        (progn
1512                          (setq file (make-temp-name prefix))
1513                          ;; return nil or signal an error.
1514                          (add-name-to-file tempfile file))
1515                      ;; let's try again.
1516                      (file-already-exists t)))
1517             file)
1518         ;; Cleanup the tempfile.
1519         (and tempfile
1520              (file-exists-p tempfile)
1521              (delete-file tempfile))
1522         ;; Cleanup the tempdir.
1523         (and tempdir
1524              (file-directory-p tempdir)
1525              (delete-directory tempdir))))))
1526
1527 ;;;###autoload
1528 (defun epg-cancel (context)
1529   (if (buffer-live-p (process-buffer (epg-context-process context)))
1530       (save-excursion
1531         (set-buffer (process-buffer (epg-context-process context)))
1532         (epg-context-set-result-for
1533          epg-context 'error
1534          (cons '(quit)
1535                (epg-context-result-for epg-context 'error)))))
1536   (if (eq (process-status (epg-context-process context)) 'run)
1537       (delete-process (epg-context-process context))))
1538   
1539 ;;;###autoload
1540 (defun epg-start-decrypt (context cipher)
1541   "Initiate a decrypt operation on CIPHER.
1542 CIPHER is a data object.
1543
1544 If you use this function, you will need to wait for the completion of
1545 `epg-gpg-program' by using `epg-wait-for-completion' and call
1546 `epg-reset' to clear a temporaly output file.
1547 If you are unsure, use synchronous version of this function
1548 `epg-decrypt-file' or `epg-decrypt-string' instead."
1549   (unless (epg-data-file cipher)
1550     (error "Not a file"))
1551   (epg-context-set-operation context 'decrypt)
1552   (epg-context-set-result context nil)
1553   (epg--start context (list "--decrypt" (epg-data-file cipher)))
1554   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1555   (unless (eq (epg-context-protocol context) 'CMS)
1556     (epg-wait-for-status context '("BEGIN_DECRYPTION"))))
1557
1558 ;;;###autoload
1559 (defun epg-decrypt-file (context cipher plain)
1560   "Decrypt a file CIPHER and store the result to a file PLAIN.
1561 If PLAIN is nil, it returns the result as a string."
1562   (unwind-protect
1563       (progn
1564         (if plain
1565             (epg-context-set-output-file context plain)
1566           (epg-context-set-output-file context
1567                                        (epg--make-temp-file "epg-output")))
1568         (epg-start-decrypt context (epg-make-data-from-file cipher))
1569         (epg-wait-for-completion context)
1570         (if (epg-context-result-for context 'error)
1571             (error "Decrypt failed: %S"
1572                    (epg-context-result-for context 'error)))
1573         (unless plain
1574           (epg-read-output context)))
1575     (unless plain
1576       (epg-delete-output-file context))
1577     (epg-reset context)))
1578
1579 ;;;###autoload
1580 (defun epg-decrypt-string (context cipher)
1581   "Decrypt a string CIPHER and return the plain text."
1582   (let ((input-file (epg--make-temp-file "epg-input"))
1583         (coding-system-for-write 'binary))
1584     (unwind-protect
1585         (progn
1586           (write-region cipher nil input-file nil 'quiet)
1587           (epg-context-set-output-file context
1588                                        (epg--make-temp-file "epg-output"))
1589           (epg-start-decrypt context (epg-make-data-from-file input-file))
1590           (epg-wait-for-completion context)
1591           (if (epg-context-result-for context 'error)
1592               (error "Decrypt failed: %S"
1593                      (epg-context-result-for context 'error)))
1594           (epg-read-output context))
1595       (epg-delete-output-file context)
1596       (if (file-exists-p input-file)
1597           (delete-file input-file))
1598       (epg-reset context))))
1599
1600 ;;;###autoload
1601 (defun epg-start-verify (context signature &optional signed-text)
1602   "Initiate a verify operation on SIGNATURE.
1603 SIGNATURE and SIGNED-TEXT are a data object if they are specified.
1604
1605 For a detached signature, both SIGNATURE and SIGNED-TEXT should be set.
1606 For a normal or a clear text signature, SIGNED-TEXT should be nil.
1607
1608 If you use this function, you will need to wait for the completion of
1609 `epg-gpg-program' by using `epg-wait-for-completion' and call
1610 `epg-reset' to clear a temporaly output file.
1611 If you are unsure, use synchronous version of this function
1612 `epg-verify-file' or `epg-verify-string' instead."
1613   (epg-context-set-operation context 'verify)
1614   (epg-context-set-result context nil)
1615   (if signed-text
1616       ;; Detached signature.
1617       (if (epg-data-file signed-text)
1618           (epg--start context (list "--verify" (epg-data-file signature)
1619                                    (epg-data-file signed-text)))
1620         (epg--start context (list "--verify" (epg-data-file signature) "-"))
1621         (if (eq (process-status (epg-context-process context)) 'run)
1622             (process-send-string (epg-context-process context)
1623                                  (epg-data-string signed-text)))
1624         (if (eq (process-status (epg-context-process context)) 'run)
1625             (process-send-eof (epg-context-process context))))
1626     ;; Normal (or cleartext) signature.
1627     (if (epg-data-file signature)
1628         (epg--start context (list "--verify" (epg-data-file signature)))
1629       (epg--start context (list "--verify"))
1630       (if (eq (process-status (epg-context-process context)) 'run)
1631           (process-send-string (epg-context-process context)
1632                                (epg-data-string signature)))
1633       (if (eq (process-status (epg-context-process context)) 'run)
1634           (process-send-eof (epg-context-process context))))))
1635
1636 ;;;###autoload
1637 (defun epg-verify-file (context signature &optional signed-text plain)
1638   "Verify a file SIGNATURE.
1639 SIGNED-TEXT and PLAIN are also a file if they are specified.
1640
1641 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
1642 For a normal or a clear text signature, SIGNED-TEXT should be nil."
1643   (unwind-protect
1644       (progn
1645         (if plain
1646             (epg-context-set-output-file context plain)
1647           (epg-context-set-output-file context
1648                                        (epg--make-temp-file "epg-output")))
1649         (if signed-text
1650             (epg-start-verify context
1651                               (epg-make-data-from-file signature)
1652                               (epg-make-data-from-file signed-text))
1653           (epg-start-verify context
1654                             (epg-make-data-from-file signature)))
1655         (epg-wait-for-completion context)
1656 ;       (if (epg-context-result-for context 'error)
1657 ;           (error "Verify failed: %S"
1658 ;                  (epg-context-result-for context 'error)))
1659         (unless plain
1660           (epg-read-output context)))
1661     (unless plain
1662       (epg-delete-output-file context))
1663     (epg-reset context)))
1664
1665 ;;;###autoload
1666 (defun epg-verify-string (context signature &optional signed-text)
1667   "Verify a string SIGNATURE.
1668 SIGNED-TEXT is a string if it is specified.
1669
1670 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
1671 For a normal or a clear text signature, SIGNED-TEXT should be nil."
1672   (let ((coding-system-for-write 'binary)
1673         input-file)
1674     (unwind-protect
1675         (progn
1676           (epg-context-set-output-file context
1677                                        (epg--make-temp-file "epg-output"))
1678           (if signed-text
1679               (progn
1680                 (setq input-file (epg--make-temp-file "epg-signature"))
1681                 (write-region signature nil input-file nil 'quiet)
1682                 (epg-start-verify context
1683                                   (epg-make-data-from-file input-file)
1684                                   (epg-make-data-from-string signed-text)))
1685             (epg-start-verify context (epg-make-data-from-string signature)))
1686           (epg-wait-for-completion context)
1687 ;         (if (epg-context-result-for context 'error)
1688 ;             (error "Verify failed: %S"
1689 ;                    (epg-context-result-for context 'error)))
1690           (epg-read-output context))
1691       (epg-delete-output-file context)
1692       (if (and input-file
1693                (file-exists-p input-file))
1694           (delete-file input-file))
1695       (epg-reset context))))
1696
1697 ;;;###autoload
1698 (defun epg-start-sign (context plain &optional mode)
1699   "Initiate a sign operation on PLAIN.
1700 PLAIN is a data object.
1701
1702 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1703 If it is nil or 'normal, it makes a normal signature.
1704 Otherwise, it makes a clear text signature.
1705
1706 If you use this function, you will need to wait for the completion of
1707 `epg-gpg-program' by using `epg-wait-for-completion' and call
1708 `epg-reset' to clear a temporaly output file.
1709 If you are unsure, use synchronous version of this function
1710 `epg-sign-file' or `epg-sign-string' instead."
1711   (epg-context-set-operation context 'sign)
1712   (epg-context-set-result context nil)
1713   (epg--start context
1714              (append (list (if (memq mode '(t detached))
1715                                "--detach-sign"
1716                              (if (memq mode '(nil normal))
1717                                  "--sign"
1718                                "--clearsign")))
1719                      (apply #'nconc
1720                             (mapcar
1721                              (lambda (signer)
1722                                (list "-u"
1723                                      (epg-sub-key-id
1724                                       (car (epg-key-sub-key-list signer)))))
1725                              (epg-context-signers context)))
1726                      (if (epg-data-file plain)
1727                          (list (epg-data-file plain)))))
1728   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1729   (unless (eq (epg-context-protocol context) 'CMS)
1730     (epg-wait-for-status context '("BEGIN_SIGNING")))
1731   (when (epg-data-string plain)
1732     (if (eq (process-status (epg-context-process context)) 'run)
1733         (process-send-string (epg-context-process context)
1734                              (epg-data-string plain)))
1735     (if (eq (process-status (epg-context-process context)) 'run)
1736         (process-send-eof (epg-context-process context)))))
1737
1738 ;;;###autoload
1739 (defun epg-sign-file (context plain signature &optional mode)
1740   "Sign a file PLAIN and store the result to a file SIGNATURE.
1741 If SIGNATURE is nil, it returns the result as a string.
1742 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1743 If it is nil or 'normal, it makes a normal signature.
1744 Otherwise, it makes a clear text signature."
1745   (unwind-protect
1746       (progn
1747         (if signature
1748             (epg-context-set-output-file context signature)
1749           (epg-context-set-output-file context
1750                                        (epg--make-temp-file "epg-output")))
1751         (epg-start-sign context (epg-make-data-from-file plain) mode)
1752         (epg-wait-for-completion context)
1753         (unless (epg-context-result-for context 'sign)
1754           (if (epg-context-result-for context 'error)
1755               (error "Sign failed: %S"
1756                      (epg-context-result-for context 'error))
1757             (error "Sign failed")))
1758         (unless signature
1759           (epg-read-output context)))
1760     (unless signature
1761       (epg-delete-output-file context))
1762     (epg-reset context)))
1763
1764 ;;;###autoload
1765 (defun epg-sign-string (context plain &optional mode)
1766   "Sign a string PLAIN and return the output as string.
1767 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1768 If it is nil or 'normal, it makes a normal signature.
1769 Otherwise, it makes a clear text signature."
1770   (unwind-protect
1771       (progn
1772         (epg-context-set-output-file context
1773                                      (epg--make-temp-file "epg-output"))
1774         (epg-start-sign context (epg-make-data-from-string plain) mode)
1775         (epg-wait-for-completion context)
1776         (unless (epg-context-result-for context 'sign)
1777           (if (epg-context-result-for context 'error)
1778               (error "Sign failed: %S"
1779                      (epg-context-result-for context 'error))
1780             (error "Sign failed")))
1781         (epg-read-output context))
1782     (epg-delete-output-file context)
1783     (epg-reset context)))
1784
1785 ;;;###autoload
1786 (defun epg-start-encrypt (context plain recipients
1787                                   &optional sign always-trust)
1788   "Initiate an encrypt operation on PLAIN.
1789 PLAIN is a data object.
1790 If RECIPIENTS is nil, it performs symmetric encryption.
1791
1792 If you use this function, you will need to wait for the completion of
1793 `epg-gpg-program' by using `epg-wait-for-completion' and call
1794 `epg-reset' to clear a temporaly output file.
1795 If you are unsure, use synchronous version of this function
1796 `epg-encrypt-file' or `epg-encrypt-string' instead."
1797   (epg-context-set-operation context 'encrypt)
1798   (epg-context-set-result context nil)
1799   (epg--start context
1800              (append (if always-trust '("--always-trust"))
1801                      (if recipients '("--encrypt") '("--symmetric"))
1802                      (if sign
1803                          (cons "--sign"
1804                                (apply #'nconc
1805                                       (mapcar
1806                                        (lambda (signer)
1807                                          (list "-u"
1808                                                (epg-sub-key-id
1809                                                 (car (epg-key-sub-key-list
1810                                                       signer)))))
1811                                        (epg-context-signers context)))))
1812                      (apply #'nconc
1813                             (mapcar
1814                              (lambda (recipient)
1815                                (list "-r"
1816                                      (epg-sub-key-id
1817                                       (car (epg-key-sub-key-list recipient)))))
1818                              recipients))
1819                      (if (epg-data-file plain)
1820                          (list (epg-data-file plain)))))
1821   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1822   (unless (eq (epg-context-protocol context) 'CMS)
1823     (if sign
1824         (epg-wait-for-status context '("BEGIN_SIGNING"))
1825       (epg-wait-for-status context '("BEGIN_ENCRYPTION"))))
1826   (when (epg-data-string plain)
1827     (if (eq (process-status (epg-context-process context)) 'run)
1828         (process-send-string (epg-context-process context)
1829                              (epg-data-string plain)))
1830     (if (eq (process-status (epg-context-process context)) 'run)
1831         (process-send-eof (epg-context-process context)))))
1832
1833 ;;;###autoload
1834 (defun epg-encrypt-file (context plain recipients
1835                                  cipher &optional sign always-trust)
1836   "Encrypt a file PLAIN and store the result to a file CIPHER.
1837 If CIPHER is nil, it returns the result as a string.
1838 If RECIPIENTS is nil, it performs symmetric encryption."
1839   (unwind-protect
1840       (progn
1841         (if cipher
1842             (epg-context-set-output-file context cipher)
1843           (epg-context-set-output-file context
1844                                        (epg--make-temp-file "epg-output")))
1845         (epg-start-encrypt context (epg-make-data-from-file plain)
1846                            recipients sign always-trust)
1847         (epg-wait-for-completion context)
1848         (if (and sign
1849                  (not (epg-context-result-for context 'sign)))
1850             (if (epg-context-result-for context 'error)
1851                 (error "Sign failed: %S"
1852                        (epg-context-result-for context 'error))
1853                 (error "Sign failed")))
1854         (if (epg-context-result-for context 'error)
1855             (error "Encrypt failed: %S"
1856                    (epg-context-result-for context 'error)))
1857         (unless cipher
1858           (epg-read-output context)))
1859     (unless cipher
1860       (epg-delete-output-file context))
1861     (epg-reset context)))
1862
1863 ;;;###autoload
1864 (defun epg-encrypt-string (context plain recipients
1865                                    &optional sign always-trust)
1866   "Encrypt a string PLAIN.
1867 If RECIPIENTS is nil, it performs symmetric encryption."
1868   (unwind-protect
1869       (progn
1870         (epg-context-set-output-file context
1871                                      (epg--make-temp-file "epg-output"))
1872         (epg-start-encrypt context (epg-make-data-from-string plain)
1873                            recipients sign always-trust)
1874         (epg-wait-for-completion context)
1875         (if (and sign
1876                  (not (epg-context-result-for context 'sign)))
1877             (if (epg-context-result-for context 'error)
1878                 (error "Sign failed: %S"
1879                        (epg-context-result-for context 'error))
1880               (error "Sign failed")))
1881         (if (epg-context-result-for context 'error)
1882             (error "Encrypt failed: %S"
1883                    (epg-context-result-for context 'error)))
1884         (epg-read-output context))
1885     (epg-delete-output-file context)
1886     (epg-reset context)))
1887
1888 ;;;###autoload
1889 (defun epg-start-export-keys (context keys)
1890   "Initiate an export keys operation.
1891
1892 If you use this function, you will need to wait for the completion of
1893 `epg-gpg-program' by using `epg-wait-for-completion' and call
1894 `epg-reset' to clear a temporaly output file.
1895 If you are unsure, use synchronous version of this function
1896 `epg-export-keys-to-file' or `epg-export-keys-to-string' instead."
1897   (epg-context-set-operation context 'export-keys)
1898   (epg-context-set-result context nil)
1899   (epg--start context (cons "--export"
1900                            (mapcar
1901                             (lambda (key)
1902                               (epg-sub-key-id
1903                                (car (epg-key-sub-key-list key))))
1904                             keys))))
1905
1906 ;;;###autoload
1907 (defun epg-export-keys-to-file (context keys file)
1908   "Extract public KEYS."
1909   (unwind-protect
1910       (progn
1911         (if keys
1912             (epg-context-set-output-file context file)
1913           (epg-context-set-output-file context
1914                                        (epg--make-temp-file "epg-output")))
1915         (epg-start-export-keys context keys)
1916         (epg-wait-for-completion context)
1917         (if (epg-context-result-for context 'error)
1918             (error "Export keys failed: %S"
1919                    (epg-context-result-for context 'error)))
1920         (unless file
1921           (epg-read-output context)))
1922     (unless file
1923       (epg-delete-output-file context))
1924     (epg-reset context)))
1925
1926 ;;;###autoload
1927 (defun epg-export-keys-to-string (context keys)
1928   "Extract public KEYS and return them as a string."
1929   (epg-export-keys-to-file context keys nil))
1930
1931 ;;;###autoload
1932 (defun epg-start-import-keys (context keys)
1933   "Initiate an import keys operation.
1934 KEYS is a data object.
1935
1936 If you use this function, you will need to wait for the completion of
1937 `epg-gpg-program' by using `epg-wait-for-completion' and call
1938 `epg-reset' to clear a temporaly output file.
1939 If you are unsure, use synchronous version of this function
1940 `epg-import-keys-from-file' or `epg-import-keys-from-string' instead."
1941   (epg-context-set-operation context 'import-keys)
1942   (epg-context-set-result context nil)
1943   (epg--start context (if (epg-data-file keys)
1944                           (list "--import" (epg-data-file keys))
1945                         (list "--import")))
1946   (when (epg-data-string keys)
1947     (if (eq (process-status (epg-context-process context)) 'run)
1948         (process-send-string (epg-context-process context)
1949                              (epg-data-string keys)))
1950     (if (eq (process-status (epg-context-process context)) 'run)
1951         (process-send-eof (epg-context-process context)))))
1952
1953 (defun epg--import-keys-1 (context keys)
1954   (unwind-protect
1955       (progn
1956         (epg-start-import-keys context keys)
1957         (epg-wait-for-completion context)
1958         (if (epg-context-result-for context 'error)
1959             (error "Import keys failed: %S"
1960                    (epg-context-result-for context 'error))))
1961     (epg-reset context)))
1962
1963 ;;;###autoload
1964 (defun epg-import-keys-from-file (context keys)
1965   "Add keys from a file KEYS."
1966   (epg--import-keys-1 context (epg-make-data-from-file keys)))
1967
1968 ;;;###autoload
1969 (defun epg-import-keys-from-string (context keys)
1970   "Add keys from a string KEYS."
1971   (epg--import-keys-1 context (epg-make-data-from-string keys)))
1972
1973 ;;;###autoload
1974 (defun epg-start-receive-keys (context key-id-list)
1975   "Initiate a receive key operation.
1976 KEY-ID-LIST is a list of key IDs.
1977
1978 If you use this function, you will need to wait for the completion of
1979 `epg-gpg-program' by using `epg-wait-for-completion' and call
1980 `epg-reset' to clear a temporaly output file.
1981 If you are unsure, use synchronous version of this function
1982 `epg-generate-key-from-file' or `epg-generate-key-from-string' instead."
1983   (epg-context-set-operation context 'receive-keys)
1984   (epg-context-set-result context nil)
1985   (epg--start context (cons "--recv-keys" key-id-list)))
1986
1987 ;;;###autoload
1988 (defun epg-receive-keys (context keys)
1989   "Add keys from server.
1990 KEYS is a list of key IDs"
1991   (unwind-protect
1992       (progn
1993         (epg-start-receive-keys context keys)
1994         (epg-wait-for-completion context)
1995         (if (epg-context-result-for context 'error)
1996             (error "Receive keys failed: %S"
1997                    (epg-context-result-for context 'error))))
1998     (epg-reset context)))
1999
2000 ;;;###autoload
2001 (defalias 'epg-import-keys-from-server 'epg-receive-keys)
2002
2003 ;;;###autoload
2004 (defun epg-start-delete-keys (context keys &optional allow-secret)
2005   "Initiate an delete keys operation.
2006
2007 If you use this function, you will need to wait for the completion of
2008 `epg-gpg-program' by using `epg-wait-for-completion' and call
2009 `epg-reset' to clear a temporaly output file.
2010 If you are unsure, use synchronous version of this function
2011 `epg-delete-keys' instead."
2012   (epg-context-set-operation context 'delete-keys)
2013   (epg-context-set-result context nil)
2014   (epg--start context (cons (if allow-secret
2015                                "--delete-secret-key"
2016                              "--delete-key")
2017                            (mapcar
2018                             (lambda (key)
2019                               (epg-sub-key-id
2020                                (car (epg-key-sub-key-list key))))
2021                             keys))))
2022
2023 ;;;###autoload
2024 (defun epg-delete-keys (context keys &optional allow-secret)
2025   "Delete KEYS from the key ring."
2026   (unwind-protect
2027       (progn
2028         (epg-start-delete-keys context keys allow-secret)
2029         (epg-wait-for-completion context)
2030         (if (epg-context-result-for context 'error)
2031             (error "Delete keys failed: %S"
2032                    (epg-context-result-for context 'error))))
2033     (epg-reset context)))
2034
2035 ;;;###autoload
2036 (defun epg-start-sign-keys (context keys &optional local)
2037   "Initiate an sign keys operation.
2038
2039 If you use this function, you will need to wait for the completion of
2040 `epg-gpg-program' by using `epg-wait-for-completion' and call
2041 `epg-reset' to clear a temporaly output file.
2042 If you are unsure, use synchronous version of this function
2043 `epg-sign-keys' instead."
2044   (epg-context-set-operation context 'sign-keys)
2045   (epg-context-set-result context nil)
2046   (epg--start context (cons (if local
2047                                "--lsign-key"
2048                              "--sign-key")
2049                            (mapcar
2050                             (lambda (key)
2051                               (epg-sub-key-id
2052                                (car (epg-key-sub-key-list key))))
2053                             keys))))
2054
2055 ;;;###autoload
2056 (defun epg-sign-keys (context keys &optional local)
2057   "Sign KEYS from the key ring."
2058   (unwind-protect
2059       (progn
2060         (epg-start-sign-keys context keys local)
2061         (epg-wait-for-completion context)
2062         (if (epg-context-result-for context 'error)
2063             (error "Sign keys failed: %S"
2064                    (epg-context-result-for context 'error))))
2065     (epg-reset context)))
2066
2067 ;;;###autoload
2068 (defun epg-start-generate-key (context parameters)
2069   "Initiate a key generation.
2070 PARAMETERS specifies parameters for the key.
2071
2072 If you use this function, you will need to wait for the completion of
2073 `epg-gpg-program' by using `epg-wait-for-completion' and call
2074 `epg-reset' to clear a temporaly output file.
2075 If you are unsure, use synchronous version of this function
2076 `epg-generate-key-from-file' or `epg-generate-key-from-string' instead."
2077   (epg-context-set-operation context 'generate-key)
2078   (epg-context-set-result context nil)
2079   (if (epg-data-file parameters)
2080       (epg--start context (list "--batch" "--genkey"
2081                                (epg-data-file parameters)))
2082     (epg--start context '("--batch" "--genkey"))
2083     (if (eq (process-status (epg-context-process context)) 'run)
2084         (process-send-string (epg-context-process context)
2085                              (epg-data-string parameters)))
2086     (if (eq (process-status (epg-context-process context)) 'run)
2087         (process-send-eof (epg-context-process context)))))
2088
2089 ;;;###autoload
2090 (defun epg-generate-key-from-file (context parameters)
2091   "Generate a new key pair.
2092 PARAMETERS is a file which tells how to create the key."
2093   (unwind-protect
2094       (progn
2095         (epg-start-generate-key context (epg-make-data-from-file parameters))
2096         (epg-wait-for-completion context)
2097         (if (epg-context-result-for context 'error)
2098             (error "Generate key failed: %S"
2099                    (epg-context-result-for context 'error))))
2100     (epg-reset context)))
2101
2102 ;;;###autoload
2103 (defun epg-generate-key-from-string (context parameters)
2104   "Generate a new key pair.
2105 PARAMETERS is a string which tells how to create the key."
2106   (unwind-protect
2107       (progn
2108         (epg-start-generate-key context (epg-make-data-from-string parameters))
2109         (epg-wait-for-completion context)
2110         (if (epg-context-result-for context 'error)
2111             (error "Generate key failed: %S"
2112                    (epg-context-result-for context 'error))))
2113     (epg-reset context)))
2114
2115 (defun epg--decode-hexstring (string)
2116   (let ((index 0))
2117     (while (eq index (string-match "[0-9A-Fa-f][0-9A-Fa-f]" string index))
2118       (setq string (replace-match "\\x\\&" t nil string)
2119             index (+ index 4)))
2120     (car (read-from-string (concat "\"" string "\"")))))
2121
2122 (defun epg--decode-quotedstring (string)
2123   (let ((index 0))
2124     (while (string-match "\\\\\\(\\([,=+<>#;\\\"]\\)\\|\
2125 \\([0-9A-Fa-f][0-9A-Fa-f]\\)\\|\\(.\\)\\)"
2126                          string index)
2127       (if (match-beginning 2)
2128           (setq string (replace-match "\\2" t nil string)
2129                 index (1+ index))
2130         (if (match-beginning 3)
2131             (setq string (replace-match "\\x\\3" t nil string)
2132                   index (+ index 4))
2133           (setq string (replace-match "\\\\\\\\\\4" t nil string)
2134                 index (+ index 3)))))
2135     (car (read-from-string (concat "\"" string "\"")))))
2136
2137 (defun epg-dn-from-string (string)
2138   "Parse STRING as LADPv3 Distinguished Names (RFC2253).
2139 The return value is an alist mapping from types to values."
2140   (let ((index 0)
2141         (length (length string))
2142         alist type value group)
2143     (while (< index length)
2144       (if (eq index (string-match "[ \t\n\r]*" string index))
2145           (setq index (match-end 0)))
2146       (if (eq index (string-match
2147                      "\\([0-9]+\\(\\.[0-9]+\\)*\\)\[ \t\n\r]*=[ \t\n\r]*"
2148                      string index))
2149           (setq type (match-string 1 string)
2150                 index (match-end 0))
2151         (if (eq index (string-match "\\([0-9A-Za-z]+\\)[ \t\n\r]*=[ \t\n\r]*"
2152                                     string index))
2153             (setq type (match-string 1 string)
2154                   index (match-end 0))))
2155       (unless type
2156         (error "Invalid type"))
2157       (if (eq index (string-match
2158                      "\\([^,=+<>#;\\\"]\\|\\\\.\\)+"
2159                      string index))
2160           (setq index (match-end 0)
2161                 value (epg--decode-quotedstring (match-string 0 string)))
2162         (if (eq index (string-match "#\\([0-9A-Fa-f]+\\)" string index))
2163             (setq index (match-end 0)
2164                   value (epg--decode-hexstring (match-string 1 string)))
2165           (if (eq index (string-match "\"\\([^\\\"]\\|\\\\.\\)*\""
2166                                       string index))
2167               (setq index (match-end 0)
2168                     value (epg--decode-quotedstring
2169                            (match-string 0 string))))))
2170       (if group
2171           (if (stringp (car (car alist)))
2172               (setcar alist (list (cons type value) (car alist)))
2173             (setcar alist (cons (cons type value) (car alist))))
2174         (if (consp (car (car alist)))
2175             (setcar alist (nreverse (car alist))))
2176         (setq alist (cons (cons type value) alist)
2177               type nil
2178               value nil))
2179       (if (eq index (string-match "[ \t\n\r]*\\([,;+]\\)" string index))
2180           (setq index (match-end 0)
2181                 group (eq (aref string (match-beginning 1)) ?+))))
2182     (nreverse alist)))
2183
2184 (defun epg-decode-dn (alist)
2185   "Convert ALIST returned by `epg-dn-from-string' to a human readable form.
2186 Type names are resolved using `epg-dn-type-alist'."
2187   (mapconcat
2188    (lambda (rdn)
2189      (if (stringp (car rdn))
2190          (let ((entry (assoc (car rdn) epg-dn-type-alist)))
2191            (if entry
2192                (format "%s=%s" (cdr entry) (cdr rdn))
2193              (format "%s=%s" (car rdn) (cdr rdn))))
2194        (concat "(" (epg-decode-dn rdn) ")")))
2195    alist
2196    ", "))
2197
2198 (provide 'epg)
2199
2200 ;;; epg.el ends here