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