Avoid div-by-zero error.
[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                 #'epg-progress-callback-function
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                              "--enable-progress-filter")
792                        (if epg-gpg-home-directory
793                            (list "--homedir" epg-gpg-home-directory))
794                        (unless (eq (epg-context-protocol context) 'CMS)
795                          (list "--command-fd" "0"))
796                        (if (epg-context-armor context) '("--armor"))
797                        (if (epg-context-textmode context) '("--textmode"))
798                        (if (epg-context-output-file context)
799                            (list "--output" (epg-context-output-file context)))
800                        args))
801          (coding-system-for-write 'binary)
802          process-connection-type
803          (orig-mode (default-file-modes))
804          (buffer (generate-new-buffer " *epg*"))
805          process)
806     (if epg-debug
807         (save-excursion
808           (unless epg-debug-buffer
809             (setq epg-debug-buffer (generate-new-buffer " *epg-debug*")))
810           (set-buffer epg-debug-buffer)
811           (goto-char (point-max))
812           (insert (format "%s %s\n"
813                           (if (eq (epg-context-protocol context) 'CMS)
814                               epg-gpgsm-program
815                            epg-gpg-program)
816                           (mapconcat #'identity args " ")))))
817     (with-current-buffer buffer
818       (make-local-variable 'epg-read-point)
819       (setq epg-read-point (point-min))
820       (make-local-variable 'epg-process-filter-running)
821       (setq epg-process-filter-running nil)
822       (make-local-variable 'epg-pending-status-list)
823       (setq epg-pending-status-list nil)
824       (make-local-variable 'epg-key-id)
825       (setq epg-key-id nil)
826       (make-local-variable 'epg-context)
827       (setq epg-context context))
828     (unwind-protect
829         (progn
830           (set-default-file-modes 448)
831           (setq process
832                 (apply #'start-process "epg" buffer
833                        (if (eq (epg-context-protocol context) 'CMS)
834                            epg-gpgsm-program
835                          epg-gpg-program)
836                        args)))
837       (set-default-file-modes orig-mode))
838     (set-process-filter process #'epg--process-filter)
839     (epg-context-set-process context process)))
840
841 (defun epg--process-filter (process input)
842   (if epg-debug
843       (save-excursion
844         (unless epg-debug-buffer
845           (setq epg-debug-buffer (generate-new-buffer " *epg-debug*")))
846         (set-buffer epg-debug-buffer)
847         (goto-char (point-max))
848         (insert input)))
849   (if (buffer-live-p (process-buffer process))
850       (save-excursion
851         (set-buffer (process-buffer process))
852         (goto-char (point-max))
853         (insert input)
854         (unless epg-process-filter-running
855           (unwind-protect
856               (progn
857                 (setq epg-process-filter-running t)
858                 (goto-char epg-read-point)
859                 (beginning-of-line)
860                 (while (looking-at ".*\n") ;the input line finished
861                   (if (looking-at "\\[GNUPG:] \\([A-Z_]+\\) ?\\(.*\\)")
862                       (let* ((status (match-string 1))
863                              (string (match-string 2))
864                              (symbol (intern-soft (concat "epg--status-"
865                                                           status))))
866                         (if (member status epg-pending-status-list)
867                             (setq epg-pending-status-list nil))
868                         (if (and symbol
869                                  (fboundp symbol))
870                             (funcall symbol epg-context string))))
871                   (forward-line)
872                   (setq epg-read-point (point))))
873             (setq epg-process-filter-running nil))))))
874
875 (defun epg-read-output (context)
876   "Read the output file CONTEXT and return the content as a string."
877   (with-temp-buffer
878     (if (fboundp 'set-buffer-multibyte)
879         (set-buffer-multibyte nil))
880     (if (file-exists-p (epg-context-output-file context))
881         (let ((coding-system-for-read 'binary))
882           (insert-file-contents (epg-context-output-file context))
883           (buffer-string)))))
884
885 (defun epg-wait-for-status (context status-list)
886   "Wait until one of elements in STATUS-LIST arrives."
887   (with-current-buffer (process-buffer (epg-context-process context))
888     (setq epg-pending-status-list status-list)
889     (while (and (eq (process-status (epg-context-process context)) 'run)
890                 epg-pending-status-list)
891       (accept-process-output (epg-context-process context) 1))))
892
893 (defun epg-wait-for-completion (context)
894   "Wait until the `epg-gpg-program' process completes."
895   (while (eq (process-status (epg-context-process context)) 'run)
896     (accept-process-output (epg-context-process context) 1)))
897
898 (defun epg-reset (context)
899   "Reset the CONTEXT."
900   (if (and (epg-context-process context)
901            (buffer-live-p (process-buffer (epg-context-process context))))
902       (kill-buffer (process-buffer (epg-context-process context))))
903   (epg-context-set-process context nil))
904
905 (defun epg-delete-output-file (context)
906   "Delete the output file of CONTEXT."
907   (if (and (epg-context-output-file context)
908            (file-exists-p (epg-context-output-file context)))
909       (delete-file (epg-context-output-file context))))
910
911 (defun epg--status-USERID_HINT (context string)
912   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
913       (let* ((key-id (match-string 1 string))
914              (user-id (match-string 2 string))
915              (entry (assoc key-id epg-user-id-alist)))
916         (if entry
917             (setcdr entry user-id)
918           (setq epg-user-id-alist (cons (cons key-id user-id)
919                                         epg-user-id-alist))))))
920
921 (defun epg--status-NEED_PASSPHRASE (context string)
922   (if (string-match "\\`\\([^ ]+\\)" string)
923       (setq epg-key-id (match-string 1 string))))
924
925 (defun epg--status-NEED_PASSPHRASE_SYM (context string)
926   (setq epg-key-id 'SYM))
927
928 (defun epg--status-NEED_PASSPHRASE_PIN (context string)
929   (setq epg-key-id 'PIN))
930
931 (defun epg--status-GET_HIDDEN (context string)
932   (if (and epg-key-id
933            (string-match "\\`passphrase\\." string))
934       (let (inhibit-quit
935             passphrase
936             passphrase-with-new-line
937             encoded-passphrase-with-new-line)
938         (unwind-protect
939             (condition-case nil
940                 (progn
941                   (setq passphrase
942                         (funcall
943                          (if (consp (epg-context-passphrase-callback context))
944                              (car (epg-context-passphrase-callback context))
945                            (epg-context-passphrase-callback context))
946                          context
947                          epg-key-id
948                          (if (consp (epg-context-passphrase-callback context))
949                              (cdr (epg-context-passphrase-callback context)))))
950                   (when passphrase
951                     (setq passphrase-with-new-line (concat passphrase "\n"))
952                     (epg--clear-string passphrase)
953                     (setq passphrase nil)
954                     (if epg-passphrase-coding-system
955                         (progn
956                           (setq encoded-passphrase-with-new-line
957                                 (encode-coding-string
958                                  passphrase-with-new-line
959                                  epg-passphrase-coding-system))
960                           (epg--clear-string passphrase-with-new-line)
961                           (setq passphrase-with-new-line nil))
962                       (setq encoded-passphrase-with-new-line
963                             passphrase-with-new-line
964                             passphrase-with-new-line nil))
965                     (process-send-string (epg-context-process context)
966                                          encoded-passphrase-with-new-line)))
967               (quit
968                (epg-context-set-result-for
969                 context 'error
970                 (cons '(quit)
971                       (epg-context-result-for context 'error)))
972                (delete-process (epg-context-process context))))
973           (if passphrase
974               (epg--clear-string passphrase))
975           (if passphrase-with-new-line
976               (epg--clear-string passphrase-with-new-line))
977           (if encoded-passphrase-with-new-line
978               (epg--clear-string encoded-passphrase-with-new-line))))))
979
980 (defun epg--status-GET_BOOL (context string)
981   (let ((entry (assoc string epg-prompt-alist))
982         inhibit-quit)
983     (condition-case nil
984       (if (y-or-n-p (if entry (cdr entry) (concat string "? ")))
985           (process-send-string (epg-context-process context) "y\n")
986         (process-send-string (epg-context-process context) "n\n"))
987       (quit
988        (epg-context-set-result-for
989         context 'error
990         (cons '(quit)
991               (epg-context-result-for context 'error)))
992        (delete-process (epg-context-process context))))))
993
994 (defun epg--status-GET_LINE (context string)
995   (let ((entry (assoc string epg-prompt-alist))
996         inhibit-quit)
997     (condition-case nil
998         (process-send-string (epg-context-process context)
999                              (concat (read-string
1000                                       (if entry
1001                                           (cdr entry)
1002                                         (concat string ": ")))
1003                                      "\n"))
1004       (quit
1005        (epg-context-set-result-for
1006         context 'error
1007         (cons '(quit)
1008               (epg-context-result-for context 'error)))
1009        (delete-process (epg-context-process context))))))
1010
1011 (defun epg--status-*SIG (context status string)
1012   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
1013       (let* ((key-id (match-string 1 string))
1014              (user-id (match-string 2 string))
1015              (entry (assoc key-id epg-user-id-alist)))
1016         (epg-context-set-result-for
1017          context
1018          'verify
1019          (cons (epg-make-signature status key-id)
1020                (epg-context-result-for context 'verify)))
1021         (if (eq (epg-context-protocol context) 'CMS)
1022             (condition-case nil
1023                 (setq user-id (epg-dn-from-string user-id))
1024               (error)))
1025         (if entry
1026             (setcdr entry user-id)
1027           (setq epg-user-id-alist
1028                 (cons (cons key-id user-id) epg-user-id-alist))))
1029     (epg-context-set-result-for
1030      context
1031      'verify
1032      (cons (epg-make-signature status)
1033            (epg-context-result-for context 'verify)))))
1034
1035 (defun epg--status-GOODSIG (context string)
1036   (epg--status-*SIG context 'good string))
1037
1038 (defun epg--status-EXPSIG (context string)
1039   (epg--status-*SIG context 'expired string))
1040
1041 (defun epg--status-EXPKEYSIG (context string)
1042   (epg--status-*SIG context 'expired-key string))
1043
1044 (defun epg--status-REVKEYSIG (context string)
1045   (epg--status-*SIG context 'revoked-key string))
1046
1047 (defun epg--status-BADSIG (context string)
1048   (epg--status-*SIG context 'bad string))
1049
1050 (defun epg--status-NO_PUBKEY (context string)
1051   (let ((signature (car (epg-context-result-for context 'verify))))
1052     (if (and signature
1053              (eq (epg-signature-status signature) 'error)
1054              (equal (epg-signature-key-id signature) string))
1055         (epg-signature-set-status signature 'no-pubkey))))
1056
1057 (defun epg--time-from-seconds (seconds)
1058   (let ((number-seconds (string-to-number (concat seconds ".0"))))
1059     (cons (floor (/ number-seconds 65536))
1060           (floor (mod number-seconds 65536)))))
1061
1062 (defun epg--status-ERRSIG (context string)
1063   (if (string-match "\\`\\([^ ]+\\) \\([0-9]+\\) \\([0-9]+\\) \
1064 \\([0-9A-Fa-f][0-9A-Fa-f]\\) \\([^ ]+\\) \\([0-9]+\\)"
1065                     string)
1066       (let ((signature (epg-make-signature 'error)))
1067         (epg-context-set-result-for
1068          context
1069          'verify
1070          (cons signature
1071                (epg-context-result-for context 'verify)))
1072         (epg-signature-set-key-id
1073          signature
1074          (match-string 1 string))
1075         (epg-signature-set-pubkey-algorithm
1076          signature
1077          (string-to-number (match-string 2 string)))
1078         (epg-signature-set-digest-algorithm
1079          signature
1080          (string-to-number (match-string 3 string)))
1081         (epg-signature-set-class
1082          signature
1083          (string-to-number (match-string 4 string) 16))
1084         (epg-signature-set-creation-time
1085          signature
1086          (epg--time-from-seconds (match-string 5 string))))))
1087
1088 (defun epg--status-VALIDSIG (context string)
1089   (let ((signature (car (epg-context-result-for context 'verify))))
1090     (when (and signature
1091                (eq (epg-signature-status signature) 'good)
1092                (string-match "\\`\\([^ ]+\\) [^ ]+ \\([^ ]+\\) \\([^ ]+\\) \
1093 \\([0-9]+\\) [^ ]+ \\([0-9]+\\) \\([0-9]+\\) \\([0-9A-Fa-f][0-9A-Fa-f]\\) \
1094 \\(.*\\)"
1095                            string))
1096       (epg-signature-set-fingerprint
1097        signature
1098        (match-string 1 string))
1099       (epg-signature-set-creation-time
1100        signature
1101        (epg--time-from-seconds (match-string 2 string)))
1102       (epg-signature-set-expiration-time
1103        signature
1104        (epg--time-from-seconds (match-string 3 string)))
1105       (epg-signature-set-version
1106        signature
1107        (string-to-number (match-string 4 string)))
1108       (epg-signature-set-pubkey-algorithm
1109        signature 
1110        (string-to-number (match-string 5 string)))
1111       (epg-signature-set-digest-algorithm
1112        signature
1113        (string-to-number (match-string 6 string)))
1114       (epg-signature-set-class
1115        signature
1116        (string-to-number (match-string 7 string) 16)))))
1117
1118 (defun epg--status-TRUST_UNDEFINED (context string)
1119   (let ((signature (car (epg-context-result-for context 'verify))))
1120     (if (and signature
1121              (eq (epg-signature-status signature) 'good))
1122         (epg-signature-set-validity signature 'undefined))))
1123
1124 (defun epg--status-TRUST_NEVER (context string)
1125   (let ((signature (car (epg-context-result-for context 'verify))))
1126     (if (and signature
1127              (eq (epg-signature-status signature) 'good))
1128         (epg-signature-set-validity signature 'never))))
1129
1130 (defun epg--status-TRUST_MARGINAL (context string)
1131   (let ((signature (car (epg-context-result-for context 'verify))))
1132     (if (and signature
1133              (eq (epg-signature-status signature) 'marginal))
1134         (epg-signature-set-validity signature 'marginal))))
1135
1136 (defun epg--status-TRUST_FULLY (context string)
1137   (let ((signature (car (epg-context-result-for context 'verify))))
1138     (if (and signature
1139              (eq (epg-signature-status signature) 'good))
1140         (epg-signature-set-validity signature 'full))))
1141
1142 (defun epg--status-TRUST_ULTIMATE (context string)
1143   (let ((signature (car (epg-context-result-for context 'verify))))
1144     (if (and signature
1145              (eq (epg-signature-status signature) 'good))
1146         (epg-signature-set-validity signature 'ultimate))))
1147
1148 (defun epg--status-PROGRESS (context string)
1149   (if (string-match "\\`\\([^ ]+\\) \\([^ ]\\) \\([0-9]+\\) \\([0-9]+\\)"
1150                     string)
1151       (funcall (if (consp (epg-context-progress-callback context))
1152                    (car (epg-context-progress-callback context))
1153                  (epg-context-progress-callback context))
1154                context
1155                (match-string 1 string)
1156                (match-string 2 string)
1157                (string-to-number (match-string 3 string))
1158                (string-to-number (match-string 4 string))
1159                (if (consp (epg-context-progress-callback context))
1160                    (cdr (epg-context-progress-callback context))))))
1161
1162 (defun epg--status-DECRYPTION_FAILED (context string)
1163   (epg-context-set-result-for
1164    context 'error
1165    (cons '(decryption-failed)
1166          (epg-context-result-for context 'error))))
1167
1168 (defun epg--status-NODATA (context string)
1169   (epg-context-set-result-for
1170    context 'error
1171    (cons (list 'no-data (cons 'reason (string-to-number string)))
1172          (epg-context-result-for context 'error))))
1173
1174 (defun epg--status-UNEXPECTED (context string)
1175   (epg-context-set-result-for
1176    context 'error
1177    (cons (list 'unexpected (cons 'reason (string-to-number string)))
1178          (epg-context-result-for context 'error))))
1179
1180 (defun epg--status-KEYEXPIRED (context string)
1181   (epg-context-set-result-for
1182    context 'error
1183    (cons (list 'key-expired (cons 'expiration-time
1184                                   (epg--time-from-seconds string)))
1185          (epg-context-result-for context 'error))))
1186
1187 (defun epg--status-KEYREVOKED (context string)
1188   (epg-context-set-result-for
1189    context 'error
1190    (cons '(key-revoked)
1191          (epg-context-result-for context 'error))))
1192
1193 (defun epg--status-BADARMOR (context string)
1194   (epg-context-set-result-for
1195    context 'error
1196    (cons '(bad-armor)
1197          (epg-context-result-for context 'error))))
1198
1199 (defun epg--status-INV_RECP (context string)
1200   (if (string-match "\\`\\([0-9]+\\) \\(.*\\)" string)
1201       (epg-context-set-result-for
1202        context 'error
1203        (cons (list 'invalid-recipient
1204                    (cons 'reason
1205                          (string-to-number (match-string 1 string)))
1206                    (cons 'requested-recipient
1207                          (match-string 2 string)))
1208              (epg-context-result-for context 'error)))))
1209
1210 (defun epg--status-NO_RECP (context string)
1211   (epg-context-set-result-for
1212    context 'error
1213    (cons '(no-recipients)
1214          (epg-context-result-for context 'error))))
1215
1216 (defun epg--status-DELETE_PROBLEM (context string)
1217   (if (string-match "\\`\\([0-9]+\\)" string)
1218       (epg-context-set-result-for
1219        context 'error
1220        (cons (list 'delete-problem
1221                    (cons 'reason (string-to-number (match-string 1 string))))
1222              (epg-context-result-for context 'error)))))
1223
1224 (defun epg--status-SIG_CREATED (context string)
1225   (if (string-match "\\`\\([DCS]\\) \\([0-9]+\\) \\([0-9]+\\) \
1226 \\([0-9A-Fa-F][0-9A-Fa-F]\\) \\(.*\\) " string)
1227       (epg-context-set-result-for
1228        context 'sign
1229        (cons (epg-make-new-signature
1230               (cdr (assq (aref (match-string 1 string) 0)
1231                          epg-new-signature-type-alist))
1232               (string-to-number (match-string 2 string))
1233               (string-to-number (match-string 3 string))
1234               (string-to-number (match-string 4 string) 16)
1235               (epg--time-from-seconds (match-string 5 string))
1236               (substring string (match-end 0)))
1237              (epg-context-result-for context 'sign)))))
1238
1239 (defun epg--status-KEY_CREATED (context string)
1240   (if (string-match "\\`\\([BPS]\\) \\([^ ]+\\)" string)
1241       (epg-context-set-result-for
1242        context 'generate-key
1243        (cons (list (cons 'type (string-to-char (match-string 1 string)))
1244                    (cons 'fingerprint (match-string 2 string)))
1245              (epg-context-result-for context 'generate-key)))))
1246
1247 (defun epg--status-KEY_NOT_CREATED (context string)
1248   (epg-context-set-result-for
1249    context 'error
1250    (cons '(key-not-created)
1251          (epg-context-result-for context 'error))))
1252
1253 (defun epg--status-IMPORTED (context string)
1254   (if (string-match "\\`\\([^ ]+\\) \\(.*\\)" string)
1255       (let* ((key-id (match-string 1 string))
1256              (user-id (match-string 2 string))
1257              (entry (assoc key-id epg-user-id-alist)))
1258         (if entry
1259             (setcdr entry user-id)
1260           (setq epg-user-id-alist (cons (cons key-id user-id)
1261                                         epg-user-id-alist)))
1262         (epg-context-set-result-for
1263          context 'import
1264          (cons (list (cons 'key-id key-id)
1265                      (cons 'user-id user-id))
1266                (epg-context-result-for context 'import))))))
1267
1268 (defun epg--status-IMPORT_OK (context string)
1269   (let ((result (epg-context-result-for context 'import)))
1270     (if (and result
1271              (string-match "\\`\\([0-9]+\\)\\( \\(.+\\)\\)?" string))
1272         (setcar result
1273                 (append (list (cons 'reason
1274                                     (string-to-number
1275                                      (match-string 1 string))))
1276                         (if (match-beginning 2)
1277                             (list (cons 'fingerprint
1278                                         (match-string 3 string))))
1279                         (car result))))))
1280
1281 (defun epg--status-IMPORT_PROBLEM (context string)
1282   (if (string-match "\\`\\([0-9]+\\)\\( \\(.+\\)\\)?" string)
1283       (epg-context-set-result-for
1284        context 'error
1285        (cons (cons 'import-problem
1286                    (append (list (cons 'reason
1287                                        (string-to-number
1288                                         (match-string 1 string))))
1289                            (if (match-beginning 2)
1290                                (list (cons 'fingerprint
1291                                            (match-string 3 string))))))
1292              (epg-context-result-for context 'error)))))
1293
1294 (defun epg-passphrase-callback-function (context key-id handback)
1295   (if (eq key-id 'SYM)
1296       (read-passwd "Passphrase for symmetric encryption: "
1297                    (eq (epg-context-operation context) 'encrypt))
1298     (read-passwd
1299      (if (eq key-id 'PIN)
1300         "Passphrase for PIN: "
1301        (let ((entry (assoc key-id epg-user-id-alist)))
1302          (if entry
1303              (format "Passphrase for %s %s: " key-id (cdr entry))
1304            (format "Passphrase for %s: " key-id)))))))
1305
1306 (defun epg-progress-callback-function (context what char current total
1307                                                handback)
1308   (message "%s: %d%% (%d/%d)" what (if (> total 0) (/ current 1.0 total) 0)
1309            current total))
1310
1311 (defun epg--list-keys-1 (context name mode)
1312   (let ((args (append (if epg-gpg-home-directory
1313                           (list "--homedir" epg-gpg-home-directory))
1314                       (list "--with-colons" "--no-greeting" "--batch"
1315                             "--with-fingerprint"
1316                             "--with-fingerprint"
1317                             (if (memq mode '(t secret))
1318                                 "--list-secret-keys"
1319                               (if (memq mode '(nil public))
1320                                   "--list-keys"
1321                                 "--list-sigs")))
1322                       (unless (eq (epg-context-protocol context) 'CMS)
1323                         '("--fixed-list-mode"))
1324                       (if name (list name))))
1325         keys string field index)
1326     (with-temp-buffer
1327       (apply #'call-process
1328              (if (eq (epg-context-protocol context) 'CMS)
1329                  epg-gpgsm-program
1330                epg-gpg-program)
1331              nil (list t nil) nil args)
1332       (goto-char (point-min))
1333       (while (re-search-forward "^[a-z][a-z][a-z]:.*" nil t)
1334         (setq keys (cons (make-vector 15 nil) keys)
1335               string (match-string 0)
1336               index 0
1337               field 0)
1338         (while (eq index
1339                    (string-match "\\([^:]+\\)?:" string index))
1340           (setq index (match-end 0))
1341           (aset (car keys) field (match-string 1 string))
1342           (setq field (1+ field))))
1343       (nreverse keys))))
1344
1345 (defun epg--make-sub-key-1 (line)
1346   (epg-make-sub-key
1347    (if (aref line 1)
1348        (cdr (assq (string-to-char (aref line 1)) epg-key-validity-alist)))
1349    (delq nil
1350          (mapcar (lambda (char) (cdr (assq char epg-key-capablity-alist)))
1351                  (aref line 11)))
1352    (member (aref line 0) '("sec" "ssb"))
1353    (string-to-number (aref line 3))
1354    (string-to-number (aref line 2))
1355    (aref line 4)
1356    (epg--time-from-seconds (aref line 5))
1357    (epg--time-from-seconds (aref line 6))))
1358
1359 ;;;###autoload
1360 (defun epg-list-keys (context &optional name mode)
1361   "Return a list of epg-key objects matched with NAME.
1362 If MODE is nil or 'public, only public keyring should be searched.
1363 If MODE is t or 'secret, only secret keyring should be searched. 
1364 Otherwise, only public keyring should be searched and the key
1365 signatures should be included."
1366   (let ((lines (epg--list-keys-1 context name mode))
1367         keys cert pointer pointer-1)
1368     (while lines
1369       (cond
1370        ((member (aref (car lines) 0) '("pub" "sec" "crt" "crs"))
1371         (setq cert (member (aref (car lines) 0) '("crt" "crs"))
1372               keys (cons (epg-make-key
1373                           (if (aref (car lines) 8)
1374                               (cdr (assq (string-to-char (aref (car lines) 8))
1375                                          epg-key-validity-alist))))
1376                          keys))
1377         (epg-key-set-sub-key-list
1378          (car keys)
1379          (cons (epg--make-sub-key-1 (car lines))
1380                (epg-key-sub-key-list (car keys)))))
1381        ((member (aref (car lines) 0) '("sub" "ssb"))
1382         (epg-key-set-sub-key-list
1383          (car keys)
1384          (cons (epg--make-sub-key-1 (car lines))
1385                (epg-key-sub-key-list (car keys)))))
1386        ((equal (aref (car lines) 0) "uid")
1387         (epg-key-set-user-id-list
1388          (car keys)
1389          (cons (epg-make-user-id
1390                 (if (aref (car lines) 1)
1391                     (cdr (assq (string-to-char (aref (car lines) 1))
1392                                epg-key-validity-alist)))
1393                 (if cert
1394                     (condition-case nil
1395                         (epg-dn-from-string (aref (car lines) 9))
1396                       (error (aref (car lines) 9)))
1397                   (aref (car lines) 9)))
1398                (epg-key-user-id-list (car keys)))))
1399        ((equal (aref (car lines) 0) "fpr")
1400         (epg-sub-key-set-fingerprint (car (epg-key-sub-key-list (car keys)))
1401                                      (aref (car lines) 9)))
1402        ((equal (aref (car lines) 0) "sig")
1403         (epg-user-id-set-signature-list
1404          (car (epg-key-user-id-list (car keys)))
1405          (cons
1406           (epg-make-key-signature
1407            (if (aref (car lines) 1)
1408                (cdr (assq (string-to-char (aref (car lines) 1))
1409                           epg-key-validity-alist)))
1410            (string-to-number (aref (car lines) 3))
1411            (aref (car lines) 4)
1412            (epg--time-from-seconds (aref (car lines) 5))
1413            (epg--time-from-seconds (aref (car lines) 6))
1414            (aref (car lines) 9)
1415            (string-to-number (aref (car lines) 10) 16)
1416            (eq (aref (aref (car lines) 10) 2) ?x))
1417           (epg-user-id-signature-list
1418            (car (epg-key-user-id-list (car keys))))))))
1419       (setq lines (cdr lines)))
1420     (setq keys (nreverse keys)
1421           pointer keys)
1422     (while pointer
1423       (epg-key-set-sub-key-list
1424        (car pointer)
1425        (nreverse (epg-key-sub-key-list (car pointer))))
1426       (setq pointer-1 (epg-key-set-user-id-list
1427                           (car pointer)
1428                           (nreverse (epg-key-user-id-list (car pointer)))))
1429       (while pointer-1
1430         (epg-user-id-set-signature-list
1431          (car pointer-1)
1432          (nreverse (epg-user-id-signature-list (car pointer-1))))
1433         (setq pointer-1 (cdr pointer-1)))
1434       (setq pointer (cdr pointer)))
1435     keys))
1436
1437 (if (fboundp 'make-temp-file)
1438     (defalias 'epg--make-temp-file 'make-temp-file)
1439   (defvar temporary-file-directory)
1440   ;; stolen from poe.el.
1441   (defun epg--make-temp-file (prefix)
1442     "Create a temporary file.
1443 The returned file name (created by appending some random characters at the end
1444 of PREFIX, and expanding against `temporary-file-directory' if necessary),
1445 is guaranteed to point to a newly created empty file.
1446 You can then use `write-region' to write new data into the file."
1447     (let (tempdir tempfile)
1448       (setq prefix (expand-file-name prefix
1449                                      (if (featurep 'xemacs)
1450                                          (temp-directory)
1451                                        temporary-file-directory)))
1452       (unwind-protect
1453           (let (file)
1454             ;; First, create a temporary directory.
1455             (while (condition-case ()
1456                        (progn
1457                          (setq tempdir (make-temp-name
1458                                         (concat
1459                                          (file-name-directory prefix)
1460                                          "DIR")))
1461                          ;; return nil or signal an error.
1462                          (make-directory tempdir))
1463                      ;; let's try again.
1464                      (file-already-exists t)))
1465             (set-file-modes tempdir 448)
1466             ;; Second, create a temporary file in the tempdir.
1467             ;; There *is* a race condition between `make-temp-name'
1468             ;; and `write-region', but we don't care it since we are
1469             ;; in a private directory now.
1470             (setq tempfile (make-temp-name (concat tempdir "/EMU")))
1471             (write-region "" nil tempfile nil 'silent)
1472             (set-file-modes tempfile 384)
1473             ;; Finally, make a hard-link from the tempfile.
1474             (while (condition-case ()
1475                        (progn
1476                          (setq file (make-temp-name prefix))
1477                          ;; return nil or signal an error.
1478                          (add-name-to-file tempfile file))
1479                      ;; let's try again.
1480                      (file-already-exists t)))
1481             file)
1482         ;; Cleanup the tempfile.
1483         (and tempfile
1484              (file-exists-p tempfile)
1485              (delete-file tempfile))
1486         ;; Cleanup the tempdir.
1487         (and tempdir
1488              (file-directory-p tempdir)
1489              (delete-directory tempdir))))))
1490
1491 (if (fboundp 'clear-string)
1492     (defalias 'epg--clear-string 'clear-string)
1493   (defun epg--clear-string (string)
1494     (fillarray string 0)))
1495
1496 ;;;###autoload
1497 (defun epg-cancel (context)
1498   (if (buffer-live-p (process-buffer (epg-context-process context)))
1499       (save-excursion
1500         (set-buffer (process-buffer (epg-context-process context)))
1501         (epg-context-set-result-for
1502          epg-context 'error
1503          (cons '(quit)
1504                (epg-context-result-for epg-context 'error)))))
1505   (if (eq (process-status (epg-context-process context)) 'run)
1506       (delete-process (epg-context-process context))))
1507   
1508 ;;;###autoload
1509 (defun epg-start-decrypt (context cipher)
1510   "Initiate a decrypt operation on CIPHER.
1511 CIPHER is a data object.
1512
1513 If you use this function, you will need to wait for the completion of
1514 `epg-gpg-program' by using `epg-wait-for-completion' and call
1515 `epg-reset' to clear a temporaly output file.
1516 If you are unsure, use synchronous version of this function
1517 `epg-decrypt-file' or `epg-decrypt-string' instead."
1518   (unless (epg-data-file cipher)
1519     (error "Not a file"))
1520   (epg-context-set-operation context 'decrypt)
1521   (epg-context-set-result context nil)
1522   (epg--start context (list "--decrypt" (epg-data-file cipher)))
1523   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1524   (unless (eq (epg-context-protocol context) 'CMS)
1525     (epg-wait-for-status context '("BEGIN_DECRYPTION"))))
1526
1527 ;;;###autoload
1528 (defun epg-decrypt-file (context cipher plain)
1529   "Decrypt a file CIPHER and store the result to a file PLAIN.
1530 If PLAIN is nil, it returns the result as a string."
1531   (unwind-protect
1532       (progn
1533         (if plain
1534             (epg-context-set-output-file context plain)
1535           (epg-context-set-output-file context
1536                                        (epg--make-temp-file "epg-output")))
1537         (epg-start-decrypt context (epg-make-data-from-file cipher))
1538         (epg-wait-for-completion context)
1539         (if (epg-context-result-for context 'error)
1540             (error "Decrypt failed: %S"
1541                    (epg-context-result-for context 'error)))
1542         (unless plain
1543           (epg-read-output context)))
1544     (unless plain
1545       (epg-delete-output-file context))
1546     (epg-reset context)))
1547
1548 ;;;###autoload
1549 (defun epg-decrypt-string (context cipher)
1550   "Decrypt a string CIPHER and return the plain text."
1551   (let ((input-file (epg--make-temp-file "epg-input"))
1552         (coding-system-for-write 'binary))
1553     (unwind-protect
1554         (progn
1555           (write-region cipher nil input-file nil 'quiet)
1556           (epg-context-set-output-file context
1557                                        (epg--make-temp-file "epg-output"))
1558           (epg-start-decrypt context (epg-make-data-from-file input-file))
1559           (epg-wait-for-completion context)
1560           (if (epg-context-result-for context 'error)
1561               (error "Decrypt failed: %S"
1562                      (epg-context-result-for context 'error)))
1563           (epg-read-output context))
1564       (epg-delete-output-file context)
1565       (if (file-exists-p input-file)
1566           (delete-file input-file))
1567       (epg-reset context))))
1568
1569 ;;;###autoload
1570 (defun epg-start-verify (context signature &optional signed-text)
1571   "Initiate a verify operation on SIGNATURE.
1572 SIGNATURE and SIGNED-TEXT are a data object if they are specified.
1573
1574 For a detached signature, both SIGNATURE and SIGNED-TEXT should be set.
1575 For a normal or a clear text signature, SIGNED-TEXT should be nil.
1576
1577 If you use this function, you will need to wait for the completion of
1578 `epg-gpg-program' by using `epg-wait-for-completion' and call
1579 `epg-reset' to clear a temporaly output file.
1580 If you are unsure, use synchronous version of this function
1581 `epg-verify-file' or `epg-verify-string' instead."
1582   (epg-context-set-operation context 'verify)
1583   (epg-context-set-result context nil)
1584   (if signed-text
1585       ;; Detached signature.
1586       (if (epg-data-file signed-text)
1587           (epg--start context (list "--verify" (epg-data-file signature)
1588                                    (epg-data-file signed-text)))
1589         (epg--start context (list "--verify" (epg-data-file signature) "-"))
1590         (if (eq (process-status (epg-context-process context)) 'run)
1591             (process-send-string (epg-context-process context)
1592                                  (epg-data-string signed-text)))
1593         (if (eq (process-status (epg-context-process context)) 'run)
1594             (process-send-eof (epg-context-process context))))
1595     ;; Normal (or cleartext) signature.
1596     (if (epg-data-file signature)
1597         (epg--start context (list "--verify" (epg-data-file signature)))
1598       (epg--start context (list "--verify"))
1599       (if (eq (process-status (epg-context-process context)) 'run)
1600           (process-send-string (epg-context-process context)
1601                                (epg-data-string signature)))
1602       (if (eq (process-status (epg-context-process context)) 'run)
1603           (process-send-eof (epg-context-process context))))))
1604
1605 ;;;###autoload
1606 (defun epg-verify-file (context signature &optional signed-text plain)
1607   "Verify a file SIGNATURE.
1608 SIGNED-TEXT and PLAIN are also a file if they are specified.
1609
1610 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
1611 For a normal or a clear text signature, SIGNED-TEXT should be nil."
1612   (unwind-protect
1613       (progn
1614         (if plain
1615             (epg-context-set-output-file context plain)
1616           (epg-context-set-output-file context
1617                                        (epg--make-temp-file "epg-output")))
1618         (if signed-text
1619             (epg-start-verify context
1620                               (epg-make-data-from-file signature)
1621                               (epg-make-data-from-file signed-text))
1622           (epg-start-verify context
1623                             (epg-make-data-from-file signature)))
1624         (epg-wait-for-completion context)
1625 ;       (if (epg-context-result-for context 'error)
1626 ;           (error "Verify failed: %S"
1627 ;                  (epg-context-result-for context 'error)))
1628         (unless plain
1629           (epg-read-output context)))
1630     (unless plain
1631       (epg-delete-output-file context))
1632     (epg-reset context)))
1633
1634 ;;;###autoload
1635 (defun epg-verify-string (context signature &optional signed-text)
1636   "Verify a string SIGNATURE.
1637 SIGNED-TEXT is a string if it is specified.
1638
1639 For a detached signature, both SIGNATURE and SIGNED-TEXT should be string.
1640 For a normal or a clear text signature, SIGNED-TEXT should be nil."
1641   (let ((coding-system-for-write 'binary)
1642         input-file)
1643     (unwind-protect
1644         (progn
1645           (epg-context-set-output-file context
1646                                        (epg--make-temp-file "epg-output"))
1647           (if signed-text
1648               (progn
1649                 (setq input-file (epg--make-temp-file "epg-signature"))
1650                 (write-region signature nil input-file nil 'quiet)
1651                 (epg-start-verify context
1652                                   (epg-make-data-from-file input-file)
1653                                   (epg-make-data-from-string signed-text)))
1654             (epg-start-verify context (epg-make-data-from-string signature)))
1655           (epg-wait-for-completion context)
1656 ;         (if (epg-context-result-for context 'error)
1657 ;             (error "Verify failed: %S"
1658 ;                    (epg-context-result-for context 'error)))
1659           (epg-read-output context))
1660       (epg-delete-output-file context)
1661       (if (and input-file
1662                (file-exists-p input-file))
1663           (delete-file input-file))
1664       (epg-reset context))))
1665
1666 ;;;###autoload
1667 (defun epg-start-sign (context plain &optional mode)
1668   "Initiate a sign operation on PLAIN.
1669 PLAIN is a data object.
1670
1671 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1672 If it is nil or 'normal, it makes a normal signature.
1673 Otherwise, it makes a clear text signature.
1674
1675 If you use this function, you will need to wait for the completion of
1676 `epg-gpg-program' by using `epg-wait-for-completion' and call
1677 `epg-reset' to clear a temporaly output file.
1678 If you are unsure, use synchronous version of this function
1679 `epg-sign-file' or `epg-sign-string' instead."
1680   (epg-context-set-operation context 'sign)
1681   (epg-context-set-result context nil)
1682   (epg--start context
1683              (append (list (if (memq mode '(t detached))
1684                                "--detach-sign"
1685                              (if (memq mode '(nil normal))
1686                                  "--sign"
1687                                "--clearsign")))
1688                      (apply #'nconc
1689                             (mapcar
1690                              (lambda (signer)
1691                                (list "-u"
1692                                      (epg-sub-key-id
1693                                       (car (epg-key-sub-key-list signer)))))
1694                              (epg-context-signers context)))
1695                      (if (epg-data-file plain)
1696                          (list (epg-data-file plain)))))
1697   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1698   (unless (eq (epg-context-protocol context) 'CMS)
1699     (epg-wait-for-status context '("BEGIN_SIGNING")))
1700   (when (epg-data-string plain)
1701     (if (eq (process-status (epg-context-process context)) 'run)
1702         (process-send-string (epg-context-process context)
1703                              (epg-data-string plain)))
1704     (if (eq (process-status (epg-context-process context)) 'run)
1705         (process-send-eof (epg-context-process context)))))
1706
1707 ;;;###autoload
1708 (defun epg-sign-file (context plain signature &optional mode)
1709   "Sign a file PLAIN and store the result to a file SIGNATURE.
1710 If SIGNATURE is nil, it returns the result as a string.
1711 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1712 If it is nil or 'normal, it makes a normal signature.
1713 Otherwise, it makes a clear text signature."
1714   (unwind-protect
1715       (progn
1716         (if signature
1717             (epg-context-set-output-file context signature)
1718           (epg-context-set-output-file context
1719                                        (epg--make-temp-file "epg-output")))
1720         (epg-start-sign context (epg-make-data-from-file plain) mode)
1721         (epg-wait-for-completion context)
1722         (unless (epg-context-result-for context 'sign)
1723           (if (epg-context-result-for context 'error)
1724               (error "Sign failed: %S"
1725                      (epg-context-result-for context 'error))
1726             (error "Sign failed")))
1727         (unless signature
1728           (epg-read-output context)))
1729     (unless signature
1730       (epg-delete-output-file context))
1731     (epg-reset context)))
1732
1733 ;;;###autoload
1734 (defun epg-sign-string (context plain &optional mode)
1735   "Sign a string PLAIN and return the output as string.
1736 If optional 3rd argument MODE is t or 'detached, it makes a detached signature.
1737 If it is nil or 'normal, it makes a normal signature.
1738 Otherwise, it makes a clear text signature."
1739   (unwind-protect
1740       (progn
1741         (epg-context-set-output-file context
1742                                      (epg--make-temp-file "epg-output"))
1743         (epg-start-sign context (epg-make-data-from-string plain) mode)
1744         (epg-wait-for-completion context)
1745         (unless (epg-context-result-for context 'sign)
1746           (if (epg-context-result-for context 'error)
1747               (error "Sign failed: %S"
1748                      (epg-context-result-for context 'error))
1749             (error "Sign failed")))
1750         (epg-read-output context))
1751     (epg-delete-output-file context)
1752     (epg-reset context)))
1753
1754 ;;;###autoload
1755 (defun epg-start-encrypt (context plain recipients
1756                                   &optional sign always-trust)
1757   "Initiate an encrypt operation on PLAIN.
1758 PLAIN is a data object.
1759 If RECIPIENTS is nil, it performs symmetric encryption.
1760
1761 If you use this function, you will need to wait for the completion of
1762 `epg-gpg-program' by using `epg-wait-for-completion' and call
1763 `epg-reset' to clear a temporaly output file.
1764 If you are unsure, use synchronous version of this function
1765 `epg-encrypt-file' or `epg-encrypt-string' instead."
1766   (epg-context-set-operation context 'encrypt)
1767   (epg-context-set-result context nil)
1768   (epg--start context
1769              (append (if always-trust '("--always-trust"))
1770                      (if recipients '("--encrypt") '("--symmetric"))
1771                      (if sign
1772                          (cons "--sign"
1773                                (apply #'nconc
1774                                       (mapcar
1775                                        (lambda (signer)
1776                                          (list "-u"
1777                                                (epg-sub-key-id
1778                                                 (car (epg-key-sub-key-list
1779                                                       signer)))))
1780                                        (epg-context-signers context)))))
1781                      (apply #'nconc
1782                             (mapcar
1783                              (lambda (recipient)
1784                                (list "-r"
1785                                      (epg-sub-key-id
1786                                       (car (epg-key-sub-key-list recipient)))))
1787                              recipients))
1788                      (if (epg-data-file plain)
1789                          (list (epg-data-file plain)))))
1790   ;; `gpgsm' does not read passphrase from stdin, so waiting is not needed.
1791   (unless (eq (epg-context-protocol context) 'CMS)
1792     (if sign
1793         (epg-wait-for-status context '("BEGIN_SIGNING"))
1794       (epg-wait-for-status context '("BEGIN_ENCRYPTION"))))
1795   (when (epg-data-string plain)
1796     (if (eq (process-status (epg-context-process context)) 'run)
1797         (process-send-string (epg-context-process context)
1798                              (epg-data-string plain)))
1799     (if (eq (process-status (epg-context-process context)) 'run)
1800         (process-send-eof (epg-context-process context)))))
1801
1802 ;;;###autoload
1803 (defun epg-encrypt-file (context plain recipients
1804                                  cipher &optional sign always-trust)
1805   "Encrypt a file PLAIN and store the result to a file CIPHER.
1806 If CIPHER is nil, it returns the result as a string.
1807 If RECIPIENTS is nil, it performs symmetric encryption."
1808   (unwind-protect
1809       (progn
1810         (if cipher
1811             (epg-context-set-output-file context cipher)
1812           (epg-context-set-output-file context
1813                                        (epg--make-temp-file "epg-output")))
1814         (epg-start-encrypt context (epg-make-data-from-file plain)
1815                            recipients sign always-trust)
1816         (epg-wait-for-completion context)
1817         (if (and sign
1818                  (not (epg-context-result-for context 'sign)))
1819             (if (epg-context-result-for context 'error)
1820                 (error "Sign failed: %S"
1821                        (epg-context-result-for context 'error))
1822                 (error "Sign failed")))
1823         (if (epg-context-result-for context 'error)
1824             (error "Encrypt failed: %S"
1825                    (epg-context-result-for context 'error)))
1826         (unless cipher
1827           (epg-read-output context)))
1828     (unless cipher
1829       (epg-delete-output-file context))
1830     (epg-reset context)))
1831
1832 ;;;###autoload
1833 (defun epg-encrypt-string (context plain recipients
1834                                    &optional sign always-trust)
1835   "Encrypt a string PLAIN.
1836 If RECIPIENTS is nil, it performs symmetric encryption."
1837   (unwind-protect
1838       (progn
1839         (epg-context-set-output-file context
1840                                      (epg--make-temp-file "epg-output"))
1841         (epg-start-encrypt context (epg-make-data-from-string plain)
1842                            recipients sign always-trust)
1843         (epg-wait-for-completion context)
1844         (if (and sign
1845                  (not (epg-context-result-for context 'sign)))
1846             (if (epg-context-result-for context 'error)
1847                 (error "Sign failed: %S"
1848                        (epg-context-result-for context 'error))
1849               (error "Sign failed")))
1850         (if (epg-context-result-for context 'error)
1851             (error "Encrypt failed: %S"
1852                    (epg-context-result-for context 'error)))
1853         (epg-read-output context))
1854     (epg-delete-output-file context)
1855     (epg-reset context)))
1856
1857 ;;;###autoload
1858 (defun epg-start-export-keys (context keys)
1859   "Initiate an export keys operation.
1860
1861 If you use this function, you will need to wait for the completion of
1862 `epg-gpg-program' by using `epg-wait-for-completion' and call
1863 `epg-reset' to clear a temporaly output file.
1864 If you are unsure, use synchronous version of this function
1865 `epg-export-keys-to-file' or `epg-export-keys-to-string' instead."
1866   (epg-context-set-operation context 'export-keys)
1867   (epg-context-set-result context nil)
1868   (epg--start context (cons "--export"
1869                            (mapcar
1870                             (lambda (key)
1871                               (epg-sub-key-id
1872                                (car (epg-key-sub-key-list key))))
1873                             keys))))
1874
1875 ;;;###autoload
1876 (defun epg-export-keys-to-file (context keys file)
1877   "Extract public KEYS."
1878   (unwind-protect
1879       (progn
1880         (if keys
1881             (epg-context-set-output-file context file)
1882           (epg-context-set-output-file context
1883                                        (epg--make-temp-file "epg-output")))
1884         (epg-start-export-keys context keys)
1885         (epg-wait-for-completion context)
1886         (if (epg-context-result-for context 'error)
1887             (error "Export keys failed: %S"
1888                    (epg-context-result-for context 'error)))
1889         (unless file
1890           (epg-read-output context)))
1891     (unless file
1892       (epg-delete-output-file context))
1893     (epg-reset context)))
1894
1895 ;;;###autoload
1896 (defun epg-export-keys-to-string (context keys)
1897   "Extract public KEYS and return them as a string."
1898   (epg-export-keys-to-file context keys nil))
1899
1900 ;;;###autoload
1901 (defun epg-start-import-keys (context keys)
1902   "Initiate an import keys operation.
1903 KEYS is a data object.
1904
1905 If you use this function, you will need to wait for the completion of
1906 `epg-gpg-program' by using `epg-wait-for-completion' and call
1907 `epg-reset' to clear a temporaly output file.
1908 If you are unsure, use synchronous version of this function
1909 `epg-import-keys-from-file' or `epg-import-keys-from-string' instead."
1910   (epg-context-set-operation context 'import-keys)
1911   (epg-context-set-result context nil)
1912   (epg--start context (if (epg-data-file keys)
1913                           (list "--import" (epg-data-file keys))
1914                         (list "--import")))
1915   (when (epg-data-string keys)
1916     (if (eq (process-status (epg-context-process context)) 'run)
1917         (process-send-string (epg-context-process context)
1918                              (epg-data-string keys)))
1919     (if (eq (process-status (epg-context-process context)) 'run)
1920         (process-send-eof (epg-context-process context)))))
1921
1922 (defun epg--import-keys-1 (context keys)
1923   (unwind-protect
1924       (progn
1925         (epg-start-import-keys context keys)
1926         (epg-wait-for-completion context)
1927         (if (epg-context-result-for context 'error)
1928             (error "Import keys failed: %S"
1929                    (epg-context-result-for context 'error))))
1930     (epg-reset context)))
1931
1932 ;;;###autoload
1933 (defun epg-import-keys-from-file (context keys)
1934   "Add keys from a file KEYS."
1935   (epg--import-keys-1 context (epg-make-data-from-file keys)))
1936
1937 ;;;###autoload
1938 (defun epg-import-keys-from-string (context keys)
1939   "Add keys from a string KEYS."
1940   (epg--import-keys-1 context (epg-make-data-from-string keys)))
1941
1942 ;;;###autoload
1943 (defun epg-start-receive-keys (context key-id-list)
1944   "Initiate a receive key operation.
1945 KEY-ID-LIST is a list of key IDs.
1946
1947 If you use this function, you will need to wait for the completion of
1948 `epg-gpg-program' by using `epg-wait-for-completion' and call
1949 `epg-reset' to clear a temporaly output file.
1950 If you are unsure, use synchronous version of this function
1951 `epg-generate-key-from-file' or `epg-generate-key-from-string' instead."
1952   (epg-context-set-operation context 'receive-keys)
1953   (epg-context-set-result context nil)
1954   (epg--start context (cons "--recv-keys" key-id-list)))
1955
1956 ;;;###autoload
1957 (defun epg-receive-keys (context keys)
1958   "Add keys from server.
1959 KEYS is a list of key IDs"
1960   (unwind-protect
1961       (progn
1962         (epg-start-receive-keys context keys)
1963         (epg-wait-for-completion context)
1964         (if (epg-context-result-for context 'error)
1965             (error "Receive keys failed: %S"
1966                    (epg-context-result-for context 'error))))
1967     (epg-reset context)))
1968
1969 ;;;###autoload
1970 (defalias 'epg-import-keys-from-server 'epg-receive-keys)
1971
1972 ;;;###autoload
1973 (defun epg-start-delete-keys (context keys &optional allow-secret)
1974   "Initiate an delete keys operation.
1975
1976 If you use this function, you will need to wait for the completion of
1977 `epg-gpg-program' by using `epg-wait-for-completion' and call
1978 `epg-reset' to clear a temporaly output file.
1979 If you are unsure, use synchronous version of this function
1980 `epg-delete-keys' instead."
1981   (epg-context-set-operation context 'delete-keys)
1982   (epg-context-set-result context nil)
1983   (epg--start context (cons (if allow-secret
1984                                "--delete-secret-key"
1985                              "--delete-key")
1986                            (mapcar
1987                             (lambda (key)
1988                               (epg-sub-key-id
1989                                (car (epg-key-sub-key-list key))))
1990                             keys))))
1991
1992 ;;;###autoload
1993 (defun epg-delete-keys (context keys &optional allow-secret)
1994   "Delete KEYS from the key ring."
1995   (unwind-protect
1996       (progn
1997         (epg-start-delete-keys context keys allow-secret)
1998         (epg-wait-for-completion context)
1999         (if (epg-context-result-for context 'error)
2000             (error "Delete keys failed: %S"
2001                    (epg-context-result-for context 'error))))
2002     (epg-reset context)))
2003
2004 ;;;###autoload
2005 (defun epg-start-sign-keys (context keys &optional local)
2006   "Initiate an sign keys operation.
2007
2008 If you use this function, you will need to wait for the completion of
2009 `epg-gpg-program' by using `epg-wait-for-completion' and call
2010 `epg-reset' to clear a temporaly output file.
2011 If you are unsure, use synchronous version of this function
2012 `epg-sign-keys' instead."
2013   (epg-context-set-operation context 'sign-keys)
2014   (epg-context-set-result context nil)
2015   (epg--start context (cons (if local
2016                                "--lsign-key"
2017                              "--sign-key")
2018                            (mapcar
2019                             (lambda (key)
2020                               (epg-sub-key-id
2021                                (car (epg-key-sub-key-list key))))
2022                             keys))))
2023
2024 ;;;###autoload
2025 (defun epg-sign-keys (context keys &optional local)
2026   "Sign KEYS from the key ring."
2027   (unwind-protect
2028       (progn
2029         (epg-start-sign-keys context keys local)
2030         (epg-wait-for-completion context)
2031         (if (epg-context-result-for context 'error)
2032             (error "Sign keys failed: %S"
2033                    (epg-context-result-for context 'error))))
2034     (epg-reset context)))
2035
2036 ;;;###autoload
2037 (defun epg-start-generate-key (context parameters)
2038   "Initiate a key generation.
2039 PARAMETERS specifies parameters for the key.
2040
2041 If you use this function, you will need to wait for the completion of
2042 `epg-gpg-program' by using `epg-wait-for-completion' and call
2043 `epg-reset' to clear a temporaly output file.
2044 If you are unsure, use synchronous version of this function
2045 `epg-generate-key-from-file' or `epg-generate-key-from-string' instead."
2046   (epg-context-set-operation context 'generate-key)
2047   (epg-context-set-result context nil)
2048   (if (epg-data-file parameters)
2049       (epg--start context (list "--batch" "--genkey"
2050                                (epg-data-file parameters)))
2051     (epg--start context '("--batch" "--genkey"))
2052     (if (eq (process-status (epg-context-process context)) 'run)
2053         (process-send-string (epg-context-process context)
2054                              (epg-data-string parameters)))
2055     (if (eq (process-status (epg-context-process context)) 'run)
2056         (process-send-eof (epg-context-process context)))))
2057
2058 ;;;###autoload
2059 (defun epg-generate-key-from-file (context parameters)
2060   "Generate a new key pair.
2061 PARAMETERS is a file which tells how to create the key."
2062   (unwind-protect
2063       (progn
2064         (epg-start-generate-key context (epg-make-data-from-file parameters))
2065         (epg-wait-for-completion context)
2066         (if (epg-context-result-for context 'error)
2067             (error "Generate key failed: %S"
2068                    (epg-context-result-for context 'error))))
2069     (epg-reset context)))
2070
2071 ;;;###autoload
2072 (defun epg-generate-key-from-string (context parameters)
2073   "Generate a new key pair.
2074 PARAMETERS is a string which tells how to create the key."
2075   (unwind-protect
2076       (progn
2077         (epg-start-generate-key context (epg-make-data-from-string parameters))
2078         (epg-wait-for-completion context)
2079         (if (epg-context-result-for context 'error)
2080             (error "Generate key failed: %S"
2081                    (epg-context-result-for context 'error))))
2082     (epg-reset context)))
2083
2084 (defun epg--decode-hexstring (string)
2085   (let ((index 0))
2086     (while (eq index (string-match "[0-9A-Fa-f][0-9A-Fa-f]" string index))
2087       (setq string (replace-match "\\x\\&" t nil string)
2088             index (+ index 4)))
2089     (car (read-from-string (concat "\"" string "\"")))))
2090
2091 (defun epg--decode-quotedstring (string)
2092   (let ((index 0))
2093     (while (string-match "\\\\\\(\\([,=+<>#;\\\"]\\)\\|\
2094 \\([0-9A-Fa-f][0-9A-Fa-f]\\)\\|\\(.\\)\\)"
2095                          string index)
2096       (if (match-beginning 2)
2097           (setq string (replace-match "\\2" t nil string)
2098                 index (1+ index))
2099         (if (match-beginning 3)
2100             (setq string (replace-match "\\x\\3" t nil string)
2101                   index (+ index 4))
2102           (setq string (replace-match "\\\\\\\\\\4" t nil string)
2103                 index (+ index 3)))))
2104     (car (read-from-string (concat "\"" string "\"")))))
2105
2106 (defun epg-dn-from-string (string)
2107   "Parse STRING as LADPv3 Distinguished Names (RFC2253).
2108 The return value is an alist mapping from types to values."
2109   (let ((index 0)
2110         (length (length string))
2111         alist type value group)
2112     (while (< index length)
2113       (if (eq index (string-match "[ \t\n\r]*" string index))
2114           (setq index (match-end 0)))
2115       (if (eq index (string-match
2116                      "\\([0-9]+\\(\\.[0-9]+\\)*\\)\[ \t\n\r]*=[ \t\n\r]*"
2117                      string index))
2118           (setq type (match-string 1 string)
2119                 index (match-end 0))
2120         (if (eq index (string-match "\\([0-9A-Za-z]+\\)[ \t\n\r]*=[ \t\n\r]*"
2121                                     string index))
2122             (setq type (match-string 1 string)
2123                   index (match-end 0))))
2124       (unless type
2125         (error "Invalid type"))
2126       (if (eq index (string-match
2127                      "\\([^,=+<>#;\\\"]\\|\\\\.\\)+"
2128                      string index))
2129           (setq index (match-end 0)
2130                 value (epg--decode-quotedstring (match-string 0 string)))
2131         (if (eq index (string-match "#\\([0-9A-Fa-f]+\\)" string index))
2132             (setq index (match-end 0)
2133                   value (epg--decode-hexstring (match-string 1 string)))
2134           (if (eq index (string-match "\"\\([^\\\"]\\|\\\\.\\)*\""
2135                                       string index))
2136               (setq index (match-end 0)
2137                     value (epg--decode-quotedstring
2138                            (match-string 0 string))))))
2139       (if group
2140           (if (stringp (car (car alist)))
2141               (setcar alist (list (cons type value) (car alist)))
2142             (setcar alist (cons (cons type value) (car alist))))
2143         (if (consp (car (car alist)))
2144             (setcar alist (nreverse (car alist))))
2145         (setq alist (cons (cons type value) alist)
2146               type nil
2147               value nil))
2148       (if (eq index (string-match "[ \t\n\r]*\\([,;+]\\)" string index))
2149           (setq index (match-end 0)
2150                 group (eq (aref string (match-beginning 1)) ?+))))
2151     (nreverse alist)))
2152
2153 (defun epg-decode-dn (alist)
2154   "Convert ALIST returned by `epg-dn-from-string' to a human readable form.
2155 Type names are resolved using `epg-dn-type-alist'."
2156   (mapconcat
2157    (lambda (rdn)
2158      (if (stringp (car rdn))
2159          (let ((entry (assoc (car rdn) epg-dn-type-alist)))
2160            (if entry
2161                (format "%s=%s" (cdr entry) (cdr rdn))
2162              (format "%s=%s" (car rdn) (cdr rdn))))
2163        (concat "(" (epg-decode-dn rdn) ")")))
2164    alist
2165    ", "))
2166
2167 (provide 'epg)
2168
2169 ;;; epg.el ends here