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