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