view lisp/pgg-gpg.el @ 81166:4c7d6994e8d6

(org-export-region-as-html, org-replace-region-by-html) (org-number-to-letters, org-table-fedit-finish) (org-normalize-color, org-table-fedit-ref-right) (org-date-to-gregorian, org-table-fedit-move) (org-table-convert-refs-to-rc, org-calendar-holiday) (org-table-fedit-toggle-ref-type, org-write-agenda) (org-colgroup-info-to-vline-list, org-agenda-todo-previousset) (org-defkey, org-encode-for-stdout) (org-indent-line-function, org-export-as-html-to-buffer) (org-store-agenda-views, org-update-mode-line) (org-find-if, org-delete-all) (org-table-fedit-convert-buffer, org-emphasize) (org-uniquify, org-table-fedit-lisp-indent) (org-table-fedit-scroll, org-get-todo-sequence-head) (org-table-fedit-scroll-down, org-table-fedit-line-down) (org-table-fedit-ref-left, org-agenda-export-csv-mapper) (org-table-fedit-toggle-coordinates, org-dvipng-color) (org-table-fedit-line-up, org-table-fedit-ref-down) (org-table-formula-from-user, org-mode-flyspell-verify) (org-cycle-show-empty-lines, org-ctrl-c-ret) (org-table-formula-to-user, org-diary-to-ical-string) (orgtbl-export, org-table-fedit-post-command) (org-closed-in-range, org-shiftcontrolright) (org-table-convert-refs-to-an, org-table-hline-and-move) (org-table-formula-less-p, org-format-table-ascii) (org-agenda-get-sexps, org-shift-refpart) (org-diary-sexp-entry, org-time-string-to-absolute) (org-table-show-reference, org-letters-to-number) (org-fix-agenda-info, org-table-fedit-ref-up) (org-table-fedit-shift-reference, org-table-fedit-abort) (org-closest-date, org-shiftcontrolleft) (org-at-heading-or-item-p, org-rematch-and-replace) (org-agenda-todo-nextset, org-export-grab-title-from-buffer): New function. (org-table-edit-scroll-down, org-finish-edit-formulas) (org-table-edit-next-field, org-abort-edit-formulas) (org-font-lock-level, org-export-find-first-heading-line) (org-table-edit-line-down, org-table-edit-backward-field) (org-edit-formula-lisp-indent, org-table-edit-move) (org-check-log-option, org-this-word) (org-table-edit-line-up, org-table-edit-formulas-post-command) (org-agenda-file-to-end, org-expand-file-name) (org-fake-empty-table-line, org-table-edit-scroll) (org-toggle-log-option, org-show-reference): Function removed. (org-inhibit-invisibility, org-table-formula-make-cmp-string): New defsubst. (org-unmodified, org-batch-store-agenda-views) (org-batch-agenda-csv): New macro. (org-agenda-export): New customization group. (org-agenda-skip-deadline-if-done, org-agenda-remove-tags) (org-highest-priority, org-agenda-exporter-settings) (org-log-done-with-time, org-replace-disputed-keys) (org-format-latex-header, org-export-table-header-tags) (org-cycle-separator-lines, org-export-table-data-tags) (org-icalendar-include-sexps) (org-empty-line-terminates-plain-lists) (org-log-repeat, org-special-ctrl-a) (org-table-use-standard-references, org-disputed-keys) (org-export-skip-text-before-1st-heading, org-agenda-with-colors) (org-agenda-export-html-style): New option. (org-allow-auto-repeat, org-agenda-remove-tags-when-in-prefix) (org-CUA-compatible): Option removed. (org-agenda-structure, org-sexp-date): New face. (org-todo-keywords-for-agenda, org-not-done-keywords) (org-planning-or-clock-line-re, org-agenda-name) (org-table-colgroup-info, org-todo-sets) (constants-unit-system, org-clock-mode-line-entry) (org-mode-line-timer, org-table-current-begin-pos) (org-todo-keywords-1, org-mode-line-string) (org-table-clean-did-remove-column, org-table-fedit-map) (org-clock-heading, org-table-buffer-is-an) (org-agenda-info, org-done-keywords) (org-done-keywords-for-agenda, org-todo-heads) (org-todo-kwd-alist, org-clock-start-time): New variable. (org-todo-kwd-priority-p, org-edit-formulas-map) (org-repeat-re, org-todo-kwd-max-priority) (org-version, org-done-string) (org-table-clean-did-remove-column-1, org-disputed-keys): Variable removed. (org-table-translate-regexp, org-repeat-re, org-version): New constant. (org-ts-lengths): Constant removed. (org-follow-gnus-link): Don't ask how many articles to read. (org-export-find-first-export-line): Renamed from `org-export-find-first-heading'. Use `org-export-skip-text-before-1st-heading'. (org-table-fedit-post-command): Renamed from `org-table-edit-formulas-post-command'. (org-table-fedit-finish): Renamed from `org-finish-edit-formulas'. (org-table-fedit-abort): Renamed from `org-abort-edit-formulas'. (org-table-fedit-lisp-indent): Renamed from `org-edit-formula-lisp-indent'. (org-table-show-reference): Renamed from `org-show-reference'. (org-table-store-formulas): Use `org-table-formula-less-p'. (org-table-edit-formulas): Position cursor to current field equation. (org-update-checkbox-count, org-hide-archived-subtrees) (org-timestamp-up-day, org-timestamp-down-day) (org-shiftmetaleft, org-shiftmetaright, org-shiftmetaup) (org-shiftmetadown, org-metaleft, org-metaright, org-metaup) (org-metadown, org-shiftup, org-shiftdown, org-shiftright) (org-shiftleft, org-ctrl-c-ctrl-c, org-context): Let `org-on-heading-p' also check for invisible heading. (org-read-date): Match am/pm times. (org-eval-in-calendar): Fix default date in prompt.
author Carsten Dominik <dominik@science.uva.nl>
date Wed, 06 Jun 2007 15:13:27 +0000
parents d6f2673064e7
children 9355f9b7bbff
line wrap: on
line source

