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