(mime-display-entity): Find `header-presentation-method' only if
[elisp/semi.git] / pgg.el
1 ;;; pgg.el --- glue for the various PGP implementations.
2
3 ;; Copyright (C) 1999,2000 Daiki Ueno
4
5 ;; Author: Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
6 ;; Created: 1999/10/28
7 ;; Keywords: PGP
8
9 ;; This file is part of SEMI (Secure Emacs MIME Interface).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program 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., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26
27 ;;; Commentary:
28 ;; 
29
30 ;;; Code:
31
32 (require 'calist)
33
34 (eval-and-compile (require 'luna))
35
36 (require 'pgg-def)
37 (require 'pgg-parse)
38
39 (eval-when-compile
40   (ignore-errors
41     (require 'w3)
42     (require 'url)))
43
44 (in-calist-package 'pgg)
45
46 (defun pgg-field-match-method-with-containment
47   (calist field-type field-value)
48   (let ((s-field (assq field-type calist)))
49     (cond ((null s-field)
50            (cons (cons field-type field-value) calist))
51           ((memq (cdr s-field) field-value)
52            calist))))
53
54 (define-calist-field-match-method 'signature-version
55   #'pgg-field-match-method-with-containment)
56
57 (define-calist-field-match-method 'symmetric-key-algorithm
58   #'pgg-field-match-method-with-containment)
59
60 (define-calist-field-match-method 'public-key-algorithm
61   #'pgg-field-match-method-with-containment)
62
63 (define-calist-field-match-method 'hash-algorithm
64   #'pgg-field-match-method-with-containment)
65
66 (defvar pgg-verify-condition nil
67   "Condition-tree about which PGP implementation is used for verifying.")
68
69 (defvar pgg-decrypt-condition nil
70   "Condition-tree about which PGP implementation is used for decrypting.")
71
72 (ctree-set-calist-strictly
73  'pgg-verify-condition
74  '((signature-version 3)(public-key-algorithm RSA)(hash-algorithm MD5)
75    (scheme . pgp)))
76
77 (ctree-set-calist-strictly
78  'pgg-decrypt-condition
79  '((public-key-algorithm RSA)(symmetric-key-algorithm IDEA)
80    (scheme . pgp)))
81
82 (ctree-set-calist-strictly
83  'pgg-verify-condition
84  '((signature-version 3 4)
85    (public-key-algorithm RSA ELG DSA)
86    (hash-algorithm MD5 SHA1 RIPEMD160)
87    (scheme . pgp5)))
88
89 (ctree-set-calist-strictly
90  'pgg-decrypt-condition
91  '((public-key-algorithm RSA ELG DSA)
92    (symmetric-key-algorithm 3DES CAST5 IDEA)
93    (scheme . pgp5)))
94
95 (ctree-set-calist-strictly
96  'pgg-verify-condition
97  '((signature-version 3 4)
98    (public-key-algorithm ELG-E DSA ELG)
99    (hash-algorithm MD5 SHA1 RIPEMD160)
100    (scheme . gpg)))
101
102 (ctree-set-calist-strictly
103  'pgg-decrypt-condition
104  '((public-key-algorithm ELG-E DSA ELG)
105    (symmetric-key-algorithm 3DES CAST5 BLOWFISH TWOFISH)
106    (scheme . gpg)))
107
108 ;;; @ definition of the implementation scheme
109 ;;;
110
111 (eval-and-compile
112   (luna-define-class pgg-scheme ())
113
114   (luna-define-internal-accessors 'pgg-scheme))
115
116 (luna-define-generic pgg-scheme-lookup-key (scheme string &optional type)
117   "Search keys associated with STRING")
118
119 (luna-define-generic pgg-scheme-encrypt-region (scheme start end recipients)
120   "Encrypt the current region between START and END.")
121
122 (luna-define-generic pgg-scheme-decrypt-region (scheme start end)
123   "Decrypt the current region between START and END.")
124
125 (luna-define-generic pgg-scheme-sign-region
126   (scheme start end &optional cleartext)
127   "Make detached signature from text between START and END.")
128
129 (luna-define-generic pgg-scheme-verify-region
130   (scheme start end &optional signature)
131   "Verify region between START and END
132 as the detached signature SIGNATURE.")
133
134 (luna-define-generic pgg-scheme-insert-key (scheme)
135   "Insert public key at point.")
136
137 (luna-define-generic pgg-scheme-snarf-keys-region (scheme start end)
138   "Add all public keys in region between START
139 and END to the keyring.")
140
141 ;;; @ utility functions
142 ;;;
143
144 (defvar pgg-fetch-key-function (function pgg-fetch-key-with-w3))
145
146 (defmacro pgg-make-scheme (scheme)
147   `(progn
148      (require (intern (format "pgg-%s" ,scheme)))
149      (funcall (intern (format "pgg-make-scheme-%s"
150                               ,scheme)))))
151
152 (put 'pgg-save-coding-system 'lisp-indent-function 2)
153
154 (defmacro pgg-save-coding-system (start end &rest body)
155   `(if (interactive-p)
156        (let ((buffer (current-buffer)))
157          (with-temp-buffer
158            (let (buffer-undo-list)
159              (insert-buffer-substring buffer ,start ,end)
160              (encode-coding-region (point-min)(point-max)
161                                    buffer-file-coding-system)
162              (prog1 (save-excursion ,@body)
163                (push nil buffer-undo-list)
164                (ignore-errors (undo))))))
165      (save-restriction
166        (narrow-to-region ,start ,end)
167        ,@body)))
168
169 (defun pgg-temp-buffer-show-function (buffer)
170   (if (one-window-p (selected-window))
171       (let ((window (split-window-vertically
172                      (- (window-height) 
173                         (/ (window-height) 5)))))
174         (set-window-buffer window buffer))
175     (display-buffer buffer)))
176
177 (defun pgg-display-output-buffer (start end status)
178   (if status
179       (progn
180         (delete-region start end)
181         (insert-buffer-substring pgg-output-buffer)
182         (decode-coding-region start (point) buffer-file-coding-system))
183     (let ((temp-buffer-show-function 
184            (function pgg-temp-buffer-show-function)))
185       (with-output-to-temp-buffer pgg-echo-buffer
186         (set-buffer standard-output)
187         (insert-buffer-substring pgg-errors-buffer)))))
188
189 (defvar pgg-passphrase-cache-expiry 16)
190 (defvar pgg-passphrase-cache (make-vector 7 0))
191
192 (defvar pgg-read-passphrase nil)
193 (defun pgg-read-passphrase (prompt &optional key)
194   (if (not pgg-read-passphrase)
195       (if (functionp 'read-passwd)
196           (setq pgg-read-passphrase 'read-passwd)
197         (if (load "passwd" t)
198             (setq pgg-read-passphrase 'read-passwd)
199           (autoload 'ange-ftp-read-passwd "ange-ftp")
200           (setq pgg-read-passphrase 'ange-ftp-read-passwd))))
201   (or (and pgg-cache-passphrase
202            key (setq key (pgg-truncate-key-identifier key))
203            (symbol-value (intern-soft key pgg-passphrase-cache)))
204       (funcall pgg-read-passphrase prompt)))
205
206 (defun pgg-add-passphrase-cache (key passphrase)
207   (setq key (pgg-truncate-key-identifier key))
208   (set (intern key pgg-passphrase-cache)
209        passphrase)
210   (run-at-time pgg-passphrase-cache-expiry nil
211                #'pgg-remove-passphrase-cache
212                key))
213
214 (defun pgg-remove-passphrase-cache (key)
215   (let ((passphrase (symbol-value (intern-soft key pgg-passphrase-cache))))
216     (when passphrase
217       (fillarray passphrase ?_)
218       (unintern key pgg-passphrase-cache))))
219
220 (defmacro pgg-convert-lbt-region (start end lbt)
221   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
222      (goto-char ,start)
223      (case ,lbt
224        (CRLF
225         (while (progn
226                  (end-of-line)
227                  (> (marker-position pgg-conversion-end) (point)))
228           (insert "\r")
229           (forward-line 1)))
230        (LF
231         (while (re-search-forward "\r$" pgg-conversion-end t)
232           (replace-match ""))))))
233
234 (put 'pgg-as-lbt 'lisp-indent-function 3)
235
236 (defmacro pgg-as-lbt (start end lbt &rest body)
237   `(let ((inhibit-read-only t)
238          buffer-read-only
239          buffer-undo-list)
240      (pgg-convert-lbt-region ,start ,end ,lbt)
241      (let ((,end (point)))
242        ,@body)
243      (push nil buffer-undo-list)
244      (ignore-errors (undo))))
245
246 (put 'pgg-process-when-success 'lisp-indent-function 0)
247
248 (defmacro pgg-process-when-success (&rest body)
249   `(with-current-buffer pgg-output-buffer
250      (if (zerop (buffer-size)) nil ,@body t)))
251
252
253 ;;; @ interface functions
254 ;;;
255
256 ;;;###autoload
257 (defun pgg-encrypt-region (start end rcpts)
258   "Encrypt the current region between START and END for RCPTS."
259   (interactive
260    (list (region-beginning)(region-end)
261          (split-string (read-string "Recipients: ") "[ \t,]+")))
262   (let* ((entity (pgg-make-scheme pgg-default-scheme))
263          (status 
264           (pgg-save-coding-system start end
265             (pgg-scheme-encrypt-region entity (point-min)(point-max) rcpts))))
266     (when (interactive-p)
267       (pgg-display-output-buffer start end status))
268     status))
269
270 ;;;###autoload
271 (defun pgg-decrypt-region (start end)
272   "Decrypt the current region between START and END."
273   (interactive "r")
274   (let* ((packet (cdr (assq 1 (pgg-parse-armor-region start end))))
275          (scheme
276           (or pgg-scheme
277               (cdr (assq 'scheme
278                          (progn
279                            (in-calist-package 'pgg)
280                            (ctree-match-calist pgg-decrypt-condition
281                                                packet))))
282               pgg-default-scheme))
283          (entity (pgg-make-scheme scheme))
284          (status
285           (pgg-save-coding-system start end
286             (pgg-scheme-decrypt-region entity (point-min)(point-max)))))
287     (when (interactive-p)
288       (pgg-display-output-buffer start end status))
289     status))
290
291 ;;;###autoload
292 (defun pgg-sign-region (start end &optional cleartext)
293   "Make the signature from text between START and END.
294 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
295 a detached signature."
296   (interactive "r")
297   (let* ((entity (pgg-make-scheme pgg-default-scheme))
298          (status (pgg-save-coding-system start end
299                    (pgg-scheme-sign-region entity (point-min)(point-max)
300                                            (or (interactive-p) cleartext)))))
301     (when (interactive-p)
302       (pgg-display-output-buffer start end status))
303     status))
304
305 ;;;###autoload
306 (defun pgg-verify-region (start end &optional signature fetch)
307   "Verify the current region between START and END.
308 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
309 the detached signature of the current region.
310
311 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
312 signer's public key from `pgg-default-keyserver-address'."
313   (interactive "r")
314   (let* ((packet
315           (if (null signature) nil
316             (with-temp-buffer
317               (buffer-disable-undo)
318               (set-buffer-multibyte nil)
319               (insert-file-contents signature)
320               (cdr (assq 2 (pgg-decode-armor-region 
321                             (point-min)(point-max)))))))
322          (scheme
323           (or pgg-scheme
324               (cdr (assq 'scheme
325                          (progn
326                            (in-calist-package 'pgg)
327                            (ctree-match-calist pgg-verify-condition
328                                                packet))))
329               pgg-default-scheme))
330          (entity (pgg-make-scheme scheme))
331          (key (cdr (assq 'key-identifier packet)))
332          status keyserver)
333     (and (stringp key)
334          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
335          (null (let ((pgg-scheme scheme))
336                  (pgg-lookup-key key)))
337          (or fetch (interactive-p))
338          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
339          (setq keyserver
340                (or (cdr (assq 'preferred-key-server packet))
341                    pgg-default-keyserver-address))
342          (pgg-fetch-key keyserver key))
343     (setq status (pgg-save-coding-system start end
344                    (pgg-scheme-verify-region entity (point-min)(point-max)
345                                              signature)))
346     (when (interactive-p)
347       (let ((temp-buffer-show-function
348              (function pgg-temp-buffer-show-function)))
349         (with-output-to-temp-buffer pgg-echo-buffer
350           (set-buffer standard-output)
351           (insert-buffer-substring (if status pgg-output-buffer
352                                      pgg-errors-buffer)))))
353     status))
354
355 ;;;###autoload
356 (defun pgg-insert-key ()
357   "Insert the ASCII armored public key."
358   (interactive)
359   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
360     (pgg-scheme-insert-key entity)))
361
362 ;;;###autoload
363 (defun pgg-snarf-keys-region (start end)
364   "Import public keys in the current region between START and END."
365   (interactive "r")
366   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
367     (pgg-save-coding-system start end
368       (pgg-scheme-snarf-keys-region entity start end))))
369
370 (defun pgg-lookup-key (string &optional type)
371   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
372     (pgg-scheme-lookup-key entity string type)))
373
374 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
375
376 (defun pgg-insert-url-with-w3 (url)
377   (require 'w3)
378   (require 'url)
379   (let (buffer-file-name)
380     (url-insert-file-contents url)))
381
382 (defvar pgg-insert-url-extra-arguments nil)
383 (defvar pgg-insert-url-program nil)
384
385 (defun pgg-insert-url-with-program (url)
386   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
387         process)
388     (insert
389      (with-temp-buffer
390        (setq process
391              (apply #'start-process " *PGG url*" (current-buffer)
392                     pgg-insert-url-program (nconc args (list url))))
393        (set-process-sentinel process #'ignore)
394        (while (eq 'run (process-status process))
395          (accept-process-output process 5))
396        (delete-process process)
397        (if (and process (eq 'run (process-status process)))
398            (interrupt-process process))
399        (buffer-string)))))
400
401 (defun pgg-fetch-key (keyserver key)
402   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
403   (with-current-buffer (get-buffer-create pgg-output-buffer)
404     (buffer-disable-undo)
405     (erase-buffer)
406     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
407                      (substring keyserver 0 (1- (match-end 0))))))
408       (save-excursion
409         (funcall pgg-insert-url-function
410                  (if proto keyserver
411                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
412                            keyserver key))))
413       (when (re-search-forward "^-+BEGIN" nil 'last)
414         (delete-region (point-min) (match-beginning 0))
415         (when (re-search-forward "^-+END" nil t)
416           (delete-region (progn (end-of-line) (point))
417                          (point-max)))
418         (insert "\n")
419         (with-temp-buffer
420           (insert-buffer-substring pgg-output-buffer)
421           (pgg-snarf-keys-region (point-min)(point-max)))))))
422
423
424 (provide 'pgg)
425
426 ;;; pgg.el ends here