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