OSDN Git Service

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