Removed gnus-move.el and pointers to it, since it doesn't really work.
[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.