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