366d9b5d95eead6a268003fcf448f0b9083ad2f2
[gnus] / lisp / pgg-gpg.el
1 ;;; pgg-gpg.el --- GnuPG support for PGG.
2
3 ;; Copyright (C) 1999, 2000, 2003 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 GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU 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 (eval-when-compile
29   (require 'cl)                         ; for gpg macros
30   (require 'pgg))
31
32 (defgroup pgg-gpg ()
33   "GnuPG interface"
34   :group 'pgg)
35
36 (defcustom pgg-gpg-program "gpg" 
37   "The GnuPG executable."
38   :group 'pgg-gpg
39   :type 'string)
40
41 (defcustom pgg-gpg-extra-args nil
42   "Extra arguments for every GnuPG invocation."
43   :group 'pgg-gpg
44   :type '(choice
45           (const :tag "None" nil)
46           (string :tag "Arguments")))
47
48 (defvar pgg-gpg-user-id nil
49   "GnuPG ID of your default identity.")
50
51 (defun pgg-gpg-process-region (start end passphrase program args)
52   (let* ((output-file-name (pgg-make-temp-file "pgg-output"))
53          (args
54           `("--status-fd" "2"
55             ,@(if passphrase '("--passphrase-fd" "0"))
56             "--yes" ; overwrite
57             "--output" ,output-file-name
58             ,@pgg-gpg-extra-args ,@args))
59          (output-buffer pgg-output-buffer)
60          (errors-buffer pgg-errors-buffer)
61          (orig-mode (default-file-modes))
62          (process-connection-type nil)
63          exit-status)
64     (with-current-buffer (get-buffer-create errors-buffer)
65       (buffer-disable-undo)
66       (erase-buffer))
67     (unwind-protect
68         (progn
69           (set-default-file-modes 448)
70           (let ((coding-system-for-write 'binary)
71                 (input (buffer-substring-no-properties start end))
72                 (default-enable-multibyte-characters nil))
73             (with-temp-buffer
74               (when passphrase
75                 (insert passphrase "\n"))
76               (insert input)
77               (setq exit-status
78                     (apply #'call-process-region (point-min) (point-max) program
79                            nil errors-buffer nil args))))
80           (with-current-buffer (get-buffer-create output-buffer)
81             (buffer-disable-undo)
82             (erase-buffer)
83             (if (file-exists-p output-file-name)
84                 (let ((coding-system-for-read 'raw-text-dos))
85                   (insert-file-contents output-file-name)))
86             (set-buffer errors-buffer)
87             (if (not (equal exit-status 0))
88                 (insert (format "\n%s exited abnormally: '%s'\n"
89                                 program exit-status)))))
90       (if (file-exists-p output-file-name)
91           (delete-file output-file-name))
92       (set-default-file-modes orig-mode))))
93
94 (defun pgg-gpg-possibly-cache-passphrase (passphrase)
95   (if (and pgg-cache-passphrase
96            (progn
97              (goto-char (point-min))
98              (re-search-forward "^\\[GNUPG:] GOOD_PASSPHRASE\\>" nil t)))
99       (pgg-add-passphrase-cache
100        (progn
101          (goto-char (point-min))
102          (if (re-search-forward
103               "^\\[GNUPG:] NEED_PASSPHRASE \\w+ ?\\w*" nil t)
104              (substring (match-string 0) -8)))
105        passphrase)))
106
107 (defun pgg-gpg-lookup-key (string &optional type)
108   "Search keys associated with STRING."
109   (let ((args (list "--with-colons" "--no-greeting" "--batch"
110                     (if type "--list-secret-keys" "--list-keys")
111                     string)))
112     (with-temp-buffer
113       (apply #'call-process pgg-gpg-program nil t nil args)
114       (goto-char (point-min))
115       (if (re-search-forward "^\\(sec\\|pub\\):"  nil t)
116           (substring
117            (nth 3 (split-string
118                    (buffer-substring (match-end 0)
119                                      (progn (end-of-line)(point)))
120                    ":")) 8)))))
121
122 (defun pgg-gpg-encrypt-region (start end recipients &optional sign)
123   "Encrypt the current region between START and END.
124 If optional argument SIGN is non-nil, do a combined sign and encrypt."
125   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
126          (passphrase
127           (when sign
128             (pgg-read-passphrase
129              (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
130              (pgg-gpg-lookup-key pgg-gpg-user-id 'encrypt))))
131          (args
132           (append
133            (list "--batch" "--armor" "--always-trust" "--encrypt")
134            (if sign (list "--sign" "--local-user" pgg-gpg-user-id))
135            (if recipients
136                (apply #'nconc
137                       (mapcar (lambda (rcpt)
138                                 (list "--remote-user" rcpt))
139                               (append recipients
140                                       (if pgg-encrypt-for-me
141                                           (list pgg-gpg-user-id)))))))))
142     (pgg-as-lbt start end 'CRLF
143       (pgg-gpg-process-region start end passphrase pgg-gpg-program args))
144     (when sign
145       (with-current-buffer pgg-errors-buffer
146         (pgg-gpg-possibly-cache-passphrase passphrase)))
147     (pgg-process-when-success)))
148
149 (defun pgg-gpg-decrypt-region (start end)
150   "Decrypt the current region between START and END."
151   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
152          (passphrase
153           (pgg-read-passphrase
154            (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
155            (pgg-gpg-lookup-key pgg-gpg-user-id 'encrypt)))
156          (args '("--batch" "--decrypt")))
157     (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
158     (with-current-buffer pgg-errors-buffer
159       (pgg-gpg-possibly-cache-passphrase passphrase)
160       (goto-char (point-min))
161       (re-search-forward "^\\[GNUPG:] DECRYPTION_OKAY\\>" nil t))))
162
163 (defun pgg-gpg-sign-region (start end &optional cleartext)
164   "Make detached signature from text between START and END."
165   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
166          (passphrase
167           (pgg-read-passphrase
168            (format "GnuPG passphrase for %s: " pgg-gpg-user-id)
169            (pgg-gpg-lookup-key pgg-gpg-user-id 'sign)))
170          (args
171           (list (if cleartext "--clearsign" "--detach-sign")
172                 "--armor" "--batch" "--verbose"
173                 "--local-user" pgg-gpg-user-id))
174          (inhibit-read-only t)
175          buffer-read-only)
176     (pgg-as-lbt start end 'CRLF
177       (pgg-gpg-process-region start end passphrase pgg-gpg-program args))
178     (with-current-buffer pgg-errors-buffer
179       (pgg-gpg-possibly-cache-passphrase passphrase))
180     (pgg-process-when-success)))
181
182 (defun pgg-gpg-verify-region (start end &optional signature)
183   "Verify region between START and END as the detached signature SIGNATURE."
184   (let ((args '("--batch" "--verify")))
185     (when (stringp signature)
186       (setq args (append args (list signature))))
187     (setq args (append args '("-")))
188     (pgg-gpg-process-region start end nil pgg-gpg-program args)
189     (with-current-buffer pgg-errors-buffer
190       (goto-char (point-min))
191       (while (re-search-forward "^gpg: \\(.*\\)\n" nil t)
192         (with-current-buffer pgg-output-buffer
193           (insert-buffer-substring pgg-errors-buffer
194                                    (match-beginning 1) (match-end 0)))
195         (delete-region (match-beginning 0) (match-end 0)))
196       (goto-char (point-min))
197       (re-search-forward "^\\[GNUPG:] GOODSIG\\>" nil t))))
198
199 (defun pgg-gpg-insert-key ()
200   "Insert public key at point."
201   (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
202          (args (list "--batch" "--export" "--armor"
203                      pgg-gpg-user-id)))
204     (pgg-gpg-process-region (point)(point) nil pgg-gpg-program args)
205     (insert-buffer-substring pgg-output-buffer)))
206
207 (defun pgg-gpg-snarf-keys-region (start end)
208   "Add all public keys in region between START and END to the keyring."
209   (let ((args '("--import" "--batch" "-")) status)
210     (pgg-gpg-process-region start end nil pgg-gpg-program args)
211     (set-buffer pgg-errors-buffer)
212     (goto-char (point-min))
213     (when (re-search-forward "^\\[GNUPG:] IMPORT_RES\\>" nil t)
214       (setq status (buffer-substring (match-end 0)
215                                      (progn (end-of-line)(point)))
216             status (vconcat (mapcar #'string-to-int (split-string status))))
217       (erase-buffer)
218       (insert (format "Imported %d key(s).
219 \tArmor contains %d key(s) [%d bad, %d old].\n"
220                       (+ (aref status 2)
221                          (aref status 10))
222                       (aref status 0)
223                       (aref status 1)
224                       (+ (aref status 4)
225                          (aref status 11)))
226               (if (zerop (aref status 9))
227                   ""
228                 "\tSecret keys are imported.\n")))
229     (append-to-buffer pgg-output-buffer (point-min)(point-max))
230     (pgg-process-when-success)))
231
232 (provide 'pgg-gpg)
233
234 ;;; pgg-gpg.el ends here