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