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