;;; pgg-gpg.el --- GnuPG support for PGG.

;; Copyright (C) 1999, 2000, 2002, 2003, 2004,
;;   2005, 2006, 2007 Free Software Foundation, Inc.

;; Author: Daiki Ueno <ueno@unixuser.org>
;; Symmetric encryption and gpg-agent support added by: 
;;   Sascha Wilde <wilde@sha-bang.de>
;; Created: 1999/10/28
;; Keywords: PGP, OpenPGP, GnuPG

;; This file is part of GNU Emacs.

;; GNU Emacs is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING.  If not, write to the
;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;; Boston, MA 02110-1301, USA.

;;; Code:

(eval-when-compile
  (require 'cl)				; for gpg macros
  (require 'pgg))

(defgroup pgg-gpg ()
  "GnuPG interface."
  :group 'pgg)

(defcustom pgg-gpg-program "gpg"
  "The GnuPG executable."
  :group 'pgg-gpg
  :type 'string)

(defcustom pgg-gpg-extra-args nil
  "Extra arguments for every GnuPG invocation."
  :group 'pgg-gpg
  :type '(repeat (string :tag "Argument")))

(defcustom pgg-gpg-recipient-argument "--recipient"
  "GnuPG option to specify recipient."
  :group 'pgg-gpg
  :type '(choice (const :tag "New `--recipient' option" "--recipient")
		 (const :tag "Old `--remote-user' option" "--remote-user")))

(defcustom pgg-gpg-use-agent t
  "Whether to use gnupg agent for key caching."
  :group 'pgg-gpg
  :type 'boolean)

(defvar pgg-gpg-user-id nil
  "GnuPG ID of your default identity.")

(defun pgg-gpg-process-region (start end passphrase program args)
  (let* ((use-agent (and (null passphrase) (pgg-gpg-use-agent-p)))
	 (output-file-name (pgg-make-temp-file "pgg-output"))
	 (args
	  `("--status-fd" "2"
	    ,@(if use-agent '("--use-agent")
		(if passphrase '("--passphrase-fd" "0")))
	    "--yes" ; overwrite
	    "--output" ,output-file-name
	    ,@pgg-gpg-extra-args ,@args))
	 (output-buffer pgg-output-buffer)
	 (errors-buffer pgg-errors-buffer)
	 (orig-mode (default-file-modes))
	 (process-connection-type nil)
	 (inhibit-redisplay t)
	 process status exit-status
	 passphrase-with-newline
	 encoded-passphrase-with-new-line)
    (with-current-buffer (get-buffer-create errors-buffer)
      (buffer-disable-undo)
      (erase-buffer))
    (unwind-protect
	(progn
	  (set-default-file-modes 448)
	  (let ((coding-system-for-write 'binary))
	    (setq process
		  (apply #'start-process "*GnuPG*" errors-buffer
			 program args)))
	  (set-process-sentinel process #'ignore)
	  (when passphrase
	    (setq passphrase-with-newline (concat passphrase "\n"))
	    (if pgg-passphrase-coding-system
		(progn
		  (setq encoded-passphrase-with-new-line
			(encode-coding-string
			 passphrase-with-newline
			 (coding-system-change-eol-conversion
			  pgg-passphrase-coding-system 'unix)))
		  (pgg-clear-string passphrase-with-newline))
	      (setq encoded-passphrase-with-new-line passphrase-with-newline
		    passphrase-with-newline nil))
	    (process-send-string process encoded-passphrase-with-new-line))
	  (process-send-region process start end)
	  (process-send-eof process)
	  (while (eq 'run (process-status process))
	    (accept-process-output process 5))
	  (setq status (process-status process)
		exit-status (process-exit-status process))
	  (delete-process process)
	  (with-current-buffer (get-buffer-create output-buffer)
	    (buffer-disable-undo)
	    (erase-buffer)
	    (if (file-exists-p output-file-name)
		(let ((coding-system-for-read (if pgg-text-mode
						  'raw-text
						'binary)))
		  (insert-file-contents output-file-name)))
	    (set-buffer errors-buffer)
	    (if (memq status '(stop signal))
		(error "%s exited abnormally: '%s'" program exit-status))
	    (if (= 127 exit-status)
		(error "%s could not be found" program))))
      (if passphrase-with-newline
	  (pgg-clear-string passphrase-with-newline))
      (if encoded-passphrase-with-new-line
	  (pgg-clear-string encoded-passphrase-with-new-line))
      (if (and process (eq 'run (process-status process)))
	  (interrupt-process process))
      (if (file-exists-p output-file-name)
	  (delete-file output-file-name))
      (set-default-file-modes orig-mode))))

(defun pgg-gpg-possibly-cache-passphrase (passphrase &optional key notruncate)
  (if (and passphrase
	   pgg-cache-passphrase
	   (progn
	     (goto-char (point-min))
	     (re-search-forward "^\\[GNUPG:] \\(GOOD_PASSPHRASE\\>\\)\\|\\(SIG_CREATED\\)" nil t)))
      (pgg-add-passphrase-to-cache
       (or key
	   (progn
	     (goto-char (point-min))
	     (if (re-search-forward
		  "^\\[GNUPG:] NEED_PASSPHRASE\\(_PIN\\)? \\w+ ?\\w*" nil t)
		 (substring (match-string 0) -8))))
       passphrase
       notruncate)))

(defvar pgg-gpg-all-secret-keys 'unknown)

(defun pgg-gpg-lookup-all-secret-keys ()
  "Return all secret keys present in secret key ring."
  (when (eq pgg-gpg-all-secret-keys 'unknown)
    (setq pgg-gpg-all-secret-keys '())
    (let ((args (list "--with-colons" "--no-greeting" "--batch"
		      "--list-secret-keys")))
      (with-temp-buffer
	(apply #'call-process pgg-gpg-program nil t nil args)
	(goto-char (point-min))
	(while (re-search-forward
		"^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)" nil t)
	  (push (substring (match-string 2) 8)
		pgg-gpg-all-secret-keys)))))
  pgg-gpg-all-secret-keys)

(defun pgg-gpg-lookup-key (string &optional type)
  "Search keys associated with STRING."
  (let ((args (list "--with-colons" "--no-greeting" "--batch"
		    (if type "--list-secret-keys" "--list-keys")
		    string)))
    (with-temp-buffer
      (apply #'call-process pgg-gpg-program nil t nil args)
      (goto-char (point-min))
      (if (re-search-forward "^\\(sec\\|pub\\):[^:]*:[^:]*:[^:]*:\\([^:]*\\)"
			     nil t)
	  (substring (match-string 2) 8)))))

(defun pgg-gpg-lookup-key-owner (string &optional all)
  "Search keys associated with STRING and return owner of identified key.

The value may be just the bare key id, or it may be a combination of the
user name associated with the key and the key id, with the key id enclosed
in \"<...>\" angle brackets.

Optional ALL non-nil means search all keys, including secret keys."
  (let ((args (list "--with-colons" "--no-greeting" "--batch"
		    (if all "--list-secret-keys" "--list-keys")
		    string))
	(key-regexp (concat "^\\(sec\\|pub\\)"
			    ":[^:]*:[^:]*:[^:]*:\\([^:]*\\):[^:]*"
			    ":[^:]*:[^:]*:[^:]*:\\([^:]*\\):")))
    (with-temp-buffer
      (apply #'call-process pgg-gpg-program nil t nil args)
      (goto-char (point-min))
      (if (re-search-forward key-regexp
			     nil t)
	  (match-string 3)))))

(defun pgg-gpg-key-id-from-key-owner (key-owner)
  (cond ((not key-owner) nil)
	;; Extract bare key id from outermost paired angle brackets, if any:
	((string-match "[^<]*<\\(.+\\)>[^>]*" key-owner)
	 (substring key-owner (match-beginning 1)(match-end 1)))
	(key-owner)))

(defun pgg-gpg-encrypt-region (start end recipients &optional sign passphrase)
  "Encrypt the current region between START and END.

If optional argument SIGN is non-nil, do a combined sign and encrypt.

If optional PASSPHRASE is not specified, it will be obtained from the
passphrase cache or user."
  (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
	 (passphrase (or passphrase
			 (when (and sign (not (pgg-gpg-use-agent-p)))
			   (pgg-read-passphrase
			    (format "GnuPG passphrase for %s: "
				    pgg-gpg-user-id)
			    pgg-gpg-user-id))))
	 (args
	  (append
	   (list "--batch" "--armor" "--always-trust" "--encrypt")
	   (if pgg-text-mode (list "--textmode"))
	   (if sign (list "--sign" "--local-user" pgg-gpg-user-id))
	   (if (or recipients pgg-encrypt-for-me)
	       (apply #'nconc
		      (mapcar (lambda (rcpt)
				(list pgg-gpg-recipient-argument rcpt))
			      (append recipients
				      (if pgg-encrypt-for-me
					  (list pgg-gpg-user-id)))))))))
    (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
    (when sign
      (with-current-buffer pgg-errors-buffer
	;; Possibly cache passphrase under, e.g. "jas", for future sign.
	(pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
	;; Possibly cache passphrase under, e.g. B565716F, for future decrypt.
	(pgg-gpg-possibly-cache-passphrase passphrase)))
    (pgg-process-when-success)))

(defun pgg-gpg-encrypt-symmetric-region (start end &optional passphrase)
  "Encrypt the current region between START and END with symmetric cipher.

If optional PASSPHRASE is not specified, it will be obtained from the
passphrase cache or user."
  (let* ((passphrase (or passphrase
			 (when (not (pgg-gpg-use-agent-p))
			   (pgg-read-passphrase
			    "GnuPG passphrase for symmetric encryption: "))))
	 (args
	  (append (list "--batch" "--armor" "--symmetric" )
		  (if pgg-text-mode (list "--textmode")))))
    (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
    (pgg-process-when-success)))

(defun pgg-gpg-decrypt-region (start end &optional passphrase)
  "Decrypt the current region between START and END.

If optional PASSPHRASE is not specified, it will be obtained from the
passphrase cache or user."
  (let* ((current-buffer (current-buffer))
	 (message-keys (with-temp-buffer
			 (insert-buffer-substring current-buffer)
			 (pgg-decode-armor-region (point-min) (point-max))))
	 (secret-keys (pgg-gpg-lookup-all-secret-keys))
	 ;; XXX the user is stuck if they need to use the passphrase for
	 ;;     any but the first secret key for which the message is
	 ;;     encrypted.  ideally, we would incrementally give them a
	 ;;     chance with subsequent keys each time they fail with one.
	 (key (pgg-gpg-select-matching-key message-keys secret-keys))
	 (key-owner (and key (pgg-gpg-lookup-key-owner key t)))
	 (key-id (pgg-gpg-key-id-from-key-owner key-owner))
	 (pgg-gpg-user-id (or key-id key
			      pgg-gpg-user-id pgg-default-user-id))
	 (passphrase (or passphrase
			 (when (not (pgg-gpg-use-agent-p))
			   (pgg-read-passphrase
			    (format (if (pgg-gpg-symmetric-key-p message-keys)
					"Passphrase for symmetric decryption: "
				      "GnuPG passphrase for %s: ")
				    (or key-owner "??"))
			    pgg-gpg-user-id))))
	 (args '("--batch" "--decrypt")))
    (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
    (with-current-buffer pgg-errors-buffer
      (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
      (goto-char (point-min))
      (re-search-forward "^\\[GNUPG:] DECRYPTION_OKAY\\>" nil t))))

;;;###autoload
(defun pgg-gpg-symmetric-key-p (message-keys)
  "True if decoded armor MESSAGE-KEYS has symmetric encryption indicator."
  (let (result)
    (dolist (key message-keys result)
      (when (and (eq (car key) 3)
		 (member '(symmetric-key-algorithm) key))
	(setq result key)))))

(defun pgg-gpg-select-matching-key (message-keys secret-keys)
  "Choose a key from MESSAGE-KEYS that matches one of the keys in SECRET-KEYS."
  (loop for message-key in message-keys
	for message-key-id = (and (equal (car message-key) 1)
				  (cdr (assq 'key-identifier
					     (cdr message-key))))
	for key = (and message-key-id (pgg-lookup-key message-key-id 'encrypt))
	when (and key (member key secret-keys)) return key))

(defun pgg-gpg-sign-region (start end &optional cleartext passphrase)
  "Make detached signature from text between START and END."
  (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
	 (passphrase (or passphrase
			 (when (not (pgg-gpg-use-agent-p))
			   (pgg-read-passphrase
			    (format "GnuPG passphrase for %s: "
				    pgg-gpg-user-id)
			    pgg-gpg-user-id))))
	 (args
	  (append (list (if cleartext "--clearsign" "--detach-sign")
			"--armor" "--batch" "--verbose"
			"--local-user" pgg-gpg-user-id)
		  (if pgg-text-mode (list "--textmode"))))
	 (inhibit-read-only t)
	 buffer-read-only)
    (pgg-gpg-process-region start end passphrase pgg-gpg-program args)
    (with-current-buffer pgg-errors-buffer
      ;; Possibly cache passphrase under, e.g. "jas", for future sign.
      (pgg-gpg-possibly-cache-passphrase passphrase pgg-gpg-user-id)
      ;; Possibly cache passphrase under, e.g. B565716F, for future decrypt.
      (pgg-gpg-possibly-cache-passphrase passphrase))
    (pgg-process-when-success)))

(defun pgg-gpg-verify-region (start end &optional signature)
  "Verify region between START and END as the detached signature SIGNATURE."
  (let ((args '("--batch" "--verify")))
    (when (stringp signature)
      (setq args (append args (list signature))))
    (setq args (append args '("-")))
    (pgg-gpg-process-region start end nil pgg-gpg-program args)
    (with-current-buffer pgg-errors-buffer
      (goto-char (point-min))
      (while (re-search-forward "^gpg: \\(.*\\)\n" nil t)
	(with-current-buffer pgg-output-buffer
	  (insert-buffer-substring pgg-errors-buffer
				   (match-beginning 1) (match-end 0)))
	(delete-region (match-beginning 0) (match-end 0)))
      (goto-char (point-min))
      (re-search-forward "^\\[GNUPG:] GOODSIG\\>" nil t))))

(defun pgg-gpg-insert-key ()
  "Insert public key at point."
  (let* ((pgg-gpg-user-id (or pgg-gpg-user-id pgg-default-user-id))
	 (args (list "--batch" "--export" "--armor"
		     pgg-gpg-user-id)))
    (pgg-gpg-process-region (point)(point) nil pgg-gpg-program args)
    (insert-buffer-substring pgg-output-buffer)))

(defun pgg-gpg-snarf-keys-region (start end)
  "Add all public keys in region between START and END to the keyring."
  (let ((args '("--import" "--batch" "-")) status)
    (pgg-gpg-process-region start end nil pgg-gpg-program args)
    (set-buffer pgg-errors-buffer)
    (goto-char (point-min))
    (when (re-search-forward "^\\[GNUPG:] IMPORT_RES\\>" nil t)
      (setq status (buffer-substring (match-end 0)
				     (progn (end-of-line)(point)))
	    status (vconcat (mapcar #'string-to-number (split-string status))))
      (erase-buffer)
      (insert (format "Imported %d key(s).
\tArmor contains %d key(s) [%d bad, %d old].\n"
		      (+ (aref status 2)
			 (aref status 10))
		      (aref status 0)
		      (aref status 1)
		      (+ (aref status 4)
			 (aref status 11)))
	      (if (zerop (aref status 9))
		  ""
		"\tSecret keys are imported.\n")))
    (append-to-buffer pgg-output-buffer (point-min)(point-max))
    (pgg-process-when-success)))

(defun pgg-gpg-update-agent ()
  "Try to connet to gpg-agent and send UPDATESTARTUPTTY."
  (if (fboundp 'make-network-process)
      (let* ((agent-info (getenv "GPG_AGENT_INFO"))
	     (socket (and agent-info
			  (string-match "^\\([^:]*\\)" agent-info)
			  (match-string 1 agent-info)))
	     (conn (and socket
			(make-network-process :name "gpg-agent-process"
					      :host 'local :family 'local
					      :service socket))))
	(when (and conn (eq (process-status conn) 'open))
	  (process-send-string conn "UPDATESTARTUPTTY\n")
	  (delete-process conn)
	  t))
    ;; We can't check, so assume gpg-agent is up.
    t))

(defun pgg-gpg-use-agent-p ()
  "Return t if `pgg-gpg-use-agent' is t and gpg-agent is available."
  (and pgg-gpg-use-agent (pgg-gpg-update-agent)))

(provide 'pgg-gpg)

;;; arch-tag: 2aa5d5d8-93a0-4865-9312-33e29830e000
;;; pgg-gpg.el ends here