Merge from emacs--devo--0, emacs--rel--22
[gnus] / lisp / pgg.el
1 ;;; pgg.el --- glue for the various PGP implementations.
2
3 ;; Copyright (C) 1999, 2000, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007 Free Software Foundation, Inc.
5
6 ;; Author: Daiki Ueno <ueno@unixuser.org>
7 ;; Symmetric encryption added by: Sascha Wilde <wilde@sha-bang.de>
8 ;; Created: 1999/10/28
9 ;; Keywords: PGP
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 3, or (at your option)
16 ;; any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
25 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
26 ;; Boston, MA 02110-1301, USA.
27
28 ;;; Commentary:
29
30 ;;; Code:
31
32 (require 'pgg-def)
33 (require 'pgg-parse)
34 (autoload 'run-at-time "timer")
35
36 ;; Don't merge these two `eval-when-compile's.
37 (eval-when-compile
38   (require 'cl))
39
40 ;;; @ utility functions
41 ;;;
42
43 (eval-when-compile
44   (unless (featurep 'xemacs)
45     (defalias 'pgg-run-at-time 'run-at-time)
46     (defalias 'pgg-cancel-timer 'cancel-timer))
47
48   (when (featurep 'xemacs)
49     (defmacro pgg-run-at-time-1 (time repeat function args)
50       (if (condition-case nil
51               (let ((delete-itimer 'delete-itimer)
52                     (itimer-driver-start 'itimer-driver-start)
53                     (itimer-value 'itimer-value)
54                     (start-itimer 'start-itimer))
55                 (unless (or (symbol-value 'itimer-process)
56                             (symbol-value 'itimer-timer))
57                   (funcall itimer-driver-start))
58                 ;; Check whether there is a bug to which the difference of
59                 ;; the present time and the time when the itimer driver was
60                 ;; woken up is subtracted from the initial itimer value.
61                 (let* ((inhibit-quit t)
62                        (ctime (current-time))
63                        (itimer-timer-last-wakeup
64                         (prog1
65                             ctime
66                           (setcar ctime (1- (car ctime)))))
67                        (itimer-list nil)
68                        (itimer (funcall start-itimer "pgg-run-at-time"
69                                         'ignore 5)))
70                   (sleep-for 0.1) ;; Accept the timeout interrupt.
71                   (prog1
72                       (> (funcall itimer-value itimer) 0)
73                     (funcall delete-itimer itimer))))
74             (error nil))
75           `(let ((time ,time))
76              (apply #'start-itimer "pgg-run-at-time"
77                     ,function (if time (max time 1e-9) 1e-9)
78                     ,repeat nil t ,args)))
79       `(let ((time ,time)
80              (itimers (list nil)))
81          (setcar
82           itimers
83           (apply #'start-itimer "pgg-run-at-time"
84                  (lambda (itimers repeat function &rest args)
85                    (let ((itimer (car itimers)))
86                      (if repeat
87                          (progn
88                            (set-itimer-function
89                             itimer
90                             (lambda (itimer repeat function &rest args)
91                               (set-itimer-restart itimer repeat)
92                               (set-itimer-function itimer function)
93                               (set-itimer-function-arguments itimer args)
94                               (apply function args)))
95                            (set-itimer-function-arguments
96                             itimer
97                             (append (list itimer repeat function) args)))
98                        (set-itimer-function
99                         itimer
100                         (lambda (itimer function &rest args)
101                           (delete-itimer itimer)
102                           (apply function args)))
103                        (set-itimer-function-arguments
104                         itimer
105                         (append (list itimer function) args)))))
106                  1e-9 (if time (max time 1e-9) 1e-9)
107                  nil t itimers ,repeat ,function ,args))))
108
109     (defun pgg-run-at-time (time repeat function &rest args)
110       "Emulating function run as `run-at-time'.
111 TIME should be nil meaning now, or a number of seconds from now.
112 Return an itimer object which can be used in either `delete-itimer'
113 or `cancel-timer'."
114       (pgg-run-at-time-1 time repeat function args))
115     (defun pgg-cancel-timer (timer)
116       "Emulate cancel-timer for xemacs."
117       (let ((delete-itimer 'delete-itimer))
118         (funcall delete-itimer timer)))
119     ))
120
121 (defun pgg-invoke (func scheme &rest args)
122   (progn
123     (require (intern (format "pgg-%s" scheme)))
124     (apply 'funcall (intern (format "pgg-%s-%s" scheme func)) args)))
125
126 (put 'pgg-save-coding-system 'lisp-indent-function 2)
127
128 (defmacro pgg-save-coding-system (start end &rest body)
129   `(if (interactive-p)
130        (let ((buffer (current-buffer)))
131          (with-temp-buffer
132            (let (buffer-undo-list)
133              (insert-buffer-substring buffer ,start ,end)
134              (encode-coding-region (point-min)(point-max)
135                                    buffer-file-coding-system)
136              (prog1 (save-excursion ,@body)
137                (push nil buffer-undo-list)
138                (ignore-errors (undo))))))
139      (save-restriction
140        (narrow-to-region ,start ,end)
141        ,@body)))
142
143 (defun pgg-temp-buffer-show-function (buffer)
144   (let ((window (or (get-buffer-window buffer 'visible)
145                     (split-window-vertically))))
146     (set-window-buffer window buffer)
147     (shrink-window-if-larger-than-buffer window)))
148
149 ;; XXX `pgg-display-output-buffer' is a horrible name for this function.
150 ;;     It should be something like `pgg-situate-output-or-display-error'.
151 (defun pgg-display-output-buffer (start end status)
152   "Situate en/decryption results or pop up an error buffer.
153
154 Text from START to END is replaced by contents of output buffer if STATUS
155 is true, or else the output buffer is displayed."
156   (if status
157       (pgg-situate-output start end)
158     (pgg-display-error-buffer)))
159
160 (defun pgg-situate-output (start end)
161   "Place en/decryption result in place of current text from START to END."
162   (delete-region start end)
163   (insert-buffer-substring pgg-output-buffer)
164   (decode-coding-region start (point) buffer-file-coding-system))
165
166 (defun pgg-display-error-buffer ()
167   "Pop up an error buffer indicating the reason for an en/decryption failure."
168   (let ((temp-buffer-show-function
169          (function pgg-temp-buffer-show-function)))
170     (with-output-to-temp-buffer pgg-echo-buffer
171       (set-buffer standard-output)
172       (insert-buffer-substring pgg-errors-buffer))))
173
174 (defvar pgg-passphrase-cache (make-vector 7 0))
175
176 (defvar pgg-pending-timers (make-vector 7 0)
177   "Hash table for managing scheduled pgg cache management timers.
178
179 We associate key and timer, so the timer can be cancelled if a new
180 timeout for the key is set while an old one is still pending.")
181
182 (defun pgg-read-passphrase (prompt &optional key notruncate)
183   "Using PROMPT, obtain passphrase for KEY from cache or user.
184
185 Truncate the key to 8 trailing characters unless NOTRUNCATE is true
186 \(default false).
187
188 Custom variables `pgg-cache-passphrase' and `pgg-passphrase-cache-expiry'
189 regulate cache behavior."
190   (or (pgg-read-passphrase-from-cache key notruncate)
191       (read-passwd prompt)))
192
193 (defun pgg-read-passphrase-from-cache (key &optional notruncate)
194   "Obtain passphrase for KEY from time-limited passphrase cache.
195
196 Truncate the key to 8 trailing characters unless NOTRUNCATE is true
197 \(default false).
198
199 Custom variables `pgg-cache-passphrase' and `pgg-passphrase-cache-expiry'
200 regulate cache behavior."
201   (and pgg-cache-passphrase
202        key (or notruncate
203                 (setq key (pgg-truncate-key-identifier key)))
204        (symbol-value (intern-soft key pgg-passphrase-cache))))
205
206 (defun pgg-add-passphrase-to-cache (key passphrase &optional notruncate)
207   "Associate KEY with PASSPHRASE in time-limited passphrase cache.
208
209 Truncate the key to 8 trailing characters unless NOTRUNCATE is true
210 \(default false).
211
212 Custom variables `pgg-cache-passphrase' and `pgg-passphrase-cache-expiry'
213 regulate cache behavior."
214
215   (let* ((key (if notruncate key (pgg-truncate-key-identifier key)))
216          (interned-timer-key (intern-soft key pgg-pending-timers))
217          (old-timer (symbol-value interned-timer-key))
218          new-timer)
219     (when old-timer
220         (cancel-timer old-timer)
221         (unintern interned-timer-key pgg-pending-timers))
222     (set (intern key pgg-passphrase-cache)
223          passphrase)
224     (set (intern key pgg-pending-timers)
225          (pgg-run-at-time pgg-passphrase-cache-expiry nil
226                            #'pgg-remove-passphrase-from-cache
227                            key notruncate))))
228
229 (if (fboundp 'clear-string)
230     (defalias 'pgg-clear-string 'clear-string)
231   (defun pgg-clear-string (string)
232     (fillarray string ?_)))
233
234 (declare-function pgg-clear-string "pgg" (string))
235
236 (defun pgg-remove-passphrase-from-cache (key &optional notruncate)
237   "Omit passphrase associated with KEY in time-limited passphrase cache.
238
239 Truncate the key to 8 trailing characters unless NOTRUNCATE is true
240 \(default false).
241
242 This is a no-op if there is not entry for KEY (eg, it's already expired.
243
244 The memory for the passphrase is filled with underscores to clear any
245 references to it.
246
247 Custom variables `pgg-cache-passphrase' and `pgg-passphrase-cache-expiry'
248 regulate cache behavior."
249   (let* ((passphrase (pgg-read-passphrase-from-cache key notruncate))
250          (key (if notruncate key (pgg-truncate-key-identifier key)))
251          (interned-timer-key (intern-soft key pgg-pending-timers))
252          (old-timer (symbol-value interned-timer-key)))
253     (when passphrase
254       (pgg-clear-string passphrase)
255       (unintern key pgg-passphrase-cache))
256     (when old-timer
257       (pgg-cancel-timer old-timer)
258       (unintern interned-timer-key pgg-pending-timers))))
259
260 (defmacro pgg-convert-lbt-region (start end lbt)
261   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
262      (goto-char ,start)
263      (case ,lbt
264        (CRLF
265         (while (progn
266                  (end-of-line)
267                  (> (marker-position pgg-conversion-end) (point)))
268           (insert "\r")
269           (forward-line 1)))
270        (LF
271         (while (re-search-forward "\r$" pgg-conversion-end t)
272           (replace-match ""))))))
273
274 (put 'pgg-as-lbt 'lisp-indent-function 3)
275
276 (defmacro pgg-as-lbt (start end lbt &rest body)
277   `(let ((inhibit-read-only t)
278          buffer-read-only
279          buffer-undo-list)
280      (pgg-convert-lbt-region ,start ,end ,lbt)
281      (let ((,end (point)))
282        ,@body)
283      (push nil buffer-undo-list)
284      (ignore-errors (undo))))
285
286 (put 'pgg-process-when-success 'lisp-indent-function 0)
287
288 (defmacro pgg-process-when-success (&rest body)
289   `(with-current-buffer pgg-output-buffer
290      (if (zerop (buffer-size)) nil ,@body t)))
291
292 (defalias 'pgg-make-temp-file
293   (if (fboundp 'make-temp-file)
294       'make-temp-file
295     (lambda (prefix &optional dir-flag)
296       (let ((file (expand-file-name
297                    (make-temp-name prefix)
298                    (if (fboundp 'temp-directory)
299                        (temp-directory)
300                      temporary-file-directory))))
301         (if dir-flag
302             (make-directory file))
303         file))))
304
305 ;;; @ interface functions
306 ;;;
307
308 ;;;###autoload
309 (defun pgg-encrypt-region (start end rcpts &optional sign passphrase)
310   "Encrypt the current region between START and END for RCPTS.
311
312 If optional argument SIGN is non-nil, do a combined sign and encrypt.
313
314 If optional PASSPHRASE is not specified, it will be obtained from the
315 passphrase cache or user."
316   (interactive
317    (list (region-beginning)(region-end)
318          (split-string (read-string "Recipients: ") "[ \t,]+")))
319   (let ((status
320          (pgg-save-coding-system start end
321            (pgg-invoke "encrypt-region" (or pgg-scheme pgg-default-scheme)
322                        (point-min) (point-max) rcpts sign passphrase))))
323     (when (interactive-p)
324       (pgg-display-output-buffer start end status))
325     status))
326
327 ;;;###autoload
328 (defun pgg-encrypt-symmetric-region (start end &optional passphrase)
329   "Encrypt the current region between START and END symmetric with passphrase.
330
331 If optional PASSPHRASE is not specified, it will be obtained from the
332 cache or user."
333   (interactive "r")
334   (let ((status
335          (pgg-save-coding-system start end
336            (pgg-invoke "encrypt-symmetric-region"
337                        (or pgg-scheme pgg-default-scheme)
338                        (point-min) (point-max) passphrase))))
339     (when (interactive-p)
340       (pgg-display-output-buffer start end status))
341     status))
342
343 ;;;###autoload
344 (defun pgg-encrypt-symmetric (&optional start end passphrase)
345   "Encrypt the current buffer using a symmetric, rather than key-pair, cipher.
346
347 If optional arguments START and END are specified, only encrypt within
348 the region.
349
350 If optional PASSPHRASE is not specified, it will be obtained from the
351 passphrase cache or user."
352   (interactive)
353   (let* ((start (or start (point-min)))
354          (end (or end (point-max)))
355          (status (pgg-encrypt-symmetric-region start end passphrase)))
356     (when (interactive-p)
357       (pgg-display-output-buffer start end status))
358     status))
359
360 ;;;###autoload
361 (defun pgg-encrypt (rcpts &optional sign start end passphrase)
362   "Encrypt the current buffer for RCPTS.
363
364 If optional argument SIGN is non-nil, do a combined sign and encrypt.
365
366 If optional arguments START and END are specified, only encrypt within
367 the region.
368
369 If optional PASSPHRASE is not specified, it will be obtained from the
370 passphrase cache or user."
371   (interactive (list (split-string (read-string "Recipients: ") "[ \t,]+")))
372   (let* ((start (or start (point-min)))
373          (end (or end (point-max)))
374          (status (pgg-encrypt-region start end rcpts sign passphrase)))
375     (when (interactive-p)
376       (pgg-display-output-buffer start end status))
377     status))
378
379 ;;;###autoload
380 (defun pgg-decrypt-region (start end &optional passphrase)
381   "Decrypt the current region between START and END.
382
383 If optional PASSPHRASE is not specified, it will be obtained from the
384 passphrase cache or user."
385   (interactive "r")
386   (let* ((buf (current-buffer))
387          (status
388           (pgg-save-coding-system start end
389             (pgg-invoke "decrypt-region" (or pgg-scheme pgg-default-scheme)
390                         (point-min) (point-max) passphrase))))
391     (when (interactive-p)
392       (pgg-display-output-buffer start end status))
393     status))
394
395 ;;;###autoload
396 (defun pgg-decrypt (&optional start end passphrase)
397   "Decrypt the current buffer.
398
399 If optional arguments START and END are specified, only decrypt within
400 the region.
401
402 If optional PASSPHRASE is not specified, it will be obtained from the
403 passphrase cache or user."
404   (interactive "")
405   (let* ((start (or start (point-min)))
406          (end (or end (point-max)))
407          (status (pgg-decrypt-region start end passphrase)))
408     (when (interactive-p)
409       (pgg-display-output-buffer start end status))
410     status))
411
412 ;;;###autoload
413 (defun pgg-sign-region (start end &optional cleartext passphrase)
414   "Make the signature from text between START and END.
415
416 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
417 a detached signature.
418
419 If this function is called interactively, CLEARTEXT is enabled
420 and the output is displayed.
421
422 If optional PASSPHRASE is not specified, it will be obtained from the
423 passphrase cache or user."
424   (interactive "r")
425   (let ((status (pgg-save-coding-system start end
426                   (pgg-invoke "sign-region" (or pgg-scheme pgg-default-scheme)
427                               (point-min) (point-max)
428                               (or (interactive-p) cleartext)
429                               passphrase))))
430     (when (interactive-p)
431       (pgg-display-output-buffer start end status))
432     status))
433
434 ;;;###autoload
435 (defun pgg-sign (&optional cleartext start end passphrase)
436   "Sign the current buffer.
437
438 If the optional argument CLEARTEXT is non-nil, it does not create a
439 detached signature.
440
441 If optional arguments START and END are specified, only sign data
442 within the region.
443
444 If this function is called interactively, CLEARTEXT is enabled
445 and the output is displayed.
446
447 If optional PASSPHRASE is not specified, it will be obtained from the
448 passphrase cache or user."
449   (interactive "")
450   (let* ((start (or start (point-min)))
451          (end (or end (point-max)))
452          (status (pgg-sign-region start end
453                                   (or (interactive-p) cleartext)
454                                   passphrase)))
455     (when (interactive-p)
456       (pgg-display-output-buffer start end status))
457     status))
458
459 ;;;###autoload
460 (defun pgg-verify-region (start end &optional signature fetch)
461   "Verify the current region between START and END.
462 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
463 the detached signature of the current region.
464
465 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
466 signer's public key from `pgg-default-keyserver-address'."
467   (interactive "r")
468   (let* ((packet
469           (if (null signature) nil
470             (with-temp-buffer
471               (buffer-disable-undo)
472               (if (fboundp 'set-buffer-multibyte)
473                   (set-buffer-multibyte nil))
474               (insert-file-contents signature)
475               (cdr (assq 2 (pgg-decode-armor-region
476                             (point-min)(point-max)))))))
477          (key (cdr (assq 'key-identifier packet)))
478          status keyserver)
479     (and (stringp key)
480          pgg-query-keyserver
481          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
482          (null (pgg-lookup-key key))
483          (or fetch (interactive-p))
484          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
485          (setq keyserver
486                (or (cdr (assq 'preferred-key-server packet))
487                    pgg-default-keyserver-address))
488          (pgg-fetch-key keyserver key))
489     (setq status
490           (pgg-save-coding-system start end
491             (pgg-invoke "verify-region" (or pgg-scheme pgg-default-scheme)
492                         (point-min) (point-max) signature)))
493     (when (interactive-p)
494       (let ((temp-buffer-show-function
495              (function pgg-temp-buffer-show-function)))
496         (with-output-to-temp-buffer pgg-echo-buffer
497           (set-buffer standard-output)
498           (insert-buffer-substring (if status pgg-output-buffer
499                                      pgg-errors-buffer)))))
500     status))
501
502 ;;;###autoload
503 (defun pgg-verify (&optional signature fetch start end)
504   "Verify the current buffer.
505 If the optional argument SIGNATURE is non-nil, it is treated as
506 the detached signature of the current region.
507 If the optional argument FETCH is non-nil, we attempt to fetch the
508 signer's public key from `pgg-default-keyserver-address'.
509 If optional arguments START and END are specified, only verify data
510 within the region."
511   (interactive "")
512   (let* ((start (or start (point-min)))
513          (end (or end (point-max)))
514          (status (pgg-verify-region start end signature fetch)))
515     (when (interactive-p)
516       (let ((temp-buffer-show-function
517              (function pgg-temp-buffer-show-function)))
518         (with-output-to-temp-buffer pgg-echo-buffer
519           (set-buffer standard-output)
520           (insert-buffer-substring (if status pgg-output-buffer
521                                      pgg-errors-buffer)))))
522     status))
523
524 ;;;###autoload
525 (defun pgg-insert-key ()
526   "Insert the ASCII armored public key."
527   (interactive)
528   (pgg-invoke "insert-key" (or pgg-scheme pgg-default-scheme)))
529
530 ;;;###autoload
531 (defun pgg-snarf-keys-region (start end)
532   "Import public keys in the current region between START and END."
533   (interactive "r")
534   (pgg-save-coding-system start end
535     (pgg-invoke "snarf-keys-region" (or pgg-scheme pgg-default-scheme)
536                 start end)))
537
538 ;;;###autoload
539 (defun pgg-snarf-keys ()
540   "Import public keys in the current buffer."
541   (interactive "")
542   (pgg-snarf-keys-region (point-min) (point-max)))
543
544 (defun pgg-lookup-key (string &optional type)
545   (pgg-invoke "lookup-key" (or pgg-scheme pgg-default-scheme) string type))
546
547 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
548
549 (defun pgg-insert-url-with-w3 (url)
550   (ignore-errors
551     (require 'url)
552     (let (buffer-file-name)
553       (url-insert-file-contents url))))
554
555 (defvar pgg-insert-url-extra-arguments nil)
556 (defvar pgg-insert-url-program nil)
557
558 (defun pgg-insert-url-with-program (url)
559   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
560         process)
561     (insert
562      (with-temp-buffer
563        (setq process
564              (apply #'start-process " *PGG url*" (current-buffer)
565                     pgg-insert-url-program (nconc args (list url))))
566        (set-process-sentinel process #'ignore)
567        (while (eq 'run (process-status process))
568          (accept-process-output process 5))
569        (delete-process process)
570        (if (and process (eq 'run (process-status process)))
571            (interrupt-process process))
572        (buffer-string)))))
573
574 (defun pgg-fetch-key (keyserver key)
575   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
576   (with-current-buffer (get-buffer-create pgg-output-buffer)
577     (buffer-disable-undo)
578     (erase-buffer)
579     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
580                      (substring keyserver 0 (1- (match-end 0))))))
581       (save-excursion
582         (funcall pgg-insert-url-function
583                  (if proto keyserver
584                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
585                            keyserver key))))
586       (when (re-search-forward "^-+BEGIN" nil 'last)
587         (delete-region (point-min) (match-beginning 0))
588         (when (re-search-forward "^-+END" nil t)
589           (delete-region (progn (end-of-line) (point))
590                          (point-max)))
591         (insert "\n")
592         (with-temp-buffer
593           (insert-buffer-substring pgg-output-buffer)
594           (pgg-snarf-keys-region (point-min)(point-max)))))))
595
596
597 (provide 'pgg)
598
599 ;;; arch-tag: 9cc705dd-1e6a-4c90-8dce-c3561f9a2cf4
600 ;;; pgg.el ends here