Merge semi21-D20010129.
[elisp/lemi.git] / mime / pgg-gpg.el
1 ;;; pgg-gpg.el --- GnuPG support for PGG.
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, OpenPGP, GnuPG
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 ;;; Code:
27
28 (require 'mel) ; binary-to-text-funcall
29 (eval-when-compile (require 'pgg))
30
31 (defgroup pgg-gpg ()
32   "GnuPG interface"
33   :group 'pgg)
34
35 (defcustom pgg-gpg-program "gpg" 
36   "The GnuPG executable."
37   :group 'pgg-gpg
38   :type 'string)
39
40 (defcustom pgg-gpg-extra-args nil
41   "Extra arguments for every GnuPG invocation."
42   :group 'pgg-gpg
43   :type 'string)
44
45 (eval-and-compile
46   (luna-define-class pgg-scheme-gpg (pgg-scheme)))
47
48 (defvar pgg-gpg-user-id nil
49   "GnuPG ID of your default identity.")
50
51 (defvar pgg-gpg-messages-coding-system pgg-messages-coding-system
52   "Coding system used when reading from a GnuPG external process.")
53
54 (defvar pgg-scheme-gpg-instance nil)
55
56 ;;;###autoload
57 (defun pgg-make-scheme-gpg ()
58   (or pgg-scheme-gpg-instance
59       (setq pgg-scheme-gpg-instance
60             (luna-make-entity 'pgg-scheme-gpg))))
61
62 (defun pgg-gpg-process-region (start end passphrase program args)
63   (let* ((output-file-name
64           (concat temporary-file-directory (make-temp-name "pgg-output")))
65          (args
66           `("--status-fd" "2"
67             ,@(if passphrase '("--passphrase-fd" "0"))
68             "--output" ,output-file-name
69             ,@pgg-gpg-extra-args ,@args))
70          (output-buffer pgg-output-buffer)
71          (errors-buffer pgg-errors-buffer)
72          (orig-mode (default-file-modes))
73          (process-connection-type nil)
74          process status exit-status)
75     (with-current-buffer (get-buffer-create errors-buffer)
76       (buffer-disable-undo)
77       (erase-buffer))
78     (unwind-protect
79         (progn
80           (set-default-file-modes 448)
81           (setq process
82                 (apply #'binary-to-text-funcall
83                        pgg-gpg-messages-coding-system
84                        #'start-process "*GnuPG*" errors-buffer
85                        program args))
86           (set-process-sentinel process #'ignore)
87           (when passphrase
88             (process-send-string process (concat passphrase "\n")))
89           (process-send-region process start end)
90           (process-send-eof process)
91           (while (eq 'run (process-status process))
92             (accept-process-output process 5))
93           (setq status (process-status process)
94                 exit-status (process-exit-status process))
95           (delete-process process)
96           (with-current-buffer (get-buffer-create output-buffer)
97             (buffer-disable-undo)
98             (erase-buffer)
99             (if (file-exists-p output-file-name)
100                 (let ((coding-system-for-read 'raw-text-dos))
101                   (insert-file-contents output-file-name)))
102             (set-buffer errors-buffer)
103             (if (memq status '(stop signal))
104                 (error "%s exited abnormally: '%s'" program exit-status))
105             (if (= 127 exit-status)
106                 (error "%s could not be found" program))))
107       (if (and process (eq 'run (process-status process)))
108           (interrupt-process process))
109       (if (file-exists-p output-file-name)
110           (delete-file output-file-name))
111       (set-default-file-modes orig-mode))))
112
113 (defun pgg-gpg-possibly-cache-passphrase (passphrase)
114   (if (and pgg-cache-passphrase
115            (progn
116              (goto-char (point-min))
117              (re-search-forward "^\\[GNUPG:] GOOD_PASSPHRASE\\>" nil t)))
118       (pgg-add-passphrase-cache
119        (progn
120          (goto-char (point-min))
121          (if (re-search-forward
122               "^\\[GNUPG:] NEED_PASSPHRASE \\w+ ?\\w*" nil t)
123              (substring (match-string 0) -8)))
124        passphrase)))
125
126 (luna-define-method pgg-scheme-lookup-key ((scheme pgg-scheme-gpg)
127                                            string &optional type)
128   (let ((args (list "--with-colons" "--no-greeting" "--batch"
129                     (if type "--list-secret-keys" "--list-keys")
130                     string)))
131     (with-temp-buffer
132       (apply #'call-process pgg-gpg-program nil t nil args)
133       (goto-char (point-min))
134       (if (re-search-forward "^\\(sec\\|pub\\):"  nil t)
135           (substring
136            (nth 3 (split-string
137                    (buffer-substring (match-end 0)
138                                      (progn (end-of-line)(point)))
139                    ":")) 8)))))
140
141 (luna-define-method pgg-scheme-encrypt-region ((scheme pgg-scheme-gpg)
142                                                start end recipients)
143   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
144          (args
145           `("--batch" "--armor" "--always-trust" "--encrypt"
146             ,@(if recipients
147                   (apply #'nconc
148                          (mapcar (lambda (rcpt)
149                                    (list "--remote-user" rcpt))
150                                  (append recipients
151                                          (if pgg-encrypt-for-me
152                                              (list pgg-gpg-user-id)))))))))
153     (pgg-as-lbt start end 'CRLF
154       (pgg-gpg-process-region start end nil pgg-gpg-program args))
155     (pgg-process-when-success)))
156
157 (luna-define-method pgg-scheme-decrypt-region ((scheme pgg-scheme-gpg)
158                                                start end)
159   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
160          (passphrase
161           (pgg-read-passphrase
162            (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
163            (pgg-scheme-lookup-key scheme pgg-gpg-user-id 'encrypt)))
164          (args '("--batch" "--decrypt")))
165     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
166     (with-current-buffer pgg-errors-buffer
167       (pgg-gpg-possibly-cache-passphrase passphrase)
168       (goto-char (point-min))
169       (re-search-forward "^\\[GNUPG:] DECRYPTION_OKAY\\>" nil t))))
170
171 (luna-define-method pgg-scheme-sign-region ((scheme pgg-scheme-gpg)
172                                             start end &optional cleartext)
173   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
174          (passphrase
175           (pgg-read-passphrase
176            (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
177            (pgg-scheme-lookup-key scheme pgg-gpg-user-id 'sign)))
178          (args
179           (list (if cleartext "--clearsign" "--detach-sign")
180                 "--armor" "--batch" "--verbose"
181                 "--local-user" pgg-gpg-user-id))
182          (inhibit-read-only t)
183          buffer-read-only)
184     (pgg-as-lbt start end 'CRLF
185       (pgg-gpg-process-region start end passphrase pgg-gpg-program args))
186     (with-current-buffer pgg-errors-buffer
187       (pgg-gpg-possibly-cache-passphrase passphrase))
188     (pgg-process-when-success)))
189
190 (luna-define-method pgg-scheme-verify-region ((scheme pgg-scheme-gpg)
191                                               start end &optional signature)
192   (let ((args '("--batch" "--verify")))
193     (when (stringp signature)
194       (setq args (append args (list signature))))
195     (setq args (append args '("-")))
196     (pgg-gpg-process-region start end nil pgg-gpg-program args)
197     (with-current-buffer pgg-errors-buffer
198       (goto-char (point-min))
199       (while (re-search-forward "^gpg: " nil t)
200         (replace-match ""))
201       (goto-char (point-min))
202       (prog1 (re-search-forward "^\\[GNUPG:] GOODSIG\\>" nil t)
203         (goto-char (point-min))
204         (delete-matching-lines "^warning\\|\\[GNUPG:]")
205         (set-buffer pgg-output-buffer)
206         (insert-buffer-substring pgg-errors-buffer)))))
207
208 (luna-define-method pgg-scheme-insert-key ((scheme pgg-scheme-gpg))
209   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
210          (args (list "--batch" "--export" "--armor"
211                      pgg-gpg-user-id)))
212     (pgg-gpg-process-region (point)(point) nil pgg-gpg-program args)
213     (insert-buffer-substring pgg-output-buffer)))
214
215 (luna-define-method pgg-scheme-snarf-keys-region ((scheme pgg-scheme-gpg)
216                                                   start end)
217   (let ((args '("--import" "--batch" "-")) status)
218     (pgg-gpg-process-region start end nil pgg-gpg-program args)
219     (set-buffer pgg-errors-buffer)
220     (goto-char (point-min))
221     (when (re-search-forward "^\\[GNUPG:] IMPORT_RES\\>" nil t)
222       (setq status (buffer-substring (match-end 0)
223                                      (progn (end-of-line)(point)))
224             status (vconcat (mapcar #'string-to-int (split-string status))))
225       (erase-buffer)
226       (insert (format "Imported %d key(s).
227 \tArmor contains %d key(s) [%d bad, %d old].\n"
228                       (+ (aref status 2)
229                          (aref status 10))
230                       (aref status 0)
231                       (aref status 1)
232                       (+ (aref status 4)
233                          (aref status 11)))
234               (if (zerop (aref status 9))
235                   ""
236                 "\tSecret keys are imported.\n")))
237     (append-to-buffer pgg-output-buffer (point-min)(point-max))
238     (pgg-process-when-success)))
239
240 (provide 'pgg-gpg)
241
242 ;;; pgg-gpg.el ends here