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