1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2011 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This is the auth-source.el package. It lets users tell Gnus how to
26 ;; authenticate in a single place. Simplicity is the goal. Instead
27 ;; of providing 5000 options, we'll stick to simple, easy to
28 ;; understand options.
30 ;; See the auth.info Info documentation for details.
34 ;; - never decode the backend file unless it's necessary
35 ;; - a more generic way to match backends and search backend contents
36 ;; - absorb netrc.el and simplify it
37 ;; - protect passwords better
38 ;; - allow creating and changing netrc lines (not files) e.g. change a password
42 (require 'password-cache)
47 (eval-when-compile (require 'cl))
49 (or (ignore-errors (require 'eieio))
50 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
52 (let ((load-path (cons (expand-file-name
53 "gnus-fallback-lib/eieio"
54 (file-name-directory (locate-library "gnus")))
58 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
60 (autoload 'secrets-create-item "secrets")
61 (autoload 'secrets-delete-item "secrets")
62 (autoload 'secrets-get-alias "secrets")
63 (autoload 'secrets-get-attributes "secrets")
64 (autoload 'secrets-get-secret "secrets")
65 (autoload 'secrets-list-collections "secrets")
66 (autoload 'secrets-search-items "secrets")
68 (autoload 'rfc2104-hash "rfc2104")
70 (autoload 'plstore-open "plstore")
71 (autoload 'plstore-find "plstore")
72 (autoload 'plstore-put "plstore")
73 (autoload 'plstore-save "plstore")
74 (autoload 'plstore-get-file "plstore")
76 (autoload 'epa-passphrase-callback-function "epa")
78 (autoload 'epg-context-operation "epg")
79 (autoload 'epg-make-context "epg")
80 (autoload 'epg-context-set-passphrase-callback "epg")
81 (autoload 'epg-decrypt-string "epg")
82 (autoload 'epg-context-set-armor "epg")
83 (autoload 'epg-context-set-passphrase-callback "epg")
84 (autoload 'epg-encrypt-string "epg")
86 (defvar secrets-enabled)
88 (defgroup auth-source nil
89 "Authentication sources."
90 :version "23.1" ;; No Gnus
94 (defcustom auth-source-cache-expiry 7200
95 "How many seconds passwords are cached, or nil to disable
96 expiring. Overrides `password-cache-expiry' through a
99 :type '(choice (const :tag "Never" nil)
100 (const :tag "All Day" 86400)
101 (const :tag "2 Hours" 7200)
102 (const :tag "30 Minutes" 1800)
103 (integer :tag "Seconds")))
105 (defclass auth-source-backend ()
106 ((type :initarg :type
110 :documentation "The backend type.")
111 (source :initarg :source
114 :documentation "The backend source.")
119 :documentation "The backend host.")
124 :documentation "The backend user.")
129 :documentation "The backend protocol.")
132 :documentation "The backend arg.")
133 (create-function :initarg :create-function
137 :documentation "The create function.")
138 (search-function :initarg :search-function
142 :documentation "The search function.")))
144 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
145 (pop3 "pop3" "pop" "pop3s" "110" "995")
149 "List of authentication protocols and their names"
152 :version "23.2" ;; No Gnus
153 :type '(repeat :tag "Authentication Protocols"
154 (cons :tag "Protocol Entry"
155 (symbol :tag "Protocol")
157 (string :tag "Name")))))
159 ;;; generate all the protocols in a format Customize can use
160 ;;; TODO: generate on the fly from auth-source-protocols
161 (defconst auth-source-protocols-customize
163 (let ((p (car-safe a)))
165 :tag (upcase (symbol-name p))
167 auth-source-protocols))
169 (defvar auth-source-creation-defaults nil
170 "Defaults for creating token values. Usually let-bound.")
172 (defvar auth-source-creation-prompts nil
173 "Default prompts for token values. Usually let-bound.")
175 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
177 (defcustom auth-source-save-behavior 'ask
178 "If set, auth-source will respect it for save behavior."
180 :version "23.2" ;; No Gnus
182 :tag "auth-source new token save behavior"
183 (const :tag "Always save" t)
184 (const :tag "Never save" nil)
185 (const :tag "Ask" ask)))
187 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") never) (t gpg)))
188 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
190 (defcustom auth-source-netrc-use-gpg-tokens 'never
191 "Set this to tell auth-source when to create GPG password
192 tokens in netrc files. It's either an alist or `never'.
193 Note that if EPA/EPG is not available, this should NOT be used."
195 :version "23.2" ;; No Gnus
197 (const :tag "Always use GPG password tokens" (t gpg))
198 (const :tag "Never use GPG password tokens" never)
199 (repeat :tag "Use a lookup list"
201 (choice :tag "Matcher"
202 (const :tag "Match anything" t)
203 (const :tag "The EPA encrypted file extensions"
204 ,(if (boundp 'epa-file-auto-mode-alist-entry)
206 'epa-file-auto-mode-alist-entry))
208 (regexp :tag "Regular expression"))
209 (choice :tag "What to do"
210 (const :tag "Save GPG-encrypted password tokens" gpg)
211 (const :tag "Don't encrypt tokens" never))))))
213 (defvar auth-source-magic "auth-source-magic ")
215 (defcustom auth-source-do-cache t
216 "Whether auth-source should cache information with `password-cache'."
218 :version "23.2" ;; No Gnus
221 (defcustom auth-source-debug nil
222 "Whether auth-source should log debug messages.
224 If the value is nil, debug messages are not logged.
226 If the value is t, debug messages are logged with `message'. In
227 that case, your authentication data will be in the clear (except
230 If the value is a function, debug messages are logged by calling
231 that function using the same arguments as `message'."
233 :version "23.2" ;; No Gnus
235 :tag "auth-source debugging mode"
236 (const :tag "Log using `message' to the *Messages* buffer" t)
237 (const :tag "Log all trivia with `message' to the *Messages* buffer"
239 (function :tag "Function that takes arguments like `message'")
240 (const :tag "Don't log anything" nil)))
242 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
243 "List of authentication sources.
245 The default will get login and password information from
246 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
247 packages to be encrypted. If that file doesn't exist, it will
248 try the unencrypted version \"~/.authinfo\" and the famous
251 See the auth.info manual for details.
253 Each entry is the authentication type with optional properties.
255 It's best to customize this with `M-x customize-variable' because the choices
256 can get pretty complex."
258 :version "24.1" ;; No Gnus
259 :type `(repeat :tag "Authentication Sources"
261 (string :tag "Just a file")
262 (const :tag "Default Secrets API Collection" 'default)
263 (const :tag "Login Secrets API Collection" "secrets:Login")
264 (const :tag "Temp Secrets API Collection" "secrets:session")
265 (list :tag "Source definition"
266 (const :format "" :value :source)
267 (choice :tag "Authentication backend choice"
268 (string :tag "Authentication Source (file)")
270 :tag "Secret Service API/KWallet/GNOME Keyring"
271 (const :format "" :value :secrets)
272 (choice :tag "Collection to use"
273 (string :tag "Collection name")
274 (const :tag "Default" 'default)
275 (const :tag "Login" "Login")
277 :tag "Temporary" "session"))))
278 (repeat :tag "Extra Parameters" :inline t
279 (choice :tag "Extra parameter"
282 (const :format "" :value :host)
283 (choice :tag "Host (machine) choice"
286 :tag "Regular expression")))
289 (const :format "" :value :port)
293 ,@auth-source-protocols-customize))
294 (list :tag "User" :inline t
295 (const :format "" :value :user)
297 :tag "Personality/Username"
302 (defcustom auth-source-gpg-encrypt-to t
303 "List of recipient keys that `authinfo.gpg' encrypted to.
304 If the value is not a list, symmetric encryption will be used."
306 :version "24.1" ;; No Gnus
307 :type '(choice (const :tag "Symmetric encryption" t)
308 (repeat :tag "Recipient public keys"
309 (string :tag "Recipient public key"))))
311 ;; temp for debugging
312 ;; (unintern 'auth-source-protocols)
313 ;; (unintern 'auth-sources)
314 ;; (customize-variable 'auth-sources)
315 ;; (setq auth-sources nil)
316 ;; (format "%S" auth-sources)
317 ;; (customize-variable 'auth-source-protocols)
318 ;; (setq auth-source-protocols nil)
319 ;; (format "%S" auth-source-protocols)
320 ;; (auth-source-pick nil :host "a" :port 'imap)
321 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
322 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
323 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
324 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
325 ;; (auth-source-protocol-defaults 'imap)
327 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
328 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
329 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
330 (defun auth-source-do-debug (&rest msg)
331 (when auth-source-debug
332 (apply 'auth-source-do-warn msg)))
334 (defun auth-source-do-trivia (&rest msg)
335 (when (or (eq auth-source-debug 'trivia)
336 (functionp auth-source-debug))
337 (apply 'auth-source-do-warn msg)))
339 (defun auth-source-do-warn (&rest msg)
341 ;; set logger to either the function in auth-source-debug or 'message
342 ;; note that it will be 'message if auth-source-debug is nil
343 (if (functionp auth-source-debug)
349 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
350 (defun auth-source-read-char-choice (prompt choices)
351 "Read one of CHOICES by `read-char-choice', or `read-char'.
352 `dropdown-list' support is disabled because it doesn't work reliably.
353 Only one of CHOICES will be returned. The PROMPT is augmented
354 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
356 (let* ((prompt-choices
357 (apply 'concat (loop for c in choices
358 collect (format "%c/" c))))
359 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
360 (full-prompt (concat prompt prompt-choices))
363 (while (not (memq k choices))
365 ((fboundp 'read-char-choice)
366 (read-char-choice full-prompt choices))
367 (t (message "%s" full-prompt)
368 (setq k (read-char))))))
371 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
372 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
373 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
374 ;; (:source (:secrets "session") :host t :port t :user "joe")
375 ;; (:source (:secrets "Login") :host t :port t)
376 ;; (:source "~/.authinfo.gpg" :host t :port t)))
378 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
379 ;; (:source (:secrets "session") :host t :port t :user "joe")
380 ;; (:source (:secrets "Login") :host t :port t)
383 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
385 ;; (auth-source-backend-parse "myfile.gpg")
386 ;; (auth-source-backend-parse 'default)
387 ;; (auth-source-backend-parse "secrets:Login")
389 (defun auth-source-backend-parse (entry)
390 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
391 (auth-source-backend-parse-parameters
394 ;; take 'default and recurse to get it as a Secrets API default collection
395 ;; matching any user, host, and protocol
397 (auth-source-backend-parse '(:source (:secrets default))))
398 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
399 ;; matching any user, host, and protocol
400 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
401 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
402 ;; take just a file name and recurse to get it as a netrc file
403 ;; matching any user, host, and protocol
405 (auth-source-backend-parse `(:source ,entry)))
407 ;; a file name with parameters
408 ((stringp (plist-get entry :source))
409 (if (equal (file-name-extension (plist-get entry :source)) "plist")
411 (plist-get entry :source)
412 :source (plist-get entry :source)
414 :search-function 'auth-source-plstore-search
415 :create-function 'auth-source-plstore-create
416 :arg (plstore-open (plist-get entry :source)))
418 (plist-get entry :source)
419 :source (plist-get entry :source)
421 :search-function 'auth-source-netrc-search
422 :create-function 'auth-source-netrc-create)))
424 ;; the Secrets API. We require the package, in order to have a
425 ;; defined value for `secrets-enabled'.
427 (not (null (plist-get entry :source))) ; the source must not be nil
428 (listp (plist-get entry :source)) ; and it must be a list
429 (require 'secrets nil t) ; and we must load the Secrets API
430 secrets-enabled) ; and that API must be enabled
432 ;; the source is either the :secrets key in ENTRY or
433 ;; if that's missing or nil, it's "session"
434 (let ((source (or (plist-get (plist-get entry :source) :secrets)
437 ;; if the source is a symbol, we look for the alias named so,
438 ;; and if that alias is missing, we use "Login"
439 (when (symbolp source)
440 (setq source (or (secrets-get-alias (symbol-name source))
443 (if (featurep 'secrets)
445 (format "Secrets API (%s)" source)
448 :search-function 'auth-source-secrets-search
449 :create-function 'auth-source-secrets-create)
451 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
453 (format "Ignored Secrets API (%s)" source)
460 "auth-source-backend-parse: invalid backend spec: %S" entry)
466 (defun auth-source-backend-parse-parameters (entry backend)
467 "Fills in the extra auth-source-backend parameters of ENTRY.
468 Using the plist ENTRY, get the :host, :port, and :user search
470 (let ((entry (if (stringp entry)
474 (when (setq val (plist-get entry :host))
475 (oset backend host val))
476 (when (setq val (plist-get entry :user))
477 (oset backend user val))
478 (when (setq val (plist-get entry :port))
479 (oset backend port val)))
482 ;; (mapcar 'auth-source-backend-parse auth-sources)
484 (defun* auth-source-search (&rest spec
485 &key type max host user port secret
486 require create delete
488 "Search or modify authentication backends according to SPEC.
490 This function parses `auth-sources' for matches of the SPEC
491 plist. It can optionally create or update an authentication
492 token if requested. A token is just a standard Emacs property
493 list with a :secret property that can be a function; all the
494 other properties will always hold scalar values.
496 Typically the :secret property, if present, contains a password.
498 Common search keys are :max, :host, :port, and :user. In
499 addition, :create specifies how tokens will be or created.
500 Finally, :type can specify which backend types you want to check.
502 A string value is always matched literally. A symbol is matched
503 as its string value, literally. All the SPEC values can be
504 single values (symbol or string) or lists thereof (in which case
505 any of the search terms matches).
507 :create t means to create a token if possible.
509 A new token will be created if no matching tokens were found.
510 The new token will have only the keys the backend requires. For
511 the netrc backend, for instance, that's the user, host, and
516 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
517 (A . \"default A\"))))
518 (auth-source-search :host \"mine\" :type 'netrc :max 1
519 :P \"pppp\" :Q \"qqqq\"
524 \"Search for any entry matching host 'mine' in backends of type
525 'netrc', maximum one result.
527 Create a new entry if you found none. The netrc backend will
528 automatically require host, user, and port. The host will be
529 'mine'. We prompt for the user with default 'defaultUser' and
530 for the port without a default. We will not prompt for A, Q,
531 or P. The resulting token will only have keys user, host, and
534 :create '(A B C) also means to create a token if possible.
536 The behavior is like :create t but if the list contains any
537 parameter, that parameter will be required in the resulting
538 token. The value for that parameter will be obtained from the
539 search parameters or from user input. If any queries are needed,
540 the alist `auth-source-creation-defaults' will be checked for the
541 default value. If the user, host, or port are missing, the alist
542 `auth-source-creation-prompts' will be used to look up the
543 prompts IN THAT ORDER (so the 'user prompt will be queried first,
544 then 'host, then 'port, and finally 'secret). Each prompt string
545 can use %u, %h, and %p to show the user, host, and port.
549 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
550 (A . \"default A\")))
551 (auth-source-creation-prompts
552 '((password . \"Enter IMAP password for %h:%p: \"))))
553 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
554 :P \"pppp\" :Q \"qqqq\"
559 \"Search for any entry matching host 'nonesuch'
560 or 'twosuch' in backends of type 'netrc', maximum one result.
562 Create a new entry if you found none. The netrc backend will
563 automatically require host, user, and port. The host will be
564 'nonesuch' and Q will be 'qqqq'. We prompt for the password
565 with the shown prompt. We will not prompt for Q. The resulting
566 token will have keys user, host, port, A, B, and Q. It will not
567 have P with any value, even though P is used in the search to
568 find only entries that have P set to 'pppp'.\"
570 When multiple values are specified in the search parameter, the
571 user is prompted for which one. So :host (X Y Z) would ask the
572 user to choose between X, Y, and Z.
574 This creation can fail if the search was not specific enough to
575 create a new token (it's up to the backend to decide that). You
576 should `catch' the backend-specific error as usual. Some
577 backends (netrc, at least) will prompt the user rather than throw
580 :require (A B C) means that only results that contain those
581 tokens will be returned. Thus for instance requiring :secret
582 will ensure that any results will actually have a :secret
585 :delete t means to delete any found entries. nil by default.
586 Use `auth-source-delete' in ELisp code instead of calling
587 `auth-source-search' directly with this parameter.
589 :type (X Y Z) will check only those backend types. 'netrc and
590 'secrets are the only ones supported right now.
592 :max N means to try to return at most N items (defaults to 1).
593 When 0 the function will return just t or nil to indicate if any
594 matches were found. More than N items may be returned, depending
595 on the search and the backend.
597 :host (X Y Z) means to match only hosts X, Y, or Z according to
598 the match rules above. Defaults to t.
600 :user (X Y Z) means to match only users X, Y, or Z according to
601 the match rules above. Defaults to t.
603 :port (P Q R) means to match only protocols P, Q, or R.
606 :K (V1 V2 V3) for any other key K will match values V1, V2, or
607 V3 (note the match rules above).
609 The return value is a list with at most :max tokens. Each token
610 is a plist with keys :backend :host :port :user, plus any other
611 keys provided by the backend (notably :secret). But note the
612 exception for :max 0, which see above.
614 The token can hold a :save-function key. If you call that, the
615 user will be prompted to save the data to the backend. You can't
616 request that this should happen right after creation, because
617 `auth-source-search' has no way of knowing if the token is
618 actually useful. So the caller must arrange to call this function.
620 The token's :secret key can hold a function. In that case you
621 must call it to obtain the actual value."
622 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
624 (ignored-keys '(:require :create :delete :max))
625 (keys (loop for i below (length spec) by 2
626 unless (memq (nth i spec) ignored-keys)
627 collect (nth i spec)))
628 (cached (auth-source-remembered-p spec))
629 ;; note that we may have cached results but found is still nil
630 ;; (there were no results from the search)
631 (found (auth-source-recall spec))
632 filtered-backends accessor-key backend)
634 (if (and cached auth-source-do-cache)
635 (auth-source-do-debug
636 "auth-source-search: found %d CACHED results matching %S"
640 (or (eq t create) (listp create)) t
641 "Invalid auth-source :create parameter (must be t or a list): %s %s")
645 "Invalid auth-source :require parameter (must be a list): %s")
647 (setq filtered-backends (copy-sequence backends))
648 (dolist (backend backends)
650 ;; ignore invalid slots
651 (condition-case signal
652 (unless (eval `(auth-source-search-collection
654 (oref backend ,key)))
655 (setq filtered-backends (delq backend filtered-backends))
657 (invalid-slot-name))))
659 (auth-source-do-trivia
660 "auth-source-search: found %d backends matching %S"
661 (length filtered-backends) spec)
663 ;; (debug spec "filtered" filtered-backends)
664 ;; First go through all the backends without :create, so we can
666 (setq found (auth-source-search-backends filtered-backends
670 ;; create is always nil here
674 (auth-source-do-debug
675 "auth-source-search: found %d results (max %d) matching %S"
676 (length found) max spec)
678 ;; If we didn't find anything, then we allow the backend(s) to
679 ;; create the entries.
682 (setq found (auth-source-search-backends filtered-backends
688 (auth-source-do-debug
689 "auth-source-search: CREATED %d results (max %d) matching %S"
690 (length found) max spec))
692 ;; note we remember the lack of result too, if it's applicable
693 (when auth-source-do-cache
694 (auth-source-remember spec found)))
698 (defun auth-source-search-backends (backends spec max create delete require)
700 (dolist (backend backends)
701 (when (> max (length matches)) ; when we need more matches...
702 (let* ((bmatches (apply
703 (slot-value backend 'search-function)
705 ;; note we're overriding whatever the spec
706 ;; has for :require, :create, and :delete
712 (auth-source-do-trivia
713 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
714 (length bmatches) max
715 (slot-value backend :type)
716 (slot-value backend :source)
718 (setq matches (append matches bmatches))))))
721 ;;; (auth-source-search :max 1)
722 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
723 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
724 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
726 (defun* auth-source-delete (&rest spec
729 "Delete entries from the authentication backends according to SPEC.
730 Calls `auth-source-search' with the :delete property in SPEC set to t.
731 The backend may not actually delete the entries.
733 Returns the deleted entries."
734 (auth-source-search (plist-put spec :delete t)))
736 (defun auth-source-search-collection (collection value)
737 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
738 (when (and (atom collection) (not (eq t collection)))
739 (setq collection (list collection)))
741 ;; (debug :collection collection :value value)
742 (or (eq collection t)
744 (equal collection value)
745 (member value collection)))
747 (defvar auth-source-netrc-cache nil)
749 (defun auth-source-forget-all-cached ()
750 "Forget all cached auth-source data."
752 (loop for sym being the symbols of password-data
753 ;; when the symbol name starts with auth-source-magic
754 when (string-match (concat "^" auth-source-magic)
757 do (password-cache-remove (symbol-name sym)))
758 (setq auth-source-netrc-cache nil))
760 (defun auth-source-remember (spec found)
761 "Remember FOUND search results for SPEC."
762 (let ((password-cache-expiry auth-source-cache-expiry))
764 (concat auth-source-magic (format "%S" spec)) found)))
766 (defun auth-source-recall (spec)
767 "Recall FOUND search results for SPEC."
768 (password-read-from-cache
769 (concat auth-source-magic (format "%S" spec))))
771 (defun auth-source-remembered-p (spec)
772 "Check if SPEC is remembered."
774 (concat auth-source-magic (format "%S" spec))))
776 (defun auth-source-forget (spec)
777 "Forget any cached data matching SPEC exactly.
779 This is the same SPEC you passed to `auth-source-search'.
780 Returns t or nil for forgotten or not found."
781 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
783 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
785 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
786 ;;; (auth-source-remembered-p '(:host "wedd"))
787 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
788 ;;; (auth-source-remembered-p '(:host "xedd"))
789 ;;; (auth-source-remembered-p '(:host "zedd"))
790 ;;; (auth-source-recall '(:host "xedd"))
791 ;;; (auth-source-recall '(:host t))
792 ;;; (auth-source-forget+ :host t)
794 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
795 "Forget any cached data matching SPEC. Returns forgotten count.
797 This is not a full `auth-source-search' spec but works similarly.
798 For instance, \(:host \"myhost\" \"yourhost\") would find all the
799 cached data that was found with a search for those two hosts,
800 while \(:host t) would find all host entries."
803 (loop for sym being the symbols of password-data
804 ;; when the symbol name matches with auth-source-magic
805 when (and (setq sname (symbol-name sym))
806 (string-match (concat "^" auth-source-magic "\\(.+\\)")
808 ;; and the spec matches what was stored in the cache
809 (auth-source-specmatchp spec (read (match-string 1 sname))))
812 (password-cache-remove sname)
816 (defun auth-source-specmatchp (spec stored)
817 (let ((keys (loop for i below (length spec) by 2
818 collect (nth i spec))))
821 (unless (auth-source-search-collection (plist-get stored key)
822 (plist-get spec key))
826 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
827 ;;; (auth-source-pick-first-password :port "imap")
828 (defun auth-source-pick-first-password (&rest spec)
829 "Pick the first secret found from applying SPEC to `auth-source-search'."
830 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
831 (secret (plist-get result :secret)))
833 (if (functionp secret)
837 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
838 (defun auth-source-format-prompt (prompt alist)
839 "Format PROMPT using %x (for any character x) specifiers in ALIST."
841 (let ((c (nth 0 cell))
844 (setq prompt (replace-regexp-in-string (format "%%%c" c)
849 (defun auth-source-ensure-strings (values)
850 (unless (listp values)
851 (setq values (list values)))
852 (mapcar (lambda (value)
858 ;;; Backend specific parsing: netrc/authinfo backend
860 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
861 (defun* auth-source-netrc-parse (&rest
863 &key file max host user port delete require
865 "Parse FILE and return a list of all entries in the file.
866 Note that the MAX parameter is used so we can exit the parse early."
868 ;; We got already parsed contents; just return it.
870 (when (file-exists-p file)
871 (setq port (auth-source-ensure-strings port))
873 (let* ((tokens '("machine" "host" "default" "login" "user"
874 "password" "account" "macdef" "force"
876 (max (or max 5000)) ; sanity check: default to stop at 5K
878 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
879 (cached-mtime (plist-get cached :mtime))
880 (cached-secrets (plist-get cached :secret))
881 alist elem result pair)
883 (if (and (functionp cached-secrets)
885 (nth 5 (file-attributes file))))
887 (auth-source-do-trivia
888 "auth-source-netrc-parse: using CACHED file data for %s"
890 (insert (funcall cached-secrets)))
891 (insert-file-contents file)
892 ;; cache all netrc files (used to be just .gpg files)
893 ;; Store the contents of the file heavily encrypted in memory.
894 ;; (note for the irony-impaired: they are just obfuscated)
895 (aput 'auth-source-netrc-cache file
896 (list :mtime (nth 5 (file-attributes file))
897 :secret (lexical-let ((v (rot13-string
898 (base64-encode-string
900 (lambda () (base64-decode-string
901 (rot13-string v)))))))
902 (goto-char (point-min))
903 ;; Go through the file, line by line.
904 (while (and (not (eobp))
907 (narrow-to-region (point) (point-at-eol))
908 ;; For each line, get the tokens and values.
910 (skip-chars-forward "\t ")
911 ;; Skip lines that begin with a "#".
912 (if (eq (char-after) ?#)
913 (goto-char (point-max))
916 (if (= (following-char) ?\")
917 (read (current-buffer))
919 (point) (progn (skip-chars-forward "^\t ")
922 ((equal elem "macdef")
923 ;; We skip past the macro definition.
925 (while (and (zerop (forward-line 1))
927 (narrow-to-region (point) (point)))
928 ((member elem tokens)
929 ;; Tokens that don't have a following value are ignored,
931 (when (and pair (or (cdr pair)
932 (equal (car pair) "default")))
934 (setq pair (list elem)))
936 ;; Values that haven't got a preceding token are ignored.
940 (setq pair nil)))))))
944 (auth-source-search-collection
947 (aget alist "machine")
950 (auth-source-search-collection
954 (aget alist "account")
957 (auth-source-search-collection
961 (aget alist "protocol")
964 ;; the required list of keys is nil, or
966 ;; every element of require is in the normalized list
967 (let ((normalized (nth 0 (auth-source-netrc-normalize
968 (list alist) file))))
969 (loop for req in require
970 always (plist-get normalized req)))))
972 (push (nreverse alist) result)
973 ;; to delete a line, we just comment it out
975 (goto-char (point-min))
984 (when auth-source-gpg-encrypt-to
985 ;; (see bug#7487) making `epa-file-encrypt-to' local to
986 ;; this buffer lets epa-file skip the key selection query
987 ;; (see the `local-variable-p' check in
988 ;; `epa-file-write-region').
989 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
990 (make-local-variable 'epa-file-encrypt-to))
991 (if (listp auth-source-gpg-encrypt-to)
992 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
994 ;; ask AFTER we've successfully opened the file
995 (when (y-or-n-p (format "Save file %s? (%d deletions)"
997 (write-region (point-min) (point-max) file nil 'silent)
998 (auth-source-do-debug
999 "auth-source-netrc-parse: modified %d lines in %s"
1002 (nreverse result))))))
1004 (defvar auth-source-passphrase-alist nil)
1006 (defun auth-source-passphrase-callback-function (context key-id handback
1007 &optional sym-detail)
1008 "Exactly like `epa-passphrase-callback-function' but takes an
1009 extra SYM-DETAIL parameter which will be printed at the end of
1010 the symmetric passphrase prompt, and assumes symmetric
1013 (format "Passphrase for symmetric encryption%s%s: "
1014 ;; Add the file name to the prompt, if any.
1015 (if (stringp handback)
1016 (format " for %s" handback)
1018 (if (stringp sym-detail)
1021 (eq (epg-context-operation context) 'encrypt)))
1023 (defun auth-source-token-passphrase-callback-function (context key-id file)
1024 (if (eq key-id 'SYM)
1025 (let* ((file (file-truename file))
1026 (entry (assoc file auth-source-passphrase-alist))
1028 ;; return the saved passphrase, calling a function if needed
1029 (or (copy-sequence (if (functionp (cdr entry))
1030 (funcall (cdr entry))
1034 (setq entry (list file))
1035 (push entry auth-source-passphrase-alist))
1036 (setq passphrase (auth-source-passphrase-callback-function context
1040 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1043 (epa-passphrase-callback-function context key-id file)))
1045 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1046 (defun auth-source-epa-extract-gpg-token (secret file)
1047 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1048 FILE is the file from which we obtained this token."
1049 (when (string-match "^gpg:\\(.+\\)" secret)
1050 (setq secret (base64-decode-string (match-string 1 secret))))
1051 (let ((context (epg-make-context 'OpenPGP))
1053 (epg-context-set-passphrase-callback
1055 (cons #'auth-source-token-passphrase-callback-function
1057 (epg-decrypt-string context secret)))
1059 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1060 (defun auth-source-epa-make-gpg-token (secret file)
1061 (let ((context (epg-make-context 'OpenPGP))
1062 (pp-escape-newlines nil)
1064 (epg-context-set-armor context t)
1065 (epg-context-set-passphrase-callback
1067 (cons #'auth-source-token-passphrase-callback-function
1069 (setq cipher (epg-encrypt-string context secret nil))
1072 (base64-encode-region (point-min) (point-max) t)
1073 (concat "gpg:" (buffer-substring-no-properties
1077 (defun auth-source-netrc-normalize (alist filename)
1078 (mapcar (lambda (entry)
1080 (while (setq item (pop entry))
1081 (let ((k (car item))
1084 ;; apply key aliases
1085 (setq k (cond ((member k '("machine")) "host")
1086 ((member k '("login" "account")) "user")
1087 ((member k '("protocol")) "port")
1088 ((member k '("password")) "secret")
1091 ;; send back the secret in a function (lexical binding)
1092 (when (equal k "secret")
1093 (setq v (lexical-let ((lexv v)
1094 (token-decoder nil))
1095 (when (string-match "^gpg:" lexv)
1096 ;; it's a GPG token: create a token decoder
1097 ;; which unsets itself once
1101 (auth-source-epa-extract-gpg-token
1104 (setq token-decoder nil)))))
1107 (setq lexv (funcall token-decoder lexv)))
1109 (setq ret (plist-put ret
1110 (intern (concat ":" k))
1115 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1116 ;;; (funcall secret)
1118 (defun* auth-source-netrc-search (&rest
1120 &key backend require create delete
1121 type max host user port
1123 "Given a property list SPEC, return search matches from the :backend.
1124 See `auth-source-search' for details on SPEC."
1125 ;; just in case, check that the type is correct (null or same as the backend)
1126 (assert (or (null type) (eq type (oref backend type)))
1127 t "Invalid netrc search: %s %s")
1129 (let ((results (auth-source-netrc-normalize
1130 (auth-source-netrc-parse
1134 :file (oref backend source)
1138 (oref backend source))))
1140 ;; if we need to create an entry AND none were found to match
1144 ;; create based on the spec and record the value
1146 ;; if the user did not want to create the entry
1147 ;; in the file, it will be returned
1148 (apply (slot-value backend 'create-function) spec)
1149 ;; if not, we do the search again without :create
1150 ;; to get the updated data.
1152 ;; the result will be returned, even if the search fails
1153 (apply 'auth-source-netrc-search
1154 (plist-put spec :create nil)))))
1157 (defun auth-source-netrc-element-or-first (v)
1162 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1163 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1165 (defun* auth-source-netrc-create (&rest spec
1167 secret host user port create
1169 (let* ((base-required '(host user port secret))
1170 ;; we know (because of an assertion in auth-source-search) that the
1171 ;; :create parameter is either t or a list (which includes nil)
1172 (create-extra (if (eq t create) nil create))
1173 (current-data (car (auth-source-search :max 1
1176 (required (append base-required create-extra))
1177 (file (oref backend source))
1179 ;; `valist' is an alist
1181 ;; `artificial' will be returned if no creation is needed
1184 ;; only for base required elements (defined as function parameters):
1185 ;; fill in the valist with whatever data we may have from the search
1186 ;; we complete the first value if it's a list and use the value otherwise
1187 (dolist (br base-required)
1188 (when (symbol-value br)
1189 (let ((br-choice (cond
1190 ;; all-accepting choice (predicate is t)
1191 ((eq t (symbol-value br)) nil)
1192 ;; just the value otherwise
1193 (t (symbol-value br)))))
1195 (aput 'valist br br-choice)))))
1197 ;; for extra required elements, see if the spec includes a value for them
1198 (dolist (er create-extra)
1199 (let ((name (concat ":" (symbol-name er)))
1200 (keys (loop for i below (length spec) by 2
1201 collect (nth i spec))))
1203 (when (equal (symbol-name k) name)
1204 (aput 'valist er (plist-get spec k))))))
1206 ;; for each required element
1207 (dolist (r required)
1208 (let* ((data (aget valist r))
1209 ;; take the first element if the data is a list
1210 (data (or (auth-source-netrc-element-or-first data)
1211 (plist-get current-data
1212 (intern (format ":%s" r) obarray))))
1213 ;; this is the default to be offered
1214 (given-default (aget auth-source-creation-defaults r))
1215 ;; the default supplementals are simple:
1216 ;; for the user, try `given-default' and then (user-login-name);
1217 ;; otherwise take `given-default'
1219 ((and (not given-default) (eq r 'user))
1222 (printable-defaults (list
1225 (auth-source-netrc-element-or-first
1226 (aget valist 'user))
1227 (plist-get artificial :user)
1231 (auth-source-netrc-element-or-first
1232 (aget valist 'host))
1233 (plist-get artificial :host)
1237 (auth-source-netrc-element-or-first
1238 (aget valist 'port))
1239 (plist-get artificial :port)
1241 (prompt (or (aget auth-source-creation-prompts r)
1243 (secret "%p password for %u@%h: ")
1244 (user "%p user name for %h: ")
1245 (host "%p host name for user %u: ")
1246 (port "%p port for %u@%h: "))
1247 (format "Enter %s (%%u@%%h:%%p): " r)))
1248 (prompt (auth-source-format-prompt
1250 `((?u ,(aget printable-defaults 'user))
1251 (?h ,(aget printable-defaults 'host))
1252 (?p ,(aget printable-defaults 'port))))))
1254 ;; Store the data, prompting for the password if needed.
1257 ((and (null data) (eq r 'secret))
1258 ;; Special case prompt for passwords.
1259 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1260 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1261 (let* ((ep (format "Use GPG password tokens in %s?" file))
1264 ((eq auth-source-netrc-use-gpg-tokens 'never)
1266 ((listp auth-source-netrc-use-gpg-tokens)
1267 (let ((check (copy-sequence
1268 auth-source-netrc-use-gpg-tokens))
1271 (setq item (pop check))
1272 (when (or (eq (car item) t)
1273 (string-match (car item) file))
1274 (setq ret (cdr item))
1275 (setq check nil)))))
1277 (plain (read-passwd prompt)))
1278 ;; ask if we don't know what to do (in which case
1279 ;; auth-source-netrc-use-gpg-tokens must be a list)
1281 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1282 ;; TODO: save the defcustom now? or ask?
1283 (setq auth-source-netrc-use-gpg-tokens
1284 (cons `(,file ,gpg-encrypt)
1285 auth-source-netrc-use-gpg-tokens)))
1286 (if (eq gpg-encrypt 'gpg)
1287 (auth-source-epa-make-gpg-token plain file)
1292 (if (string-match ": *\\'" prompt)
1293 (concat (substring prompt 0 (match-beginning 0))
1294 " (default " default "): ")
1295 (concat prompt "(default " default ") "))))
1296 (read-string prompt nil nil default))
1297 (t (or data default))))
1300 (setq artificial (plist-put artificial
1301 (intern (concat ":" (symbol-name r)))
1303 (lexical-let ((data data))
1307 ;; When r is not an empty string...
1308 (when (and (stringp data)
1309 (< 0 (length data)))
1310 ;; this function is not strictly necessary but I think it
1311 ;; makes the code clearer -tzz
1312 (let ((printer (lambda ()
1313 ;; append the key (the symbol name of r)
1314 ;; and the value in r
1317 (if (zerop (length add)) "" " ")
1318 ;; remap auth-source tokens to netrc
1323 (port "port") ; redundant but clearer
1324 (t (symbol-name r)))
1325 (if (string-match "[\" ]" data)
1328 (setq add (concat add (funcall printer)))))))
1333 (lexical-let ((file file)
1335 (lambda () (auth-source-netrc-saver file add))))
1339 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1340 (defun auth-source-netrc-saver (file add)
1341 "Save a line ADD in FILE, prompting along the way.
1342 Respects `auth-source-save-behavior'. Uses
1343 `auth-source-netrc-cache' to avoid prompting more than once."
1344 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1345 (cached (assoc key auth-source-netrc-cache)))
1348 (auth-source-do-trivia
1349 "auth-source-netrc-saver: found previous run for key %s, returning"
1352 (when (file-exists-p file)
1353 (insert-file-contents file))
1354 (when auth-source-gpg-encrypt-to
1355 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1356 ;; this buffer lets epa-file skip the key selection query
1357 ;; (see the `local-variable-p' check in
1358 ;; `epa-file-write-region').
1359 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1360 (make-local-variable 'epa-file-encrypt-to))
1361 (if (listp auth-source-gpg-encrypt-to)
1362 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1363 ;; we want the new data to be found first, so insert at beginning
1364 (goto-char (point-min))
1366 ;; Ask AFTER we've successfully opened the file.
1367 (let ((prompt (format "Save auth info to file %s? " file))
1368 (done (not (eq auth-source-save-behavior 'ask)))
1369 (bufname "*auth-source Help*")
1372 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1376 (with-output-to-temp-buffer bufname
1378 (concat "(y)es, save\n"
1379 "(n)o but use the info\n"
1380 "(N)o and don't ask to save again\n"
1382 "(?) for help as you can see.\n"))
1383 ;; Why? Doesn't with-output-to-temp-buffer already do
1384 ;; the exact same thing anyway? --Stef
1385 (set-buffer standard-output)
1392 (customize-save-variable 'auth-source-save-behavior nil))
1393 (?e (setq add (read-string "Line to add: " add)))
1396 (when (get-buffer-window bufname)
1397 (delete-window (get-buffer-window bufname)))
1399 ;; Make sure the info is not saved.
1400 (when (null auth-source-save-behavior)
1403 (when (< 0 (length add))
1408 (write-region (point-min) (point-max) file nil 'silent)
1409 (auth-source-do-debug
1410 "auth-source-netrc-create: wrote 1 new line to %s"
1412 (message "Saved new authentication information to %s" file)
1414 (aput 'auth-source-netrc-cache key "ran"))))
1416 ;;; Backend specific parsing: Secrets API backend
1418 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1419 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1420 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1421 ;;; (let ((auth-sources '(default))) (auth-source-search))
1422 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1423 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1425 (defun* auth-source-secrets-search (&rest
1427 &key backend create delete label
1428 type max host user port
1430 "Search the Secrets API; spec is like `auth-source'.
1432 The :label key specifies the item's label. It is the only key
1433 that can specify a substring. Any :label value besides a string
1434 will allow any label.
1436 All other search keys must match exactly. If you need substring
1437 matching, do a wider search and narrow it down yourself.
1439 You'll get back all the properties of the token as a plist.
1441 Here's an example that looks for the first item in the 'Login'
1444 \(let ((auth-sources '(\"secrets:Login\")))
1445 (auth-source-search :max 1)
1447 Here's another that looks for the first item in the 'Login'
1448 Secrets collection whose label contains 'gnus':
1450 \(let ((auth-sources '(\"secrets:Login\")))
1451 (auth-source-search :max 1 :label \"gnus\")
1453 And this one looks for the first item in the 'Login' Secrets
1454 collection that's a Google Chrome entry for the git.gnus.org site
1455 authentication tokens:
1457 \(let ((auth-sources '(\"secrets:Login\")))
1458 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1462 (assert (not create) nil
1463 "The Secrets API auth-source backend doesn't support creation yet")
1465 ;; (secrets-delete-item coll elt)
1466 (assert (not delete) nil
1467 "The Secrets API auth-source backend doesn't support deletion yet")
1469 (let* ((coll (oref backend source))
1470 (max (or max 5000)) ; sanity check: default to stop at 5K
1471 (ignored-keys '(:create :delete :max :backend :label))
1472 (search-keys (loop for i below (length spec) by 2
1473 unless (memq (nth i spec) ignored-keys)
1474 collect (nth i spec)))
1475 ;; build a search spec without the ignored keys
1476 ;; if a search key is nil or t (match anything), we skip it
1477 (search-spec (apply 'append (mapcar
1479 (if (or (null (plist-get spec k))
1480 (eq t (plist-get spec k)))
1482 (list k (plist-get spec k))))
1484 ;; needed keys (always including host, login, port, and secret)
1485 (returned-keys (mm-delete-duplicates (append
1486 '(:host :login :port :secret)
1488 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1489 unless (and (stringp label)
1490 (not (string-match label item)))
1492 ;; TODO: respect max in `secrets-search-items', not after the fact
1493 (items (butlast items (- (length items) max)))
1494 ;; convert the item name to a full plist
1495 (items (mapcar (lambda (item)
1497 ;; make an entry for the secret (password) element
1500 (lexical-let ((v (secrets-get-secret coll item)))
1502 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1504 (mapcar (lambda (entry)
1505 (list (car entry) (cdr entry)))
1506 (secrets-get-attributes coll item)))))
1508 ;; ensure each item has each key in `returned-keys'
1509 (items (mapcar (lambda (plist)
1512 (mapcar (lambda (req)
1513 (if (plist-get plist req)
1521 (defun* auth-source-secrets-create (&rest
1523 &key backend type max host user port
1526 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1529 ;;; Backend specific parsing: PLSTORE backend
1531 (defun* auth-source-plstore-search (&rest
1533 &key backend create delete label
1534 type max host user port
1536 "Search the PLSTORE; spec is like `auth-source'."
1539 (assert (not delete) nil
1540 "The PLSTORE auth-source backend doesn't support deletion yet")
1542 (let* ((store (oref backend arg))
1543 (max (or max 5000)) ; sanity check: default to stop at 5K
1544 (ignored-keys '(:create :delete :max :backend :require))
1545 (search-keys (loop for i below (length spec) by 2
1546 unless (memq (nth i spec) ignored-keys)
1547 collect (nth i spec)))
1548 ;; build a search spec without the ignored keys
1549 ;; if a search key is nil or t (match anything), we skip it
1550 (search-spec (apply 'append (mapcar
1552 (let ((v (plist-get spec k)))
1560 ;; needed keys (always including host, login, port, and secret)
1561 (returned-keys (mm-delete-duplicates (append
1562 '(:host :login :port :secret)
1564 (items (plstore-find store search-spec))
1565 (items (butlast items (- (length items) max)))
1566 ;; convert the item to a full plist
1567 (items (mapcar (lambda (item)
1568 (let* ((plist (copy-tree (cdr item)))
1569 (secret (plist-member plist :secret)))
1573 (lexical-let ((v (car (cdr secret))))
1577 ;; ensure each item has each key in `returned-keys'
1578 (items (mapcar (lambda (plist)
1581 (mapcar (lambda (req)
1582 (if (plist-get plist req)
1588 ;; if we need to create an entry AND none were found to match
1592 ;; create based on the spec and record the value
1594 ;; if the user did not want to create the entry
1595 ;; in the file, it will be returned
1596 (apply (slot-value backend 'create-function) spec)
1597 ;; if not, we do the search again without :create
1598 ;; to get the updated data.
1600 ;; the result will be returned, even if the search fails
1601 (apply 'auth-source-plstore-search
1602 (plist-put spec :create nil)))))
1605 (defun* auth-source-plstore-create (&rest spec
1607 secret host user port create
1609 (let* ((base-required '(host user port secret))
1610 (base-secret '(secret))
1611 ;; we know (because of an assertion in auth-source-search) that the
1612 ;; :create parameter is either t or a list (which includes nil)
1613 (create-extra (if (eq t create) nil create))
1614 (current-data (car (auth-source-search :max 1
1617 (required (append base-required create-extra))
1618 (file (oref backend source))
1620 ;; `valist' is an alist
1622 ;; `artificial' will be returned if no creation is needed
1626 ;; only for base required elements (defined as function parameters):
1627 ;; fill in the valist with whatever data we may have from the search
1628 ;; we complete the first value if it's a list and use the value otherwise
1629 (dolist (br base-required)
1630 (when (symbol-value br)
1631 (let ((br-choice (cond
1632 ;; all-accepting choice (predicate is t)
1633 ((eq t (symbol-value br)) nil)
1634 ;; just the value otherwise
1635 (t (symbol-value br)))))
1637 (aput 'valist br br-choice)))))
1639 ;; for extra required elements, see if the spec includes a value for them
1640 (dolist (er create-extra)
1641 (let ((name (concat ":" (symbol-name er)))
1642 (keys (loop for i below (length spec) by 2
1643 collect (nth i spec))))
1645 (when (equal (symbol-name k) name)
1646 (aput 'valist er (plist-get spec k))))))
1648 ;; for each required element
1649 (dolist (r required)
1650 (let* ((data (aget valist r))
1651 ;; take the first element if the data is a list
1652 (data (or (auth-source-netrc-element-or-first data)
1653 (plist-get current-data
1654 (intern (format ":%s" r) obarray))))
1655 ;; this is the default to be offered
1656 (given-default (aget auth-source-creation-defaults r))
1657 ;; the default supplementals are simple:
1658 ;; for the user, try `given-default' and then (user-login-name);
1659 ;; otherwise take `given-default'
1661 ((and (not given-default) (eq r 'user))
1664 (printable-defaults (list
1667 (auth-source-netrc-element-or-first
1668 (aget valist 'user))
1669 (plist-get artificial :user)
1673 (auth-source-netrc-element-or-first
1674 (aget valist 'host))
1675 (plist-get artificial :host)
1679 (auth-source-netrc-element-or-first
1680 (aget valist 'port))
1681 (plist-get artificial :port)
1683 (prompt (or (aget auth-source-creation-prompts r)
1685 (secret "%p password for %u@%h: ")
1686 (user "%p user name for %h: ")
1687 (host "%p host name for user %u: ")
1688 (port "%p port for %u@%h: "))
1689 (format "Enter %s (%%u@%%h:%%p): " r)))
1690 (prompt (auth-source-format-prompt
1692 `((?u ,(aget printable-defaults 'user))
1693 (?h ,(aget printable-defaults 'host))
1694 (?p ,(aget printable-defaults 'port))))))
1696 ;; Store the data, prompting for the password if needed.
1699 ((and (null data) (eq r 'secret))
1700 ;; Special case prompt for passwords.
1701 (read-passwd prompt))
1705 (if (string-match ": *\\'" prompt)
1706 (concat (substring prompt 0 (match-beginning 0))
1707 " (default " default "): ")
1708 (concat prompt "(default " default ") "))))
1709 (read-string prompt nil nil default))
1710 (t (or data default))))
1713 (if (member r base-secret)
1714 (setq secret-artificial
1715 (plist-put secret-artificial
1716 (intern (concat ":" (symbol-name r)))
1718 (setq artificial (plist-put artificial
1719 (intern (concat ":" (symbol-name r)))
1721 (plstore-put (oref backend arg)
1722 (sha1 (format "%s@%s:%s"
1723 (plist-get artificial :user)
1724 (plist-get artificial :host)
1725 (plist-get artificial :port)))
1726 artificial secret-artificial)
1727 (if (y-or-n-p (format "Save auth info to file %s? "
1728 (plstore-get-file (oref backend arg))))
1729 (plstore-save (oref backend arg)))))
1733 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1735 ;; deprecate the old interface
1736 (make-obsolete 'auth-source-user-or-password
1737 'auth-source-search "Emacs 24.1")
1738 (make-obsolete 'auth-source-forget-user-or-password
1739 'auth-source-forget "Emacs 24.1")
1741 (defun auth-source-user-or-password
1742 (mode host port &optional username create-missing delete-existing)
1743 "Find MODE (string or list of strings) matching HOST and PORT.
1745 DEPRECATED in favor of `auth-source-search'!
1747 USERNAME is optional and will be used as \"login\" in a search
1748 across the Secret Service API (see secrets.el) if the resulting
1749 items don't have a username. This means that if you search for
1750 username \"joe\" and it matches an item but the item doesn't have
1751 a :user attribute, the username \"joe\" will be returned.
1753 A non nil DELETE-EXISTING means deleting any matching password
1754 entry in the respective sources. This is useful only when
1755 CREATE-MISSING is non nil as well; the intended use case is to
1756 remove wrong password entries.
1758 If no matching entry is found, and CREATE-MISSING is non nil,
1759 the password will be retrieved interactively, and it will be
1760 stored in the password database which matches best (see
1763 MODE can be \"login\" or \"password\"."
1764 (auth-source-do-debug
1765 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1766 mode host port username)
1768 (let* ((listy (listp mode))
1769 (mode (if listy mode (list mode)))
1771 (format "%s %s:%s %s" mode host port username)
1772 (format "%s %s:%s" mode host port)))
1773 (search (list :host host :port port))
1774 (search (if username (append search (list :user username)) search))
1775 (search (if create-missing
1776 (append search (list :create t))
1778 (search (if delete-existing
1779 (append search (list :delete t))
1781 ;; (found (if (not delete-existing)
1782 ;; (gethash cname auth-source-cache)
1783 ;; (remhash cname auth-source-cache)
1788 (auth-source-do-debug
1789 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1791 ;; don't show the password
1792 (if (and (member "password" mode) t)
1796 found) ; return the found data
1797 ;; else, if not found, search with a max of 1
1798 (let ((choice (nth 0 (apply 'auth-source-search
1799 (append '(:max 1) search)))))
1803 ((equal "password" m)
1804 (push (if (plist-get choice :secret)
1805 (funcall (plist-get choice :secret))
1808 (push (plist-get choice :user) found)))))
1809 (setq found (nreverse found))
1810 (setq found (if listy found (car-safe found)))))
1814 (provide 'auth-source)
1816 ;;; auth-source.el ends here