Merge remote-tracking branch 'tarleb/sieve'
[gnus] / lisp / mml2015.el
1 ;;; mml2015.el --- MIME Security with Pretty Good Privacy (PGP)
2
3 ;; Copyright (C) 2000-2013 Free Software Foundation, Inc.
4
5 ;; Author: Shenghuo Zhu <zsh@cs.rochester.edu>
6 ;; Keywords: PGP MIME MML
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; RFC 2015 is updated by RFC 3156, this file should be compatible
26 ;; with both.
27
28 ;;; Code:
29
30 (eval-and-compile
31   ;; For Emacs <22.2 and XEmacs.
32   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
33
34   (if (locate-library "password-cache")
35       (require 'password-cache)
36     (require 'password)))
37
38 (eval-when-compile (require 'cl))
39 (require 'mm-decode)
40 (require 'mm-util)
41 (require 'mml)
42 (require 'mml-sec)
43
44 (defvar mc-pgp-always-sign)
45
46 (declare-function epg-check-configuration "ext:epg-config"
47                   (config &optional minimum-version))
48 (declare-function epg-configuration "ext:epg-config" ())
49
50 ;; Maybe this should be in eg mml-sec.el (and have a different name).
51 ;; Then mml1991 would not need to require mml2015, and mml1991-use
52 ;; could be removed.
53 (defvar mml2015-use (or
54                      (condition-case nil
55                          (progn
56                            (require 'epg-config)
57                            (epg-check-configuration (epg-configuration))
58                            'epg)
59                        (error))
60                      (progn
61                        (let ((abs-file (locate-library "pgg")))
62                          ;; Don't load PGG if it is marked as obsolete
63                          ;; (Emacs 24).
64                          (when (and abs-file
65                                     (not (string-match "/obsolete/[^/]*\\'"
66                                                        abs-file)))
67                            (ignore-errors (require 'pgg))
68                            (and (fboundp 'pgg-sign-region)
69                                 'pgg))))
70                      (progn (ignore-errors
71                               (load "mc-toplev"))
72                             (and (fboundp 'mc-encrypt-generic)
73                                  (fboundp 'mc-sign-generic)
74                                  (fboundp 'mc-cleanup-recipient-headers)
75                                  'mailcrypt)))
76   "The package used for PGP/MIME.
77 Valid packages include `epg', `pgg' and `mailcrypt'.")
78
79 ;; Something is not RFC2015.
80 (defvar mml2015-function-alist
81   '((mailcrypt mml2015-mailcrypt-sign
82                mml2015-mailcrypt-encrypt
83                mml2015-mailcrypt-verify
84                mml2015-mailcrypt-decrypt
85                mml2015-mailcrypt-clear-verify
86                mml2015-mailcrypt-clear-decrypt)
87     (pgg mml2015-pgg-sign
88          mml2015-pgg-encrypt
89          mml2015-pgg-verify
90          mml2015-pgg-decrypt
91          mml2015-pgg-clear-verify
92          mml2015-pgg-clear-decrypt)
93     (epg mml2015-epg-sign
94          mml2015-epg-encrypt
95          mml2015-epg-verify
96          mml2015-epg-decrypt
97          mml2015-epg-clear-verify
98          mml2015-epg-clear-decrypt))
99   "Alist of PGP/MIME functions.")
100
101 (defvar mml2015-result-buffer nil)
102
103 (defcustom mml2015-unabbrev-trust-alist
104   '(("TRUST_UNDEFINED" . nil)
105     ("TRUST_NEVER"     . nil)
106     ("TRUST_MARGINAL"  . t)
107     ("TRUST_FULLY"     . t)
108     ("TRUST_ULTIMATE"  . t))
109   "Map GnuPG trust output values to a boolean saying if you trust the key."
110   :version "22.1"
111   :group 'mime-security
112   :type '(repeat (cons (regexp :tag "GnuPG output regexp")
113                        (boolean :tag "Trust key"))))
114
115 (defcustom mml2015-cache-passphrase mml-secure-cache-passphrase
116   "If t, cache passphrase."
117   :group 'mime-security
118   :type 'boolean)
119
120 (defcustom mml2015-passphrase-cache-expiry mml-secure-passphrase-cache-expiry
121   "How many seconds the passphrase is cached.
122 Whether the passphrase is cached at all is controlled by
123 `mml2015-cache-passphrase'."
124   :group 'mime-security
125   :type 'integer)
126
127 (defcustom mml2015-signers nil
128   "A list of your own key ID(s) which will be used to sign a message.
129 If set, it overrides the setting of `mml2015-sign-with-sender'."
130   :group 'mime-security
131   :type '(repeat (string :tag "Key ID")))
132
133 (defcustom mml2015-sign-with-sender nil
134   "If t, use message sender so find a key to sign with."
135   :group 'mime-security
136   :type 'boolean
137   :version "24.1")
138
139 (defcustom mml2015-encrypt-to-self nil
140   "If t, add your own key ID to recipient list when encryption."
141   :group 'mime-security
142   :type 'boolean)
143
144 (defcustom mml2015-always-trust t
145   "If t, GnuPG skip key validation on encryption."
146   :group 'mime-security
147   :type 'boolean)
148
149 (defcustom mml2015-maximum-key-image-dimension 64
150   "The maximum dimension (width or height) of any key images."
151   :group 'mime-security
152   :type 'integer)
153
154 ;; Extract plaintext from cleartext signature.  IMO, this kind of task
155 ;; should be done by GnuPG rather than Elisp, but older PGP backends
156 ;; (such as Mailcrypt, and PGG) discard the output from GnuPG.
157 (defun mml2015-extract-cleartext-signature ()
158   ;; Daiki Ueno in
159   ;; <54a15d860801080142l70b95d7dkac4bf51a86196011@mail.gmail.com>: ``I still
160   ;; believe that the right way is to use the plaintext output from GnuPG as
161   ;; it is, and mml2015-extract-cleartext-signature is just a kludge for
162   ;; misdesigned libraries like PGG, which have no ability to do that.  So, I
163   ;; think it should not have descriptive documentation.''
164   ;;
165   ;; This function doesn't handle NotDashEscaped correctly.  EasyPG handles it
166   ;; correctly.
167   ;; http://thread.gmane.org/gmane.emacs.gnus.general/66062/focus=66082
168   ;; http://thread.gmane.org/gmane.emacs.gnus.general/65087/focus=65109
169   (goto-char (point-min))
170   (forward-line)
171   ;; We need to be careful not to strip beyond the armor headers.
172   ;; Previously, an attacker could replace the text inside our
173   ;; markup with trailing garbage by injecting whitespace into the
174   ;; message.
175   (while (looking-at "Hash:")           ; The only header allowed in cleartext
176     (forward-line))                     ; signatures according to RFC2440.
177   (when (looking-at "[\t ]*$")
178     (forward-line))
179   (delete-region (point-min) (point))
180   (if (re-search-forward "^-----BEGIN PGP SIGNATURE-----" nil t)
181       (delete-region (match-beginning 0) (point-max)))
182   (goto-char (point-min))
183   (while (re-search-forward "^- " nil t)
184     (replace-match "" t t)
185     (forward-line 1)))
186
187 ;;; mailcrypt wrapper
188
189 (autoload 'mailcrypt-decrypt "mailcrypt")
190 (autoload 'mailcrypt-verify "mailcrypt")
191 (autoload 'mc-pgp-always-sign "mailcrypt")
192 (autoload 'mc-encrypt-generic "mc-toplev")
193 (autoload 'mc-cleanup-recipient-headers "mc-toplev")
194 (autoload 'mc-sign-generic "mc-toplev")
195
196 (defvar mml2015-decrypt-function 'mailcrypt-decrypt)
197 (defvar mml2015-verify-function 'mailcrypt-verify)
198
199 (defun mml2015-format-error (err)
200   (if (stringp (cadr err))
201       (cadr err)
202     (format "%S" (cdr err))))
203
204 (defun mml2015-mailcrypt-decrypt (handle ctl)
205   (catch 'error
206     (let (child handles result)
207       (unless (setq child (mm-find-part-by-type
208                            (cdr handle)
209                            "application/octet-stream" nil t))
210         (mm-set-handle-multipart-parameter
211          mm-security-handle 'gnus-info "Corrupted")
212         (throw 'error handle))
213       (with-temp-buffer
214         (mm-insert-part child)
215         (setq result
216               (condition-case err
217                   (funcall mml2015-decrypt-function)
218                 (error
219                  (mm-set-handle-multipart-parameter
220                   mm-security-handle 'gnus-details (mml2015-format-error err))
221                  nil)
222                 (quit
223                  (mm-set-handle-multipart-parameter
224                   mm-security-handle 'gnus-details "Quit.")
225                  nil)))
226         (unless (car result)
227           (mm-set-handle-multipart-parameter
228            mm-security-handle 'gnus-info "Failed")
229           (throw 'error handle))
230         (setq handles (mm-dissect-buffer t)))
231       (mm-destroy-parts handle)
232       (mm-set-handle-multipart-parameter
233        mm-security-handle 'gnus-info
234        (concat "OK"
235                (let ((sig (with-current-buffer mml2015-result-buffer
236                             (mml2015-gpg-extract-signature-details))))
237                  (concat ", Signer: " sig))))
238       (if (listp (car handles))
239           handles
240         (list handles)))))
241
242 (defun mml2015-gpg-pretty-print-fpr (fingerprint)
243   (let* ((result "")
244          (fpr-length (string-width fingerprint))
245          (n-slice 0)
246          slice)
247     (setq fingerprint (string-to-list fingerprint))
248     (while fingerprint
249       (setq fpr-length (- fpr-length 4))
250       (setq slice (butlast fingerprint fpr-length))
251       (setq fingerprint (nthcdr 4 fingerprint))
252       (setq n-slice (1+ n-slice))
253       (setq result
254             (concat
255              result
256              (case n-slice
257                (1  slice)
258                (otherwise (concat " " slice))))))
259     result))
260
261 (defun mml2015-gpg-extract-signature-details ()
262   (goto-char (point-min))
263   (let* ((expired (re-search-forward
264                    "^\\[GNUPG:\\] SIGEXPIRED$"
265                    nil t))
266          (signer (and (re-search-forward
267                        "^\\[GNUPG:\\] GOODSIG \\([0-9A-Za-z]*\\) \\(.*\\)$"
268                        nil t)
269                       (cons (match-string 1) (match-string 2))))
270          (fprint (and (re-search-forward
271                        "^\\[GNUPG:\\] VALIDSIG \\([0-9a-zA-Z]*\\) "
272                        nil t)
273                       (match-string 1)))
274          (trust  (and (re-search-forward
275                        "^\\[GNUPG:\\] \\(TRUST_.*\\)$"
276                        nil t)
277                       (match-string 1)))
278          (trust-good-enough-p
279           (cdr (assoc trust mml2015-unabbrev-trust-alist))))
280     (cond ((and signer fprint)
281            (concat (cdr signer)
282                    (unless trust-good-enough-p
283                      (concat "\nUntrusted, Fingerprint: "
284                              (mml2015-gpg-pretty-print-fpr fprint)))
285                    (when expired
286                      (format "\nWARNING: Signature from expired key (%s)"
287                              (car signer)))))
288           ((re-search-forward
289             "^\\(gpg: \\)?Good signature from \"\\(.*\\)\"$" nil t)
290            (match-string 2))
291           (t
292            "From unknown user"))))
293
294 (defun mml2015-mailcrypt-clear-decrypt ()
295   (let (result)
296     (setq result
297           (condition-case err
298               (funcall mml2015-decrypt-function)
299             (error
300              (mm-set-handle-multipart-parameter
301               mm-security-handle 'gnus-details (mml2015-format-error err))
302              nil)
303             (quit
304              (mm-set-handle-multipart-parameter
305               mm-security-handle 'gnus-details "Quit.")
306              nil)))
307     (if (car result)
308         (mm-set-handle-multipart-parameter
309          mm-security-handle 'gnus-info "OK")
310       (mm-set-handle-multipart-parameter
311        mm-security-handle 'gnus-info "Failed"))))
312
313 (defun mml2015-fix-micalg (alg)
314   (and alg
315        ;; Mutt/1.2.5i has seen sending micalg=php-sha1
316        (upcase (if (string-match "^p[gh]p-" alg)
317                    (substring alg (match-end 0))
318                  alg))))
319
320 (defun mml2015-mailcrypt-verify (handle ctl)
321   (catch 'error
322     (let (part)
323       (unless (setq part (mm-find-raw-part-by-type
324                           ctl (or (mm-handle-multipart-ctl-parameter
325                                    ctl 'protocol)
326                                   "application/pgp-signature")
327                           t))
328         (mm-set-handle-multipart-parameter
329          mm-security-handle 'gnus-info "Corrupted")
330         (throw 'error handle))
331       (with-temp-buffer
332         (insert "-----BEGIN PGP SIGNED MESSAGE-----\n")
333         (insert (format "Hash: %s\n\n"
334                         (or (mml2015-fix-micalg
335                              (mm-handle-multipart-ctl-parameter
336                               ctl 'micalg))
337                             "SHA1")))
338         (save-restriction
339           (narrow-to-region (point) (point))
340           (insert part "\n")
341           (goto-char (point-min))
342           (while (not (eobp))
343             (if (looking-at "^-")
344                 (insert "- "))
345             (forward-line)))
346         (unless (setq part (mm-find-part-by-type
347                             (cdr handle) "application/pgp-signature" nil t))
348           (mm-set-handle-multipart-parameter
349            mm-security-handle 'gnus-info "Corrupted")
350           (throw 'error handle))
351         (save-restriction
352           (narrow-to-region (point) (point))
353           (mm-insert-part part)
354           (goto-char (point-min))
355           (if (re-search-forward "^-----BEGIN PGP [^-]+-----\r?$" nil t)
356               (replace-match "-----BEGIN PGP SIGNATURE-----" t t))
357           (if (re-search-forward "^-----END PGP [^-]+-----\r?$" nil t)
358               (replace-match "-----END PGP SIGNATURE-----" t t)))
359         (let ((mc-gpg-debug-buffer (get-buffer-create " *gnus gpg debug*")))
360           (unless (condition-case err
361                       (prog1
362                           (funcall mml2015-verify-function)
363                         (if (get-buffer " *mailcrypt stderr temp")
364                             (mm-set-handle-multipart-parameter
365                              mm-security-handle 'gnus-details
366                              (with-current-buffer " *mailcrypt stderr temp"
367                                (buffer-string))))
368                         (if (get-buffer " *mailcrypt stdout temp")
369                             (kill-buffer " *mailcrypt stdout temp"))
370                         (if (get-buffer " *mailcrypt stderr temp")
371                             (kill-buffer " *mailcrypt stderr temp"))
372                         (if (get-buffer " *mailcrypt status temp")
373                             (kill-buffer " *mailcrypt status temp"))
374                         (if (get-buffer mc-gpg-debug-buffer)
375                             (kill-buffer mc-gpg-debug-buffer)))
376                     (error
377                      (mm-set-handle-multipart-parameter
378                       mm-security-handle 'gnus-details (mml2015-format-error err))
379                      nil)
380                     (quit
381                      (mm-set-handle-multipart-parameter
382                       mm-security-handle 'gnus-details "Quit.")
383                      nil))
384             (mm-set-handle-multipart-parameter
385              mm-security-handle 'gnus-info "Failed")
386             (throw 'error handle))))
387       (mm-set-handle-multipart-parameter
388        mm-security-handle 'gnus-info "OK")
389       handle)))
390
391 (defun mml2015-mailcrypt-clear-verify ()
392   (let ((mc-gpg-debug-buffer (get-buffer-create " *gnus gpg debug*")))
393     (if (condition-case err
394             (prog1
395                 (funcall mml2015-verify-function)
396               (if (get-buffer " *mailcrypt stderr temp")
397                   (mm-set-handle-multipart-parameter
398                    mm-security-handle 'gnus-details
399                    (with-current-buffer " *mailcrypt stderr temp"
400                      (buffer-string))))
401               (if (get-buffer " *mailcrypt stdout temp")
402                   (kill-buffer " *mailcrypt stdout temp"))
403               (if (get-buffer " *mailcrypt stderr temp")
404                   (kill-buffer " *mailcrypt stderr temp"))
405               (if (get-buffer " *mailcrypt status temp")
406                   (kill-buffer " *mailcrypt status temp"))
407               (if (get-buffer mc-gpg-debug-buffer)
408                   (kill-buffer mc-gpg-debug-buffer)))
409           (error
410            (mm-set-handle-multipart-parameter
411             mm-security-handle 'gnus-details (mml2015-format-error err))
412            nil)
413           (quit
414            (mm-set-handle-multipart-parameter
415             mm-security-handle 'gnus-details "Quit.")
416            nil))
417         (mm-set-handle-multipart-parameter
418          mm-security-handle 'gnus-info "OK")
419       (mm-set-handle-multipart-parameter
420        mm-security-handle 'gnus-info "Failed")))
421   (mml2015-extract-cleartext-signature))
422
423 (defun mml2015-mailcrypt-sign (cont)
424   (mc-sign-generic (message-options-get 'message-sender)
425                    nil nil nil nil)
426   (let ((boundary (mml-compute-boundary cont))
427         hash point)
428     (goto-char (point-min))
429     (unless (re-search-forward "^-----BEGIN PGP SIGNED MESSAGE-----\r?$" nil t)
430       (error "Cannot find signed begin line"))
431     (goto-char (match-beginning 0))
432     (forward-line 1)
433     (unless (looking-at "Hash:[ \t]*\\([a-zA-Z0-9]+\\)")
434       (error "Cannot not find PGP hash"))
435     (setq hash (match-string 1))
436     (unless (re-search-forward "^$" nil t)
437       (error "Cannot not find PGP message"))
438     (forward-line 1)
439     (delete-region (point-min) (point))
440     (insert (format "Content-Type: multipart/signed; boundary=\"%s\";\n"
441                     boundary))
442     (insert (format "\tmicalg=pgp-%s; protocol=\"application/pgp-signature\"\n"
443                     (downcase hash)))
444     (insert (format "\n--%s\n" boundary))
445     (setq point (point))
446     (goto-char (point-max))
447     (unless (re-search-backward "^-----END PGP SIGNATURE-----\r?$" nil t)
448       (error "Cannot find signature part"))
449     (replace-match "-----END PGP MESSAGE-----" t t)
450     (goto-char (match-beginning 0))
451     (unless (re-search-backward "^-----BEGIN PGP SIGNATURE-----\r?$"
452                                 nil t)
453       (error "Cannot find signature part"))
454     (replace-match "-----BEGIN PGP MESSAGE-----" t t)
455     (goto-char (match-beginning 0))
456     (save-restriction
457       (narrow-to-region point (point))
458       (goto-char point)
459       (while (re-search-forward "^- -" nil t)
460         (replace-match "-" t t))
461       (goto-char (point-max)))
462     (insert (format "--%s\n" boundary))
463     (insert "Content-Type: application/pgp-signature\n\n")
464     (goto-char (point-max))
465     (insert (format "--%s--\n" boundary))
466     (goto-char (point-max))))
467
468 ;; We require mm-decode, which requires mm-bodies, which autoloads
469 ;; message-options-get (!).
470 (declare-function message-options-set "message" (symbol value))
471
472 (defun mml2015-mailcrypt-encrypt (cont &optional sign)
473   (let ((mc-pgp-always-sign
474          (or mc-pgp-always-sign
475              sign
476              (eq t (or (message-options-get 'message-sign-encrypt)
477                        (message-options-set
478                         'message-sign-encrypt
479                         (or (y-or-n-p "Sign the message? ")
480                             'not))))
481              'never)))
482     (mm-with-unibyte-current-buffer
483       (mc-encrypt-generic
484        (or (message-options-get 'message-recipients)
485            (message-options-set 'message-recipients
486                               (mc-cleanup-recipient-headers
487                                (read-string "Recipients: "))))
488        nil nil nil
489        (message-options-get 'message-sender))))
490   (goto-char (point-min))
491   (unless (looking-at "-----BEGIN PGP MESSAGE-----")
492     (error "Fail to encrypt the message"))
493   (let ((boundary (mml-compute-boundary cont)))
494     (insert (format "Content-Type: multipart/encrypted; boundary=\"%s\";\n"
495                     boundary))
496     (insert "\tprotocol=\"application/pgp-encrypted\"\n\n")
497     (insert (format "--%s\n" boundary))
498     (insert "Content-Type: application/pgp-encrypted\n\n")
499     (insert "Version: 1\n\n")
500     (insert (format "--%s\n" boundary))
501     (insert "Content-Type: application/octet-stream\n\n")
502     (goto-char (point-max))
503     (insert (format "--%s--\n" boundary))
504     (goto-char (point-max))))
505
506 ;;; pgg wrapper
507
508 (defvar pgg-default-user-id)
509 (defvar pgg-errors-buffer)
510 (defvar pgg-output-buffer)
511
512 (autoload 'pgg-decrypt-region "pgg")
513 (autoload 'pgg-verify-region "pgg")
514 (autoload 'pgg-sign-region "pgg")
515 (autoload 'pgg-encrypt-region "pgg")
516 (autoload 'pgg-parse-armor "pgg-parse")
517
518 (defun mml2015-pgg-decrypt (handle ctl)
519   (catch 'error
520     (let ((pgg-errors-buffer mml2015-result-buffer)
521           child handles result decrypt-status)
522       (unless (setq child (mm-find-part-by-type
523                            (cdr handle)
524                            "application/octet-stream" nil t))
525         (mm-set-handle-multipart-parameter
526          mm-security-handle 'gnus-info "Corrupted")
527         (throw 'error handle))
528       (with-temp-buffer
529         (mm-insert-part child)
530         (if (condition-case err
531                 (prog1
532                     (pgg-decrypt-region (point-min) (point-max))
533                   (setq decrypt-status
534                         (with-current-buffer mml2015-result-buffer
535                           (buffer-string)))
536                   (mm-set-handle-multipart-parameter
537                    mm-security-handle 'gnus-details
538                    decrypt-status))
539               (error
540                (mm-set-handle-multipart-parameter
541                 mm-security-handle 'gnus-details (mml2015-format-error err))
542                nil)
543               (quit
544                (mm-set-handle-multipart-parameter
545                 mm-security-handle 'gnus-details "Quit.")
546                nil))
547             (with-current-buffer pgg-output-buffer
548               (goto-char (point-min))
549               (while (search-forward "\r\n" nil t)
550                 (replace-match "\n" t t))
551               (setq handles (mm-dissect-buffer t))
552               (mm-destroy-parts handle)
553               (mm-set-handle-multipart-parameter
554                mm-security-handle 'gnus-info "OK")
555               (mm-set-handle-multipart-parameter
556                mm-security-handle 'gnus-details
557                (concat decrypt-status
558                        (when (stringp (car handles))
559                          "\n" (mm-handle-multipart-ctl-parameter
560                                handles 'gnus-details))))
561               (if (listp (car handles))
562                   handles
563                 (list handles)))
564           (mm-set-handle-multipart-parameter
565            mm-security-handle 'gnus-info "Failed")
566           (throw 'error handle))))))
567
568 (defun mml2015-pgg-clear-decrypt ()
569   (let ((pgg-errors-buffer mml2015-result-buffer))
570     (if (prog1
571             (pgg-decrypt-region (point-min) (point-max))
572           (mm-set-handle-multipart-parameter
573            mm-security-handle 'gnus-details
574            (with-current-buffer mml2015-result-buffer
575              (buffer-string))))
576         (progn
577           (erase-buffer)
578           ;; Treat data which pgg returns as a unibyte string.
579           (mm-disable-multibyte)
580           (insert-buffer-substring pgg-output-buffer)
581           (goto-char (point-min))
582           (while (search-forward "\r\n" nil t)
583             (replace-match "\n" t t))
584           (mm-set-handle-multipart-parameter
585            mm-security-handle 'gnus-info "OK"))
586       (mm-set-handle-multipart-parameter
587        mm-security-handle 'gnus-info "Failed"))))
588
589 (defun mml2015-pgg-verify (handle ctl)
590   (let ((pgg-errors-buffer mml2015-result-buffer)
591         signature-file part signature)
592     (if (or (null (setq part (mm-find-raw-part-by-type
593                               ctl (or (mm-handle-multipart-ctl-parameter
594                                        ctl 'protocol)
595                                       "application/pgp-signature")
596                               t)))
597             (null (setq signature (mm-find-part-by-type
598                                    (cdr handle) "application/pgp-signature" nil t))))
599         (progn
600           (mm-set-handle-multipart-parameter
601            mm-security-handle 'gnus-info "Corrupted")
602           handle)
603       (with-temp-buffer
604         (insert part)
605         ;; Convert <LF> to <CR><LF> in signed text.  If --textmode is
606         ;; specified when signing, the conversion is not necessary.
607         (goto-char (point-min))
608         (end-of-line)
609         (while (not (eobp))
610           (unless (eq (char-before) ?\r)
611             (insert "\r"))
612           (forward-line)
613           (end-of-line))
614         (with-temp-file (setq signature-file (mm-make-temp-file "pgg"))
615           (mm-insert-part signature))
616         (if (condition-case err
617                 (prog1
618                     (pgg-verify-region (point-min) (point-max)
619                                        signature-file t)
620                   (goto-char (point-min))
621                   (while (search-forward "\r\n" nil t)
622                     (replace-match "\n" t t))
623                   (mm-set-handle-multipart-parameter
624                    mm-security-handle 'gnus-details
625                    (concat (with-current-buffer pgg-output-buffer
626                              (buffer-string))
627                            (with-current-buffer pgg-errors-buffer
628                              (buffer-string)))))
629               (error
630                (mm-set-handle-multipart-parameter
631                 mm-security-handle 'gnus-details (mml2015-format-error err))
632                nil)
633               (quit
634                (mm-set-handle-multipart-parameter
635                 mm-security-handle 'gnus-details "Quit.")
636                nil))
637             (progn
638               (delete-file signature-file)
639               (mm-set-handle-multipart-parameter
640                mm-security-handle 'gnus-info
641                (with-current-buffer pgg-errors-buffer
642                  (mml2015-gpg-extract-signature-details))))
643           (delete-file signature-file)
644           (mm-set-handle-multipart-parameter
645            mm-security-handle 'gnus-info "Failed")))))
646   handle)
647
648 (defun mml2015-pgg-clear-verify ()
649   (let ((pgg-errors-buffer mml2015-result-buffer)
650         (text (buffer-string))
651         (coding-system buffer-file-coding-system))
652     (if (condition-case err
653             (prog1
654                 (mm-with-unibyte-buffer
655                   (insert (mm-encode-coding-string text coding-system))
656                   (pgg-verify-region (point-min) (point-max) nil t))
657               (goto-char (point-min))
658               (while (search-forward "\r\n" nil t)
659                 (replace-match "\n" t t))
660               (mm-set-handle-multipart-parameter
661                mm-security-handle 'gnus-details
662                (concat (with-current-buffer pgg-output-buffer
663                          (buffer-string))
664                        (with-current-buffer pgg-errors-buffer
665                          (buffer-string)))))
666           (error
667            (mm-set-handle-multipart-parameter
668             mm-security-handle 'gnus-details (mml2015-format-error err))
669            nil)
670           (quit
671            (mm-set-handle-multipart-parameter
672             mm-security-handle 'gnus-details "Quit.")
673            nil))
674         (mm-set-handle-multipart-parameter
675          mm-security-handle 'gnus-info
676          (with-current-buffer pgg-errors-buffer
677            (mml2015-gpg-extract-signature-details)))
678       (mm-set-handle-multipart-parameter
679        mm-security-handle 'gnus-info "Failed")))
680   (mml2015-extract-cleartext-signature))
681
682 (defun mml2015-pgg-sign (cont)
683   (let ((pgg-errors-buffer mml2015-result-buffer)
684         (boundary (mml-compute-boundary cont))
685         (pgg-default-user-id (or (message-options-get 'mml-sender)
686                                  pgg-default-user-id))
687         (pgg-text-mode t)
688         entry)
689     (unless (pgg-sign-region (point-min) (point-max))
690       (pop-to-buffer mml2015-result-buffer)
691       (error "Sign error"))
692     (goto-char (point-min))
693     (insert (format "Content-Type: multipart/signed; boundary=\"%s\";\n"
694                     boundary))
695     (if (setq entry (assq 2 (pgg-parse-armor
696                              (with-current-buffer pgg-output-buffer
697                                (buffer-string)))))
698         (setq entry (assq 'hash-algorithm (cdr entry))))
699     (insert (format "\tmicalg=%s; "
700                     (if (cdr entry)
701                         (downcase (format "pgp-%s" (cdr entry)))
702                       "pgp-sha1")))
703     (insert "protocol=\"application/pgp-signature\"\n")
704     (insert (format "\n--%s\n" boundary))
705     (goto-char (point-max))
706     (insert (format "\n--%s\n" boundary))
707     (insert "Content-Type: application/pgp-signature\n\n")
708     (insert-buffer-substring pgg-output-buffer)
709     (goto-char (point-max))
710     (insert (format "--%s--\n" boundary))
711     (goto-char (point-max))))
712
713 (defun mml2015-pgg-encrypt (cont &optional sign)
714   (let ((pgg-errors-buffer mml2015-result-buffer)
715         (pgg-text-mode t)
716         (boundary (mml-compute-boundary cont)))
717     (unless (pgg-encrypt-region (point-min) (point-max)
718                                 (split-string
719                                  (or
720                                   (message-options-get 'message-recipients)
721                                   (message-options-set 'message-recipients
722                                                        (read-string "Recipients: ")))
723                                  "[ \f\t\n\r\v,]+")
724                                 sign)
725       (pop-to-buffer mml2015-result-buffer)
726       (error "Encrypt error"))
727     (delete-region (point-min) (point-max))
728     (goto-char (point-min))
729     (insert (format "Content-Type: multipart/encrypted; boundary=\"%s\";\n"
730                     boundary))
731     (insert "\tprotocol=\"application/pgp-encrypted\"\n\n")
732     (insert (format "--%s\n" boundary))
733     (insert "Content-Type: application/pgp-encrypted\n\n")
734     (insert "Version: 1\n\n")
735     (insert (format "--%s\n" boundary))
736     (insert "Content-Type: application/octet-stream\n\n")
737     (insert-buffer-substring pgg-output-buffer)
738     (goto-char (point-max))
739     (insert (format "--%s--\n" boundary))
740     (goto-char (point-max))))
741
742 ;;; epg wrapper
743
744 (defvar epg-user-id-alist)
745 (defvar epg-digest-algorithm-alist)
746 (defvar epg-gpg-program)
747 (defvar inhibit-redisplay)
748
749 (autoload 'epg-make-context "epg")
750 (autoload 'epg-context-set-armor "epg")
751 (autoload 'epg-context-set-textmode "epg")
752 (autoload 'epg-context-set-signers "epg")
753 (autoload 'epg-context-result-for "epg")
754 (autoload 'epg-new-signature-digest-algorithm "epg")
755 (autoload 'epg-list-keys "epg")
756 (autoload 'epg-decrypt-string "epg")
757 (autoload 'epg-verify-string "epg")
758 (autoload 'epg-sign-string "epg")
759 (autoload 'epg-encrypt-string "epg")
760 (autoload 'epg-passphrase-callback-function "epg")
761 (autoload 'epg-context-set-passphrase-callback "epg")
762 (autoload 'epg-key-sub-key-list "epg")
763 (autoload 'epg-sub-key-capability "epg")
764 (autoload 'epg-sub-key-validity "epg")
765 (autoload 'epg-sub-key-fingerprint "epg")
766 (autoload 'epg-signature-key-id "epg")
767 (autoload 'epg-signature-to-string "epg")
768 (autoload 'epg-key-user-id-list "epg")
769 (autoload 'epg-user-id-string "epg")
770 (autoload 'epg-user-id-validity "epg")
771 (autoload 'epg-configuration "epg-config")
772 (autoload 'epg-expand-group "epg-config")
773 (autoload 'epa-select-keys "epa")
774
775 (defvar mml2015-epg-secret-key-id-list nil)
776
777 (defun mml2015-epg-passphrase-callback (context key-id ignore)
778   (if (eq key-id 'SYM)
779       (epg-passphrase-callback-function context key-id nil)
780     (let* ((password-cache-key-id
781             (if (eq key-id 'PIN)
782                 "PIN"
783                key-id))
784            entry
785            (passphrase
786             (password-read
787              (if (eq key-id 'PIN)
788                  "Passphrase for PIN: "
789                (if (setq entry (assoc key-id epg-user-id-alist))
790                    (format "Passphrase for %s %s: " key-id (cdr entry))
791                  (format "Passphrase for %s: " key-id)))
792              password-cache-key-id)))
793       (when passphrase
794         (let ((password-cache-expiry mml2015-passphrase-cache-expiry))
795           (password-cache-add password-cache-key-id passphrase))
796         (setq mml2015-epg-secret-key-id-list
797               (cons password-cache-key-id mml2015-epg-secret-key-id-list))
798         (copy-sequence passphrase)))))
799
800 (defun mml2015-epg-check-user-id (key recipient)
801   (let ((pointer (epg-key-user-id-list key))
802         result)
803     (while pointer
804       (if (and (equal (car (mail-header-parse-address
805                             (epg-user-id-string (car pointer))))
806                       (car (mail-header-parse-address
807                             recipient)))
808                (not (memq (epg-user-id-validity (car pointer))
809                           '(revoked expired))))
810           (setq result t
811                 pointer nil)
812         (setq pointer (cdr pointer))))
813     result))
814
815 (defun mml2015-epg-check-sub-key (key usage)
816   (let ((pointer (epg-key-sub-key-list key))
817         result)
818     ;; The primary key will be marked as disabled, when the entire
819     ;; key is disabled (see 12 Field, Format of colon listings, in
820     ;; gnupg/doc/DETAILS)
821     (unless (memq 'disabled (epg-sub-key-capability (car pointer)))
822       (while pointer
823         (if (and (memq usage (epg-sub-key-capability (car pointer)))
824                  (not (memq (epg-sub-key-validity (car pointer))
825                             '(revoked expired))))
826             (setq result t
827                   pointer nil)
828           (setq pointer (cdr pointer)))))
829     result))
830
831 (defun mml2015-epg-find-usable-key (context name usage
832                                             &optional name-is-key-id)
833   (let ((keys (epg-list-keys context name))
834         key)
835     (while keys
836       (if (and (or name-is-key-id
837                    ;; Non email user-id can be supplied through
838                    ;; mml2015-signers if mml2015-encrypt-to-self is set.
839                    ;; Treat it as valid, as it is user's intention.
840                    (not (string-match "\\`<" name))
841                    (mml2015-epg-check-user-id (car keys) name))
842                (mml2015-epg-check-sub-key (car keys) usage))
843           (setq key (car keys)
844                 keys nil)
845         (setq keys (cdr keys))))
846     key))
847
848 ;; XXX: since gpg --list-secret-keys does not return validity of each
849 ;; key, `mml2015-epg-find-usable-key' defined above is not enough for
850 ;; secret keys.  The function `mml2015-epg-find-usable-secret-key'
851 ;; below looks at appropriate public keys to check usability.
852 (defun mml2015-epg-find-usable-secret-key (context name usage)
853   (let ((secret-keys (epg-list-keys context name t))
854         secret-key)
855     (while (and (not secret-key) secret-keys)
856       (if (mml2015-epg-find-usable-key
857            context
858            (epg-sub-key-fingerprint
859             (car (epg-key-sub-key-list
860                   (car secret-keys))))
861            usage
862            t)
863           (setq secret-key (car secret-keys)
864                 secret-keys nil)
865         (setq secret-keys (cdr secret-keys))))
866     secret-key))
867
868 (defun mml2015-epg-key-image (key-id)
869   "Return the image of a key, if any"
870   (with-temp-buffer
871     (mm-set-buffer-multibyte nil)
872     (let* ((coding-system-for-write 'binary)
873            (coding-system-for-read 'binary)
874            (data (shell-command-to-string
875                   (format "%s --list-options no-show-photos --attribute-fd 3 --list-keys %s 3>&1 >/dev/null 2>&1"
876                           (shell-quote-argument epg-gpg-program) key-id))))
877       (when (> (length data) 0)
878         (insert (substring data 16))
879         (create-image (buffer-string) nil t)))))
880
881 (autoload 'gnus-rescale-image "gnus-util")
882
883 (defun mml2015-epg-key-image-to-string (key-id)
884   "Return a string with the image of a key, if any"
885   (let* ((result "")
886          (key-image (mml2015-epg-key-image key-id)))
887     (when key-image
888       (setq result "  ")
889       (put-text-property
890        1 2 'display
891        (gnus-rescale-image key-image
892                            (cons mml2015-maximum-key-image-dimension
893                                  mml2015-maximum-key-image-dimension))
894        result))
895     result))
896
897 (defun mml2015-epg-signature-to-string (signature)
898   (concat (epg-signature-to-string signature)
899           (mml2015-epg-key-image-to-string (epg-signature-key-id signature))))
900
901 (defun mml2015-epg-verify-result-to-string (verify-result)
902   (mapconcat #'mml2015-epg-signature-to-string verify-result "\n"))
903
904 (defun mml2015-epg-decrypt (handle ctl)
905   (catch 'error
906     (let ((inhibit-redisplay t)
907           context plain child handles result decrypt-status)
908       (unless (setq child (mm-find-part-by-type
909                            (cdr handle)
910                            "application/octet-stream" nil t))
911         (mm-set-handle-multipart-parameter
912          mm-security-handle 'gnus-info "Corrupted")
913         (throw 'error handle))
914       (setq context (epg-make-context))
915       (if mml2015-cache-passphrase
916           (epg-context-set-passphrase-callback
917            context
918            #'mml2015-epg-passphrase-callback))
919       (condition-case error
920           (setq plain (epg-decrypt-string context (mm-get-part child))
921                 mml2015-epg-secret-key-id-list nil)
922         (error
923          (while mml2015-epg-secret-key-id-list
924            (password-cache-remove (car mml2015-epg-secret-key-id-list))
925            (setq mml2015-epg-secret-key-id-list
926                  (cdr mml2015-epg-secret-key-id-list)))
927          (mm-set-handle-multipart-parameter
928           mm-security-handle 'gnus-info "Failed")
929          (if (eq (car error) 'quit)
930              (mm-set-handle-multipart-parameter
931               mm-security-handle 'gnus-details "Quit.")
932            (mm-set-handle-multipart-parameter
933             mm-security-handle 'gnus-details (mml2015-format-error error)))
934          (throw 'error handle)))
935       (with-temp-buffer
936         (insert plain)
937         (goto-char (point-min))
938         (while (search-forward "\r\n" nil t)
939           (replace-match "\n" t t))
940         (setq handles (mm-dissect-buffer t))
941         (mm-destroy-parts handle)
942         (if (epg-context-result-for context 'verify)
943             (mm-set-handle-multipart-parameter
944              mm-security-handle 'gnus-info
945              (concat "OK\n"
946                      (mml2015-epg-verify-result-to-string
947                       (epg-context-result-for context 'verify))))
948           (mm-set-handle-multipart-parameter
949            mm-security-handle 'gnus-info "OK"))
950         (if (stringp (car handles))
951             (mm-set-handle-multipart-parameter
952              mm-security-handle 'gnus-details
953              (mm-handle-multipart-ctl-parameter handles 'gnus-details))))
954         (if (listp (car handles))
955             handles
956           (list handles)))))
957
958 (defun mml2015-epg-clear-decrypt ()
959   (let ((inhibit-redisplay t)
960         (context (epg-make-context))
961         plain)
962     (if mml2015-cache-passphrase
963         (epg-context-set-passphrase-callback
964          context
965          #'mml2015-epg-passphrase-callback))
966     (condition-case error
967         (setq plain (epg-decrypt-string context (buffer-string))
968               mml2015-epg-secret-key-id-list nil)
969       (error
970        (while mml2015-epg-secret-key-id-list
971          (password-cache-remove (car mml2015-epg-secret-key-id-list))
972          (setq mml2015-epg-secret-key-id-list
973                (cdr mml2015-epg-secret-key-id-list)))
974        (mm-set-handle-multipart-parameter
975         mm-security-handle 'gnus-info "Failed")
976        (if (eq (car error) 'quit)
977            (mm-set-handle-multipart-parameter
978             mm-security-handle 'gnus-details "Quit.")
979          (mm-set-handle-multipart-parameter
980           mm-security-handle 'gnus-details (mml2015-format-error error)))))
981     (when plain
982       (erase-buffer)
983       ;; Treat data which epg returns as a unibyte string.
984       (mm-disable-multibyte)
985       (insert plain)
986       (goto-char (point-min))
987       (while (search-forward "\r\n" nil t)
988         (replace-match "\n" t t))
989       (mm-set-handle-multipart-parameter
990        mm-security-handle 'gnus-info "OK")
991       (if (epg-context-result-for context 'verify)
992           (mm-set-handle-multipart-parameter
993            mm-security-handle 'gnus-details
994            (mml2015-epg-verify-result-to-string
995             (epg-context-result-for context 'verify)))))))
996
997 (defun mml2015-epg-verify (handle ctl)
998   (catch 'error
999     (let ((inhibit-redisplay t)
1000           context plain signature-file part signature)
1001       (when (or (null (setq part (mm-find-raw-part-by-type
1002                                   ctl (or (mm-handle-multipart-ctl-parameter
1003                                            ctl 'protocol)
1004                                           "application/pgp-signature")
1005                                   t)))
1006                 (null (setq signature (mm-find-part-by-type
1007                                        (cdr handle) "application/pgp-signature"
1008                                        nil t))))
1009         (mm-set-handle-multipart-parameter
1010          mm-security-handle 'gnus-info "Corrupted")
1011         (throw 'error handle))
1012       (setq part (mm-replace-in-string part "\n" "\r\n")
1013             signature (mm-get-part signature)
1014             context (epg-make-context))
1015       (condition-case error
1016           (setq plain (epg-verify-string context signature part))
1017         (error
1018          (mm-set-handle-multipart-parameter
1019           mm-security-handle 'gnus-info "Failed")
1020          (if (eq (car error) 'quit)
1021              (mm-set-handle-multipart-parameter
1022               mm-security-handle 'gnus-details "Quit.")
1023            (mm-set-handle-multipart-parameter
1024             mm-security-handle 'gnus-details (mml2015-format-error error)))
1025          (throw 'error handle)))
1026       (mm-set-handle-multipart-parameter
1027        mm-security-handle 'gnus-info
1028        (mml2015-epg-verify-result-to-string
1029         (epg-context-result-for context 'verify)))
1030       handle)))
1031
1032 (defun mml2015-epg-clear-verify ()
1033   (let ((inhibit-redisplay t)
1034         (context (epg-make-context))
1035         (signature (mm-encode-coding-string (buffer-string)
1036                                             coding-system-for-write))
1037         plain)
1038     (condition-case error
1039         (setq plain (epg-verify-string context signature))
1040       (error
1041        (mm-set-handle-multipart-parameter
1042         mm-security-handle 'gnus-info "Failed")
1043        (if (eq (car error) 'quit)
1044            (mm-set-handle-multipart-parameter
1045             mm-security-handle 'gnus-details "Quit.")
1046          (mm-set-handle-multipart-parameter
1047           mm-security-handle 'gnus-details (mml2015-format-error error)))))
1048     (if plain
1049         (progn
1050           (mm-set-handle-multipart-parameter
1051            mm-security-handle 'gnus-info
1052            (mml2015-epg-verify-result-to-string
1053             (epg-context-result-for context 'verify)))
1054           (delete-region (point-min) (point-max))
1055           (insert (mm-decode-coding-string plain coding-system-for-read)))
1056       (mml2015-extract-cleartext-signature))))
1057
1058 (defun mml2015-epg-sign (cont)
1059   (let* ((inhibit-redisplay t)
1060          (context (epg-make-context))
1061          (boundary (mml-compute-boundary cont))
1062          (sender (message-options-get 'message-sender))
1063          (signer-names (or mml2015-signers
1064                            (if (and mml2015-sign-with-sender sender)
1065                                (list (concat "<" sender ">")))))
1066          signer-key
1067          (signers
1068           (or (message-options-get 'mml2015-epg-signers)
1069               (message-options-set
1070                'mml2015-epg-signers
1071                (if (eq mm-sign-option 'guided)
1072                    (epa-select-keys context "\
1073 Select keys for signing.
1074 If no one is selected, default secret key is used.  "
1075                                     signer-names
1076                                     t)
1077                  (if (or sender mml2015-signers)
1078                      (delq nil
1079                            (mapcar
1080                             (lambda (signer)
1081                               (setq signer-key
1082                                     (mml2015-epg-find-usable-secret-key
1083                                      context signer 'sign))
1084                               (unless (or signer-key
1085                                           (y-or-n-p
1086                                            (format
1087                                             "No secret key for %s; skip it? "
1088                                             signer)))
1089                                 (error "No secret key for %s" signer))
1090                               signer-key)
1091                             signer-names)))))))
1092          signature micalg)
1093     (epg-context-set-armor context t)
1094     (epg-context-set-textmode context t)
1095     (epg-context-set-signers context signers)
1096     (if mml2015-cache-passphrase
1097         (epg-context-set-passphrase-callback
1098          context
1099          #'mml2015-epg-passphrase-callback))
1100     ;; Signed data must end with a newline (RFC 3156, 5).
1101     (goto-char (point-max))
1102     (unless (bolp)
1103       (insert "\n"))
1104     (condition-case error
1105         (setq signature (epg-sign-string context (buffer-string) t)
1106               mml2015-epg-secret-key-id-list nil)
1107       (error
1108        (while mml2015-epg-secret-key-id-list
1109          (password-cache-remove (car mml2015-epg-secret-key-id-list))
1110          (setq mml2015-epg-secret-key-id-list
1111                (cdr mml2015-epg-secret-key-id-list)))
1112        (signal (car error) (cdr error))))
1113     (if (epg-context-result-for context 'sign)
1114         (setq micalg (epg-new-signature-digest-algorithm
1115                       (car (epg-context-result-for context 'sign)))))
1116     (goto-char (point-min))
1117     (insert (format "Content-Type: multipart/signed; boundary=\"%s\";\n"
1118                     boundary))
1119     (if micalg
1120         (insert (format "\tmicalg=pgp-%s; "
1121                         (downcase
1122                          (cdr (assq micalg
1123                                     epg-digest-algorithm-alist))))))
1124     (insert "protocol=\"application/pgp-signature\"\n")
1125     (insert (format "\n--%s\n" boundary))
1126     (goto-char (point-max))
1127     (insert (format "\n--%s\n" boundary))
1128     (insert "Content-Type: application/pgp-signature; name=\"signature.asc\"\n\n")
1129     (insert signature)
1130     (goto-char (point-max))
1131     (insert (format "--%s--\n" boundary))
1132     (goto-char (point-max))))
1133
1134 (defun mml2015-epg-encrypt (cont &optional sign)
1135   (let* ((inhibit-redisplay t)
1136          (context (epg-make-context))
1137          (boundary (mml-compute-boundary cont))
1138          (config (epg-configuration))
1139          (recipients (message-options-get 'mml2015-epg-recipients))
1140          cipher
1141          (sender (message-options-get 'message-sender))
1142          (signer-names (or mml2015-signers
1143                            (if (and mml2015-sign-with-sender sender)
1144                                (list (concat "<" sender ">")))))
1145          signers
1146          recipient-key signer-key)
1147     (unless recipients
1148       (setq recipients
1149             (apply #'nconc
1150                    (mapcar
1151                     (lambda (recipient)
1152                       (or (epg-expand-group config recipient)
1153                           (list (concat "<" recipient ">"))))
1154                     (split-string
1155                      (or (message-options-get 'message-recipients)
1156                          (message-options-set 'message-recipients
1157                                               (read-string "Recipients: ")))
1158                      "[ \f\t\n\r\v,]+"))))
1159       (when mml2015-encrypt-to-self
1160         (unless signer-names
1161           (error "Neither message sender nor mml2015-signers are set"))
1162         (setq recipients (nconc recipients signer-names)))
1163       (if (eq mm-encrypt-option 'guided)
1164           (setq recipients
1165                 (epa-select-keys context "\
1166 Select recipients for encryption.
1167 If no one is selected, symmetric encryption will be performed.  "
1168                                  recipients))
1169         (setq recipients
1170               (delq nil
1171                     (mapcar
1172                      (lambda (recipient)
1173                        (setq recipient-key (mml2015-epg-find-usable-key
1174                                             context recipient 'encrypt))
1175                        (unless (or recipient-key
1176                                    (y-or-n-p
1177                                     (format "No public key for %s; skip it? "
1178                                             recipient)))
1179                          (error "No public key for %s" recipient))
1180                        recipient-key)
1181                      recipients)))
1182         (unless recipients
1183           (error "No recipient specified")))
1184       (message-options-set 'mml2015-epg-recipients recipients))
1185     (when sign
1186       (setq signers
1187             (or (message-options-get 'mml2015-epg-signers)
1188                 (message-options-set
1189                  'mml2015-epg-signers
1190                  (if (eq mm-sign-option 'guided)
1191                      (epa-select-keys context "\
1192 Select keys for signing.
1193 If no one is selected, default secret key is used.  "
1194                                       signer-names
1195                                       t)
1196                    (if (or sender mml2015-signers)
1197                        (delq nil
1198                              (mapcar
1199                               (lambda (signer)
1200                                 (setq signer-key
1201                                       (mml2015-epg-find-usable-secret-key
1202                                        context signer 'sign))
1203                                 (unless (or signer-key
1204                                             (y-or-n-p
1205                                              (format
1206                                               "No secret key for %s; skip it? "
1207                                               signer)))
1208                                   (error "No secret key for %s" signer))
1209                                 signer-key)
1210                               signer-names)))))))
1211       (epg-context-set-signers context signers))
1212     (epg-context-set-armor context t)
1213     (epg-context-set-textmode context t)
1214     (if mml2015-cache-passphrase
1215         (epg-context-set-passphrase-callback
1216          context
1217          #'mml2015-epg-passphrase-callback))
1218     (condition-case error
1219         (setq cipher
1220               (epg-encrypt-string context (buffer-string) recipients sign
1221                                   mml2015-always-trust)
1222               mml2015-epg-secret-key-id-list nil)
1223       (error
1224        (while mml2015-epg-secret-key-id-list
1225          (password-cache-remove (car mml2015-epg-secret-key-id-list))
1226          (setq mml2015-epg-secret-key-id-list
1227                (cdr mml2015-epg-secret-key-id-list)))
1228        (signal (car error) (cdr error))))
1229     (delete-region (point-min) (point-max))
1230     (goto-char (point-min))
1231     (insert (format "Content-Type: multipart/encrypted; boundary=\"%s\";\n"
1232                     boundary))
1233     (insert "\tprotocol=\"application/pgp-encrypted\"\n\n")
1234     (insert (format "--%s\n" boundary))
1235     (insert "Content-Type: application/pgp-encrypted\n\n")
1236     (insert "Version: 1\n\n")
1237     (insert (format "--%s\n" boundary))
1238     (insert "Content-Type: application/octet-stream\n\n")
1239     (insert cipher)
1240     (goto-char (point-max))
1241     (insert (format "--%s--\n" boundary))
1242     (goto-char (point-max))))
1243
1244 ;;; General wrapper
1245
1246 (autoload 'gnus-buffer-live-p "gnus-util")
1247 (autoload 'gnus-get-buffer-create "gnus")
1248
1249 (defun mml2015-clean-buffer ()
1250   (if (gnus-buffer-live-p mml2015-result-buffer)
1251       (with-current-buffer mml2015-result-buffer
1252         (erase-buffer)
1253         t)
1254     (setq mml2015-result-buffer
1255           (gnus-get-buffer-create " *MML2015 Result*"))
1256     nil))
1257
1258 (defsubst mml2015-clear-decrypt-function ()
1259   (nth 6 (assq mml2015-use mml2015-function-alist)))
1260
1261 (defsubst mml2015-clear-verify-function ()
1262   (nth 5 (assq mml2015-use mml2015-function-alist)))
1263
1264 ;;;###autoload
1265 (defun mml2015-decrypt (handle ctl)
1266   (mml2015-clean-buffer)
1267   (let ((func (nth 4 (assq mml2015-use mml2015-function-alist))))
1268     (if func
1269         (funcall func handle ctl)
1270       handle)))
1271
1272 ;;;###autoload
1273 (defun mml2015-decrypt-test (handle ctl)
1274   mml2015-use)
1275
1276 ;;;###autoload
1277 (defun mml2015-verify (handle ctl)
1278   (mml2015-clean-buffer)
1279   (let ((func (nth 3 (assq mml2015-use mml2015-function-alist))))
1280     (if func
1281         (funcall func handle ctl)
1282       handle)))
1283
1284 ;;;###autoload
1285 (defun mml2015-verify-test (handle ctl)
1286   mml2015-use)
1287
1288 ;;;###autoload
1289 (defun mml2015-encrypt (cont &optional sign)
1290   (mml2015-clean-buffer)
1291   (let ((func (nth 2 (assq mml2015-use mml2015-function-alist))))
1292     (if func
1293         (funcall func cont sign)
1294       (error "Cannot find encrypt function"))))
1295
1296 ;;;###autoload
1297 (defun mml2015-sign (cont)
1298   (mml2015-clean-buffer)
1299   (let ((func (nth 1 (assq mml2015-use mml2015-function-alist))))
1300     (if func
1301         (funcall func cont)
1302       (error "Cannot find sign function"))))
1303
1304 ;;;###autoload
1305 (defun mml2015-self-encrypt ()
1306   (mml2015-encrypt nil))
1307
1308 (provide 'mml2015)
1309
1310 ;;; mml2015.el ends here