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)
49 (eval-when-compile (require 'cl))
51 (or (ignore-errors (require 'eieio))
52 ;; gnus-fallback-lib/ from gnus/lisp/gnus-fallback-lib
54 (let ((load-path (cons (expand-file-name
55 "gnus-fallback-lib/eieio"
56 (file-name-directory (locate-library "gnus")))
60 "eieio not found in `load-path' or gnus-fallback-lib/ directory.")))
62 (autoload 'secrets-create-item "secrets")
63 (autoload 'secrets-delete-item "secrets")
64 (autoload 'secrets-get-alias "secrets")
65 (autoload 'secrets-get-attributes "secrets")
66 (autoload 'secrets-get-secret "secrets")
67 (autoload 'secrets-list-collections "secrets")
68 (autoload 'secrets-search-items "secrets")
70 (autoload 'rfc2104-hash "rfc2104")
72 (autoload 'plstore-open "plstore")
73 (autoload 'plstore-find "plstore")
74 (autoload 'plstore-put "plstore")
75 (autoload 'plstore-save "plstore")
76 (autoload 'plstore-get-file "plstore")
78 (defvar secrets-enabled)
80 (defgroup auth-source nil
81 "Authentication sources."
82 :version "23.1" ;; No Gnus
86 (defcustom auth-source-cache-expiry 7200
87 "How many seconds passwords are cached, or nil to disable
88 expiring. Overrides `password-cache-expiry' through a
91 :type '(choice (const :tag "Never" nil)
92 (const :tag "All Day" 86400)
93 (const :tag "2 Hours" 7200)
94 (const :tag "30 Minutes" 1800)
95 (integer :tag "Seconds")))
97 (defclass auth-source-backend ()
102 :documentation "The backend type.")
103 (source :initarg :source
106 :documentation "The backend source.")
111 :documentation "The backend host.")
116 :documentation "The backend user.")
121 :documentation "The backend protocol.")
124 :documentation "The backend arg.")
125 (create-function :initarg :create-function
129 :documentation "The create function.")
130 (search-function :initarg :search-function
134 :documentation "The search function.")))
136 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
137 (pop3 "pop3" "pop" "pop3s" "110" "995")
141 "List of authentication protocols and their names"
144 :version "23.2" ;; No Gnus
145 :type '(repeat :tag "Authentication Protocols"
146 (cons :tag "Protocol Entry"
147 (symbol :tag "Protocol")
149 (string :tag "Name")))))
151 ;;; generate all the protocols in a format Customize can use
152 ;;; TODO: generate on the fly from auth-source-protocols
153 (defconst auth-source-protocols-customize
155 (let ((p (car-safe a)))
157 :tag (upcase (symbol-name p))
159 auth-source-protocols))
161 (defvar auth-source-creation-defaults nil
162 "Defaults for creating token values. Usually let-bound.")
164 (defvar auth-source-creation-prompts nil
165 "Default prompts for token values. Usually let-bound.")
167 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
169 (defcustom auth-source-save-behavior 'ask
170 "If set, auth-source will respect it for save behavior."
172 :version "23.2" ;; No Gnus
174 :tag "auth-source new token save behavior"
175 (const :tag "Always save" t)
176 (const :tag "Never save" nil)
177 (const :tag "Ask" ask)))
179 ;; 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)))
180 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
182 (defcustom auth-source-netrc-use-gpg-tokens 'never
183 "Set this to tell auth-source when to create GPG password
184 tokens in netrc files. It's either an alist or `never'."
186 :version "23.2" ;; No Gnus
188 (const :tag "Always use GPG password tokens" (t gpg))
189 (const :tag "Never use GPG password tokens" never)
190 (repeat :tag "Use a lookup list"
192 (choice :tag "Matcher"
193 (const :tag "Match anything" t)
194 (const :tag "The EPA encrypted file extensions"
195 ,(if (boundp 'epa-file-auto-mode-alist-entry)
197 'epa-file-auto-mode-alist-entry))
199 (regexp :tag "Regular expression"))
200 (choice :tag "What to do"
201 (const :tag "Save GPG-encrypted password tokens" gpg)
202 (const :tag "Don't encrypt tokens" never))))))
204 (defvar auth-source-magic "auth-source-magic ")
206 (defcustom auth-source-do-cache t
207 "Whether auth-source should cache information with `password-cache'."
209 :version "23.2" ;; No Gnus
212 (defcustom auth-source-debug nil
213 "Whether auth-source should log debug messages.
215 If the value is nil, debug messages are not logged.
217 If the value is t, debug messages are logged with `message'. In
218 that case, your authentication data will be in the clear (except
221 If the value is a function, debug messages are logged by calling
222 that function using the same arguments as `message'."
224 :version "23.2" ;; No Gnus
226 :tag "auth-source debugging mode"
227 (const :tag "Log using `message' to the *Messages* buffer" t)
228 (const :tag "Log all trivia with `message' to the *Messages* buffer"
230 (function :tag "Function that takes arguments like `message'")
231 (const :tag "Don't log anything" nil)))
233 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
234 "List of authentication sources.
236 The default will get login and password information from
237 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
238 packages to be encrypted. If that file doesn't exist, it will
239 try the unencrypted version \"~/.authinfo\" and the famous
242 See the auth.info manual for details.
244 Each entry is the authentication type with optional properties.
246 It's best to customize this with `M-x customize-variable' because the choices
247 can get pretty complex."
249 :version "24.1" ;; No Gnus
250 :type `(repeat :tag "Authentication Sources"
252 (string :tag "Just a file")
253 (const :tag "Default Secrets API Collection" 'default)
254 (const :tag "Login Secrets API Collection" "secrets:Login")
255 (const :tag "Temp Secrets API Collection" "secrets:session")
256 (list :tag "Source definition"
257 (const :format "" :value :source)
258 (choice :tag "Authentication backend choice"
259 (string :tag "Authentication Source (file)")
261 :tag "Secret Service API/KWallet/GNOME Keyring"
262 (const :format "" :value :secrets)
263 (choice :tag "Collection to use"
264 (string :tag "Collection name")
265 (const :tag "Default" 'default)
266 (const :tag "Login" "Login")
268 :tag "Temporary" "session"))))
269 (repeat :tag "Extra Parameters" :inline t
270 (choice :tag "Extra parameter"
273 (const :format "" :value :host)
274 (choice :tag "Host (machine) choice"
277 :tag "Regular expression")))
280 (const :format "" :value :port)
284 ,@auth-source-protocols-customize))
285 (list :tag "User" :inline t
286 (const :format "" :value :user)
288 :tag "Personality/Username"
293 (defcustom auth-source-gpg-encrypt-to t
294 "List of recipient keys that `authinfo.gpg' encrypted to.
295 If the value is not a list, symmetric encryption will be used."
297 :version "24.1" ;; No Gnus
298 :type '(choice (const :tag "Symmetric encryption" t)
299 (repeat :tag "Recipient public keys"
300 (string :tag "Recipient public key"))))
302 ;; temp for debugging
303 ;; (unintern 'auth-source-protocols)
304 ;; (unintern 'auth-sources)
305 ;; (customize-variable 'auth-sources)
306 ;; (setq auth-sources nil)
307 ;; (format "%S" auth-sources)
308 ;; (customize-variable 'auth-source-protocols)
309 ;; (setq auth-source-protocols nil)
310 ;; (format "%S" auth-source-protocols)
311 ;; (auth-source-pick nil :host "a" :port 'imap)
312 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
313 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
314 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
315 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
316 ;; (auth-source-protocol-defaults 'imap)
318 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
319 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
320 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
321 (defun auth-source-do-debug (&rest msg)
322 (when auth-source-debug
323 (apply 'auth-source-do-warn msg)))
325 (defun auth-source-do-trivia (&rest msg)
326 (when (or (eq auth-source-debug 'trivia)
327 (functionp auth-source-debug))
328 (apply 'auth-source-do-warn msg)))
330 (defun auth-source-do-warn (&rest msg)
332 ;; set logger to either the function in auth-source-debug or 'message
333 ;; note that it will be 'message if auth-source-debug is nil
334 (if (functionp auth-source-debug)
340 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
341 (defun auth-source-read-char-choice (prompt choices)
342 "Read one of CHOICES by `read-char-choice', or `read-char'.
343 `dropdown-list' support is disabled because it doesn't work reliably.
344 Only one of CHOICES will be returned. The PROMPT is augmented
345 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
347 (let* ((prompt-choices
348 (apply 'concat (loop for c in choices
349 collect (format "%c/" c))))
350 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
351 (full-prompt (concat prompt prompt-choices))
354 (while (not (memq k choices))
356 ((fboundp 'read-char-choice)
357 (read-char-choice full-prompt choices))
358 (t (message "%s" full-prompt)
359 (setq k (read-char))))))
362 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
363 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
364 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
365 ;; (:source (:secrets "session") :host t :port t :user "joe")
366 ;; (:source (:secrets "Login") :host t :port t)
367 ;; (:source "~/.authinfo.gpg" :host t :port t)))
369 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
370 ;; (:source (:secrets "session") :host t :port t :user "joe")
371 ;; (:source (:secrets "Login") :host t :port t)
374 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
376 ;; (auth-source-backend-parse "myfile.gpg")
377 ;; (auth-source-backend-parse 'default)
378 ;; (auth-source-backend-parse "secrets:Login")
380 (defun auth-source-backend-parse (entry)
381 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
382 (auth-source-backend-parse-parameters
385 ;; take 'default and recurse to get it as a Secrets API default collection
386 ;; matching any user, host, and protocol
388 (auth-source-backend-parse '(:source (:secrets default))))
389 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
390 ;; matching any user, host, and protocol
391 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
392 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
393 ;; take just a file name and recurse to get it as a netrc file
394 ;; matching any user, host, and protocol
396 (auth-source-backend-parse `(:source ,entry)))
398 ;; a file name with parameters
399 ((stringp (plist-get entry :source))
400 (if (equal (file-name-extension (plist-get entry :source)) "plist")
402 (plist-get entry :source)
403 :source (plist-get entry :source)
405 :search-function 'auth-source-plstore-search
406 :create-function 'auth-source-plstore-create
407 :arg (plstore-open (plist-get entry :source)))
409 (plist-get entry :source)
410 :source (plist-get entry :source)
412 :search-function 'auth-source-netrc-search
413 :create-function 'auth-source-netrc-create)))
415 ;; the Secrets API. We require the package, in order to have a
416 ;; defined value for `secrets-enabled'.
418 (not (null (plist-get entry :source))) ; the source must not be nil
419 (listp (plist-get entry :source)) ; and it must be a list
420 (require 'secrets nil t) ; and we must load the Secrets API
421 secrets-enabled) ; and that API must be enabled
423 ;; the source is either the :secrets key in ENTRY or
424 ;; if that's missing or nil, it's "session"
425 (let ((source (or (plist-get (plist-get entry :source) :secrets)
428 ;; if the source is a symbol, we look for the alias named so,
429 ;; and if that alias is missing, we use "Login"
430 (when (symbolp source)
431 (setq source (or (secrets-get-alias (symbol-name source))
434 (if (featurep 'secrets)
436 (format "Secrets API (%s)" source)
439 :search-function 'auth-source-secrets-search
440 :create-function 'auth-source-secrets-create)
442 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
444 (format "Ignored Secrets API (%s)" source)
451 "auth-source-backend-parse: invalid backend spec: %S" entry)
457 (defun auth-source-backend-parse-parameters (entry backend)
458 "Fills in the extra auth-source-backend parameters of ENTRY.
459 Using the plist ENTRY, get the :host, :port, and :user search
461 (let ((entry (if (stringp entry)
465 (when (setq val (plist-get entry :host))
466 (oset backend host val))
467 (when (setq val (plist-get entry :user))
468 (oset backend user val))
469 (when (setq val (plist-get entry :port))
470 (oset backend port val)))
473 ;; (mapcar 'auth-source-backend-parse auth-sources)
475 (defun* auth-source-search (&rest spec
476 &key type max host user port secret
477 require create delete
479 "Search or modify authentication backends according to SPEC.
481 This function parses `auth-sources' for matches of the SPEC
482 plist. It can optionally create or update an authentication
483 token if requested. A token is just a standard Emacs property
484 list with a :secret property that can be a function; all the
485 other properties will always hold scalar values.
487 Typically the :secret property, if present, contains a password.
489 Common search keys are :max, :host, :port, and :user. In
490 addition, :create specifies how tokens will be or created.
491 Finally, :type can specify which backend types you want to check.
493 A string value is always matched literally. A symbol is matched
494 as its string value, literally. All the SPEC values can be
495 single values (symbol or string) or lists thereof (in which case
496 any of the search terms matches).
498 :create t means to create a token if possible.
500 A new token will be created if no matching tokens were found.
501 The new token will have only the keys the backend requires. For
502 the netrc backend, for instance, that's the user, host, and
507 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
508 (A . \"default A\"))))
509 (auth-source-search :host \"mine\" :type 'netrc :max 1
510 :P \"pppp\" :Q \"qqqq\"
515 \"Search for any entry matching host 'mine' in backends of type
516 'netrc', maximum one result.
518 Create a new entry if you found none. The netrc backend will
519 automatically require host, user, and port. The host will be
520 'mine'. We prompt for the user with default 'defaultUser' and
521 for the port without a default. We will not prompt for A, Q,
522 or P. The resulting token will only have keys user, host, and
525 :create '(A B C) also means to create a token if possible.
527 The behavior is like :create t but if the list contains any
528 parameter, that parameter will be required in the resulting
529 token. The value for that parameter will be obtained from the
530 search parameters or from user input. If any queries are needed,
531 the alist `auth-source-creation-defaults' will be checked for the
532 default value. If the user, host, or port are missing, the alist
533 `auth-source-creation-prompts' will be used to look up the
534 prompts IN THAT ORDER (so the 'user prompt will be queried first,
535 then 'host, then 'port, and finally 'secret). Each prompt string
536 can use %u, %h, and %p to show the user, host, and port.
540 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
541 (A . \"default A\")))
542 (auth-source-creation-prompts
543 '((password . \"Enter IMAP password for %h:%p: \"))))
544 (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
545 :P \"pppp\" :Q \"qqqq\"
550 \"Search for any entry matching host 'nonesuch'
551 or 'twosuch' in backends of type 'netrc', maximum one result.
553 Create a new entry if you found none. The netrc backend will
554 automatically require host, user, and port. The host will be
555 'nonesuch' and Q will be 'qqqq'. We prompt for the password
556 with the shown prompt. We will not prompt for Q. The resulting
557 token will have keys user, host, port, A, B, and Q. It will not
558 have P with any value, even though P is used in the search to
559 find only entries that have P set to 'pppp'.\"
561 When multiple values are specified in the search parameter, the
562 user is prompted for which one. So :host (X Y Z) would ask the
563 user to choose between X, Y, and Z.
565 This creation can fail if the search was not specific enough to
566 create a new token (it's up to the backend to decide that). You
567 should `catch' the backend-specific error as usual. Some
568 backends (netrc, at least) will prompt the user rather than throw
571 :require (A B C) means that only results that contain those
572 tokens will be returned. Thus for instance requiring :secret
573 will ensure that any results will actually have a :secret
576 :delete t means to delete any found entries. nil by default.
577 Use `auth-source-delete' in ELisp code instead of calling
578 `auth-source-search' directly with this parameter.
580 :type (X Y Z) will check only those backend types. 'netrc and
581 'secrets are the only ones supported right now.
583 :max N means to try to return at most N items (defaults to 1).
584 When 0 the function will return just t or nil to indicate if any
585 matches were found. More than N items may be returned, depending
586 on the search and the backend.
588 :host (X Y Z) means to match only hosts X, Y, or Z according to
589 the match rules above. Defaults to t.
591 :user (X Y Z) means to match only users X, Y, or Z according to
592 the match rules above. Defaults to t.
594 :port (P Q R) means to match only protocols P, Q, or R.
597 :K (V1 V2 V3) for any other key K will match values V1, V2, or
598 V3 (note the match rules above).
600 The return value is a list with at most :max tokens. Each token
601 is a plist with keys :backend :host :port :user, plus any other
602 keys provided by the backend (notably :secret). But note the
603 exception for :max 0, which see above.
605 The token can hold a :save-function key. If you call that, the
606 user will be prompted to save the data to the backend. You can't
607 request that this should happen right after creation, because
608 `auth-source-search' has no way of knowing if the token is
609 actually useful. So the caller must arrange to call this function.
611 The token's :secret key can hold a function. In that case you
612 must call it to obtain the actual value."
613 (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
615 (ignored-keys '(:require :create :delete :max))
616 (keys (loop for i below (length spec) by 2
617 unless (memq (nth i spec) ignored-keys)
618 collect (nth i spec)))
619 (cached (auth-source-remembered-p spec))
620 ;; note that we may have cached results but found is still nil
621 ;; (there were no results from the search)
622 (found (auth-source-recall spec))
623 filtered-backends accessor-key backend)
625 (if (and cached auth-source-do-cache)
626 (auth-source-do-debug
627 "auth-source-search: found %d CACHED results matching %S"
631 (or (eq t create) (listp create)) t
632 "Invalid auth-source :create parameter (must be t or a list): %s %s")
636 "Invalid auth-source :require parameter (must be a list): %s")
638 (setq filtered-backends (copy-sequence backends))
639 (dolist (backend backends)
641 ;; ignore invalid slots
642 (condition-case signal
643 (unless (eval `(auth-source-search-collection
645 (oref backend ,key)))
646 (setq filtered-backends (delq backend filtered-backends))
648 (invalid-slot-name))))
650 (auth-source-do-trivia
651 "auth-source-search: found %d backends matching %S"
652 (length filtered-backends) spec)
654 ;; (debug spec "filtered" filtered-backends)
655 ;; First go through all the backends without :create, so we can
657 (setq found (auth-source-search-backends filtered-backends
661 ;; create is always nil here
665 (auth-source-do-debug
666 "auth-source-search: found %d results (max %d) matching %S"
667 (length found) max spec)
669 ;; If we didn't find anything, then we allow the backend(s) to
670 ;; create the entries.
673 (setq found (auth-source-search-backends filtered-backends
679 (auth-source-do-debug
680 "auth-source-search: CREATED %d results (max %d) matching %S"
681 (length found) max spec))
683 ;; note we remember the lack of result too, if it's applicable
684 (when auth-source-do-cache
685 (auth-source-remember spec found)))
689 (defun auth-source-search-backends (backends spec max create delete require)
691 (dolist (backend backends)
692 (when (> max (length matches)) ; when we need more matches...
693 (let* ((bmatches (apply
694 (slot-value backend 'search-function)
696 ;; note we're overriding whatever the spec
697 ;; has for :require, :create, and :delete
703 (auth-source-do-trivia
704 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
705 (length bmatches) max
706 (slot-value backend :type)
707 (slot-value backend :source)
709 (setq matches (append matches bmatches))))))
712 ;;; (auth-source-search :max 1)
713 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
714 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
715 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
717 (defun* auth-source-delete (&rest spec
720 "Delete entries from the authentication backends according to SPEC.
721 Calls `auth-source-search' with the :delete property in SPEC set to t.
722 The backend may not actually delete the entries.
724 Returns the deleted entries."
725 (auth-source-search (plist-put spec :delete t)))
727 (defun auth-source-search-collection (collection value)
728 "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
729 (when (and (atom collection) (not (eq t collection)))
730 (setq collection (list collection)))
732 ;; (debug :collection collection :value value)
733 (or (eq collection t)
735 (equal collection value)
736 (member value collection)))
738 (defvar auth-source-netrc-cache nil)
740 (defun auth-source-forget-all-cached ()
741 "Forget all cached auth-source data."
743 (loop for sym being the symbols of password-data
744 ;; when the symbol name starts with auth-source-magic
745 when (string-match (concat "^" auth-source-magic)
748 do (password-cache-remove (symbol-name sym)))
749 (setq auth-source-netrc-cache nil))
751 (defun auth-source-remember (spec found)
752 "Remember FOUND search results for SPEC."
753 (let ((password-cache-expiry auth-source-cache-expiry))
755 (concat auth-source-magic (format "%S" spec)) found)))
757 (defun auth-source-recall (spec)
758 "Recall FOUND search results for SPEC."
759 (password-read-from-cache
760 (concat auth-source-magic (format "%S" spec))))
762 (defun auth-source-remembered-p (spec)
763 "Check if SPEC is remembered."
765 (concat auth-source-magic (format "%S" spec))))
767 (defun auth-source-forget (spec)
768 "Forget any cached data matching SPEC exactly.
770 This is the same SPEC you passed to `auth-source-search'.
771 Returns t or nil for forgotten or not found."
772 (password-cache-remove (concat auth-source-magic (format "%S" spec))))
774 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
776 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
777 ;;; (auth-source-remembered-p '(:host "wedd"))
778 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
779 ;;; (auth-source-remembered-p '(:host "xedd"))
780 ;;; (auth-source-remembered-p '(:host "zedd"))
781 ;;; (auth-source-recall '(:host "xedd"))
782 ;;; (auth-source-recall '(:host t))
783 ;;; (auth-source-forget+ :host t)
785 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
786 "Forget any cached data matching SPEC. Returns forgotten count.
788 This is not a full `auth-source-search' spec but works similarly.
789 For instance, \(:host \"myhost\" \"yourhost\") would find all the
790 cached data that was found with a search for those two hosts,
791 while \(:host t) would find all host entries."
794 (loop for sym being the symbols of password-data
795 ;; when the symbol name matches with auth-source-magic
796 when (and (setq sname (symbol-name sym))
797 (string-match (concat "^" auth-source-magic "\\(.+\\)")
799 ;; and the spec matches what was stored in the cache
800 (auth-source-specmatchp spec (read (match-string 1 sname))))
803 (password-cache-remove sname)
807 (defun auth-source-specmatchp (spec stored)
808 (let ((keys (loop for i below (length spec) by 2
809 collect (nth i spec))))
812 (unless (auth-source-search-collection (plist-get stored key)
813 (plist-get spec key))
817 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
818 ;;; (auth-source-pick-first-password :port "imap")
819 (defun auth-source-pick-first-password (&rest spec)
820 "Pick the first secret found from applying SPEC to `auth-source-search'."
821 (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
822 (secret (plist-get result :secret)))
824 (if (functionp secret)
828 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
829 (defun auth-source-format-prompt (prompt alist)
830 "Format PROMPT using %x (for any character x) specifiers in ALIST."
832 (let ((c (nth 0 cell))
835 (setq prompt (replace-regexp-in-string (format "%%%c" c)
840 (defun auth-source-ensure-strings (values)
841 (unless (listp values)
842 (setq values (list values)))
843 (mapcar (lambda (value)
849 ;;; Backend specific parsing: netrc/authinfo backend
851 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
852 (defun* auth-source-netrc-parse (&rest
854 &key file max host user port delete require
856 "Parse FILE and return a list of all entries in the file.
857 Note that the MAX parameter is used so we can exit the parse early."
859 ;; We got already parsed contents; just return it.
861 (when (file-exists-p file)
862 (setq port (auth-source-ensure-strings port))
864 (let* ((tokens '("machine" "host" "default" "login" "user"
865 "password" "account" "macdef" "force"
867 (max (or max 5000)) ; sanity check: default to stop at 5K
869 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
870 (cached-mtime (plist-get cached :mtime))
871 (cached-secrets (plist-get cached :secret))
872 alist elem result pair)
874 (if (and (functionp cached-secrets)
876 (nth 5 (file-attributes file))))
878 (auth-source-do-trivia
879 "auth-source-netrc-parse: using CACHED file data for %s"
881 (insert (funcall cached-secrets)))
882 (insert-file-contents file)
883 ;; cache all netrc files (used to be just .gpg files)
884 ;; Store the contents of the file heavily encrypted in memory.
885 ;; (note for the irony-impaired: they are just obfuscated)
886 (aput 'auth-source-netrc-cache file
887 (list :mtime (nth 5 (file-attributes file))
888 :secret (lexical-let ((v (rot13-string
889 (base64-encode-string
891 (lambda () (base64-decode-string
892 (rot13-string v)))))))
893 (goto-char (point-min))
894 ;; Go through the file, line by line.
895 (while (and (not (eobp))
898 (narrow-to-region (point) (point-at-eol))
899 ;; For each line, get the tokens and values.
901 (skip-chars-forward "\t ")
902 ;; Skip lines that begin with a "#".
903 (if (eq (char-after) ?#)
904 (goto-char (point-max))
907 (if (= (following-char) ?\")
908 (read (current-buffer))
910 (point) (progn (skip-chars-forward "^\t ")
913 ((equal elem "macdef")
914 ;; We skip past the macro definition.
916 (while (and (zerop (forward-line 1))
918 (narrow-to-region (point) (point)))
919 ((member elem tokens)
920 ;; Tokens that don't have a following value are ignored,
922 (when (and pair (or (cdr pair)
923 (equal (car pair) "default")))
925 (setq pair (list elem)))
927 ;; Values that haven't got a preceding token are ignored.
931 (setq pair nil)))))))
935 (auth-source-search-collection
938 (aget alist "machine")
941 (auth-source-search-collection
945 (aget alist "account")
948 (auth-source-search-collection
952 (aget alist "protocol")
955 ;; the required list of keys is nil, or
957 ;; every element of require is in the normalized list
958 (let ((normalized (nth 0 (auth-source-netrc-normalize
959 (list alist) file))))
960 (loop for req in require
961 always (plist-get normalized req)))))
963 (push (nreverse alist) result)
964 ;; to delete a line, we just comment it out
966 (goto-char (point-min))
975 (when auth-source-gpg-encrypt-to
976 ;; (see bug#7487) making `epa-file-encrypt-to' local to
977 ;; this buffer lets epa-file skip the key selection query
978 ;; (see the `local-variable-p' check in
979 ;; `epa-file-write-region').
980 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
981 (make-local-variable 'epa-file-encrypt-to))
982 (if (listp auth-source-gpg-encrypt-to)
983 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
985 ;; ask AFTER we've successfully opened the file
986 (when (y-or-n-p (format "Save file %s? (%d deletions)"
988 (write-region (point-min) (point-max) file nil 'silent)
989 (auth-source-do-debug
990 "auth-source-netrc-parse: modified %d lines in %s"
993 (nreverse result))))))
995 (defvar auth-source-passphrase-alist nil)
997 (defun auth-source-passphrase-callback-function (context key-id handback
998 &optional sym-detail)
999 "Exactly like `epa-passphrase-callback-function' but takes an
1000 extra SYM-DETAIL parameter which will be printed at the end of
1001 the symmetric passphrase prompt, and assumes symmetric
1004 (format "Passphrase for symmetric encryption%s%s: "
1005 ;; Add the file name to the prompt, if any.
1006 (if (stringp handback)
1007 (format " for %s" handback)
1009 (if (stringp sym-detail)
1012 (eq (epg-context-operation context) 'encrypt)))
1014 (defun auth-source-token-passphrase-callback-function (context key-id file)
1015 (if (eq key-id 'SYM)
1016 (let* ((file (file-truename file))
1017 (entry (assoc file auth-source-passphrase-alist))
1019 ;; return the saved passphrase, calling a function if needed
1020 (or (copy-sequence (if (functionp (cdr entry))
1021 (funcall (cdr entry))
1025 (setq entry (list file))
1026 (push entry auth-source-passphrase-alist))
1027 (setq passphrase (auth-source-passphrase-callback-function context
1031 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1034 (epa-passphrase-callback-function context key-id file)))
1036 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1037 (defun auth-source-epa-extract-gpg-token (secret file)
1038 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1039 FILE is the file from which we obtained this token."
1040 (when (string-match "^gpg:\\(.+\\)" secret)
1041 (setq secret (base64-decode-string (match-string 1 secret))))
1042 (let ((context (epg-make-context 'OpenPGP))
1044 (epg-context-set-passphrase-callback
1046 (cons #'auth-source-token-passphrase-callback-function
1048 (epg-decrypt-string context secret)))
1050 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1051 (defun auth-source-epa-make-gpg-token (secret file)
1052 (let ((context (epg-make-context 'OpenPGP))
1053 (pp-escape-newlines nil)
1055 (epg-context-set-armor context t)
1056 (epg-context-set-passphrase-callback
1058 (cons #'auth-source-token-passphrase-callback-function
1060 (setq cipher (epg-encrypt-string context secret nil))
1063 (base64-encode-region (point-min) (point-max) t)
1064 (concat "gpg:" (buffer-substring-no-properties
1068 (defun auth-source-netrc-normalize (alist filename)
1069 (mapcar (lambda (entry)
1071 (while (setq item (pop entry))
1072 (let ((k (car item))
1075 ;; apply key aliases
1076 (setq k (cond ((member k '("machine")) "host")
1077 ((member k '("login" "account")) "user")
1078 ((member k '("protocol")) "port")
1079 ((member k '("password")) "secret")
1082 ;; send back the secret in a function (lexical binding)
1083 (when (equal k "secret")
1084 (setq v (lexical-let ((lexv v)
1085 (token-decoder nil))
1086 (when (string-match "^gpg:" lexv)
1087 ;; it's a GPG token: create a token decoder
1088 ;; which unsets itself once
1092 (auth-source-epa-extract-gpg-token
1095 (setq token-decoder nil)))))
1098 (setq lexv (funcall token-decoder lexv)))
1100 (setq ret (plist-put ret
1101 (intern (concat ":" k))
1106 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1107 ;;; (funcall secret)
1109 (defun* auth-source-netrc-search (&rest
1111 &key backend require create delete
1112 type max host user port
1114 "Given a property list SPEC, return search matches from the :backend.
1115 See `auth-source-search' for details on SPEC."
1116 ;; just in case, check that the type is correct (null or same as the backend)
1117 (assert (or (null type) (eq type (oref backend type)))
1118 t "Invalid netrc search: %s %s")
1120 (let ((results (auth-source-netrc-normalize
1121 (auth-source-netrc-parse
1125 :file (oref backend source)
1129 (oref backend source))))
1131 ;; if we need to create an entry AND none were found to match
1135 ;; create based on the spec and record the value
1137 ;; if the user did not want to create the entry
1138 ;; in the file, it will be returned
1139 (apply (slot-value backend 'create-function) spec)
1140 ;; if not, we do the search again without :create
1141 ;; to get the updated data.
1143 ;; the result will be returned, even if the search fails
1144 (apply 'auth-source-netrc-search
1145 (plist-put spec :create nil)))))
1148 (defun auth-source-netrc-element-or-first (v)
1153 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1154 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1156 (defun* auth-source-netrc-create (&rest spec
1158 secret host user port create
1160 (let* ((base-required '(host user port secret))
1161 ;; we know (because of an assertion in auth-source-search) that the
1162 ;; :create parameter is either t or a list (which includes nil)
1163 (create-extra (if (eq t create) nil create))
1164 (current-data (car (auth-source-search :max 1
1167 (required (append base-required create-extra))
1168 (file (oref backend source))
1170 ;; `valist' is an alist
1172 ;; `artificial' will be returned if no creation is needed
1175 ;; only for base required elements (defined as function parameters):
1176 ;; fill in the valist with whatever data we may have from the search
1177 ;; we complete the first value if it's a list and use the value otherwise
1178 (dolist (br base-required)
1179 (when (symbol-value br)
1180 (let ((br-choice (cond
1181 ;; all-accepting choice (predicate is t)
1182 ((eq t (symbol-value br)) nil)
1183 ;; just the value otherwise
1184 (t (symbol-value br)))))
1186 (aput 'valist br br-choice)))))
1188 ;; for extra required elements, see if the spec includes a value for them
1189 (dolist (er create-extra)
1190 (let ((name (concat ":" (symbol-name er)))
1191 (keys (loop for i below (length spec) by 2
1192 collect (nth i spec))))
1194 (when (equal (symbol-name k) name)
1195 (aput 'valist er (plist-get spec k))))))
1197 ;; for each required element
1198 (dolist (r required)
1199 (let* ((data (aget valist r))
1200 ;; take the first element if the data is a list
1201 (data (or (auth-source-netrc-element-or-first data)
1202 (plist-get current-data
1203 (intern (format ":%s" r) obarray))))
1204 ;; this is the default to be offered
1205 (given-default (aget auth-source-creation-defaults r))
1206 ;; the default supplementals are simple:
1207 ;; for the user, try `given-default' and then (user-login-name);
1208 ;; otherwise take `given-default'
1210 ((and (not given-default) (eq r 'user))
1213 (printable-defaults (list
1216 (auth-source-netrc-element-or-first
1217 (aget valist 'user))
1218 (plist-get artificial :user)
1222 (auth-source-netrc-element-or-first
1223 (aget valist 'host))
1224 (plist-get artificial :host)
1228 (auth-source-netrc-element-or-first
1229 (aget valist 'port))
1230 (plist-get artificial :port)
1232 (prompt (or (aget auth-source-creation-prompts r)
1234 (secret "%p password for %u@%h: ")
1235 (user "%p user name for %h: ")
1236 (host "%p host name for user %u: ")
1237 (port "%p port for %u@%h: "))
1238 (format "Enter %s (%%u@%%h:%%p): " r)))
1239 (prompt (auth-source-format-prompt
1241 `((?u ,(aget printable-defaults 'user))
1242 (?h ,(aget printable-defaults 'host))
1243 (?p ,(aget printable-defaults 'port))))))
1245 ;; Store the data, prompting for the password if needed.
1248 ((and (null data) (eq r 'secret))
1249 ;; Special case prompt for passwords.
1250 ;; 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)))
1251 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1252 (let* ((ep (format "Use GPG password tokens in %s?" file))
1255 ((eq auth-source-netrc-use-gpg-tokens 'never)
1257 ((listp auth-source-netrc-use-gpg-tokens)
1258 (let ((check (copy-sequence
1259 auth-source-netrc-use-gpg-tokens))
1262 (setq item (pop check))
1263 (when (or (eq (car item) t)
1264 (string-match (car item) file))
1265 (setq ret (cdr item))
1266 (setq check nil)))))
1268 (plain (read-passwd prompt)))
1269 ;; ask if we don't know what to do (in which case
1270 ;; auth-source-netrc-use-gpg-tokens must be a list)
1272 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1273 ;; TODO: save the defcustom now? or ask?
1274 (setq auth-source-netrc-use-gpg-tokens
1275 (cons `(,file ,gpg-encrypt)
1276 auth-source-netrc-use-gpg-tokens)))
1277 (if (eq gpg-encrypt 'gpg)
1278 (auth-source-epa-make-gpg-token plain file)
1283 (if (string-match ": *\\'" prompt)
1284 (concat (substring prompt 0 (match-beginning 0))
1285 " (default " default "): ")
1286 (concat prompt "(default " default ") "))))
1287 (read-string prompt nil nil default))
1288 (t (or data default))))
1291 (setq artificial (plist-put artificial
1292 (intern (concat ":" (symbol-name r)))
1294 (lexical-let ((data data))
1298 ;; When r is not an empty string...
1299 (when (and (stringp data)
1300 (< 0 (length data)))
1301 ;; this function is not strictly necessary but I think it
1302 ;; makes the code clearer -tzz
1303 (let ((printer (lambda ()
1304 ;; append the key (the symbol name of r)
1305 ;; and the value in r
1308 (if (zerop (length add)) "" " ")
1309 ;; remap auth-source tokens to netrc
1314 (port "port") ; redundant but clearer
1315 (t (symbol-name r)))
1316 (if (string-match "[\" ]" data)
1319 (setq add (concat add (funcall printer)))))))
1324 (lexical-let ((file file)
1326 (lambda () (auth-source-netrc-saver file add))))
1330 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1331 (defun auth-source-netrc-saver (file add)
1332 "Save a line ADD in FILE, prompting along the way.
1333 Respects `auth-source-save-behavior'. Uses
1334 `auth-source-netrc-cache' to avoid prompting more than once."
1335 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1336 (cached (assoc key auth-source-netrc-cache)))
1339 (auth-source-do-trivia
1340 "auth-source-netrc-saver: found previous run for key %s, returning"
1343 (when (file-exists-p file)
1344 (insert-file-contents file))
1345 (when auth-source-gpg-encrypt-to
1346 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1347 ;; this buffer lets epa-file skip the key selection query
1348 ;; (see the `local-variable-p' check in
1349 ;; `epa-file-write-region').
1350 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1351 (make-local-variable 'epa-file-encrypt-to))
1352 (if (listp auth-source-gpg-encrypt-to)
1353 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1354 ;; we want the new data to be found first, so insert at beginning
1355 (goto-char (point-min))
1357 ;; Ask AFTER we've successfully opened the file.
1358 (let ((prompt (format "Save auth info to file %s? " file))
1359 (done (not (eq auth-source-save-behavior 'ask)))
1360 (bufname "*auth-source Help*")
1363 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1367 (with-output-to-temp-buffer bufname
1369 (concat "(y)es, save\n"
1370 "(n)o but use the info\n"
1371 "(N)o and don't ask to save again\n"
1373 "(?) for help as you can see.\n"))
1374 ;; Why? Doesn't with-output-to-temp-buffer already do
1375 ;; the exact same thing anyway? --Stef
1376 (set-buffer standard-output)
1383 (customize-save-variable 'auth-source-save-behavior nil))
1384 (?e (setq add (read-string "Line to add: " add)))
1387 (when (get-buffer-window bufname)
1388 (delete-window (get-buffer-window bufname)))
1390 ;; Make sure the info is not saved.
1391 (when (null auth-source-save-behavior)
1394 (when (< 0 (length add))
1399 (write-region (point-min) (point-max) file nil 'silent)
1400 (auth-source-do-debug
1401 "auth-source-netrc-create: wrote 1 new line to %s"
1403 (message "Saved new authentication information to %s" file)
1405 (aput 'auth-source-netrc-cache key "ran"))))
1407 ;;; Backend specific parsing: Secrets API backend
1409 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1410 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1411 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1412 ;;; (let ((auth-sources '(default))) (auth-source-search))
1413 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1414 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1416 (defun* auth-source-secrets-search (&rest
1418 &key backend create delete label
1419 type max host user port
1421 "Search the Secrets API; spec is like `auth-source'.
1423 The :label key specifies the item's label. It is the only key
1424 that can specify a substring. Any :label value besides a string
1425 will allow any label.
1427 All other search keys must match exactly. If you need substring
1428 matching, do a wider search and narrow it down yourself.
1430 You'll get back all the properties of the token as a plist.
1432 Here's an example that looks for the first item in the 'Login'
1435 \(let ((auth-sources '(\"secrets:Login\")))
1436 (auth-source-search :max 1)
1438 Here's another that looks for the first item in the 'Login'
1439 Secrets collection whose label contains 'gnus':
1441 \(let ((auth-sources '(\"secrets:Login\")))
1442 (auth-source-search :max 1 :label \"gnus\")
1444 And this one looks for the first item in the 'Login' Secrets
1445 collection that's a Google Chrome entry for the git.gnus.org site
1446 authentication tokens:
1448 \(let ((auth-sources '(\"secrets:Login\")))
1449 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1453 (assert (not create) nil
1454 "The Secrets API auth-source backend doesn't support creation yet")
1456 ;; (secrets-delete-item coll elt)
1457 (assert (not delete) nil
1458 "The Secrets API auth-source backend doesn't support deletion yet")
1460 (let* ((coll (oref backend source))
1461 (max (or max 5000)) ; sanity check: default to stop at 5K
1462 (ignored-keys '(:create :delete :max :backend :label))
1463 (search-keys (loop for i below (length spec) by 2
1464 unless (memq (nth i spec) ignored-keys)
1465 collect (nth i spec)))
1466 ;; build a search spec without the ignored keys
1467 ;; if a search key is nil or t (match anything), we skip it
1468 (search-spec (apply 'append (mapcar
1470 (if (or (null (plist-get spec k))
1471 (eq t (plist-get spec k)))
1473 (list k (plist-get spec k))))
1475 ;; needed keys (always including host, login, port, and secret)
1476 (returned-keys (mm-delete-duplicates (append
1477 '(:host :login :port :secret)
1479 (items (loop for item in (apply 'secrets-search-items coll search-spec)
1480 unless (and (stringp label)
1481 (not (string-match label item)))
1483 ;; TODO: respect max in `secrets-search-items', not after the fact
1484 (items (butlast items (- (length items) max)))
1485 ;; convert the item name to a full plist
1486 (items (mapcar (lambda (item)
1488 ;; make an entry for the secret (password) element
1491 (lexical-let ((v (secrets-get-secret coll item)))
1493 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1495 (mapcar (lambda (entry)
1496 (list (car entry) (cdr entry)))
1497 (secrets-get-attributes coll item)))))
1499 ;; ensure each item has each key in `returned-keys'
1500 (items (mapcar (lambda (plist)
1503 (mapcar (lambda (req)
1504 (if (plist-get plist req)
1512 (defun* auth-source-secrets-create (&rest
1514 &key backend type max host user port
1517 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1520 ;;; Backend specific parsing: PLSTORE backend
1522 (defun* auth-source-plstore-search (&rest
1524 &key backend create delete label
1525 type max host user port
1527 "Search the PLSTORE; spec is like `auth-source'."
1530 (assert (not delete) nil
1531 "The PLSTORE auth-source backend doesn't support deletion yet")
1533 (let* ((store (oref backend arg))
1534 (max (or max 5000)) ; sanity check: default to stop at 5K
1535 (ignored-keys '(:create :delete :max :backend :require))
1536 (search-keys (loop for i below (length spec) by 2
1537 unless (memq (nth i spec) ignored-keys)
1538 collect (nth i spec)))
1539 ;; build a search spec without the ignored keys
1540 ;; if a search key is nil or t (match anything), we skip it
1541 (search-spec (apply 'append (mapcar
1543 (let ((v (plist-get spec k)))
1551 ;; needed keys (always including host, login, port, and secret)
1552 (returned-keys (mm-delete-duplicates (append
1553 '(:host :login :port :secret)
1555 (items (plstore-find store search-spec))
1556 (items (butlast items (- (length items) max)))
1557 ;; convert the item to a full plist
1558 (items (mapcar (lambda (item)
1559 (let* ((plist (copy-tree (cdr item)))
1560 (secret (plist-member plist :secret)))
1564 (lexical-let ((v (car (cdr secret))))
1568 ;; ensure each item has each key in `returned-keys'
1569 (items (mapcar (lambda (plist)
1572 (mapcar (lambda (req)
1573 (if (plist-get plist req)
1579 ;; if we need to create an entry AND none were found to match
1583 ;; create based on the spec and record the value
1585 ;; if the user did not want to create the entry
1586 ;; in the file, it will be returned
1587 (apply (slot-value backend 'create-function) spec)
1588 ;; if not, we do the search again without :create
1589 ;; to get the updated data.
1591 ;; the result will be returned, even if the search fails
1592 (apply 'auth-source-plstore-search
1593 (plist-put spec :create nil)))))
1596 (defun* auth-source-plstore-create (&rest spec
1598 secret host user port create
1600 (let* ((base-required '(host user port secret))
1601 (base-secret '(secret))
1602 ;; we know (because of an assertion in auth-source-search) that the
1603 ;; :create parameter is either t or a list (which includes nil)
1604 (create-extra (if (eq t create) nil create))
1605 (current-data (car (auth-source-search :max 1
1608 (required (append base-required create-extra))
1609 (file (oref backend source))
1611 ;; `valist' is an alist
1613 ;; `artificial' will be returned if no creation is needed
1617 ;; only for base required elements (defined as function parameters):
1618 ;; fill in the valist with whatever data we may have from the search
1619 ;; we complete the first value if it's a list and use the value otherwise
1620 (dolist (br base-required)
1621 (when (symbol-value br)
1622 (let ((br-choice (cond
1623 ;; all-accepting choice (predicate is t)
1624 ((eq t (symbol-value br)) nil)
1625 ;; just the value otherwise
1626 (t (symbol-value br)))))
1628 (aput 'valist br br-choice)))))
1630 ;; for extra required elements, see if the spec includes a value for them
1631 (dolist (er create-extra)
1632 (let ((name (concat ":" (symbol-name er)))
1633 (keys (loop for i below (length spec) by 2
1634 collect (nth i spec))))
1636 (when (equal (symbol-name k) name)
1637 (aput 'valist er (plist-get spec k))))))
1639 ;; for each required element
1640 (dolist (r required)
1641 (let* ((data (aget valist r))
1642 ;; take the first element if the data is a list
1643 (data (or (auth-source-netrc-element-or-first data)
1644 (plist-get current-data
1645 (intern (format ":%s" r) obarray))))
1646 ;; this is the default to be offered
1647 (given-default (aget auth-source-creation-defaults r))
1648 ;; the default supplementals are simple:
1649 ;; for the user, try `given-default' and then (user-login-name);
1650 ;; otherwise take `given-default'
1652 ((and (not given-default) (eq r 'user))
1655 (printable-defaults (list
1658 (auth-source-netrc-element-or-first
1659 (aget valist 'user))
1660 (plist-get artificial :user)
1664 (auth-source-netrc-element-or-first
1665 (aget valist 'host))
1666 (plist-get artificial :host)
1670 (auth-source-netrc-element-or-first
1671 (aget valist 'port))
1672 (plist-get artificial :port)
1674 (prompt (or (aget auth-source-creation-prompts r)
1676 (secret "%p password for %u@%h: ")
1677 (user "%p user name for %h: ")
1678 (host "%p host name for user %u: ")
1679 (port "%p port for %u@%h: "))
1680 (format "Enter %s (%%u@%%h:%%p): " r)))
1681 (prompt (auth-source-format-prompt
1683 `((?u ,(aget printable-defaults 'user))
1684 (?h ,(aget printable-defaults 'host))
1685 (?p ,(aget printable-defaults 'port))))))
1687 ;; Store the data, prompting for the password if needed.
1690 ((and (null data) (eq r 'secret))
1691 ;; Special case prompt for passwords.
1692 (read-passwd prompt))
1696 (if (string-match ": *\\'" prompt)
1697 (concat (substring prompt 0 (match-beginning 0))
1698 " (default " default "): ")
1699 (concat prompt "(default " default ") "))))
1700 (read-string prompt nil nil default))
1701 (t (or data default))))
1704 (if (member r base-secret)
1705 (setq secret-artificial
1706 (plist-put secret-artificial
1707 (intern (concat ":" (symbol-name r)))
1709 (setq artificial (plist-put artificial
1710 (intern (concat ":" (symbol-name r)))
1712 (plstore-put (oref backend arg)
1713 (sha1 (format "%s@%s:%s"
1714 (plist-get artificial :user)
1715 (plist-get artificial :host)
1716 (plist-get artificial :port)))
1717 artificial secret-artificial)
1718 (if (y-or-n-p (format "Save auth info to file %s? "
1719 (plstore-get-file (oref backend arg))))
1720 (plstore-save (oref backend arg)))))
1724 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1726 ;; deprecate the old interface
1727 (make-obsolete 'auth-source-user-or-password
1728 'auth-source-search "Emacs 24.1")
1729 (make-obsolete 'auth-source-forget-user-or-password
1730 'auth-source-forget "Emacs 24.1")
1732 (defun auth-source-user-or-password
1733 (mode host port &optional username create-missing delete-existing)
1734 "Find MODE (string or list of strings) matching HOST and PORT.
1736 DEPRECATED in favor of `auth-source-search'!
1738 USERNAME is optional and will be used as \"login\" in a search
1739 across the Secret Service API (see secrets.el) if the resulting
1740 items don't have a username. This means that if you search for
1741 username \"joe\" and it matches an item but the item doesn't have
1742 a :user attribute, the username \"joe\" will be returned.
1744 A non nil DELETE-EXISTING means deleting any matching password
1745 entry in the respective sources. This is useful only when
1746 CREATE-MISSING is non nil as well; the intended use case is to
1747 remove wrong password entries.
1749 If no matching entry is found, and CREATE-MISSING is non nil,
1750 the password will be retrieved interactively, and it will be
1751 stored in the password database which matches best (see
1754 MODE can be \"login\" or \"password\"."
1755 (auth-source-do-debug
1756 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1757 mode host port username)
1759 (let* ((listy (listp mode))
1760 (mode (if listy mode (list mode)))
1762 (format "%s %s:%s %s" mode host port username)
1763 (format "%s %s:%s" mode host port)))
1764 (search (list :host host :port port))
1765 (search (if username (append search (list :user username)) search))
1766 (search (if create-missing
1767 (append search (list :create t))
1769 (search (if delete-existing
1770 (append search (list :delete t))
1772 ;; (found (if (not delete-existing)
1773 ;; (gethash cname auth-source-cache)
1774 ;; (remhash cname auth-source-cache)
1779 (auth-source-do-debug
1780 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1782 ;; don't show the password
1783 (if (and (member "password" mode) t)
1787 found) ; return the found data
1788 ;; else, if not found, search with a max of 1
1789 (let ((choice (nth 0 (apply 'auth-source-search
1790 (append '(:max 1) search)))))
1794 ((equal "password" m)
1795 (push (if (plist-get choice :secret)
1796 (funcall (plist-get choice :secret))
1799 (push (plist-get choice :user) found)))))
1800 (setq found (nreverse found))
1801 (setq found (if listy found (car-safe found)))))
1805 (provide 'auth-source)
1807 ;;; auth-source.el ends here