(pgg-encrypt, pgg-decrypt, pgg-sign, pgg-verify)
[gnus] / lisp / pgg.el
1 ;;; pgg.el --- glue for the various PGP implementations.
2
3 ;; Copyright (C) 1999,2000 Free Software Foundation, Inc.
4
5 ;; Author: Daiki Ueno <ueno@unixuser.org>
6 ;; Created: 1999/10/28
7 ;; Keywords: PGP
8
9 ;; This file is part of SEMI (Secure Emacs MIME Interface).
10
11 ;; This program is free software; you can redistribute it and/or
12 ;; modify it under the terms of the GNU General Public License as
13 ;; published by the Free Software Foundation; either version 2, or (at
14 ;; your option) any later version.
15
16 ;; This program is distributed in the hope that it will be useful, but
17 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19 ;; General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26
27 ;;; Commentary:
28 ;; 
29
30 ;;; Code:
31
32 (require 'pgg-def)
33 (require 'pgg-parse)
34
35 (eval-when-compile
36   (ignore-errors
37     (require 'w3)
38     (require 'url)))
39
40 (defvar pgg-temporary-file-directory
41   (cond ((fboundp 'temp-directory) (temp-directory))
42         ((boundp 'temporary-file-directory) temporary-file-directory)
43         ("/tmp/")))
44
45 ;;; @ utility functions
46 ;;;
47
48 (defvar pgg-fetch-key-function (if (fboundp 'url-insert-file-contents)
49                                    (function pgg-fetch-key-with-w3)))
50
51 (defun pgg-invoke (func scheme &rest args)
52   (progn
53     (require (intern (format "pgg-%s" scheme)))
54     (apply 'funcall (intern (format "pgg-%s-%s" scheme func)) args)))
55
56 (put 'pgg-save-coding-system 'lisp-indent-function 2)
57
58 (defmacro pgg-save-coding-system (start end &rest body)
59   `(if (interactive-p)
60        (let ((buffer (current-buffer)))
61          (with-temp-buffer
62            (let (buffer-undo-list)
63              (insert-buffer-substring buffer ,start ,end)
64              (encode-coding-region (point-min)(point-max)
65                                    buffer-file-coding-system)
66              (prog1 (save-excursion ,@body)
67                (push nil buffer-undo-list)
68                (ignore-errors (undo))))))
69      (save-restriction
70        (narrow-to-region ,start ,end)
71        ,@body)))
72
73 (defun pgg-temp-buffer-show-function (buffer)
74   (let ((window (split-window-vertically)))
75     (set-window-buffer window buffer)
76     (shrink-window-if-larger-than-buffer window)))
77
78 (defun pgg-display-output-buffer (start end status)
79   (if status
80       (progn
81         (delete-region start end)
82         (insert-buffer-substring pgg-output-buffer)
83         (decode-coding-region start (point) buffer-file-coding-system))
84     (let ((temp-buffer-show-function
85            (function pgg-temp-buffer-show-function)))
86       (with-output-to-temp-buffer pgg-echo-buffer
87         (set-buffer standard-output)
88         (insert-buffer-substring pgg-errors-buffer)))))
89
90 (defvar pgg-passphrase-cache-expiry 16)
91 (defvar pgg-passphrase-cache (make-vector 7 0))
92
93 (defvar pgg-read-passphrase nil)
94 (defun pgg-read-passphrase (prompt &optional key)
95   (if (not pgg-read-passphrase)
96       (if (functionp 'read-passwd)
97           (setq pgg-read-passphrase 'read-passwd)
98         (if (load "passwd" t)
99             (setq pgg-read-passphrase 'read-passwd)
100           (autoload 'ange-ftp-read-passwd "ange-ftp")
101           (setq pgg-read-passphrase 'ange-ftp-read-passwd))))
102   (or (and pgg-cache-passphrase
103            key (setq key (pgg-truncate-key-identifier key))
104            (symbol-value (intern-soft key pgg-passphrase-cache)))
105       (funcall pgg-read-passphrase prompt)))
106
107 (defun pgg-add-passphrase-cache (key passphrase)
108   (setq key (pgg-truncate-key-identifier key))
109   (set (intern key pgg-passphrase-cache)
110        passphrase)
111   (run-at-time pgg-passphrase-cache-expiry nil
112                #'pgg-remove-passphrase-cache
113                key))
114
115 (defun pgg-remove-passphrase-cache (key)
116   (let ((passphrase (symbol-value (intern-soft key pgg-passphrase-cache))))
117     (when passphrase
118       (fillarray passphrase ?_)
119       (unintern key pgg-passphrase-cache))))
120
121 (defmacro pgg-convert-lbt-region (start end lbt)
122   `(let ((pgg-conversion-end (set-marker (make-marker) ,end)))
123      (goto-char ,start)
124      (case ,lbt
125        (CRLF
126         (while (progn
127                  (end-of-line)
128                  (> (marker-position pgg-conversion-end) (point)))
129           (insert "\r")
130           (forward-line 1)))
131        (LF
132         (while (re-search-forward "\r$" pgg-conversion-end t)
133           (replace-match ""))))))
134
135 (put 'pgg-as-lbt 'lisp-indent-function 3)
136
137 (defmacro pgg-as-lbt (start end lbt &rest body)
138   `(let ((inhibit-read-only t)
139          buffer-read-only
140          buffer-undo-list)
141      (pgg-convert-lbt-region ,start ,end ,lbt)
142      (let ((,end (point)))
143        ,@body)
144      (push nil buffer-undo-list)
145      (ignore-errors (undo))))
146
147 (put 'pgg-process-when-success 'lisp-indent-function 0)
148
149 (defmacro pgg-process-when-success (&rest body)
150   `(with-current-buffer pgg-output-buffer
151      (if (zerop (buffer-size)) nil ,@body t)))
152
153 ;;; @ interface functions
154 ;;;
155
156 ;;;###autoload
157 (defun pgg-encrypt-region (start end rcpts &optional sign)
158   "Encrypt the current region between START and END for RCPTS.
159 If optional argument SIGN is non-nil, do a combined sign and encrypt."
160   (interactive
161    (list (region-beginning)(region-end)
162          (split-string (read-string "Recipients: ") "[ \t,]+")))
163   (let ((status
164          (pgg-save-coding-system start end
165            (pgg-invoke "encrypt-region" (or pgg-scheme pgg-default-scheme)
166                        (point-min) (point-max) rcpts sign))))
167     (when (interactive-p)
168       (pgg-display-output-buffer start end status))
169     status))
170
171 ;;;###autoload
172 (defun pgg-encrypt (rcpts &optional sign start end)
173   "Encrypt the current buffer for RCPTS.
174 If optional argument SIGN is non-nil, do a combined sign and encrypt.
175 If optional arguments START and END are specified, only encrypt within
176 the region."
177   (interactive (list (split-string (read-string "Recipients: ") "[ \t,]+")))
178   (pgg-encrypt-region (or start (point-min)) (or end (point-max)) rcpts sign))
179
180 ;;;###autoload
181 (defun pgg-decrypt-region (start end)
182   "Decrypt the current region between START and END."
183   (interactive "r")
184   (let* ((buf (current-buffer))
185          (packet (cdr (assq 1 (with-temp-buffer
186                                 (insert-buffer buf)
187                                 (pgg-decode-armor-region
188                                  (point-min) (point-max))))))
189          (key (cdr (assq 'key-identifier packet)))
190          (pgg-default-user-id 
191           (if key
192               (concat "0x" (pgg-truncate-key-identifier key))
193             pgg-default-user-id))
194          (status
195           (pgg-save-coding-system start end
196             (pgg-invoke "decrypt-region" (or pgg-scheme pgg-default-scheme)
197                         (point-min) (point-max)))))
198     (when (interactive-p)
199       (pgg-display-output-buffer start end status))
200     status))
201
202 ;;;###autoload
203 (defun pgg-decrypt (&optional start end)
204   "Decrypt the current buffer.
205 If optional arguments START and END are specified, only decrypt within
206 the region."
207   (interactive "")
208   (pgg-decrypt-region (or start (point-min)) (or end (point-max))))
209
210 ;;;###autoload
211 (defun pgg-sign-region (start end &optional cleartext)
212   "Make the signature from text between START and END.
213 If the optional 3rd argument CLEARTEXT is non-nil, it does not create
214 a detached signature."
215   (interactive "r")
216   (let ((status (pgg-save-coding-system start end
217                   (pgg-invoke "sign-region" (or pgg-scheme pgg-default-scheme)
218                               (point-min) (point-max)
219                               (or (interactive-p) cleartext)))))
220     (when (interactive-p)
221       (pgg-display-output-buffer start end status))
222     status))
223
224 ;;;###autoload
225 (defun pgg-sign (&optional cleartext start end)
226   "Sign the current buffer.
227 If the optional argument CLEARTEXT is non-nil, it does not create a
228 detached signature.
229 If optional arguments START and END are specified, only sign data
230 within the region."
231   (interactive "")
232   (pgg-sign-region (or start (point-min)) (or end (point-max)) cleartext))
233   
234 ;;;###autoload
235 (defun pgg-verify-region (start end &optional signature fetch)
236   "Verify the current region between START and END.
237 If the optional 3rd argument SIGNATURE is non-nil, it is treated as
238 the detached signature of the current region.
239
240 If the optional 4th argument FETCH is non-nil, we attempt to fetch the
241 signer's public key from `pgg-default-keyserver-address'."
242   (interactive "r")
243   (let* ((packet
244           (if (null signature) nil
245             (with-temp-buffer
246               (buffer-disable-undo)
247               (if (fboundp 'set-buffer-multibyte)
248                   (set-buffer-multibyte nil))
249               (insert-file-contents signature)
250               (cdr (assq 2 (pgg-decode-armor-region
251                             (point-min)(point-max)))))))
252          (key (cdr (assq 'key-identifier packet)))
253          status keyserver)
254     (and (stringp key)
255          pgg-query-keyserver
256          (setq key (concat "0x" (pgg-truncate-key-identifier key)))
257          (null (pgg-lookup-key key))
258          (or fetch (interactive-p))
259          (y-or-n-p (format "Key %s not found; attempt to fetch? " key))
260          (setq keyserver
261                (or (cdr (assq 'preferred-key-server packet))
262                    pgg-default-keyserver-address))
263          (pgg-fetch-key keyserver key))
264     (setq status 
265           (pgg-save-coding-system start end
266             (pgg-invoke "verify-region" (or pgg-scheme pgg-default-scheme)
267                         (point-min) (point-max) signature)))
268     (when (interactive-p)
269       (let ((temp-buffer-show-function
270              (function pgg-temp-buffer-show-function)))
271         (with-output-to-temp-buffer pgg-echo-buffer
272           (set-buffer standard-output)
273           (insert-buffer-substring (if status pgg-output-buffer
274                                      pgg-errors-buffer)))))
275     status))
276
277 ;;;###autoload
278 (defun pgg-verify (&optional signature fetch start end)
279   "Verify the current buffer.
280 If the optional argument SIGNATURE is non-nil, it is treated as
281 the detached signature of the current region.
282 If the optional argument FETCH is non-nil, we attempt to fetch the
283 signer's public key from `pgg-default-keyserver-address'.
284 If optional arguments START and END are specified, only verify data
285 within the region."
286   (interactive "")
287   (pgg-verify-region (or start (point-min)) (or end (point-max))
288                      signature fetch))
289
290 ;;;###autoload
291 (defun pgg-insert-key ()
292   "Insert the ASCII armored public key."
293   (interactive)
294   (pgg-invoke "insert-key" (or pgg-scheme pgg-default-scheme)))
295
296 ;;;###autoload
297 (defun pgg-snarf-keys-region (start end)
298   "Import public keys in the current region between START and END."
299   (interactive "r")
300   (pgg-save-coding-system start end
301     (pgg-invoke "snarf-keys-region" (or pgg-scheme pgg-default-scheme)
302                 start end)))
303
304 ;;;###autoload
305 (defun pgg-snarf-keys ()
306   "Import public keys in the current buffer."
307   (interactive "")
308   (pgg-snarf-keys-region (or start (point-min)) (or end (point-max))))
309
310 (defun pgg-lookup-key (string &optional type)
311   (pgg-invoke "lookup-key" (or pgg-scheme pgg-default-scheme) string type))
312
313 (defvar pgg-insert-url-function  (function pgg-insert-url-with-w3))
314
315 (defun pgg-insert-url-with-w3 (url)
316   (ignore-errors
317     (require 'w3)
318     (require 'url)
319     (let (buffer-file-name)
320       (url-insert-file-contents url))))
321
322 (defvar pgg-insert-url-extra-arguments nil)
323 (defvar pgg-insert-url-program nil)
324
325 (defun pgg-insert-url-with-program (url)
326   (let ((args (copy-sequence pgg-insert-url-extra-arguments))
327         process)
328     (insert
329      (with-temp-buffer
330        (setq process
331              (apply #'start-process " *PGG url*" (current-buffer)
332                     pgg-insert-url-program (nconc args (list url))))
333        (set-process-sentinel process #'ignore)
334        (while (eq 'run (process-status process))
335          (accept-process-output process 5))
336        (delete-process process)
337        (if (and process (eq 'run (process-status process)))
338            (interrupt-process process))
339        (buffer-string)))))
340
341 (defun pgg-fetch-key (keyserver key)
342   "Attempt to fetch a KEY from KEYSERVER for addition to PGP or GnuPG keyring."
343   (with-current-buffer (get-buffer-create pgg-output-buffer)
344     (buffer-disable-undo)
345     (erase-buffer)
346     (let ((proto (if (string-match "^[a-zA-Z\\+\\.\\\\-]+:" keyserver)
347                      (substring keyserver 0 (1- (match-end 0))))))
348       (save-excursion
349         (funcall pgg-insert-url-function
350                  (if proto keyserver
351                    (format "http://%s:11371/pks/lookup?op=get&search=%s"
352                            keyserver key))))
353       (when (re-search-forward "^-+BEGIN" nil 'last)
354         (delete-region (point-min) (match-beginning 0))
355         (when (re-search-forward "^-+END" nil t)
356           (delete-region (progn (end-of-line) (point))
357                          (point-max)))
358         (insert "\n")
359         (with-temp-buffer
360           (insert-buffer-substring pgg-output-buffer)
361           (pgg-snarf-keys-region (point-min)(point-max)))))))
362
363
364 (provide 'pgg)
365
366 ;;; pgg.el ends here