Fix last change.
[elisp/semi.git] / pgg.el
1 ;;; pgg.el --- glue for the various PGP implementations.
2
3 ;; Copyright (C) 1999 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            )
52           ((memq (cdr s-field) field-value)
53            calist))))
54
55 (define-calist-field-match-method 'signature-version
56   #'pgg-field-match-method-with-containment)
57
58 (define-calist-field-match-method 'symmetric-key-algorithm
59   #'pgg-field-match-method-with-containment)
60
61 (define-calist-field-match-method 'public-key-algorithm
62   #'pgg-field-match-method-with-containment)
63
64 (define-calist-field-match-method 'hash-algorithm
65   #'pgg-field-match-method-with-containment)
66
67 (defvar pgg-verify-condition nil
68   "Condition-tree about which PGP implementation is used for verifying.")
69
70 (defvar pgg-decrypt-condition nil
71   "Condition-tree about which PGP implementation is used for decrypting.")
72
73 (ctree-set-calist-strictly
74  'pgg-verify-condition
75  '((signature-version 3)(public-key-algorithm RSA)(hash-algorithm MD5)
76    (scheme . pgp)))
77
78 (ctree-set-calist-strictly
79  'pgg-decrypt-condition
80  '((public-key-algorithm RSA)(symmetric-key-algorithm IDEA)
81    (scheme . pgp)))
82
83 (ctree-set-calist-strictly
84  'pgg-verify-condition
85  '((signature-version 3 4)
86    (public-key-algorithm RSA ELG DSA)
87    (hash-algorithm MD5 SHA1 RIPEMD160)
88    (scheme . pgp5)))
89
90 (ctree-set-calist-strictly
91  'pgg-decrypt-condition
92  '((public-key-algorithm RSA ELG DSA)
93    (symmetric-key-algorithm 3DES CAST5 IDEA)
94    (scheme . pgp5)))
95
96 (ctree-set-calist-strictly
97  'pgg-verify-condition
98  '((signature-version 3 4)
99    (public-key-algorithm ELG-E DSA ELG)
100    (hash-algorithm MD5 SHA1 RIPEMD160)
101    (scheme . gpg)))
102
103 (ctree-set-calist-strictly
104  'pgg-decrypt-condition
105  '((public-key-algorithm ELG-E DSA ELG)
106    (symmetric-key-algorithm 3DES CAST5 BLOWFISH 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
118 (luna-define-generic lookup-key-string (scheme string &optional type)
119   "Search keys associated with STRING")
120
121 (luna-define-generic encrypt-region (scheme start end recipients)
122   "Encrypt the current region between START and END.")
123
124 (luna-define-generic decrypt-region (scheme start end)
125   "Decrypt the current region between START and END.")
126
127 (luna-define-generic sign-region (scheme start end &optional cleartext)
128   "Make detached signature from text between START and END.")
129
130 (luna-define-generic verify-region (scheme start end &optional signature)
131   "Verify region between START and END
132 as the detached signature SIGNATURE.")
133
134 (luna-define-generic insert-key (scheme)
135   "Insert public key at point.")
136
137 (luna-define-generic 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              )))
166      (save-restriction
167        (narrow-to-region ,start ,end)
168        ,@body)))
169
170 (defun pgg-temp-buffer-show-function (buffer)
171   (if (one-window-p (selected-window))
172       (let ((window (split-window-vertically
173                      (- (window-height) 
174                         (/ (window-height) 5)))))
175         (set-window-buffer window buffer))
176     (display-buffer buffer)))
177
178 (defun pgg-display-output-buffer (start end status)
179   (if status
180       (progn
181         (delete-region start end)
182         (insert-buffer-substring pgg-output-buffer)
183         (decode-coding-region start (point) buffer-file-coding-system)
184         )
185     (let ((temp-buffer-show-function 
186            (function pgg-temp-buffer-show-function)))
187       (with-output-to-temp-buffer pgg-echo-buffer
188         (set-buffer standard-output)
189         (insert-buffer-substring pgg-errors-buffer)))
190     ))
191
192 (defvar pgg-passphrase-cache-expiry 16)
193 (defvar pgg-passphrase-cache (make-vector 7 0))
194
195 (defvar pgg-read-passphrase nil)
196 (defun pgg-read-passphrase (prompt &optional key)
197   (if (not pgg-read-passphrase)
198       (if (functionp 'read-passwd)
199           (setq pgg-read-passphrase 'read-passwd)
200         (if (load "passwd" t)
201             (setq pgg-read-passphrase 'read-passwd)
202           (autoload 'ange-ftp-read-passwd "ange-ftp")
203           (setq pgg-read-passphrase 'ange-ftp-read-passwd))))
204   (or (and key (setq key (pgg-truncate-key-identifier key))
205            (symbol-value (intern-soft key pgg-passphrase-cache)))
206       (funcall pgg-read-passphrase prompt)))
207
208 (defun pgg-add-passphrase-cache (key passphrase)
209   (setq key (pgg-truncate-key-identifier key))
210   (set (intern key pgg-passphrase-cache)
211        passphrase)
212   (run-at-time pgg-passphrase-cache-expiry nil
213                #'pgg-remove-passphrase-cache
214                key))
215
216 (defun pgg-remove-passphrase-cache (key)
217   (unintern key pgg-passphrase-cache))
218
219 (defmacro pgg-convert-lbt-region (start end lbt)
220   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
221      (goto-char ,start)
222      (case ,lbt
223        (CRLF
224         (while (progn
225                  (end-of-line)
226                  (> (marker-position pgg-conversion-end) (point)))
227           (insert "\r")
228           (forward-line 1)))
229        (LF
230         (while (re-search-forward "\r$" pgg-conversion-end t)
231           (replace-match ""))))
232      ))
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 (pgg-save-coding-system start end
264                    (luna-send entity 'encrypt-region entity
265                               (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 (pgg-save-coding-system start end
285                    (luna-send entity 'decrypt-region entity 
286                               (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                    (luna-send entity 'sign-region entity
300                               (point-min)(point-max)
301                               (or (interactive-p) cleartext)))))
302     (when (interactive-p)
303       (pgg-display-output-buffer start end status))
304     status))
305
306 ;;;###autoload
307 (defun pgg-verify-region (start end &optional signature fetch)
308   "Verify the current region between START and END.
309 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
310 the detached signature of the current region.
311
312 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
313 signer's public key from `pgg-default-keyserver-address'."
314   (interactive "r")
315   (let* ((packet
316           (if (null signature) nil
317             (with-temp-buffer
318               (buffer-disable-undo)
319               (set-buffer-multibyte nil)
320               (insert-file-contents signature)
321               (cdr (assq 2 (pgg-decode-armor-region (point-min)(point-max))))
322               )))
323          (scheme
324           (or pgg-scheme
325               (cdr (assq 'scheme
326                          (progn
327                            (in-calist-package 'pgg)
328                            (ctree-match-calist pgg-verify-condition
329                                                packet))))
330               pgg-default-scheme))
331          (entity (pgg-make-scheme scheme))
332          (key (cdr (assq 'key-identifier packet)))
333          status keyserver)
334     (and (stringp key)
335          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
336          (null (let ((pgg-scheme scheme))
337                  (pgg-lookup-key-string key)))
338          (or fetch (interactive-p))
339          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
340          (setq keyserver
341                (or (cdr (assq 'preferred-key-server packet))
342                    pgg-default-keyserver-address))
343          (pgg-fetch-key keyserver key))
344     (setq status (pgg-save-coding-system start end
345                    (luna-send entity 'verify-region entity 
346                               (point-min)(point-max) signature)))
347     (when (interactive-p)
348       (let ((temp-buffer-show-function
349              (function pgg-temp-buffer-show-function)))
350         (with-output-to-temp-buffer pgg-echo-buffer
351           (set-buffer standard-output)
352           (insert-buffer-substring (if status pgg-output-buffer
353                                      pgg-errors-buffer))
354           )))
355     status))
356
357 ;;;###autoload
358 (defun pgg-insert-key ()
359   "Insert the ASCII armored public key."
360   (interactive)
361   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
362     (luna-send entity 'insert-key entity)))
363
364 ;;;###autoload
365 (defun pgg-snarf-keys-region (start end)
366   "Import public keys in the current region between START and END."
367   (interactive "r")
368   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
369     (pgg-save-coding-system start end
370       (luna-send entity 'snarf-keys-region entity start end))))
371
372 (defun pgg-lookup-key-string (string &optional type)
373   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
374     (luna-send entity 'lookup-key-string entity string type)))
375
376 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
377
378 (defun pgg-insert-url-with-w3 (url)
379   (require 'w3)
380   (require 'url)
381   (let (buffer-file-name)
382     (url-insert-file-contents url)))
383
384 (defvar pgg-insert-url-extra-arguments nil)
385 (defvar pgg-insert-url-program nil)
386
387 (defun pgg-insert-url-with-program (url)
388   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
389         process)
390     (insert
391      (with-temp-buffer
392        (setq process
393              (apply #'start-process " *PGG url*" (current-buffer)
394                     pgg-insert-url-program (nconc args (list url))))
395        (set-process-sentinel process #'ignore)
396        (while (eq 'run (process-status process))
397          (accept-process-output process 5))
398        (delete-process process)
399        (if (and process (eq 'run (process-status process)))
400            (interrupt-process process))
401        (buffer-string)))
402     ))
403
404 (defun pgg-fetch-key (keyserver key)
405   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
406   (with-current-buffer (get-buffer-create pgg-output-buffer)
407     (buffer-disable-undo)
408     (erase-buffer)
409     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
410                      (substring keyserver 0 (1- (match-end 0))))))
411       (save-excursion
412         (funcall pgg-insert-url-function
413                  (if proto keyserver
414                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
415                            keyserver key))))
416       (when (re-search-forward "^-+BEGIN" nil 'last)
417         (delete-region (point-min) (match-beginning 0))
418         (when (re-search-forward "^-+END" nil t)
419           (delete-region (progn (end-of-line) (point))
420                          (point-max)))
421         (insert "\n")
422         (with-temp-buffer
423           (insert-buffer-substring pgg-output-buffer)
424           (pgg-snarf-keys-region (point-min)(point-max))))
425       )))
426
427
428 (provide 'pgg)
429
430 ;;; pgg.el ends here