Sync with semi-1_14.
[elisp/semi.git] / pgg.el
1 ;;; pgg.el --- glue for the various PGP implementations.
2
3 ;; Copyright (C) 1999,2000 Free Software Foundation, Inc.
4
5 ;; Author: Daiki Ueno <ueno@unixuser.org>
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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, 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
106     3DES CAST5 BLOWFISH RIJNDAEL RIJNDAEL192 RIJNDAEL256 TWOFISH)
107    (scheme . gpg)))
108
109 ;;; @ definition of the implementation scheme
110 ;;;
111
112 (eval-and-compile
113   (luna-define-class pgg-scheme ())
114
115   (luna-define-internal-accessors 'pgg-scheme))
116
117 (luna-define-generic pgg-scheme-lookup-key (scheme string &optional type)
118   "Search keys associated with STRING.")
119
120 (luna-define-generic pgg-scheme-encrypt-region (scheme start end recipients)
121   "Encrypt the current region between START and END.")
122
123 (luna-define-generic pgg-scheme-decrypt-region (scheme start end)
124   "Decrypt the current region between START and END.")
125
126 (luna-define-generic pgg-scheme-sign-region
127   (scheme start end &optional cleartext)
128   "Make detached signature from text between START and END.")
129
130 (luna-define-generic pgg-scheme-verify-region
131   (scheme start end &optional signature)
132   "Verify region between START and END 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 and END to the keyring.")
139
140 ;;; @ utility functions
141 ;;;
142
143 (defvar pgg-fetch-key-function (function pgg-fetch-key-with-w3))
144
145 (defmacro pgg-make-scheme (scheme)
146   `(progn
147      (require (intern (format "pgg-%s" ,scheme)))
148      (funcall (intern (format "pgg-make-scheme-%s"
149                               ,scheme)))))
150
151 (put 'pgg-save-coding-system 'lisp-indent-function 2)
152
153 (defmacro pgg-save-coding-system (start end &rest body)
154   `(if (interactive-p)
155        (let ((buffer (current-buffer)))
156          (with-temp-buffer
157            (let (buffer-undo-list)
158              (insert-buffer-substring buffer ,start ,end)
159              (encode-coding-region (point-min)(point-max)
160                                    buffer-file-coding-system)
161              (prog1 (save-excursion ,@body)
162                (push nil buffer-undo-list)
163                (ignore-errors (undo))))))
164      (save-restriction
165        (narrow-to-region ,start ,end)
166        ,@body)))
167
168 (defun pgg-temp-buffer-show-function (buffer)
169   (let ((window (split-window-vertically)))
170     (set-window-buffer window buffer)
171     (shrink-window-if-larger-than-buffer window)))
172
173 (defun pgg-display-output-buffer (start end status)
174   (if status
175       (progn
176         (delete-region start end)
177         (insert-buffer-substring pgg-output-buffer)
178         (decode-coding-region start (point) buffer-file-coding-system))
179     (let ((temp-buffer-show-function
180            (function pgg-temp-buffer-show-function)))
181       (with-output-to-temp-buffer pgg-echo-buffer
182         (set-buffer standard-output)
183         (insert-buffer-substring pgg-errors-buffer)))))
184
185 (defvar pgg-passphrase-cache-expiry 16)
186 (defvar pgg-passphrase-cache (make-vector 7 0))
187
188 (defvar pgg-read-passphrase nil)
189 (defun pgg-read-passphrase (prompt &optional key)
190   (if (not pgg-read-passphrase)
191       (if (functionp 'read-passwd)
192           (setq pgg-read-passphrase 'read-passwd)
193         (if (load "passwd" t)
194             (setq pgg-read-passphrase 'read-passwd)
195           (autoload 'ange-ftp-read-passwd "ange-ftp")
196           (setq pgg-read-passphrase 'ange-ftp-read-passwd))))
197   (or (and pgg-cache-passphrase
198            key (setq key (pgg-truncate-key-identifier key))
199            (symbol-value (intern-soft key pgg-passphrase-cache)))
200       (funcall pgg-read-passphrase prompt)))
201
202 (defun pgg-add-passphrase-cache (key passphrase)
203   (setq key (pgg-truncate-key-identifier key))
204   (set (intern key pgg-passphrase-cache)
205        passphrase)
206   (run-at-time pgg-passphrase-cache-expiry nil
207                #'pgg-remove-passphrase-cache
208                key))
209
210 (defun pgg-remove-passphrase-cache (key)
211   (let ((passphrase (symbol-value (intern-soft key pgg-passphrase-cache))))
212     (when passphrase
213       (fillarray passphrase ?_)
214       (unintern key pgg-passphrase-cache))))
215
216 (defmacro pgg-convert-lbt-region (start end lbt)
217   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
218      (goto-char ,start)
219      (case ,lbt
220        (CRLF
221         (while (progn
222                  (end-of-line)
223                  (> (marker-position pgg-conversion-end) (point)))
224           (insert "\r")
225           (forward-line 1)))
226        (LF
227         (while (re-search-forward "\r$" pgg-conversion-end t)
228           (replace-match ""))))))
229
230 (put 'pgg-as-lbt 'lisp-indent-function 3)
231
232 (defmacro pgg-as-lbt (start end lbt &rest body)
233   `(let ((inhibit-read-only t)
234          buffer-read-only
235          buffer-undo-list)
236      (pgg-convert-lbt-region ,start ,end ,lbt)
237      (let ((,end (point)))
238        ,@body)
239      (push nil buffer-undo-list)
240      (ignore-errors (undo))))
241
242 (put 'pgg-process-when-success 'lisp-indent-function 0)
243
244 (defmacro pgg-process-when-success (&rest body)
245   `(with-current-buffer pgg-output-buffer
246      (if (zerop (buffer-size)) nil ,@body t)))
247
248
249 ;;; @ interface functions
250 ;;;
251
252 ;;;###autoload
253 (defun pgg-encrypt-region (start end rcpts)
254   "Encrypt the current region between START and END for RCPTS."
255   (interactive
256    (list (region-beginning)(region-end)
257          (split-string (read-string "Recipients: ") "[ \t,]+")))
258   (let* ((entity (pgg-make-scheme pgg-default-scheme))
259          (status
260           (pgg-save-coding-system start end
261             (pgg-scheme-encrypt-region entity (point-min)(point-max) rcpts))))
262     (when (interactive-p)
263       (pgg-display-output-buffer start end status))
264     status))
265
266 ;;;###autoload
267 (defun pgg-decrypt-region (start end)
268   "Decrypt the current region between START and END."
269   (interactive "r")
270   (let* ((packet (cdr (assq 1 (pgg-parse-armor-region start end))))
271          (scheme
272           (or pgg-scheme
273               (cdr (assq 'scheme
274                          (progn
275                            (in-calist-package 'pgg)
276                            (ctree-match-calist pgg-decrypt-condition
277                                                packet))))
278               pgg-default-scheme))
279          (entity (pgg-make-scheme scheme))
280          (status
281           (pgg-save-coding-system start end
282             (pgg-scheme-decrypt-region entity (point-min)(point-max)))))
283     (when (interactive-p)
284       (pgg-display-output-buffer start end status))
285     status))
286
287 ;;;###autoload
288 (defun pgg-sign-region (start end &optional cleartext)
289   "Make the signature from text between START and END.
290 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
291 a detached signature."
292   (interactive "r")
293   (let* ((entity (pgg-make-scheme pgg-default-scheme))
294          (status (pgg-save-coding-system start end
295                    (pgg-scheme-sign-region entity (point-min)(point-max)
296                                            (or (interactive-p) cleartext)))))
297     (when (interactive-p)
298       (pgg-display-output-buffer start end status))
299     status))
300
301 ;;;###autoload
302 (defun pgg-verify-region (start end &optional signature fetch)
303   "Verify the current region between START and END.
304 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
305 the detached signature of the current region.
306
307 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
308 signer's public key from `pgg-default-keyserver-address'."
309   (interactive "r")
310   (let* ((packet
311           (if (null signature) nil
312             (with-temp-buffer
313               (buffer-disable-undo)
314               (set-buffer-multibyte nil)
315               (insert-file-contents signature)
316               (cdr (assq 2 (pgg-decode-armor-region
317                             (point-min)(point-max)))))))
318          (scheme
319           (or pgg-scheme
320               (cdr (assq 'scheme
321                          (progn
322                            (in-calist-package 'pgg)
323                            (ctree-match-calist pgg-verify-condition
324                                                packet))))
325               pgg-default-scheme))
326          (entity (pgg-make-scheme scheme))
327          (key (cdr (assq 'key-identifier packet)))
328          status keyserver)
329     (and (stringp key)
330          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
331          (null (let ((pgg-scheme scheme))
332                  (pgg-lookup-key key)))
333          (or fetch (interactive-p))
334          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
335          (setq keyserver
336                (or (cdr (assq 'preferred-key-server packet))
337                    pgg-default-keyserver-address))
338          (pgg-fetch-key keyserver key))
339     (setq status (pgg-save-coding-system start end
340                    (pgg-scheme-verify-region entity (point-min)(point-max)
341                                              signature)))
342     (when (interactive-p)
343       (let ((temp-buffer-show-function
344              (function pgg-temp-buffer-show-function)))
345         (with-output-to-temp-buffer pgg-echo-buffer
346           (set-buffer standard-output)
347           (insert-buffer-substring (if status pgg-output-buffer
348                                      pgg-errors-buffer)))))
349     status))
350
351 ;;;###autoload
352 (defun pgg-insert-key ()
353   "Insert the ASCII armored public key."
354   (interactive)
355   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
356     (pgg-scheme-insert-key entity)))
357
358 ;;;###autoload
359 (defun pgg-snarf-keys-region (start end)
360   "Import public keys in the current region between START and END."
361   (interactive "r")
362   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
363     (pgg-save-coding-system start end
364       (pgg-scheme-snarf-keys-region entity start end))))
365
366 (defun pgg-lookup-key (string &optional type)
367   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
368     (pgg-scheme-lookup-key entity string type)))
369
370 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
371
372 (defun pgg-insert-url-with-w3 (url)
373   (require 'w3)
374   (require 'url)
375   (let (buffer-file-name)
376     (url-insert-file-contents url)))
377
378 (defvar pgg-insert-url-extra-arguments nil)
379 (defvar pgg-insert-url-program nil)
380
381 (defun pgg-insert-url-with-program (url)
382   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
383         process)
384     (insert
385      (with-temp-buffer
386        (setq process
387              (apply #'start-process " *PGG url*" (current-buffer)
388                     pgg-insert-url-program (nconc args (list url))))
389        (set-process-sentinel process #'ignore)
390        (while (eq 'run (process-status process))
391          (accept-process-output process 5))
392        (delete-process process)
393        (if (and process (eq 'run (process-status process)))
394            (interrupt-process process))
395        (buffer-string)))))
396
397 (defun pgg-fetch-key (keyserver key)
398   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
399   (with-current-buffer (get-buffer-create pgg-output-buffer)
400     (buffer-disable-undo)
401     (erase-buffer)
402     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
403                      (substring keyserver 0 (1- (match-end 0))))))
404       (save-excursion
405         (funcall pgg-insert-url-function
406                  (if proto keyserver
407                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
408                            keyserver key))))
409       (when (re-search-forward "^-+BEGIN" nil 'last)
410         (delete-region (point-min) (match-beginning 0))
411         (when (re-search-forward "^-+END" nil t)
412           (delete-region (progn (end-of-line) (point))
413                          (point-max)))
414         (insert "\n")
415         (with-temp-buffer
416           (insert-buffer-substring pgg-output-buffer)
417           (pgg-snarf-keys-region (point-min)(point-max)))))))
418
419 ;;;###autoload
420 (defun pgg-universal-user-id-argument ()
421   (interactive)
422   (let* ((pgg-overriding-user-id (read-string "User ID: "))
423          (command (key-binding (read-key-sequence
424                                 (format "Command to execute on \"%s\":"
425                                         pgg-overriding-user-id)))))
426     (message "")
427     (call-interactively command)))
428
429 (provide 'pgg)
430
431 ;;; pgg.el ends here