update.
[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 ;;; @ interface 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 ((,start ,start) (,end ,end) buffer-undo-list)
159              (set-buffer-multibyte nil)
160              (insert-buffer-substring buffer ,start ,end)
161              (encode-coding-region (point-min)(point-max)
162                                    buffer-file-coding-system)
163              (setq ,start (point-min) ,end (point-max))
164              (prog1 (save-excursion ,@body)
165                (push nil buffer-undo-list)
166                (ignore-errors (undo)))
167              )))
168      ,@body))
169
170 (defun pgg-display-output-buffer (start end status)
171   (if status
172       (progn
173         (delete-region start end)
174         (insert-buffer-substring pgg-output-buffer)
175         (decode-coding-region start (point)
176                               buffer-file-coding-system)
177         )
178     (with-output-to-temp-buffer pgg-echo-buffer
179       (set-buffer standard-output)
180       (insert-buffer-substring pgg-errors-buffer)
181       )))
182
183 ;;;###autoload
184 (defun pgg-encrypt-region (start end rcpts)
185   "Encrypt the current region between START and END for RCPTS."
186   (interactive
187    (list (region-beginning)(region-end)
188          (split-string (read-string "Recipients: ") "[ \t,]+")))
189   (let* ((entity (pgg-make-scheme pgg-default-scheme))
190          (status (pgg-save-coding-system start end
191                    (luna-send entity 'encrypt-region entity
192                               start end rcpts))))
193     (when (interactive-p)
194       (pgg-display-output-buffer start end status))
195     status))
196
197 ;;;###autoload
198 (defun pgg-decrypt-region (start end)
199   "Decrypt the current region between START and END."
200   (interactive "r")
201   (let* ((packet (cdr (assq 1 (pgg-parse-armor-region start end))))
202          (scheme
203           (or pgg-scheme
204               (cdr (assq 'scheme
205                          (progn
206                            (in-calist-package 'pgg)
207                            (ctree-match-calist pgg-decrypt-condition
208                                                packet))))
209               pgg-default-scheme))
210          (entity (pgg-make-scheme scheme))
211          (status (pgg-save-coding-system start end
212                    (luna-send entity 'decrypt-region entity start end))))
213     (when (interactive-p)
214       (pgg-display-output-buffer start end status))
215     status))
216
217 ;;;###autoload
218 (defun pgg-sign-region (start end &optional cleartext)
219   "Make the signature from text between START and END.
220 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
221 a detached signature."
222   (interactive "r")
223   (let* ((entity (pgg-make-scheme pgg-default-scheme))
224          (status (pgg-save-coding-system start end
225                    (luna-send entity 'sign-region entity start end
226                               (or (interactive-p) cleartext)))))
227     (when (interactive-p)
228       (pgg-display-output-buffer start end status))
229     status))
230
231 ;;;###autoload
232 (defun pgg-verify-region (start end &optional signature fetch)
233   "Verify the current region between START and END.
234 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
235 the detached signature of the current region.
236
237 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
238 signer's public key from `pgg-default-keyserver-address'."
239   (interactive "r")
240   (let* ((packet
241           (if (null signature) nil
242             (with-temp-buffer
243               (buffer-disable-undo)
244               (set-buffer-multibyte nil)
245               (insert-file-contents signature)
246               (cdr (assq 2 (pgg-decode-armor-region (point-min)(point-max))))
247               )))
248          (scheme
249           (or pgg-scheme
250               (cdr (assq 'scheme
251                          (progn
252                            (in-calist-package 'pgg)
253                            (ctree-match-calist pgg-verify-condition
254                                                packet))))
255               pgg-default-scheme))
256          (entity (pgg-make-scheme scheme))
257          (key (cdr (assq 'key-identifier packet)))
258          status keyserver)
259     (and (stringp key)
260          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
261          (null (let ((pgg-scheme scheme))
262                  (pgg-lookup-key-string key)))
263          (or fetch (interactive-p))
264          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
265          (setq keyserver
266                (or (cdr (assq 'preferred-key-server packet))
267                    pgg-default-keyserver-address))
268          (pgg-fetch-key keyserver key))
269     (setq status (pgg-save-coding-system start end
270                    (luna-send entity 'verify-region
271                               entity start end signature)))
272     (when (interactive-p)
273       (with-output-to-temp-buffer pgg-echo-buffer
274         (set-buffer standard-output)
275         (insert-buffer-substring (if status pgg-output-buffer
276                                    pgg-errors-buffer))
277         ))
278     status))
279
280 ;;;###autoload
281 (defun pgg-insert-key ()
282   "Insert the ASCII armored public key."
283   (interactive)
284   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
285     (luna-send entity 'insert-key entity)))
286
287 ;;;###autoload
288 (defun pgg-snarf-keys-region (start end)
289   "Import public keys in the current region between START and END."
290   (interactive "r")
291   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
292     (pgg-save-coding-system start end
293       (luna-send entity 'snarf-keys-region entity start end))))
294
295 (defun pgg-lookup-key-string (string &optional type)
296   (let ((entity (pgg-make-scheme (or pgg-scheme pgg-default-scheme))))
297     (luna-send entity 'lookup-key-string entity string type)))
298
299 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
300
301 (defun pgg-insert-url-with-w3 (url)
302   (require 'w3)
303   (require 'url)
304   (let (buffer-file-name)
305     (url-insert-file-contents url)))
306
307 (defvar pgg-insert-url-extra-arguments nil)
308 (defvar pgg-insert-url-program nil)
309
310 (defun pgg-insert-url-with-program (url)
311   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
312         process)
313     (insert
314      (with-temp-buffer
315        (setq process
316              (apply #'start-process " *PGG url*" (current-buffer)
317                     pgg-insert-url-program (nconc args (list url))))
318        (set-process-sentinel process #'ignore)
319        (while (eq 'run (process-status process))
320          (accept-process-output process 5))
321        (delete-process process)
322        (if (and process (eq 'run (process-status process)))
323            (interrupt-process process))
324        (buffer-string)))
325     ))
326
327 (defun pgg-fetch-key (keyserver key)
328   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
329   (with-current-buffer (get-buffer-create pgg-output-buffer)
330     (buffer-disable-undo)
331     (erase-buffer)
332     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
333                      (substring keyserver 0 (1- (match-end 0))))))
334       (save-excursion
335         (funcall pgg-insert-url-function
336                  (if proto keyserver
337                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
338                            keyserver key))))
339       (when (re-search-forward "^-+BEGIN" nil 'last)
340         (delete-region (point-min) (match-beginning 0))
341         (when (re-search-forward "^-+END" nil t)
342           (delete-region (progn (end-of-line) (point))
343                          (point-max)))
344         (insert "\n")
345         (with-temp-buffer
346           (insert-buffer-substring pgg-output-buffer)
347           (pgg-snarf-keys-region (point-min)(point-max))))
348       )))
349
350
351 ;;; @ utility functions
352 ;;;
353
354 (defvar pgg-passphrase-cache-expiry 16)
355 (defvar pgg-passphrase-cache (make-vector 7 0))
356
357 (defvar pgg-read-passphrase nil)
358 (defun pgg-read-passphrase (prompt &optional key)
359   (if (not pgg-read-passphrase)
360       (if (functionp 'read-passwd)
361           (setq pgg-read-passphrase 'read-passwd)
362         (if (load "passwd" t)
363             (setq pgg-read-passphrase 'read-passwd)
364           (autoload 'ange-ftp-read-passwd "ange-ftp")
365           (setq pgg-read-passphrase 'ange-ftp-read-passwd))))
366   (or (and key (setq key (pgg-truncate-key-identifier key))
367            (symbol-value (intern-soft key pgg-passphrase-cache)))
368       (funcall pgg-read-passphrase prompt)))
369
370 (defun pgg-add-passphrase-cache (key passphrase)
371   (setq key (pgg-truncate-key-identifier key))
372   (set (intern key pgg-passphrase-cache)
373        passphrase)
374   (run-at-time pgg-passphrase-cache-expiry nil
375                #'pgg-remove-passphrase-cache
376                key))
377
378 (defun pgg-remove-passphrase-cache (key)
379   (unintern key pgg-passphrase-cache))
380
381 (defmacro pgg-convert-lbt-region (start end lbt)
382   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
383      (goto-char ,start)
384      (case ,lbt
385        (CRLF
386         (while (progn
387                  (end-of-line)
388                  (> (marker-position pgg-conversion-end) (point)))
389           (insert "\r")
390           (forward-line 1)))
391        (LF
392         (while (re-search-forward "\r$" pgg-conversion-end t)
393           (replace-match ""))))
394      ))
395
396 (put 'pgg-as-lbt 'lisp-indent-function 3)
397
398 (defmacro pgg-as-lbt (start end lbt &rest body)
399   `(let ((inhibit-read-only t)
400          buffer-read-only
401          buffer-undo-list)
402      (pgg-convert-lbt-region ,start ,end ,lbt)
403      (let ((,end (point)))
404        ,@body)
405      (push nil buffer-undo-list)
406      (ignore-errors (undo))))
407
408
409 ;;; @ postprocess macros
410 ;;;
411
412 (put 'pgg-process-when-success 'lisp-indent-function 0)
413
414 (defmacro pgg-process-when-success (&rest body)
415   `(with-current-buffer pgg-output-buffer
416      (if (zerop (buffer-size)) nil ,@body t)))
417
418 (provide 'pgg)
419
420 ;;; pgg.el ends here