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