Rename comment-depth (etc.) to literal-cache (etc.). Enable it by default
[emacs.git] / lisp / auth-source.el
blobcfd21a523cd9f4192bd84506bbe64166e4da9561
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
3 ;; Copyright (C) 2008-2016 Free Software Foundation, Inc.
5 ;; Author: Ted Zlatanov <tzz@lifelogs.com>
6 ;; Keywords: news
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/>.
23 ;;; Commentary:
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.
32 ;; TODO:
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
40 ;;; Code:
42 (require 'password-cache)
44 (eval-when-compile (require 'cl))
45 (require 'eieio)
47 (autoload 'secrets-create-item "secrets")
48 (autoload 'secrets-delete-item "secrets")
49 (autoload 'secrets-get-alias "secrets")
50 (autoload 'secrets-get-attributes "secrets")
51 (autoload 'secrets-get-secret "secrets")
52 (autoload 'secrets-list-collections "secrets")
53 (autoload 'secrets-search-items "secrets")
55 (autoload 'rfc2104-hash "rfc2104")
57 (autoload 'plstore-open "plstore")
58 (autoload 'plstore-find "plstore")
59 (autoload 'plstore-put "plstore")
60 (autoload 'plstore-delete "plstore")
61 (autoload 'plstore-save "plstore")
62 (autoload 'plstore-get-file "plstore")
64 (eval-when-compile (require 'epg)) ;; setf-method for `epg-context-armor'
65 (autoload 'epg-make-context "epg")
66 (autoload 'epg-context-set-passphrase-callback "epg")
67 (autoload 'epg-decrypt-string "epg")
68 (autoload 'epg-encrypt-string "epg")
70 (autoload 'help-mode "help-mode" nil t)
72 (defvar secrets-enabled)
74 (defgroup auth-source nil
75 "Authentication sources."
76 :version "23.1" ;; No Gnus
77 :group 'gnus)
79 ;;;###autoload
80 (defcustom auth-source-cache-expiry 7200
81 "How many seconds passwords are cached, or nil to disable
82 expiring. Overrides `password-cache-expiry' through a
83 let-binding."
84 :version "24.1"
85 :group 'auth-source
86 :type '(choice (const :tag "Never" nil)
87 (const :tag "All Day" 86400)
88 (const :tag "2 Hours" 7200)
89 (const :tag "30 Minutes" 1800)
90 (integer :tag "Seconds")))
92 ;; The slots below correspond with the `auth-source-search' spec,
93 ;; so a backend with :host set, for instance, would match only
94 ;; searches for that host. Normally they are nil.
95 (defclass auth-source-backend ()
96 ((type :initarg :type
97 :initform 'netrc
98 :type symbol
99 :custom symbol
100 :documentation "The backend type.")
101 (source :initarg :source
102 :type string
103 :custom string
104 :documentation "The backend source.")
105 (host :initarg :host
106 :initform t
107 :type t
108 :custom string
109 :documentation "The backend host.")
110 (user :initarg :user
111 :initform t
112 :type t
113 :custom string
114 :documentation "The backend user.")
115 (port :initarg :port
116 :initform t
117 :type t
118 :custom string
119 :documentation "The backend protocol.")
120 (data :initarg :data
121 :initform nil
122 :documentation "Internal backend data.")
123 (create-function :initarg :create-function
124 :initform ignore
125 :type function
126 :custom function
127 :documentation "The create function.")
128 (search-function :initarg :search-function
129 :initform ignore
130 :type function
131 :custom function
132 :documentation "The search function.")))
134 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
135 (pop3 "pop3" "pop" "pop3s" "110" "995")
136 (ssh "ssh" "22")
137 (sftp "sftp" "115")
138 (smtp "smtp" "25"))
139 "List of authentication protocols and their names"
141 :group 'auth-source
142 :version "23.2" ;; No Gnus
143 :type '(repeat :tag "Authentication Protocols"
144 (cons :tag "Protocol Entry"
145 (symbol :tag "Protocol")
146 (repeat :tag "Names"
147 (string :tag "Name")))))
149 ;; Generate all the protocols in a format Customize can use.
150 ;; TODO: generate on the fly from auth-source-protocols
151 (defconst auth-source-protocols-customize
152 (mapcar (lambda (a)
153 (let ((p (car-safe a)))
154 (list 'const
155 :tag (upcase (symbol-name p))
156 p)))
157 auth-source-protocols))
159 (defvar auth-source-creation-defaults nil
160 ;; FIXME: AFAICT this is not set (or let-bound) anywhere!
161 "Defaults for creating token values. Usually let-bound.")
163 (defvar auth-source-creation-prompts nil
164 "Default prompts for token values. Usually let-bound.")
166 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
168 (defcustom auth-source-save-behavior 'ask
169 "If set, auth-source will respect it for save behavior."
170 :group 'auth-source
171 :version "23.2" ;; No Gnus
172 :type `(choice
173 :tag "auth-source new token save behavior"
174 (const :tag "Always save" t)
175 (const :tag "Never save" nil)
176 (const :tag "Ask" ask)))
178 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car epa-file-auto-mode-alist-entry) "\\.gpg\\'") never) (t gpg)))
179 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
181 (defcustom auth-source-netrc-use-gpg-tokens 'never
182 "Set this to tell auth-source when to create GPG password
183 tokens in netrc files. It's either an alist or `never'.
184 Note that if EPA/EPG is not available, this should NOT be used."
185 :group 'auth-source
186 :version "23.2" ;; No Gnus
187 :type `(choice
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"
191 (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)
196 (car epa-file-auto-mode-alist-entry)
197 "\\.gpg\\'"))
198 (regexp :tag "Regular expression"))
199 (choice :tag "What to do"
200 (const :tag "Save GPG-encrypted password tokens" gpg)
201 (const :tag "Don't encrypt tokens" never))))))
203 (defvar auth-source-magic "auth-source-magic ")
205 (defcustom auth-source-do-cache t
206 "Whether auth-source should cache information with `password-cache'."
207 :group 'auth-source
208 :version "23.2" ;; No Gnus
209 :type `boolean)
211 (defcustom auth-source-debug nil
212 "Whether auth-source should log debug messages.
214 If the value is nil, debug messages are not logged.
216 If the value is t, debug messages are logged with `message'. In
217 that case, your authentication data will be in the clear (except
218 for passwords).
220 If the value is a function, debug messages are logged by calling
221 that function using the same arguments as `message'."
222 :group 'auth-source
223 :version "23.2" ;; No Gnus
224 :type `(choice
225 :tag "auth-source debugging mode"
226 (const :tag "Log using `message' to the *Messages* buffer" t)
227 (const :tag "Log all trivia with `message' to the *Messages* buffer"
228 trivia)
229 (function :tag "Function that takes arguments like `message'")
230 (const :tag "Don't log anything" nil)))
232 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
233 "List of authentication sources.
234 Each entry is the authentication type with optional properties.
235 Entries are tried in the order in which they appear.
236 See Info node `(auth)Help for users' for details.
238 If an entry names a file with the \".gpg\" extension and you have
239 EPA/EPG set up, the file will be encrypted and decrypted
240 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
241 for details.
243 It's best to customize this with `\\[customize-variable]' because the choices
244 can get pretty complex."
245 :group 'auth-source
246 :version "24.1" ;; No Gnus
247 :type `(repeat :tag "Authentication Sources"
248 (choice
249 (string :tag "Just a file")
250 (const :tag "Default Secrets API Collection" default)
251 (const :tag "Login Secrets API Collection" "secrets:Login")
252 (const :tag "Temp Secrets API Collection" "secrets:session")
254 (const :tag "Default internet Mac OS Keychain"
255 macos-keychain-internet)
257 (const :tag "Default generic Mac OS Keychain"
258 macos-keychain-generic)
260 (list :tag "Source definition"
261 (const :format "" :value :source)
262 (choice :tag "Authentication backend choice"
263 (string :tag "Authentication Source (file)")
264 (list
265 :tag "Secret Service API/KWallet/GNOME Keyring"
266 (const :format "" :value :secrets)
267 (choice :tag "Collection to use"
268 (string :tag "Collection name")
269 (const :tag "Default" default)
270 (const :tag "Login" "Login")
271 (const
272 :tag "Temporary" "session")))
273 (list
274 :tag "Mac OS internet Keychain"
275 (const :format ""
276 :value :macos-keychain-internet)
277 (choice :tag "Collection to use"
278 (string :tag "internet Keychain path")
279 (const :tag "default" default)))
280 (list
281 :tag "Mac OS generic Keychain"
282 (const :format ""
283 :value :macos-keychain-generic)
284 (choice :tag "Collection to use"
285 (string :tag "generic Keychain path")
286 (const :tag "default" default))))
287 (repeat :tag "Extra Parameters" :inline t
288 (choice :tag "Extra parameter"
289 (list
290 :tag "Host"
291 (const :format "" :value :host)
292 (choice :tag "Host (machine) choice"
293 (const :tag "Any" t)
294 (regexp
295 :tag "Regular expression")))
296 (list
297 :tag "Protocol"
298 (const :format "" :value :port)
299 (choice
300 :tag "Protocol"
301 (const :tag "Any" t)
302 ,@auth-source-protocols-customize))
303 (list :tag "User" :inline t
304 (const :format "" :value :user)
305 (choice
306 :tag "Personality/Username"
307 (const :tag "Any" t)
308 (string
309 :tag "Name")))))))))
311 (defcustom auth-source-gpg-encrypt-to t
312 "List of recipient keys that `authinfo.gpg' encrypted to.
313 If the value is not a list, symmetric encryption will be used."
314 :group 'auth-source
315 :version "24.1" ;; No Gnus
316 :type '(choice (const :tag "Symmetric encryption" t)
317 (repeat :tag "Recipient public keys"
318 (string :tag "Recipient public key"))))
320 ;; temp for debugging
321 ;; (unintern 'auth-source-protocols)
322 ;; (unintern 'auth-sources)
323 ;; (customize-variable 'auth-sources)
324 ;; (setq auth-sources nil)
325 ;; (format "%S" auth-sources)
326 ;; (customize-variable 'auth-source-protocols)
327 ;; (setq auth-source-protocols nil)
328 ;; (format "%S" auth-source-protocols)
329 ;; (auth-source-pick nil :host "a" :port 'imap)
330 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
331 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
332 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
333 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
334 ;; (auth-source-protocol-defaults 'imap)
336 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
337 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
338 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
339 (defun auth-source-do-debug (&rest msg)
340 (when auth-source-debug
341 (apply #'auth-source-do-warn msg)))
343 (defun auth-source-do-trivia (&rest msg)
344 (when (or (eq auth-source-debug 'trivia)
345 (functionp auth-source-debug))
346 (apply #'auth-source-do-warn msg)))
348 (defun auth-source-do-warn (&rest msg)
349 (apply
350 ;; set logger to either the function in auth-source-debug or 'message
351 ;; note that it will be 'message if auth-source-debug is nil
352 (if (functionp auth-source-debug)
353 auth-source-debug
354 'message)
355 msg))
358 ;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
359 (defun auth-source-read-char-choice (prompt choices)
360 "Read one of CHOICES by `read-char-choice', or `read-char'.
361 `dropdown-list' support is disabled because it doesn't work reliably.
362 Only one of CHOICES will be returned. The PROMPT is augmented
363 with \"[a/b/c] \" if CHOICES is \(?a ?b ?c)."
364 (when choices
365 (let* ((prompt-choices
366 (apply #'concat (loop for c in choices
367 collect (format "%c/" c))))
368 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
369 (full-prompt (concat prompt prompt-choices))
372 (while (not (memq k choices))
373 (setq k (read-char-choice full-prompt choices)))
374 k)))
376 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
377 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
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)
381 ;; (:source "~/.authinfo.gpg" :host t :port t)))
383 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
384 ;; (:source (:secrets "session") :host t :port t :user "joe")
385 ;; (:source (:secrets "Login") :host t :port t)
386 ;; ))
388 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
390 ;; (auth-source-backend-parse "myfile.gpg")
391 ;; (auth-source-backend-parse 'default)
392 ;; (auth-source-backend-parse "secrets:Login")
393 ;; (auth-source-backend-parse 'macos-keychain-internet)
394 ;; (auth-source-backend-parse 'macos-keychain-generic)
395 ;; (auth-source-backend-parse "macos-keychain-internet:/path/here.keychain")
396 ;; (auth-source-backend-parse "macos-keychain-generic:/path/here.keychain")
398 (defun auth-source-backend-parse (entry)
399 "Creates an auth-source-backend from an ENTRY in `auth-sources'."
400 (auth-source-backend-parse-parameters
401 entry
402 (cond
403 ;; take 'default and recurse to get it as a Secrets API default collection
404 ;; matching any user, host, and protocol
405 ((eq entry 'default)
406 (auth-source-backend-parse '(:source (:secrets default))))
407 ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
408 ;; matching any user, host, and protocol
409 ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
410 (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
412 ;; take 'macos-keychain-internet and recurse to get it as a Mac OS
413 ;; Keychain collection matching any user, host, and protocol
414 ((eq entry 'macos-keychain-internet)
415 (auth-source-backend-parse '(:source (:macos-keychain-internet default))))
416 ;; take 'macos-keychain-generic and recurse to get it as a Mac OS
417 ;; Keychain collection matching any user, host, and protocol
418 ((eq entry 'macos-keychain-generic)
419 (auth-source-backend-parse '(:source (:macos-keychain-generic default))))
420 ;; take macos-keychain-internet:XYZ and recurse to get it as MacOS
421 ;; Keychain "XYZ" matching any user, host, and protocol
422 ((and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
423 entry))
424 (auth-source-backend-parse `(:source (:macos-keychain-internet
425 ,(match-string 1 entry)))))
426 ;; take macos-keychain-generic:XYZ and recurse to get it as MacOS
427 ;; Keychain "XYZ" matching any user, host, and protocol
428 ((and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
429 entry))
430 (auth-source-backend-parse `(:source (:macos-keychain-generic
431 ,(match-string 1 entry)))))
433 ;; take just a file name and recurse to get it as a netrc file
434 ;; matching any user, host, and protocol
435 ((stringp entry)
436 (auth-source-backend-parse `(:source ,entry)))
438 ;; a file name with parameters
439 ((stringp (plist-get entry :source))
440 (if (equal (file-name-extension (plist-get entry :source)) "plist")
441 (auth-source-backend
442 (plist-get entry :source)
443 :source (plist-get entry :source)
444 :type 'plstore
445 :search-function #'auth-source-plstore-search
446 :create-function #'auth-source-plstore-create
447 :data (plstore-open (plist-get entry :source)))
448 (auth-source-backend
449 (plist-get entry :source)
450 :source (plist-get entry :source)
451 :type 'netrc
452 :search-function #'auth-source-netrc-search
453 :create-function #'auth-source-netrc-create)))
455 ;; the MacOS Keychain
456 ((and
457 (not (null (plist-get entry :source))) ; the source must not be nil
458 (listp (plist-get entry :source)) ; and it must be a list
460 (plist-get (plist-get entry :source) :macos-keychain-generic)
461 (plist-get (plist-get entry :source) :macos-keychain-internet)))
463 (let* ((source-spec (plist-get entry :source))
464 (keychain-generic (plist-get source-spec :macos-keychain-generic))
465 (keychain-type (if keychain-generic
466 'macos-keychain-generic
467 'macos-keychain-internet))
468 (source (plist-get source-spec (if keychain-generic
469 :macos-keychain-generic
470 :macos-keychain-internet))))
472 (when (symbolp source)
473 (setq source (symbol-name source)))
475 (auth-source-backend
476 (format "Mac OS Keychain (%s)" source)
477 :source source
478 :type keychain-type
479 :search-function #'auth-source-macos-keychain-search
480 :create-function #'auth-source-macos-keychain-create)))
482 ;; the Secrets API. We require the package, in order to have a
483 ;; defined value for `secrets-enabled'.
484 ((and
485 (not (null (plist-get entry :source))) ; the source must not be nil
486 (listp (plist-get entry :source)) ; and it must be a list
487 (require 'secrets nil t) ; and we must load the Secrets API
488 secrets-enabled) ; and that API must be enabled
490 ;; the source is either the :secrets key in ENTRY or
491 ;; if that's missing or nil, it's "session"
492 (let ((source (or (plist-get (plist-get entry :source) :secrets)
493 "session")))
495 ;; if the source is a symbol, we look for the alias named so,
496 ;; and if that alias is missing, we use "Login"
497 (when (symbolp source)
498 (setq source (or (secrets-get-alias (symbol-name source))
499 "Login")))
501 (if (featurep 'secrets)
502 (auth-source-backend
503 (format "Secrets API (%s)" source)
504 :source source
505 :type 'secrets
506 :search-function #'auth-source-secrets-search
507 :create-function #'auth-source-secrets-create)
508 (auth-source-do-warn
509 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
510 (auth-source-backend
511 (format "Ignored Secrets API (%s)" source)
512 :source ""
513 :type 'ignore))))
515 ;; none of them
517 (auth-source-do-warn
518 "auth-source-backend-parse: invalid backend spec: %S" entry)
519 (make-instance 'auth-source-backend
520 :source ""
521 :type 'ignore)))))
523 (defun auth-source-backend-parse-parameters (entry backend)
524 "Fills in the extra auth-source-backend parameters of ENTRY.
525 Using the plist ENTRY, get the :host, :port, and :user search
526 parameters."
527 (let ((entry (if (stringp entry)
529 entry))
530 val)
531 (when (setq val (plist-get entry :host))
532 (oset backend host val))
533 (when (setq val (plist-get entry :user))
534 (oset backend user val))
535 (when (setq val (plist-get entry :port))
536 (oset backend port val)))
537 backend)
539 ;; (mapcar 'auth-source-backend-parse auth-sources)
541 (defun* auth-source-search (&rest spec
542 &key max
543 require create delete
544 &allow-other-keys)
545 "Search or modify authentication backends according to SPEC.
547 This function parses `auth-sources' for matches of the SPEC
548 plist. It can optionally create or update an authentication
549 token if requested. A token is just a standard Emacs property
550 list with a :secret property that can be a function; all the
551 other properties will always hold scalar values.
553 Typically the :secret property, if present, contains a password.
555 Common search keys are :max, :host, :port, and :user. In
556 addition, :create specifies if and how tokens will be created.
557 Finally, :type can specify which backend types you want to check.
559 A string value is always matched literally. A symbol is matched
560 as its string value, literally. All the SPEC values can be
561 single values (symbol or string) or lists thereof (in which case
562 any of the search terms matches).
564 :create t means to create a token if possible.
566 A new token will be created if no matching tokens were found.
567 The new token will have only the keys the backend requires. For
568 the netrc backend, for instance, that's the user, host, and
569 port keys.
571 Here's an example:
573 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
574 (A . \"default A\"))))
575 (auth-source-search :host \"mine\" :type \\='netrc :max 1
576 :P \"pppp\" :Q \"qqqq\"
577 :create t))
579 which says:
581 \"Search for any entry matching host `mine' in backends of type
582 `netrc', maximum one result.
584 Create a new entry if you found none. The netrc backend will
585 automatically require host, user, and port. The host will be
586 `mine'. We prompt for the user with default `defaultUser' and
587 for the port without a default. We will not prompt for A, Q,
588 or P. The resulting token will only have keys user, host, and
589 port.\"
591 :create \\='(A B C) also means to create a token if possible.
593 The behavior is like :create t but if the list contains any
594 parameter, that parameter will be required in the resulting
595 token. The value for that parameter will be obtained from the
596 search parameters or from user input. If any queries are needed,
597 the alist `auth-source-creation-defaults' will be checked for the
598 default value. If the user, host, or port are missing, the alist
599 `auth-source-creation-prompts' will be used to look up the
600 prompts IN THAT ORDER (so the `user' prompt will be queried first,
601 then `host', then `port', and finally `secret'). Each prompt string
602 can use %u, %h, and %p to show the user, host, and port.
604 Here's an example:
606 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
607 (A . \"default A\")))
608 (auth-source-creation-prompts
609 \\='((password . \"Enter IMAP password for %h:%p: \"))))
610 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
611 :P \"pppp\" :Q \"qqqq\"
612 :create \\='(A B Q)))
614 which says:
616 \"Search for any entry matching host `nonesuch'
617 or `twosuch' in backends of type `netrc', maximum one result.
619 Create a new entry if you found none. The netrc backend will
620 automatically require host, user, and port. The host will be
621 `nonesuch' and Q will be `qqqq'. We prompt for the password
622 with the shown prompt. We will not prompt for Q. The resulting
623 token will have keys user, host, port, A, B, and Q. It will not
624 have P with any value, even though P is used in the search to
625 find only entries that have P set to `pppp'.\"
627 When multiple values are specified in the search parameter, the
628 user is prompted for which one. So :host (X Y Z) would ask the
629 user to choose between X, Y, and Z.
631 This creation can fail if the search was not specific enough to
632 create a new token (it's up to the backend to decide that). You
633 should `catch' the backend-specific error as usual. Some
634 backends (netrc, at least) will prompt the user rather than throw
635 an error.
637 :require (A B C) means that only results that contain those
638 tokens will be returned. Thus for instance requiring :secret
639 will ensure that any results will actually have a :secret
640 property.
642 :delete t means to delete any found entries. nil by default.
643 Use `auth-source-delete' in ELisp code instead of calling
644 `auth-source-search' directly with this parameter.
646 :type (X Y Z) will check only those backend types. `netrc' and
647 `secrets' are the only ones supported right now.
649 :max N means to try to return at most N items (defaults to 1).
650 More than N items may be returned, depending on the search and
651 the backend.
653 When :max is 0 the function will return just t or nil to indicate
654 if any matches were found.
656 :host (X Y Z) means to match only hosts X, Y, or Z according to
657 the match rules above. Defaults to t.
659 :user (X Y Z) means to match only users X, Y, or Z according to
660 the match rules above. Defaults to t.
662 :port (P Q R) means to match only protocols P, Q, or R.
663 Defaults to t.
665 :K (V1 V2 V3) for any other key K will match values V1, V2, or
666 V3 (note the match rules above).
668 The return value is a list with at most :max tokens. Each token
669 is a plist with keys :backend :host :port :user, plus any other
670 keys provided by the backend (notably :secret). But note the
671 exception for :max 0, which see above.
673 The token can hold a :save-function key. If you call that, the
674 user will be prompted to save the data to the backend. You can't
675 request that this should happen right after creation, because
676 `auth-source-search' has no way of knowing if the token is
677 actually useful. So the caller must arrange to call this function.
679 The token's :secret key can hold a function. In that case you
680 must call it to obtain the actual value."
681 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources))
682 (max (or max 1))
683 (ignored-keys '(:require :create :delete :max))
684 (keys (loop for i below (length spec) by 2
685 unless (memq (nth i spec) ignored-keys)
686 collect (nth i spec)))
687 (cached (auth-source-remembered-p spec))
688 ;; note that we may have cached results but found is still nil
689 ;; (there were no results from the search)
690 (found (auth-source-recall spec))
691 filtered-backends)
693 (if (and cached auth-source-do-cache)
694 (auth-source-do-debug
695 "auth-source-search: found %d CACHED results matching %S"
696 (length found) spec)
698 (assert
699 (or (eq t create) (listp create)) t
700 "Invalid auth-source :create parameter (must be t or a list): %s %s")
702 (assert
703 (listp require) t
704 "Invalid auth-source :require parameter (must be a list): %s")
706 (setq filtered-backends (copy-sequence backends))
707 (dolist (backend backends)
708 (dolist (key keys)
709 ;; ignore invalid slots
710 (condition-case nil
711 (unless (auth-source-search-collection
712 (plist-get spec key)
713 (slot-value backend key))
714 (setq filtered-backends (delq backend filtered-backends))
715 (return))
716 (invalid-slot-name nil))))
718 (auth-source-do-trivia
719 "auth-source-search: found %d backends matching %S"
720 (length filtered-backends) spec)
722 ;; (debug spec "filtered" filtered-backends)
723 ;; First go through all the backends without :create, so we can
724 ;; query them all.
725 (setq found (auth-source-search-backends filtered-backends
726 spec
727 ;; to exit early
729 ;; create is always nil here
730 nil delete
731 require))
733 (auth-source-do-debug
734 "auth-source-search: found %d results (max %d) matching %S"
735 (length found) max spec)
737 ;; If we didn't find anything, then we allow the backend(s) to
738 ;; create the entries.
739 (when (and create
740 (not found))
741 (setq found (auth-source-search-backends filtered-backends
742 spec
743 ;; to exit early
745 create delete
746 require))
747 (auth-source-do-debug
748 "auth-source-search: CREATED %d results (max %d) matching %S"
749 (length found) max spec))
751 ;; note we remember the lack of result too, if it's applicable
752 (when auth-source-do-cache
753 (auth-source-remember spec found)))
755 (if (zerop max)
756 (not (null found))
757 found)))
759 (defun auth-source-search-backends (backends spec max create delete require)
760 (let ((max (if (zerop max) 1 max)) ; stop with 1 match if we're asked for zero
761 matches)
762 (dolist (backend backends)
763 (when (> max (length matches)) ; if we need more matches...
764 (let* ((bmatches (apply
765 (slot-value backend 'search-function)
766 :backend backend
767 :type (slot-value backend 'type)
768 ;; note we're overriding whatever the spec
769 ;; has for :max, :require, :create, and :delete
770 :max max
771 :require require
772 :create create
773 :delete delete
774 spec)))
775 (when bmatches
776 (auth-source-do-trivia
777 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
778 (length bmatches) max
779 (slot-value backend 'type)
780 (slot-value backend 'source)
781 spec)
782 (setq matches (append matches bmatches))))))
783 matches))
785 ;; (auth-source-search :max 0)
786 ;; (auth-source-search :max 1)
787 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
788 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
789 ;; (auth-source-search :host "nonesuch" :type 'secrets)
791 (defun auth-source-delete (&rest spec)
792 "Delete entries from the authentication backends according to SPEC.
793 Calls `auth-source-search' with the :delete property in SPEC set to t.
794 The backend may not actually delete the entries.
796 Returns the deleted entries."
797 (auth-source-search (plist-put spec :delete t)))
799 (defun auth-source-search-collection (collection value)
800 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
801 (when (and (atom collection) (not (eq t collection)))
802 (setq collection (list collection)))
804 ;; (debug :collection collection :value value)
805 (or (eq collection t)
806 (eq value t)
807 (equal collection value)
808 (member value collection)))
810 (defvar auth-source-netrc-cache nil)
812 (defun auth-source-forget-all-cached ()
813 "Forget all cached auth-source data."
814 (interactive)
815 (loop for sym being the symbols of password-data
816 ;; when the symbol name starts with auth-source-magic
817 when (string-match (concat "^" auth-source-magic)
818 (symbol-name sym))
819 ;; remove that key
820 do (password-cache-remove (symbol-name sym)))
821 (setq auth-source-netrc-cache nil))
823 (defun auth-source-format-cache-entry (spec)
824 "Format SPEC entry to put it in the password cache."
825 (concat auth-source-magic (format "%S" spec)))
827 (defun auth-source-remember (spec found)
828 "Remember FOUND search results for SPEC."
829 (let ((password-cache-expiry auth-source-cache-expiry))
830 (password-cache-add
831 (auth-source-format-cache-entry spec) found)))
833 (defun auth-source-recall (spec)
834 "Recall FOUND search results for SPEC."
835 (password-read-from-cache (auth-source-format-cache-entry spec)))
837 (defun auth-source-remembered-p (spec)
838 "Check if SPEC is remembered."
839 (password-in-cache-p
840 (auth-source-format-cache-entry spec)))
842 (defun auth-source-forget (spec)
843 "Forget any cached data matching SPEC exactly.
845 This is the same SPEC you passed to `auth-source-search'.
846 Returns t or nil for forgotten or not found."
847 (password-cache-remove (auth-source-format-cache-entry spec)))
849 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
851 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
852 ;; (auth-source-remembered-p '(:host "wedd"))
853 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
854 ;; (auth-source-remembered-p '(:host "xedd"))
855 ;; (auth-source-remembered-p '(:host "zedd"))
856 ;; (auth-source-recall '(:host "xedd"))
857 ;; (auth-source-recall '(:host t))
858 ;; (auth-source-forget+ :host t)
860 (defun auth-source-forget+ (&rest spec)
861 "Forget any cached data matching SPEC. Returns forgotten count.
863 This is not a full `auth-source-search' spec but works similarly.
864 For instance, \(:host \"myhost\" \"yourhost\") would find all the
865 cached data that was found with a search for those two hosts,
866 while \(:host t) would find all host entries."
867 (let ((count 0)
868 sname)
869 (loop for sym being the symbols of password-data
870 ;; when the symbol name matches with auth-source-magic
871 when (and (setq sname (symbol-name sym))
872 (string-match (concat "^" auth-source-magic "\\(.+\\)")
873 sname)
874 ;; and the spec matches what was stored in the cache
875 (auth-source-specmatchp spec (read (match-string 1 sname))))
876 ;; remove that key
877 do (progn
878 (password-cache-remove sname)
879 (incf count)))
880 count))
882 (defun auth-source-specmatchp (spec stored)
883 (let ((keys (loop for i below (length spec) by 2
884 collect (nth i spec))))
885 (not (eq
886 (dolist (key keys)
887 (unless (auth-source-search-collection (plist-get stored key)
888 (plist-get spec key))
889 (return 'no)))
890 'no))))
892 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
893 ;; (auth-source-pick-first-password :port "imap")
894 (defun auth-source-pick-first-password (&rest spec)
895 "Pick the first secret found from applying SPEC to `auth-source-search'."
896 (let* ((result (nth 0 (apply #'auth-source-search (plist-put spec :max 1))))
897 (secret (plist-get result :secret)))
899 (if (functionp secret)
900 (funcall secret)
901 secret)))
903 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
904 (defun auth-source-format-prompt (prompt alist)
905 "Format PROMPT using %x (for any character x) specifiers in ALIST."
906 (dolist (cell alist)
907 (let ((c (nth 0 cell))
908 (v (nth 1 cell)))
909 (when (and c v)
910 (setq prompt (replace-regexp-in-string (format "%%%c" c)
911 (format "%s" v)
912 prompt nil t)))))
913 prompt)
915 (defun auth-source-ensure-strings (values)
916 (if (eq values t)
917 values
918 (unless (listp values)
919 (setq values (list values)))
920 (mapcar (lambda (value)
921 (if (numberp value)
922 (format "%s" value)
923 value))
924 values)))
926 ;;; Backend specific parsing: netrc/authinfo backend
928 (defun auth-source--aput-1 (alist key val)
929 (let ((seen ())
930 (rest alist))
931 (while (and (consp rest) (not (equal key (caar rest))))
932 (push (pop rest) seen))
933 (cons (cons key val)
934 (if (null rest) alist
935 (nconc (nreverse seen)
936 (if (equal key (caar rest)) (cdr rest) rest))))))
937 (defmacro auth-source--aput (var key val)
938 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
940 (defun auth-source--aget (alist key)
941 (cdr (assoc key alist)))
943 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
944 (defun* auth-source-netrc-parse (&key file max host user port require
945 &allow-other-keys)
946 "Parse FILE and return a list of all entries in the file.
947 Note that the MAX parameter is used so we can exit the parse early."
948 (if (listp file)
949 ;; We got already parsed contents; just return it.
950 file
951 (when (file-exists-p file)
952 (setq port (auth-source-ensure-strings port))
953 (with-temp-buffer
954 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
955 (modified 0)
956 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
957 (cached-mtime (plist-get cached :mtime))
958 (cached-secrets (plist-get cached :secret))
959 (check (lambda(alist)
960 (and alist
961 (auth-source-search-collection
962 host
964 (auth-source--aget alist "machine")
965 (auth-source--aget alist "host")
967 (auth-source-search-collection
968 user
970 (auth-source--aget alist "login")
971 (auth-source--aget alist "account")
972 (auth-source--aget alist "user")
974 (auth-source-search-collection
975 port
977 (auth-source--aget alist "port")
978 (auth-source--aget alist "protocol")
981 ;; the required list of keys is nil, or
982 (null require)
983 ;; every element of require is in n(ormalized)
984 (let ((n (nth 0 (auth-source-netrc-normalize
985 (list alist) file))))
986 (loop for req in require
987 always (plist-get n req)))))))
988 result)
990 (if (and (functionp cached-secrets)
991 (equal cached-mtime
992 (nth 5 (file-attributes file))))
993 (progn
994 (auth-source-do-trivia
995 "auth-source-netrc-parse: using CACHED file data for %s"
996 file)
997 (insert (funcall cached-secrets)))
998 (insert-file-contents file)
999 ;; cache all netrc files (used to be just .gpg files)
1000 ;; Store the contents of the file heavily encrypted in memory.
1001 ;; (note for the irony-impaired: they are just obfuscated)
1002 (auth-source--aput
1003 auth-source-netrc-cache file
1004 (list :mtime (nth 5 (file-attributes file))
1005 :secret (lexical-let ((v (mapcar #'1+ (buffer-string))))
1006 (lambda () (apply #'string (mapcar #'1- v)))))))
1007 (goto-char (point-min))
1008 (let ((entries (auth-source-netrc-parse-entries check max))
1009 alist)
1010 (while (setq alist (pop entries))
1011 (push (nreverse alist) result)))
1013 (when (< 0 modified)
1014 (when auth-source-gpg-encrypt-to
1015 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1016 ;; this buffer lets epa-file skip the key selection query
1017 ;; (see the `local-variable-p' check in
1018 ;; `epa-file-write-region').
1019 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1020 (make-local-variable 'epa-file-encrypt-to))
1021 (if (listp auth-source-gpg-encrypt-to)
1022 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1024 ;; ask AFTER we've successfully opened the file
1025 (when (y-or-n-p (format "Save file %s? (%d deletions)"
1026 file modified))
1027 (write-region (point-min) (point-max) file nil 'silent)
1028 (auth-source-do-debug
1029 "auth-source-netrc-parse: modified %d lines in %s"
1030 modified file)))
1032 (nreverse result))))))
1034 (defun auth-source-netrc-parse-next-interesting ()
1035 "Advance to the next interesting position in the current buffer."
1036 ;; If we're looking at a comment or are at the end of the line, move forward
1037 (while (or (looking-at "#")
1038 (and (eolp)
1039 (not (eobp))))
1040 (forward-line 1))
1041 (skip-chars-forward "\t "))
1043 (defun auth-source-netrc-parse-one ()
1044 "Read one thing from the current buffer."
1045 (auth-source-netrc-parse-next-interesting)
1047 (when (or (looking-at "'\\([^']*\\)'")
1048 (looking-at "\"\\([^\"]*\\)\"")
1049 (looking-at "\\([^ \t\n]+\\)"))
1050 (forward-char (length (match-string 0)))
1051 (auth-source-netrc-parse-next-interesting)
1052 (match-string-no-properties 1)))
1054 ;; with thanks to org-mode
1055 (defsubst auth-source-current-line (&optional pos)
1056 (save-excursion
1057 (and pos (goto-char pos))
1058 ;; works also in narrowed buffer, because we start at 1, not point-min
1059 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1061 (defun auth-source-netrc-parse-entries(check max)
1062 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1063 (let ((adder (lambda(check alist all)
1064 (when (and
1065 alist
1066 (> max (length all))
1067 (funcall check alist))
1068 (push alist all))
1069 all))
1070 item item2 all alist default)
1071 (while (setq item (auth-source-netrc-parse-one))
1072 (setq default (equal item "default"))
1073 ;; We're starting a new machine. Save the old one.
1074 (when (and alist
1075 (or default
1076 (equal item "machine")))
1077 ;; (auth-source-do-trivia
1078 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1079 (setq all (funcall adder check alist all)
1080 alist nil))
1081 ;; In default entries, we don't have a next token.
1082 ;; We store them as ("machine" . t)
1083 (if default
1084 (push (cons "machine" t) alist)
1085 ;; Not a default entry. Grab the next item.
1086 (when (setq item2 (auth-source-netrc-parse-one))
1087 ;; Did we get a "machine" value?
1088 (if (equal item2 "machine")
1089 (error
1090 "%s: Unexpected `machine' token at line %d"
1091 "auth-source-netrc-parse-entries"
1092 (auth-source-current-line))
1093 (push (cons item item2) alist)))))
1095 ;; Clean up: if there's an entry left over, use it.
1096 (when alist
1097 (setq all (funcall adder check alist all))
1098 ;; (auth-source-do-trivia
1099 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1101 (nreverse all)))
1103 (defvar auth-source-passphrase-alist nil)
1105 (defun auth-source-token-passphrase-callback-function (_context _key-id file)
1106 (let* ((file (file-truename file))
1107 (entry (assoc file auth-source-passphrase-alist))
1108 passphrase)
1109 ;; return the saved passphrase, calling a function if needed
1110 (or (copy-sequence (if (functionp (cdr entry))
1111 (funcall (cdr entry))
1112 (cdr entry)))
1113 (progn
1114 (unless entry
1115 (setq entry (list file))
1116 (push entry auth-source-passphrase-alist))
1117 (setq passphrase
1118 (read-passwd
1119 (format "Passphrase for %s tokens: " file)
1121 (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1122 (lambda () p)))
1123 passphrase))))
1125 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1126 (defun auth-source-epa-extract-gpg-token (secret file)
1127 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1128 FILE is the file from which we obtained this token."
1129 (when (string-match "^gpg:\\(.+\\)" secret)
1130 (setq secret (base64-decode-string (match-string 1 secret))))
1131 (let ((context (epg-make-context 'OpenPGP)))
1132 (epg-context-set-passphrase-callback
1133 context
1134 (cons #'auth-source-token-passphrase-callback-function
1135 file))
1136 (epg-decrypt-string context secret)))
1138 (defvar pp-escape-newlines)
1140 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1141 (defun auth-source-epa-make-gpg-token (secret file)
1142 (let ((context (epg-make-context 'OpenPGP))
1143 (pp-escape-newlines nil)
1144 cipher)
1145 (setf (epg-context-armor context) t)
1146 (epg-context-set-passphrase-callback
1147 context
1148 (cons #'auth-source-token-passphrase-callback-function
1149 file))
1150 (setq cipher (epg-encrypt-string context secret nil))
1151 (with-temp-buffer
1152 (insert cipher)
1153 (base64-encode-region (point-min) (point-max) t)
1154 (concat "gpg:" (buffer-substring-no-properties
1155 (point-min)
1156 (point-max))))))
1158 (defun auto-source--symbol-keyword (symbol)
1159 (intern (format ":%s" symbol)))
1161 (defun auth-source-netrc-normalize (alist filename)
1162 (mapcar (lambda (entry)
1163 (let (ret item)
1164 (while (setq item (pop entry))
1165 (let ((k (car item))
1166 (v (cdr item)))
1168 ;; apply key aliases
1169 (setq k (cond ((member k '("machine")) "host")
1170 ((member k '("login" "account")) "user")
1171 ((member k '("protocol")) "port")
1172 ((member k '("password")) "secret")
1173 (t k)))
1175 ;; send back the secret in a function (lexical binding)
1176 (when (equal k "secret")
1177 (setq v (lexical-let ((lexv v)
1178 (token-decoder nil))
1179 (when (string-match "^gpg:" lexv)
1180 ;; it's a GPG token: create a token decoder
1181 ;; which unsets itself once
1182 (setq token-decoder
1183 (lambda (val)
1184 (prog1
1185 (auth-source-epa-extract-gpg-token
1187 filename)
1188 (setq token-decoder nil)))))
1189 (lambda ()
1190 (when token-decoder
1191 (setq lexv (funcall token-decoder lexv)))
1192 lexv))))
1193 (setq ret (plist-put ret
1194 (auto-source--symbol-keyword k)
1195 v))))
1196 ret))
1197 alist))
1199 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1200 ;; (funcall secret)
1202 (defun* auth-source-netrc-search (&rest
1203 spec
1204 &key backend require create
1205 type max host user port
1206 &allow-other-keys)
1207 "Given a property list SPEC, return search matches from the :backend.
1208 See `auth-source-search' for details on SPEC."
1209 ;; just in case, check that the type is correct (null or same as the backend)
1210 (assert (or (null type) (eq type (oref backend type)))
1211 t "Invalid netrc search: %s %s")
1213 (let ((results (auth-source-netrc-normalize
1214 (auth-source-netrc-parse
1215 :max max
1216 :require require
1217 :file (oref backend source)
1218 :host (or host t)
1219 :user (or user t)
1220 :port (or port t))
1221 (oref backend source))))
1223 ;; if we need to create an entry AND none were found to match
1224 (when (and create
1225 (not results))
1227 ;; create based on the spec and record the value
1228 (setq results (or
1229 ;; if the user did not want to create the entry
1230 ;; in the file, it will be returned
1231 (apply (slot-value backend 'create-function) spec)
1232 ;; if not, we do the search again without :create
1233 ;; to get the updated data.
1235 ;; the result will be returned, even if the search fails
1236 (apply #'auth-source-netrc-search
1237 (plist-put spec :create nil)))))
1238 results))
1240 (defun auth-source-netrc-element-or-first (v)
1241 (if (listp v)
1242 (nth 0 v)
1245 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1246 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1248 (defun* auth-source-netrc-create (&rest spec
1249 &key backend
1250 host port create
1251 &allow-other-keys)
1252 (let* ((base-required '(host user port secret))
1253 ;; we know (because of an assertion in auth-source-search) that the
1254 ;; :create parameter is either t or a list (which includes nil)
1255 (create-extra (if (eq t create) nil create))
1256 (current-data (car (auth-source-search :max 1
1257 :host host
1258 :port port)))
1259 (required (append base-required create-extra))
1260 (file (oref backend source))
1261 (add "")
1262 ;; `valist' is an alist
1263 valist
1264 ;; `artificial' will be returned if no creation is needed
1265 artificial)
1267 ;; only for base required elements (defined as function parameters):
1268 ;; fill in the valist with whatever data we may have from the search
1269 ;; we complete the first value if it's a list and use the value otherwise
1270 (dolist (br base-required)
1271 (let ((val (plist-get spec (auto-source--symbol-keyword br))))
1272 (when val
1273 (let ((br-choice (cond
1274 ;; all-accepting choice (predicate is t)
1275 ((eq t val) nil)
1276 ;; just the value otherwise
1277 (t val))))
1278 (when br-choice
1279 (auth-source--aput valist br br-choice))))))
1281 ;; for extra required elements, see if the spec includes a value for them
1282 (dolist (er create-extra)
1283 (let ((k (auto-source--symbol-keyword er))
1284 (keys (loop for i below (length spec) by 2
1285 collect (nth i spec))))
1286 (when (memq k keys)
1287 (auth-source--aput valist er (plist-get spec k)))))
1289 ;; for each required element
1290 (dolist (r required)
1291 (let* ((data (auth-source--aget valist r))
1292 ;; take the first element if the data is a list
1293 (data (or (auth-source-netrc-element-or-first data)
1294 (plist-get current-data
1295 (auto-source--symbol-keyword r))))
1296 ;; this is the default to be offered
1297 (given-default (auth-source--aget
1298 auth-source-creation-defaults r))
1299 ;; the default supplementals are simple:
1300 ;; for the user, try `given-default' and then (user-login-name);
1301 ;; otherwise take `given-default'
1302 (default (cond
1303 ((and (not given-default) (eq r 'user))
1304 (user-login-name))
1305 (t given-default)))
1306 (printable-defaults (list
1307 (cons 'user
1309 (auth-source-netrc-element-or-first
1310 (auth-source--aget valist 'user))
1311 (plist-get artificial :user)
1312 "[any user]"))
1313 (cons 'host
1315 (auth-source-netrc-element-or-first
1316 (auth-source--aget valist 'host))
1317 (plist-get artificial :host)
1318 "[any host]"))
1319 (cons 'port
1321 (auth-source-netrc-element-or-first
1322 (auth-source--aget valist 'port))
1323 (plist-get artificial :port)
1324 "[any port]"))))
1325 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1326 (case r
1327 (secret "%p password for %u@%h: ")
1328 (user "%p user name for %h: ")
1329 (host "%p host name for user %u: ")
1330 (port "%p port for %u@%h: "))
1331 (format "Enter %s (%%u@%%h:%%p): " r)))
1332 (prompt (auth-source-format-prompt
1333 prompt
1334 `((?u ,(auth-source--aget printable-defaults 'user))
1335 (?h ,(auth-source--aget printable-defaults 'host))
1336 (?p ,(auth-source--aget printable-defaults 'port))))))
1338 ;; Store the data, prompting for the password if needed.
1339 (setq data (or data
1340 (if (eq r 'secret)
1341 ;; Special case prompt for passwords.
1342 ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car epa-file-auto-mode-alist-entry) "\\.gpg\\'") nil) (t gpg)))
1343 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1344 (let* ((ep (format "Use GPG password tokens in %s?" file))
1345 (gpg-encrypt
1346 (cond
1347 ((eq auth-source-netrc-use-gpg-tokens 'never)
1348 'never)
1349 ((listp auth-source-netrc-use-gpg-tokens)
1350 (let ((check (copy-sequence
1351 auth-source-netrc-use-gpg-tokens))
1352 item ret)
1353 (while check
1354 (setq item (pop check))
1355 (when (or (eq (car item) t)
1356 (string-match (car item) file))
1357 (setq ret (cdr item))
1358 (setq check nil)))
1359 ;; FIXME: `ret' unused.
1360 ;; Should we return it here?
1362 (t 'never)))
1363 (plain (or (eval default) (read-passwd prompt))))
1364 ;; ask if we don't know what to do (in which case
1365 ;; auth-source-netrc-use-gpg-tokens must be a list)
1366 (unless gpg-encrypt
1367 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1368 ;; TODO: save the defcustom now? or ask?
1369 (setq auth-source-netrc-use-gpg-tokens
1370 (cons `(,file ,gpg-encrypt)
1371 auth-source-netrc-use-gpg-tokens)))
1372 (if (eq gpg-encrypt 'gpg)
1373 (auth-source-epa-make-gpg-token plain file)
1374 plain))
1375 (if (stringp default)
1376 (read-string (if (string-match ": *\\'" prompt)
1377 (concat (substring prompt 0 (match-beginning 0))
1378 " (default " default "): ")
1379 (concat prompt "(default " default ") "))
1380 nil nil default)
1381 (eval default)))))
1383 (when data
1384 (setq artificial (plist-put artificial
1385 (auto-source--symbol-keyword r)
1386 (if (eq r 'secret)
1387 (lexical-let ((data data))
1388 (lambda () data))
1389 data))))
1391 ;; When r is not an empty string...
1392 (when (and (stringp data)
1393 (< 0 (length data)))
1394 ;; this function is not strictly necessary but I think it
1395 ;; makes the code clearer -tzz
1396 (let ((printer (lambda ()
1397 ;; append the key (the symbol name of r)
1398 ;; and the value in r
1399 (format "%s%s %s"
1400 ;; prepend a space
1401 (if (zerop (length add)) "" " ")
1402 ;; remap auth-source tokens to netrc
1403 (case r
1404 (user "login")
1405 (host "machine")
1406 (secret "password")
1407 (port "port") ; redundant but clearer
1408 (t (symbol-name r)))
1409 (if (string-match "[\"# ]" data)
1410 (format "%S" data)
1411 data)))))
1412 (setq add (concat add (funcall printer)))))))
1414 (plist-put
1415 artificial
1416 :save-function
1417 (lexical-let ((file file)
1418 (add add))
1419 (lambda () (auth-source-netrc-saver file add))))
1421 (list artificial)))
1423 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1424 (defun auth-source-netrc-saver (file add)
1425 "Save a line ADD in FILE, prompting along the way.
1426 Respects `auth-source-save-behavior'. Uses
1427 `auth-source-netrc-cache' to avoid prompting more than once."
1428 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1429 (cached (assoc key auth-source-netrc-cache)))
1431 (if cached
1432 (auth-source-do-trivia
1433 "auth-source-netrc-saver: found previous run for key %s, returning"
1434 key)
1435 (with-temp-buffer
1436 (when (file-exists-p file)
1437 (insert-file-contents file))
1438 (when auth-source-gpg-encrypt-to
1439 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1440 ;; this buffer lets epa-file skip the key selection query
1441 ;; (see the `local-variable-p' check in
1442 ;; `epa-file-write-region').
1443 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1444 (make-local-variable 'epa-file-encrypt-to))
1445 (if (listp auth-source-gpg-encrypt-to)
1446 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1447 ;; we want the new data to be found first, so insert at beginning
1448 (goto-char (point-min))
1450 ;; Ask AFTER we've successfully opened the file.
1451 (let ((prompt (format "Save auth info to file %s? " file))
1452 (done (not (eq auth-source-save-behavior 'ask)))
1453 (bufname "*auth-source Help*")
1455 (while (not done)
1456 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1457 (case k
1458 (?y (setq done t))
1459 (?? (save-excursion
1460 (with-output-to-temp-buffer bufname
1461 (princ
1462 (concat "(y)es, save\n"
1463 "(n)o but use the info\n"
1464 "(N)o and don't ask to save again\n"
1465 "(e)dit the line\n"
1466 "(?) for help as you can see.\n"))
1467 ;; Why? Doesn't with-output-to-temp-buffer already do
1468 ;; the exact same thing anyway? --Stef
1469 (set-buffer standard-output)
1470 (help-mode))))
1471 (?n (setq add ""
1472 done t))
1474 (setq add ""
1475 done t)
1476 (customize-save-variable 'auth-source-save-behavior nil))
1477 (?e (setq add (read-string "Line to add: " add)))
1478 (t nil)))
1480 (when (get-buffer-window bufname)
1481 (delete-window (get-buffer-window bufname)))
1483 ;; Make sure the info is not saved.
1484 (when (null auth-source-save-behavior)
1485 (setq add ""))
1487 (when (< 0 (length add))
1488 (progn
1489 (unless (bolp)
1490 (insert "\n"))
1491 (insert add "\n")
1492 (write-region (point-min) (point-max) file nil 'silent)
1493 ;; Make the .authinfo file non-world-readable.
1494 (set-file-modes file #o600)
1495 (auth-source-do-debug
1496 "auth-source-netrc-create: wrote 1 new line to %s"
1497 file)
1498 (message "Saved new authentication information to %s" file)
1499 nil))))
1500 (auth-source--aput auth-source-netrc-cache key "ran"))))
1502 ;;; Backend specific parsing: Secrets API backend
1504 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1505 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1506 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1507 ;; (let ((auth-sources '(default))) (auth-source-search))
1508 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1509 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1511 (defun auth-source-secrets-listify-pattern (pattern)
1512 "Convert a pattern with lists to a list of string patterns.
1514 auth-source patterns can have values of the form :foo (\"bar\"
1515 \"qux\"), which means to match any secret with :foo equal to
1516 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1517 only string values for patterns, so this routine returns a list
1518 of patterns that is equivalent to the single original pattern
1519 when interpreted such that if a secret matches any pattern in the
1520 list, it matches the original pattern."
1521 (if (null pattern)
1522 '(nil)
1523 (let* ((key (pop pattern))
1524 (value (pop pattern))
1525 (tails (auth-source-secrets-listify-pattern pattern))
1526 (heads (if (stringp value)
1527 (list (list key value))
1528 (mapcar (lambda (v) (list key v)) value))))
1529 (loop
1530 for h in heads
1531 nconc
1532 (loop
1533 for tl in tails
1534 collect (append h tl))))))
1536 (defun* auth-source-secrets-search (&rest
1537 spec
1538 &key backend create delete label max
1539 &allow-other-keys)
1540 "Search the Secrets API; spec is like `auth-source'.
1542 The :label key specifies the item's label. It is the only key
1543 that can specify a substring. Any :label value besides a string
1544 will allow any label.
1546 All other search keys must match exactly. If you need substring
1547 matching, do a wider search and narrow it down yourself.
1549 You'll get back all the properties of the token as a plist.
1551 Here's an example that looks for the first item in the `Login'
1552 Secrets collection:
1554 (let ((auth-sources \\='(\"secrets:Login\")))
1555 (auth-source-search :max 1)
1557 Here's another that looks for the first item in the `Login'
1558 Secrets collection whose label contains `gnus':
1560 (let ((auth-sources \\='(\"secrets:Login\")))
1561 (auth-source-search :max 1 :label \"gnus\")
1563 And this one looks for the first item in the `Login' Secrets
1564 collection that's a Google Chrome entry for the git.gnus.org site
1565 authentication tokens:
1567 (let ((auth-sources \\='(\"secrets:Login\")))
1568 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1571 ;; TODO
1572 (assert (not create) nil
1573 "The Secrets API auth-source backend doesn't support creation yet")
1574 ;; TODO
1575 ;; (secrets-delete-item coll elt)
1576 (assert (not delete) nil
1577 "The Secrets API auth-source backend doesn't support deletion yet")
1579 (let* ((coll (oref backend source))
1580 (max (or max 5000)) ; sanity check: default to stop at 5K
1581 (ignored-keys '(:create :delete :max :backend :label :require :type))
1582 (search-keys (loop for i below (length spec) by 2
1583 unless (memq (nth i spec) ignored-keys)
1584 collect (nth i spec)))
1585 ;; build a search spec without the ignored keys
1586 ;; if a search key is nil or t (match anything), we skip it
1587 (search-specs (auth-source-secrets-listify-pattern
1588 (apply #'append (mapcar
1589 (lambda (k)
1590 (if (or (null (plist-get spec k))
1591 (eq t (plist-get spec k)))
1593 (list k (plist-get spec k))))
1594 search-keys))))
1595 ;; needed keys (always including host, login, port, and secret)
1596 (returned-keys (delete-dups (append
1597 '(:host :login :port :secret)
1598 search-keys)))
1599 (items
1600 (loop for search-spec in search-specs
1601 nconc
1602 (loop for item in (apply #'secrets-search-items coll search-spec)
1603 unless (and (stringp label)
1604 (not (string-match label item)))
1605 collect item)))
1606 ;; TODO: respect max in `secrets-search-items', not after the fact
1607 (items (butlast items (- (length items) max)))
1608 ;; convert the item name to a full plist
1609 (items (mapcar (lambda (item)
1610 (append
1611 ;; make an entry for the secret (password) element
1612 (list
1613 :secret
1614 (lexical-let ((v (secrets-get-secret coll item)))
1615 (lambda () v)))
1616 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1617 (apply #'append
1618 (mapcar (lambda (entry)
1619 (list (car entry) (cdr entry)))
1620 (secrets-get-attributes coll item)))))
1621 items))
1622 ;; ensure each item has each key in `returned-keys'
1623 (items (mapcar (lambda (plist)
1624 (append
1625 (apply #'append
1626 (mapcar (lambda (req)
1627 (if (plist-get plist req)
1629 (list req nil)))
1630 returned-keys))
1631 plist))
1632 items)))
1633 items))
1635 (defun auth-source-secrets-create (&rest spec)
1636 ;; TODO
1637 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1638 (debug spec))
1640 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1642 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1643 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1644 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1645 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1647 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1648 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1649 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1650 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1652 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1653 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1654 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1))
1656 (defun* auth-source-macos-keychain-search (&rest
1657 spec
1658 &key backend create delete
1659 type max
1660 &allow-other-keys)
1661 "Search the MacOS Keychain; spec is like `auth-source'.
1663 All search keys must match exactly. If you need substring
1664 matching, do a wider search and narrow it down yourself.
1666 You'll get back all the properties of the token as a plist.
1668 The :type key is either `macos-keychain-internet' or
1669 `macos-keychain-generic'.
1671 For the internet keychain type, the :label key searches the
1672 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1673 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1674 and :port maps to \"-P PORT\" or \"-r PROT\"
1675 \(note PROT has to be a 4-character string).
1677 For the generic keychain type, the :label key searches the item's
1678 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1679 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1680 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1682 Here's an example that looks for the first item in the default
1683 generic MacOS Keychain:
1685 (let ((auth-sources \\='(macos-keychain-generic)))
1686 (auth-source-search :max 1)
1688 Here's another that looks for the first item in the internet
1689 MacOS Keychain collection whose label is `gnus':
1691 (let ((auth-sources \\='(macos-keychain-internet)))
1692 (auth-source-search :max 1 :label \"gnus\")
1694 And this one looks for the first item in the internet keychain
1695 entries for git.gnus.org:
1697 (let ((auth-sources \\='(macos-keychain-internet\")))
1698 (auth-source-search :max 1 :host \"git.gnus.org\"))
1700 ;; TODO
1701 (assert (not create) nil
1702 "The MacOS Keychain auth-source backend doesn't support creation yet")
1703 ;; TODO
1704 ;; (macos-keychain-delete-item coll elt)
1705 (assert (not delete) nil
1706 "The MacOS Keychain auth-source backend doesn't support deletion yet")
1708 (let* ((coll (oref backend source))
1709 (max (or max 5000)) ; sanity check: default to stop at 5K
1710 ;; Filter out ignored keys from the spec
1711 (ignored-keys '(:create :delete :max :backend :label :host :port))
1712 ;; Build a search spec without the ignored keys
1713 (search-keys (loop for i below (length spec) by 2
1714 unless (memq (nth i spec) ignored-keys)
1715 collect (nth i spec)))
1716 ;; If a search key value is nil or t (match anything), we skip it
1717 (search-spec (apply #'append (mapcar
1718 (lambda (k)
1719 (if (or (null (plist-get spec k))
1720 (eq t (plist-get spec k)))
1722 (list k (plist-get spec k))))
1723 search-keys)))
1724 ;; needed keys (always including host, login, port, and secret)
1725 (returned-keys (delete-dups (append
1726 '(:host :login :port :secret)
1727 search-keys)))
1728 ;; Extract host and port from spec
1729 (hosts (plist-get spec :host))
1730 (hosts (if (and hosts (listp hosts)) hosts `(,hosts)))
1731 (ports (plist-get spec :port))
1732 (ports (if (and ports (listp ports)) ports `(,ports)))
1733 ;; Loop through all combinations of host/port and pass each of these to
1734 ;; auth-source-macos-keychain-search-items
1735 (items (catch 'match
1736 (dolist (host hosts)
1737 (dolist (port ports)
1738 (let* ((port (format "%S" port))
1739 (items (apply #'auth-source-macos-keychain-search-items
1740 coll
1741 type
1743 host port
1744 search-spec)))
1745 (when items
1746 (throw 'match items)))))))
1748 ;; ensure each item has each key in `returned-keys'
1749 (items (mapcar (lambda (plist)
1750 (append
1751 (apply #'append
1752 (mapcar (lambda (req)
1753 (if (plist-get plist req)
1755 (list req nil)))
1756 returned-keys))
1757 plist))
1758 items)))
1759 items))
1761 (defun* auth-source-macos-keychain-search-items (coll _type _max
1762 host port
1763 &key label type
1764 user
1765 &allow-other-keys)
1767 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1768 (args `(,(if keychain-generic
1769 "find-generic-password"
1770 "find-internet-password")
1771 "-g"))
1772 (ret (list :type type)))
1773 (when label
1774 (setq args (append args (list "-l" label))))
1775 (when host
1776 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1777 (when user
1778 (setq args (append args (list "-a" user))))
1780 (when port
1781 (if keychain-generic
1782 (setq args (append args (list "-s" port)))
1783 (setq args (append args (list
1784 (if (string-match "[0-9]+" port) "-P" "-r")
1785 port)))))
1787 (unless (equal coll "default")
1788 (setq args (append args (list coll))))
1790 (with-temp-buffer
1791 (apply #'call-process "/usr/bin/security" nil t nil args)
1792 (goto-char (point-min))
1793 (while (not (eobp))
1794 (cond
1795 ((looking-at "^password: \"\\(.+\\)\"$")
1796 (setq ret (auth-source-macos-keychain-result-append
1798 keychain-generic
1799 "secret"
1800 (lexical-let ((v (match-string 1)))
1801 (lambda () v)))))
1802 ;; TODO: check if this is really the label
1803 ;; match 0x00000007 <blob>="AppleID"
1804 ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1805 (setq ret (auth-source-macos-keychain-result-append
1807 keychain-generic
1808 "label"
1809 (match-string 1))))
1810 ;; match "crtr"<uint32>="aapl"
1811 ;; match "svce"<blob>="AppleID"
1812 ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1813 (setq ret (auth-source-macos-keychain-result-append
1815 keychain-generic
1816 (match-string 1)
1817 (match-string 2)))))
1818 (forward-line)))
1819 ;; return `ret' iff it has the :secret key
1820 (and (plist-get ret :secret) (list ret))))
1822 (defun auth-source-macos-keychain-result-append (result generic k v)
1823 (push v result)
1824 (push (auto-source--symbol-keyword
1825 (cond
1826 ((equal k "acct") "user")
1827 ;; for generic keychains, creator is host, service is port
1828 ((and generic (equal k "crtr")) "host")
1829 ((and generic (equal k "svce")) "port")
1830 ;; for internet keychains, protocol is port, server is host
1831 ((and (not generic) (equal k "ptcl")) "port")
1832 ((and (not generic) (equal k "srvr")) "host")
1833 (t k)))
1834 result))
1836 (defun auth-source-macos-keychain-create (&rest spec)
1837 ;; TODO
1838 (debug spec))
1840 ;;; Backend specific parsing: PLSTORE backend
1842 (defun* auth-source-plstore-search (&rest
1843 spec
1844 &key backend create delete
1846 &allow-other-keys)
1847 "Search the PLSTORE; spec is like `auth-source'."
1848 (let* ((store (oref backend data))
1849 (max (or max 5000)) ; sanity check: default to stop at 5K
1850 (ignored-keys '(:create :delete :max :backend :label :require :type))
1851 (search-keys (loop for i below (length spec) by 2
1852 unless (memq (nth i spec) ignored-keys)
1853 collect (nth i spec)))
1854 ;; build a search spec without the ignored keys
1855 ;; if a search key is nil or t (match anything), we skip it
1856 (search-spec (apply #'append (mapcar
1857 (lambda (k)
1858 (let ((v (plist-get spec k)))
1859 (if (or (null v)
1860 (eq t v))
1862 (if (stringp v)
1863 (setq v (list v)))
1864 (list k v))))
1865 search-keys)))
1866 ;; needed keys (always including host, login, port, and secret)
1867 (returned-keys (delete-dups (append
1868 '(:host :login :port :secret)
1869 search-keys)))
1870 (items (plstore-find store search-spec))
1871 (item-names (mapcar #'car items))
1872 (items (butlast items (- (length items) max)))
1873 ;; convert the item to a full plist
1874 (items (mapcar (lambda (item)
1875 (let* ((plist (copy-tree (cdr item)))
1876 (secret (plist-member plist :secret)))
1877 (if secret
1878 (setcar
1879 (cdr secret)
1880 (lexical-let ((v (car (cdr secret))))
1881 (lambda () v))))
1882 plist))
1883 items))
1884 ;; ensure each item has each key in `returned-keys'
1885 (items (mapcar (lambda (plist)
1886 (append
1887 (apply #'append
1888 (mapcar (lambda (req)
1889 (if (plist-get plist req)
1891 (list req nil)))
1892 returned-keys))
1893 plist))
1894 items)))
1895 (cond
1896 ;; if we need to create an entry AND none were found to match
1897 ((and create
1898 (not items))
1900 ;; create based on the spec and record the value
1901 (setq items (or
1902 ;; if the user did not want to create the entry
1903 ;; in the file, it will be returned
1904 (apply (slot-value backend 'create-function) spec)
1905 ;; if not, we do the search again without :create
1906 ;; to get the updated data.
1908 ;; the result will be returned, even if the search fails
1909 (apply #'auth-source-plstore-search
1910 (plist-put spec :create nil)))))
1911 ((and delete
1912 item-names)
1913 (dolist (item-name item-names)
1914 (plstore-delete store item-name))
1915 (plstore-save store)))
1916 items))
1918 (defun* auth-source-plstore-create (&rest spec
1919 &key backend
1920 host port create
1921 &allow-other-keys)
1922 (let* ((base-required '(host user port secret))
1923 (base-secret '(secret))
1924 ;; we know (because of an assertion in auth-source-search) that the
1925 ;; :create parameter is either t or a list (which includes nil)
1926 (create-extra (if (eq t create) nil create))
1927 (current-data (car (auth-source-search :max 1
1928 :host host
1929 :port port)))
1930 (required (append base-required create-extra))
1931 ;; `valist' is an alist
1932 valist
1933 ;; `artificial' will be returned if no creation is needed
1934 artificial
1935 secret-artificial)
1937 ;; only for base required elements (defined as function parameters):
1938 ;; fill in the valist with whatever data we may have from the search
1939 ;; we complete the first value if it's a list and use the value otherwise
1940 (dolist (br base-required)
1941 (let ((val (plist-get spec (auto-source--symbol-keyword br))))
1942 (when val
1943 (let ((br-choice (cond
1944 ;; all-accepting choice (predicate is t)
1945 ((eq t val) nil)
1946 ;; just the value otherwise
1947 (t val))))
1948 (when br-choice
1949 (auth-source--aput valist br br-choice))))))
1951 ;; for extra required elements, see if the spec includes a value for them
1952 (dolist (er create-extra)
1953 (let ((k (auto-source--symbol-keyword er))
1954 (keys (loop for i below (length spec) by 2
1955 collect (nth i spec))))
1956 (when (memq k keys)
1957 (auth-source--aput valist er (plist-get spec k)))))
1959 ;; for each required element
1960 (dolist (r required)
1961 (let* ((data (auth-source--aget valist r))
1962 ;; take the first element if the data is a list
1963 (data (or (auth-source-netrc-element-or-first data)
1964 (plist-get current-data
1965 (auto-source--symbol-keyword r))))
1966 ;; this is the default to be offered
1967 (given-default (auth-source--aget
1968 auth-source-creation-defaults r))
1969 ;; the default supplementals are simple:
1970 ;; for the user, try `given-default' and then (user-login-name);
1971 ;; otherwise take `given-default'
1972 (default (cond
1973 ((and (not given-default) (eq r 'user))
1974 (user-login-name))
1975 (t given-default)))
1976 (printable-defaults (list
1977 (cons 'user
1979 (auth-source-netrc-element-or-first
1980 (auth-source--aget valist 'user))
1981 (plist-get artificial :user)
1982 "[any user]"))
1983 (cons 'host
1985 (auth-source-netrc-element-or-first
1986 (auth-source--aget valist 'host))
1987 (plist-get artificial :host)
1988 "[any host]"))
1989 (cons 'port
1991 (auth-source-netrc-element-or-first
1992 (auth-source--aget valist 'port))
1993 (plist-get artificial :port)
1994 "[any port]"))))
1995 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1996 (case r
1997 (secret "%p password for %u@%h: ")
1998 (user "%p user name for %h: ")
1999 (host "%p host name for user %u: ")
2000 (port "%p port for %u@%h: "))
2001 (format "Enter %s (%%u@%%h:%%p): " r)))
2002 (prompt (auth-source-format-prompt
2003 prompt
2004 `((?u ,(auth-source--aget printable-defaults 'user))
2005 (?h ,(auth-source--aget printable-defaults 'host))
2006 (?p ,(auth-source--aget printable-defaults 'port))))))
2008 ;; Store the data, prompting for the password if needed.
2009 (setq data (or data
2010 (if (eq r 'secret)
2011 (or (eval default) (read-passwd prompt))
2012 (if (stringp default)
2013 (read-string
2014 (if (string-match ": *\\'" prompt)
2015 (concat (substring prompt 0 (match-beginning 0))
2016 " (default " default "): ")
2017 (concat prompt "(default " default ") "))
2018 nil nil default)
2019 (eval default)))))
2021 (when data
2022 (if (member r base-secret)
2023 (setq secret-artificial
2024 (plist-put secret-artificial
2025 (auto-source--symbol-keyword r)
2026 data))
2027 (setq artificial (plist-put artificial
2028 (auto-source--symbol-keyword r)
2029 data))))))
2030 (plstore-put (oref backend data)
2031 (sha1 (format "%s@%s:%s"
2032 (plist-get artificial :user)
2033 (plist-get artificial :host)
2034 (plist-get artificial :port)))
2035 artificial secret-artificial)
2036 (if (y-or-n-p (format "Save auth info to file %s? "
2037 (plstore-get-file (oref backend data))))
2038 (plstore-save (oref backend data)))))
2040 ;;; older API
2042 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2044 ;; deprecate the old interface
2045 (make-obsolete 'auth-source-user-or-password
2046 'auth-source-search "Emacs 24.1")
2047 (make-obsolete 'auth-source-forget-user-or-password
2048 'auth-source-forget "Emacs 24.1")
2050 (defun auth-source-user-or-password
2051 (mode host port &optional username create-missing delete-existing)
2052 "Find MODE (string or list of strings) matching HOST and PORT.
2054 DEPRECATED in favor of `auth-source-search'!
2056 USERNAME is optional and will be used as \"login\" in a search
2057 across the Secret Service API (see secrets.el) if the resulting
2058 items don't have a username. This means that if you search for
2059 username \"joe\" and it matches an item but the item doesn't have
2060 a :user attribute, the username \"joe\" will be returned.
2062 A non nil DELETE-EXISTING means deleting any matching password
2063 entry in the respective sources. This is useful only when
2064 CREATE-MISSING is non nil as well; the intended use case is to
2065 remove wrong password entries.
2067 If no matching entry is found, and CREATE-MISSING is non nil,
2068 the password will be retrieved interactively, and it will be
2069 stored in the password database which matches best (see
2070 `auth-sources').
2072 MODE can be \"login\" or \"password\"."
2073 (auth-source-do-debug
2074 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2075 mode host port username)
2077 (let* ((listy (listp mode))
2078 (mode (if listy mode (list mode)))
2079 ;; (cname (if username
2080 ;; (format "%s %s:%s %s" mode host port username)
2081 ;; (format "%s %s:%s" mode host port)))
2082 (search (list :host host :port port))
2083 (search (if username (append search (list :user username)) search))
2084 (search (if create-missing
2085 (append search (list :create t))
2086 search))
2087 (search (if delete-existing
2088 (append search (list :delete t))
2089 search))
2090 ;; (found (if (not delete-existing)
2091 ;; (gethash cname auth-source-cache)
2092 ;; (remhash cname auth-source-cache)
2093 ;; nil)))
2094 (found nil))
2095 (if found
2096 (progn
2097 (auth-source-do-debug
2098 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2099 mode
2100 ;; don't show the password
2101 (if (and (member "password" mode) t)
2102 "SECRET"
2103 found)
2104 host port username)
2105 found) ; return the found data
2106 ;; else, if not found, search with a max of 1
2107 (let ((choice (nth 0 (apply #'auth-source-search
2108 (append '(:max 1) search)))))
2109 (when choice
2110 (dolist (m mode)
2111 (cond
2112 ((equal "password" m)
2113 (push (if (plist-get choice :secret)
2114 (funcall (plist-get choice :secret))
2115 nil) found))
2116 ((equal "login" m)
2117 (push (plist-get choice :user) found)))))
2118 (setq found (nreverse found))
2119 (setq found (if listy found (car-safe found)))))
2121 found))
2123 (defun auth-source-user-and-password (host &optional user)
2124 (let* ((auth-info (car
2125 (if user
2126 (auth-source-search
2127 :host host
2128 :user "yourusername"
2129 :max 1
2130 :require '(:user :secret)
2131 :create nil)
2132 (auth-source-search
2133 :host host
2134 :max 1
2135 :require '(:user :secret)
2136 :create nil))))
2137 (user (plist-get auth-info :user))
2138 (password (plist-get auth-info :secret)))
2139 (when (functionp password)
2140 (setq password (funcall password)))
2141 (list user password auth-info)))
2143 (provide 'auth-source)
2145 ;;; auth-source.el ends here