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