Fix encoding of characters when using GB18030 fonts
[emacs.git] / lisp / auth-source.el
blobb733054ae5fdf3ab93c1203e606ed12137848098
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2008-2018 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 <https://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-lib))
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 (defcustom auth-source-do-cache t
204 "Whether auth-source should cache information with `password-cache'."
205 :group 'auth-source
206 :version "23.2" ;; No Gnus
207 :type `boolean)
209 (defcustom auth-source-debug nil
210 "Whether auth-source should log debug messages.
212 If the value is nil, debug messages are not logged.
214 If the value is t, debug messages are logged with `message'. In
215 that case, your authentication data will be in the clear (except
216 for passwords).
218 If the value is a function, debug messages are logged by calling
219 that function using the same arguments as `message'."
220 :group 'auth-source
221 :version "23.2" ;; No Gnus
222 :type `(choice
223 :tag "auth-source debugging mode"
224 (const :tag "Log using `message' to the *Messages* buffer" t)
225 (const :tag "Log all trivia with `message' to the *Messages* buffer"
226 trivia)
227 (function :tag "Function that takes arguments like `message'")
228 (const :tag "Don't log anything" nil)))
230 (defcustom auth-sources '("~/.authinfo" "~/.authinfo.gpg" "~/.netrc")
231 "List of authentication sources.
232 Each entry is the authentication type with optional properties.
233 Entries are tried in the order in which they appear.
234 See Info node `(auth)Help for users' for details.
236 If an entry names a file with the \".gpg\" extension and you have
237 EPA/EPG set up, the file will be encrypted and decrypted
238 automatically. See Info node `(epa)Encrypting/decrypting gpg files'
239 for details.
241 It's best to customize this with `\\[customize-variable]' because the choices
242 can get pretty complex."
243 :group 'auth-source
244 :version "26.1" ;; No Gnus
245 :type `(repeat :tag "Authentication Sources"
246 (choice
247 (string :tag "Just a file")
248 (const :tag "Default Secrets API Collection" default)
249 (const :tag "Login Secrets API Collection" "secrets:Login")
250 (const :tag "Temp Secrets API Collection" "secrets:session")
252 (const :tag "Default internet Mac OS Keychain"
253 macos-keychain-internet)
255 (const :tag "Default generic Mac OS Keychain"
256 macos-keychain-generic)
258 (list :tag "Source definition"
259 (const :format "" :value :source)
260 (choice :tag "Authentication backend choice"
261 (string :tag "Authentication Source (file)")
262 (list
263 :tag "Secret Service API/KWallet/GNOME Keyring"
264 (const :format "" :value :secrets)
265 (choice :tag "Collection to use"
266 (string :tag "Collection name")
267 (const :tag "Default" default)
268 (const :tag "Login" "Login")
269 (const
270 :tag "Temporary" "session")))
271 (list
272 :tag "Mac OS internet Keychain"
273 (const :format ""
274 :value :macos-keychain-internet)
275 (choice :tag "Collection to use"
276 (string :tag "internet Keychain path")
277 (const :tag "default" default)))
278 (list
279 :tag "Mac OS generic Keychain"
280 (const :format ""
281 :value :macos-keychain-generic)
282 (choice :tag "Collection to use"
283 (string :tag "generic Keychain path")
284 (const :tag "default" default))))
285 (repeat :tag "Extra Parameters" :inline t
286 (choice :tag "Extra parameter"
287 (list
288 :tag "Host"
289 (const :format "" :value :host)
290 (choice :tag "Host (machine) choice"
291 (const :tag "Any" t)
292 (regexp
293 :tag "Regular expression")))
294 (list
295 :tag "Protocol"
296 (const :format "" :value :port)
297 (choice
298 :tag "Protocol"
299 (const :tag "Any" t)
300 ,@auth-source-protocols-customize))
301 (list :tag "User" :inline t
302 (const :format "" :value :user)
303 (choice
304 :tag "Personality/Username"
305 (const :tag "Any" t)
306 (string
307 :tag "Name"))))))
308 (sexp :tag "A data structure (external provider)"))))
310 (defcustom auth-source-gpg-encrypt-to t
311 "List of recipient keys that `authinfo.gpg' encrypted to.
312 If the value is not a list, symmetric encryption will be used."
313 :group 'auth-source
314 :version "24.1" ;; No Gnus
315 :type '(choice (const :tag "Symmetric encryption" t)
316 (repeat :tag "Recipient public keys"
317 (string :tag "Recipient public key"))))
319 (defun auth-source-do-debug (&rest msg)
320 (when auth-source-debug
321 (apply #'auth-source-do-warn msg)))
323 (defun auth-source-do-trivia (&rest msg)
324 (when (or (eq auth-source-debug 'trivia)
325 (functionp auth-source-debug))
326 (apply #'auth-source-do-warn msg)))
328 (defun auth-source-do-warn (&rest msg)
329 (apply
330 ;; set logger to either the function in auth-source-debug or 'message
331 ;; note that it will be 'message if auth-source-debug is nil
332 (if (functionp auth-source-debug)
333 auth-source-debug
334 'message)
335 msg))
337 (defun auth-source-read-char-choice (prompt choices)
338 "Read one of CHOICES by `read-char-choice', or `read-char'.
339 `dropdown-list' support is disabled because it doesn't work reliably.
340 Only one of CHOICES will be returned. The PROMPT is augmented
341 with \"[a/b/c] \" if CHOICES is \(?a ?b ?c)."
342 (when choices
343 (let* ((prompt-choices
344 (apply #'concat
345 (cl-loop for c in choices collect (format "%c/" c))))
346 (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
347 (full-prompt (concat prompt prompt-choices))
350 (while (not (memq k choices))
351 (setq k (read-char-choice full-prompt choices)))
352 k)))
354 (defvar auth-source-backend-parser-functions nil
355 "List of auth-source parser functions.
356 Each function takes an entry from `auth-sources' as parameter and
357 returns a backend or nil if the entry is not supported. Add a
358 parser function to this list with `add-hook'. Searching for a
359 backend starts with the first element on the list and stops as
360 soon as a function returns non-nil.")
362 (defun auth-source-backend-parse (entry)
363 "Create an auth-source-backend from an ENTRY in `auth-sources'."
365 (let (backend)
366 (cl-dolist (f auth-source-backend-parser-functions)
367 (when (setq backend (funcall f entry))
368 (cl-return)))
370 (unless backend
371 ;; none of the parsers worked
372 (auth-source-do-warn
373 "auth-source-backend-parse: invalid backend spec: %S" entry)
374 (setq backend (make-instance 'auth-source-backend
375 :source ""
376 :type 'ignore)))
377 (auth-source-backend-parse-parameters entry backend)))
379 (defun auth-source-backends-parser-file (entry)
380 ;; take just a file name use it as a netrc/plist file
381 ;; matching any user, host, and protocol
382 (when (stringp entry)
383 (setq entry `(:source ,entry)))
384 (cond
385 ;; a file name with parameters
386 ((stringp (plist-get entry :source))
387 (if (equal (file-name-extension (plist-get entry :source)) "plist")
388 (auth-source-backend
389 (plist-get entry :source)
390 :source (plist-get entry :source)
391 :type 'plstore
392 :search-function #'auth-source-plstore-search
393 :create-function #'auth-source-plstore-create
394 :data (plstore-open (plist-get entry :source)))
395 (auth-source-backend
396 (plist-get entry :source)
397 :source (plist-get entry :source)
398 :type 'netrc
399 :search-function #'auth-source-netrc-search
400 :create-function #'auth-source-netrc-create)))))
402 ;; Note this function should be last in the parser functions, so we add it first
403 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-file)
405 (defun auth-source-backends-parser-macos-keychain (entry)
406 ;; take macos-keychain-{internet,generic}:XYZ and use it as macOS
407 ;; Keychain "XYZ" matching any user, host, and protocol
408 (when (and (stringp entry) (string-match "^macos-keychain-internet:\\(.+\\)"
409 entry))
410 (setq entry `(:source (:macos-keychain-internet
411 ,(match-string 1 entry)))))
412 (when (and (stringp entry) (string-match "^macos-keychain-generic:\\(.+\\)"
413 entry))
414 (setq entry `(:source (:macos-keychain-generic
415 ,(match-string 1 entry)))))
416 ;; take 'macos-keychain-internet or generic and use it as a Mac OS
417 ;; Keychain collection matching any user, host, and protocol
418 (when (eq entry 'macos-keychain-internet)
419 (setq entry '(:source (:macos-keychain-internet default))))
420 (when (eq entry 'macos-keychain-generic)
421 (setq entry '(:source (:macos-keychain-generic default))))
422 (cond
423 ;; the macOS Keychain
424 ((and
425 (not (null (plist-get entry :source))) ; the source must not be nil
426 (listp (plist-get entry :source)) ; and it must be a list
428 (plist-get (plist-get entry :source) :macos-keychain-generic)
429 (plist-get (plist-get entry :source) :macos-keychain-internet)))
431 (let* ((source-spec (plist-get entry :source))
432 (keychain-generic (plist-get source-spec :macos-keychain-generic))
433 (keychain-type (if keychain-generic
434 'macos-keychain-generic
435 'macos-keychain-internet))
436 (source (plist-get source-spec (if keychain-generic
437 :macos-keychain-generic
438 :macos-keychain-internet))))
440 (when (symbolp source)
441 (setq source (symbol-name source)))
443 (auth-source-backend
444 (format "Mac OS Keychain (%s)" source)
445 :source source
446 :type keychain-type
447 :search-function #'auth-source-macos-keychain-search
448 :create-function #'auth-source-macos-keychain-create)))))
450 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-macos-keychain)
452 (defun auth-source-backends-parser-secrets (entry)
453 ;; take secrets:XYZ and use it as Secrets API collection "XYZ"
454 ;; matching any user, host, and protocol
455 (when (and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
456 (setq entry `(:source (:secrets ,(match-string 1 entry)))))
457 ;; take 'default and use it as a Secrets API default collection
458 ;; matching any user, host, and protocol
459 (when (eq entry 'default)
460 (setq entry '(:source (:secrets default))))
461 (cond
462 ;; the Secrets API. We require the package, in order to have a
463 ;; defined value for `secrets-enabled'.
464 ((and
465 (not (null (plist-get entry :source))) ; the source must not be nil
466 (listp (plist-get entry :source)) ; and it must be a list
467 (not (null (plist-get
468 (plist-get entry :source)
469 :secrets))) ; the source must have :secrets
470 (require 'secrets nil t) ; and we must load the Secrets API
471 secrets-enabled) ; and that API must be enabled
473 ;; the source is either the :secrets key in ENTRY or
474 ;; if that's missing or nil, it's "session"
475 (let ((source (plist-get (plist-get entry :source) :secrets)))
477 ;; if the source is a symbol, we look for the alias named so,
478 ;; and if that alias is missing, we use "Login"
479 (when (symbolp source)
480 (setq source (or (secrets-get-alias (symbol-name source))
481 "Login")))
483 (if (featurep 'secrets)
484 (auth-source-backend
485 (format "Secrets API (%s)" source)
486 :source source
487 :type 'secrets
488 :search-function #'auth-source-secrets-search
489 :create-function #'auth-source-secrets-create)
490 (auth-source-do-warn
491 "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
492 (auth-source-backend
493 (format "Ignored Secrets API (%s)" source)
494 :source ""
495 :type 'ignore))))))
497 (add-hook 'auth-source-backend-parser-functions 'auth-source-backends-parser-secrets)
499 (defun auth-source-backend-parse-parameters (entry backend)
500 "Fills in the extra auth-source-backend parameters of ENTRY.
501 Using the plist ENTRY, get the :host, :port, and :user search
502 parameters."
503 (let ((entry (if (stringp entry)
505 entry))
506 val)
507 (when (setq val (plist-get entry :host))
508 (oset backend host val))
509 (when (setq val (plist-get entry :user))
510 (oset backend user val))
511 (when (setq val (plist-get entry :port))
512 (oset backend port val)))
513 backend)
515 ;; (mapcar 'auth-source-backend-parse auth-sources)
517 (cl-defun auth-source-search (&rest spec
518 &key max require create delete
519 &allow-other-keys)
520 "Search or modify authentication backends according to SPEC.
522 This function parses `auth-sources' for matches of the SPEC
523 plist. It can optionally create or update an authentication
524 token if requested. A token is just a standard Emacs property
525 list with a :secret property that can be a function; all the
526 other properties will always hold scalar values.
528 Typically the :secret property, if present, contains a password.
530 Common search keys are :max, :host, :port, and :user. In
531 addition, :create specifies if and how tokens will be created.
532 Finally, :type can specify which backend types you want to check.
534 A string value is always matched literally. A symbol is matched
535 as its string value, literally. All the SPEC values can be
536 single values (symbol or string) or lists thereof (in which case
537 any of the search terms matches).
539 :create t means to create a token if possible.
541 A new token will be created if no matching tokens were found.
542 The new token will have only the keys the backend requires. For
543 the netrc backend, for instance, that's the user, host, and
544 port keys.
546 Here's an example:
548 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
549 (A . \"default A\"))))
550 (auth-source-search :host \"mine\" :type \\='netrc :max 1
551 :P \"pppp\" :Q \"qqqq\"
552 :create t))
554 which says:
556 \"Search for any entry matching host `mine' in backends of type
557 `netrc', maximum one result.
559 Create a new entry if you found none. The netrc backend will
560 automatically require host, user, and port. The host will be
561 `mine'. We prompt for the user with default `defaultUser' and
562 for the port without a default. We will not prompt for A, Q,
563 or P. The resulting token will only have keys user, host, and
564 port.\"
566 :create \\='(A B C) also means to create a token if possible.
568 The behavior is like :create t but if the list contains any
569 parameter, that parameter will be required in the resulting
570 token. The value for that parameter will be obtained from the
571 search parameters or from user input. If any queries are needed,
572 the alist `auth-source-creation-defaults' will be checked for the
573 default value. If the user, host, or port are missing, the alist
574 `auth-source-creation-prompts' will be used to look up the
575 prompts IN THAT ORDER (so the `user' prompt will be queried first,
576 then `host', then `port', and finally `secret'). Each prompt string
577 can use %u, %h, and %p to show the user, host, and port.
579 Here's an example:
581 \(let ((auth-source-creation-defaults \\='((user . \"defaultUser\")
582 (A . \"default A\")))
583 (auth-source-creation-prompts
584 \\='((password . \"Enter IMAP password for %h:%p: \"))))
585 (auth-source-search :host \\='(\"nonesuch\" \"twosuch\") :type \\='netrc :max 1
586 :P \"pppp\" :Q \"qqqq\"
587 :create \\='(A B Q)))
589 which says:
591 \"Search for any entry matching host `nonesuch'
592 or `twosuch' in backends of type `netrc', maximum one result.
594 Create a new entry if you found none. The netrc backend will
595 automatically require host, user, and port. The host will be
596 `nonesuch' and Q will be `qqqq'. We prompt for the password
597 with the shown prompt. We will not prompt for Q. The resulting
598 token will have keys user, host, port, A, B, and Q. It will not
599 have P with any value, even though P is used in the search to
600 find only entries that have P set to `pppp'.\"
602 When multiple values are specified in the search parameter, the
603 user is prompted for which one. So :host (X Y Z) would ask the
604 user to choose between X, Y, and Z.
606 This creation can fail if the search was not specific enough to
607 create a new token (it's up to the backend to decide that). You
608 should `catch' the backend-specific error as usual. Some
609 backends (netrc, at least) will prompt the user rather than throw
610 an error.
612 :require (A B C) means that only results that contain those
613 tokens will be returned. Thus for instance requiring :secret
614 will ensure that any results will actually have a :secret
615 property.
617 :delete t means to delete any found entries. nil by default.
618 Use `auth-source-delete' in ELisp code instead of calling
619 `auth-source-search' directly with this parameter.
621 :type (X Y Z) will check only those backend types. `netrc' and
622 `secrets' are the only ones supported right now.
624 :max N means to try to return at most N items (defaults to 1).
625 More than N items may be returned, depending on the search and
626 the backend.
628 When :max is 0 the function will return just t or nil to indicate
629 if any matches were found.
631 :host (X Y Z) means to match only hosts X, Y, or Z according to
632 the match rules above. Defaults to t.
634 :user (X Y Z) means to match only users X, Y, or Z according to
635 the match rules above. Defaults to t.
637 :port (P Q R) means to match only protocols P, Q, or R.
638 Defaults to t.
640 :K (V1 V2 V3) for any other key K will match values V1, V2, or
641 V3 (note the match rules above).
643 The return value is a list with at most :max tokens. Each token
644 is a plist with keys :backend :host :port :user, plus any other
645 keys provided by the backend (notably :secret). But note the
646 exception for :max 0, which see above.
648 The token can hold a :save-function key. If you call that, the
649 user will be prompted to save the data to the backend. You can't
650 request that this should happen right after creation, because
651 `auth-source-search' has no way of knowing if the token is
652 actually useful. So the caller must arrange to call this function.
654 The token's :secret key can hold a function. In that case you
655 must call it to obtain the actual value."
656 (let* ((backends (mapcar #'auth-source-backend-parse auth-sources))
657 (max (or max 1))
658 (ignored-keys '(:require :create :delete :max))
659 (keys (cl-loop for i below (length spec) by 2
660 unless (memq (nth i spec) ignored-keys)
661 collect (nth i spec)))
662 (cached (auth-source-remembered-p spec))
663 ;; note that we may have cached results but found is still nil
664 ;; (there were no results from the search)
665 (found (auth-source-recall spec))
666 filtered-backends)
668 (if (and cached auth-source-do-cache)
669 (auth-source-do-debug
670 "auth-source-search: found %d CACHED results matching %S"
671 (length found) spec)
673 (cl-assert
674 (or (eq t create) (listp create)) t
675 "Invalid auth-source :create parameter (must be t or a list): %s %s")
677 (cl-assert
678 (listp require) t
679 "Invalid auth-source :require parameter (must be a list): %s")
681 (setq filtered-backends (copy-sequence backends))
682 (dolist (backend backends)
683 (cl-dolist (key keys)
684 ;; ignore invalid slots
685 (condition-case nil
686 (unless (auth-source-search-collection
687 (plist-get spec key)
688 (slot-value backend key))
689 (setq filtered-backends (delq backend filtered-backends))
690 (cl-return))
691 (invalid-slot-name nil))))
693 (auth-source-do-trivia
694 "auth-source-search: found %d backends matching %S"
695 (length filtered-backends) spec)
697 ;; (debug spec "filtered" filtered-backends)
698 ;; First go through all the backends without :create, so we can
699 ;; query them all.
700 (setq found (auth-source-search-backends filtered-backends
701 spec
702 ;; to exit early
704 ;; create is always nil here
705 nil delete
706 require))
708 (auth-source-do-debug
709 "auth-source-search: found %d results (max %d) matching %S"
710 (length found) max spec)
712 ;; If we didn't find anything, then we allow the backend(s) to
713 ;; create the entries.
714 (when (and create
715 (not found))
716 (setq found (auth-source-search-backends filtered-backends
717 spec
718 ;; to exit early
720 create delete
721 require))
722 (auth-source-do-debug
723 "auth-source-search: CREATED %d results (max %d) matching %S"
724 (length found) max spec))
726 ;; note we remember the lack of result too, if it's applicable
727 (when auth-source-do-cache
728 (auth-source-remember spec found)))
730 (if (zerop max)
731 (not (null found))
732 found)))
734 (defun auth-source-search-backends (backends spec max create delete require)
735 (let ((max (if (zerop max) 1 max)) ; stop with 1 match if we're asked for zero
736 matches)
737 (dolist (backend backends)
738 (when (> max (length matches)) ; if we need more matches...
739 (let* ((bmatches (apply
740 (slot-value backend 'search-function)
741 :backend backend
742 :type (slot-value backend 'type)
743 ;; note we're overriding whatever the spec
744 ;; has for :max, :require, :create, and :delete
745 :max max
746 :require require
747 :create create
748 :delete delete
749 spec)))
750 (when bmatches
751 (auth-source-do-trivia
752 "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
753 (length bmatches) max
754 (slot-value backend 'type)
755 (slot-value backend 'source)
756 spec)
757 (setq matches (append matches bmatches))))))
758 matches))
760 (defun auth-source-delete (&rest spec)
761 "Delete entries from the authentication backends according to SPEC.
762 Calls `auth-source-search' with the :delete property in SPEC set to t.
763 The backend may not actually delete the entries.
765 Returns the deleted entries."
766 (auth-source-search (plist-put spec :delete t)))
768 (defun auth-source-search-collection (collection value)
769 "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
770 (when (and (atom collection) (not (eq t collection)))
771 (setq collection (list collection)))
773 ;; (debug :collection collection :value value)
774 (or (eq collection t)
775 (eq value t)
776 (equal collection value)
777 (member value collection)))
779 (defvar auth-source-netrc-cache nil)
781 (defun auth-source-forget-all-cached ()
782 "Forget all cached auth-source data."
783 (interactive)
784 (maphash (lambda (key _password)
785 (when (eq 'auth-source (car-safe key))
786 ;; remove that key
787 (password-cache-remove key)))
788 password-data)
789 (setq auth-source-netrc-cache nil))
791 (defun auth-source-format-cache-entry (spec)
792 "Format SPEC entry to put it in the password cache."
793 `(auth-source . ,spec))
795 (defun auth-source-remember (spec found)
796 "Remember FOUND search results for SPEC."
797 (let ((password-cache-expiry auth-source-cache-expiry))
798 (password-cache-add
799 (auth-source-format-cache-entry spec) found)))
801 (defun auth-source-recall (spec)
802 "Recall FOUND search results for SPEC."
803 (password-read-from-cache (auth-source-format-cache-entry spec)))
805 (defun auth-source-remembered-p (spec)
806 "Check if SPEC is remembered."
807 (password-in-cache-p
808 (auth-source-format-cache-entry spec)))
810 (defun auth-source-forget (spec)
811 "Forget any cached data matching SPEC exactly.
813 This is the same SPEC you passed to `auth-source-search'.
814 Returns t or nil for forgotten or not found."
815 (password-cache-remove (auth-source-format-cache-entry spec)))
817 (defun auth-source-forget+ (&rest spec)
818 "Forget any cached data matching SPEC. Returns forgotten count.
820 This is not a full `auth-source-search' spec but works similarly.
821 For instance, \(:host \"myhost\" \"yourhost\") would find all the
822 cached data that was found with a search for those two hosts,
823 while \(:host t) would find all host entries."
824 (let ((count 0))
825 (maphash
826 (lambda (key _password)
827 (when (and (eq 'auth-source (car-safe key))
828 ;; and the spec matches what was stored in the cache
829 (auth-source-specmatchp spec (cdr key)))
830 ;; remove that key
831 (password-cache-remove key)
832 (cl-incf count)))
833 password-data)
834 count))
836 (defun auth-source-specmatchp (spec stored)
837 (let ((keys (cl-loop for i below (length spec) by 2
838 collect (nth i spec))))
839 (not (eq
840 (cl-dolist (key keys)
841 (unless (auth-source-search-collection (plist-get stored key)
842 (plist-get spec key))
843 (cl-return 'no)))
844 'no))))
846 (defun auth-source-pick-first-password (&rest spec)
847 "Pick the first secret found from applying SPEC to `auth-source-search'."
848 (let* ((result (nth 0 (apply #'auth-source-search (plist-put spec :max 1))))
849 (secret (plist-get result :secret)))
851 (if (functionp secret)
852 (funcall secret)
853 secret)))
855 (defun auth-source-format-prompt (prompt alist)
856 "Format PROMPT using %x (for any character x) specifiers in ALIST."
857 (dolist (cell alist)
858 (let ((c (nth 0 cell))
859 (v (nth 1 cell)))
860 (when (and c v)
861 (setq prompt (replace-regexp-in-string (format "%%%c" c)
862 (format "%s" v)
863 prompt nil t)))))
864 prompt)
866 (defun auth-source-ensure-strings (values)
867 (if (eq values t)
868 values
869 (unless (listp values)
870 (setq values (list values)))
871 (mapcar (lambda (value)
872 (if (numberp value)
873 (format "%s" value)
874 value))
875 values)))
877 ;;; Backend specific parsing: netrc/authinfo backend
879 (defun auth-source--aput-1 (alist key val)
880 (let ((seen ())
881 (rest alist))
882 (while (and (consp rest) (not (equal key (caar rest))))
883 (push (pop rest) seen))
884 (cons (cons key val)
885 (if (null rest) alist
886 (nconc (nreverse seen)
887 (if (equal key (caar rest)) (cdr rest) rest))))))
888 (defmacro auth-source--aput (var key val)
889 `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
891 (defun auth-source--aget (alist key)
892 (cdr (assoc key alist)))
894 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
895 (cl-defun auth-source-netrc-parse (&key file max host user port require
896 &allow-other-keys)
897 "Parse FILE and return a list of all entries in the file.
898 Note that the MAX parameter is used so we can exit the parse early."
899 (if (listp file)
900 ;; We got already parsed contents; just return it.
901 file
902 (when (file-exists-p file)
903 (setq port (auth-source-ensure-strings port))
904 (with-temp-buffer
905 (let* ((max (or max 5000)) ; sanity check: default to stop at 5K
906 (modified 0)
907 (cached (cdr-safe (assoc file auth-source-netrc-cache)))
908 (cached-mtime (plist-get cached :mtime))
909 (cached-secrets (plist-get cached :secret))
910 (check (lambda(alist)
911 (and alist
912 (auth-source-search-collection
913 host
915 (auth-source--aget alist "machine")
916 (auth-source--aget alist "host")
918 (auth-source-search-collection
919 user
921 (auth-source--aget alist "login")
922 (auth-source--aget alist "account")
923 (auth-source--aget alist "user")
925 (auth-source-search-collection
926 port
928 (auth-source--aget alist "port")
929 (auth-source--aget alist "protocol")
932 ;; the required list of keys is nil, or
933 (null require)
934 ;; every element of require is in n (normalized)
935 (let ((n (nth 0 (auth-source-netrc-normalize
936 (list alist) file))))
937 (cl-loop for req in require
938 always (plist-get n req)))))))
939 result)
941 (if (and (functionp cached-secrets)
942 (equal cached-mtime
943 (nth 5 (file-attributes file))))
944 (progn
945 (auth-source-do-trivia
946 "auth-source-netrc-parse: using CACHED file data for %s"
947 file)
948 (insert (funcall cached-secrets)))
949 (insert-file-contents file)
950 ;; cache all netrc files (used to be just .gpg files)
951 ;; Store the contents of the file heavily encrypted in memory.
952 ;; (note for the irony-impaired: they are just obfuscated)
953 (auth-source--aput
954 auth-source-netrc-cache file
955 (list :mtime (nth 5 (file-attributes file))
956 :secret (let ((v (mapcar #'1+ (buffer-string))))
957 (lambda () (apply #'string (mapcar #'1- v)))))))
958 (goto-char (point-min))
959 (let ((entries (auth-source-netrc-parse-entries check max))
960 alist)
961 (while (setq alist (pop entries))
962 (push (nreverse alist) result)))
964 (when (< 0 modified)
965 (when auth-source-gpg-encrypt-to
966 ;; (see bug#7487) making `epa-file-encrypt-to' local to
967 ;; this buffer lets epa-file skip the key selection query
968 ;; (see the `local-variable-p' check in
969 ;; `epa-file-write-region').
970 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
971 (make-local-variable 'epa-file-encrypt-to))
972 (if (listp auth-source-gpg-encrypt-to)
973 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
975 ;; ask AFTER we've successfully opened the file
976 (when (y-or-n-p (format "Save file %s? (%d deletions)"
977 file modified))
978 (write-region (point-min) (point-max) file nil 'silent)
979 (auth-source-do-debug
980 "auth-source-netrc-parse: modified %d lines in %s"
981 modified file)))
983 (nreverse result))))))
985 (defun auth-source-netrc-parse-next-interesting ()
986 "Advance to the next interesting position in the current buffer."
987 ;; If we're looking at a comment or are at the end of the line, move forward
988 (while (or (looking-at "#")
989 (and (eolp)
990 (not (eobp))))
991 (forward-line 1))
992 (skip-chars-forward "\t "))
994 (defun auth-source-netrc-parse-one ()
995 "Read one thing from the current buffer."
996 (auth-source-netrc-parse-next-interesting)
998 (when (or (looking-at "'\\([^']*\\)'")
999 (looking-at "\"\\([^\"]*\\)\"")
1000 (looking-at "\\([^ \t\n]+\\)"))
1001 (forward-char (length (match-string 0)))
1002 (auth-source-netrc-parse-next-interesting)
1003 (match-string-no-properties 1)))
1005 ;; with thanks to org-mode
1006 (defsubst auth-source-current-line (&optional pos)
1007 (save-excursion
1008 (and pos (goto-char pos))
1009 ;; works also in narrowed buffer, because we start at 1, not point-min
1010 (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1012 (defun auth-source-netrc-parse-entries(check max)
1013 "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1014 (let ((adder (lambda(check alist all)
1015 (when (and
1016 alist
1017 (> max (length all))
1018 (funcall check alist))
1019 (push alist all))
1020 all))
1021 item item2 all alist default)
1022 (while (setq item (auth-source-netrc-parse-one))
1023 (setq default (equal item "default"))
1024 ;; We're starting a new machine. Save the old one.
1025 (when (and alist
1026 (or default
1027 (equal item "machine")))
1028 ;; (auth-source-do-trivia
1029 ;; "auth-source-netrc-parse-entries: got entry %S" alist)
1030 (setq all (funcall adder check alist all)
1031 alist nil))
1032 ;; In default entries, we don't have a next token.
1033 ;; We store them as ("machine" . t)
1034 (if default
1035 (push (cons "machine" t) alist)
1036 ;; Not a default entry. Grab the next item.
1037 (when (setq item2 (auth-source-netrc-parse-one))
1038 ;; Did we get a "machine" value?
1039 (if (equal item2 "machine")
1040 (error
1041 "%s: Unexpected `machine' token at line %d"
1042 "auth-source-netrc-parse-entries"
1043 (auth-source-current-line))
1044 (push (cons item item2) alist)))))
1046 ;; Clean up: if there's an entry left over, use it.
1047 (when alist
1048 (setq all (funcall adder check alist all))
1049 ;; (auth-source-do-trivia
1050 ;; "auth-source-netrc-parse-entries: got2 entry %S" alist)
1052 (nreverse all)))
1054 (defvar auth-source-passphrase-alist nil)
1056 (defun auth-source-token-passphrase-callback-function (_context _key-id file)
1057 (let* ((file (file-truename file))
1058 (entry (assoc file auth-source-passphrase-alist))
1059 passphrase)
1060 ;; return the saved passphrase, calling a function if needed
1061 (or (copy-sequence (if (functionp (cdr entry))
1062 (funcall (cdr entry))
1063 (cdr entry)))
1064 (progn
1065 (unless entry
1066 (setq entry (list file))
1067 (push entry auth-source-passphrase-alist))
1068 (setq passphrase
1069 (read-passwd
1070 (format "Passphrase for %s tokens: " file)
1072 (setcdr entry (let ((p (copy-sequence passphrase)))
1073 (lambda () p)))
1074 passphrase))))
1076 (defun auth-source-epa-extract-gpg-token (secret file)
1077 "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1078 FILE is the file from which we obtained this token."
1079 (when (string-match "^gpg:\\(.+\\)" secret)
1080 (setq secret (base64-decode-string (match-string 1 secret))))
1081 (let ((context (epg-make-context 'OpenPGP)))
1082 (epg-context-set-passphrase-callback
1083 context
1084 (cons #'auth-source-token-passphrase-callback-function
1085 file))
1086 (epg-decrypt-string context secret)))
1088 (defvar pp-escape-newlines)
1090 (defun auth-source-epa-make-gpg-token (secret file)
1091 (let ((context (epg-make-context 'OpenPGP))
1092 (pp-escape-newlines nil)
1093 cipher)
1094 (setf (epg-context-armor context) t)
1095 (epg-context-set-passphrase-callback
1096 context
1097 (cons #'auth-source-token-passphrase-callback-function
1098 file))
1099 (setq cipher (epg-encrypt-string context secret nil))
1100 (with-temp-buffer
1101 (insert cipher)
1102 (base64-encode-region (point-min) (point-max) t)
1103 (concat "gpg:" (buffer-substring-no-properties
1104 (point-min)
1105 (point-max))))))
1107 (defun auth-source--symbol-keyword (symbol)
1108 (intern (format ":%s" symbol)))
1110 (defun auth-source-netrc-normalize (alist filename)
1111 (mapcar (lambda (entry)
1112 (let (ret item)
1113 (while (setq item (pop entry))
1114 (let ((k (car item))
1115 (v (cdr item)))
1117 ;; apply key aliases
1118 (setq k (cond ((member k '("machine")) "host")
1119 ((member k '("login" "account")) "user")
1120 ((member k '("protocol")) "port")
1121 ((member k '("password")) "secret")
1122 (t k)))
1124 ;; send back the secret in a function (lexical binding)
1125 (when (equal k "secret")
1126 (setq v (let ((lexv v)
1127 (token-decoder nil))
1128 (when (string-match "^gpg:" lexv)
1129 ;; it's a GPG token: create a token decoder
1130 ;; which unsets itself once
1131 (setq token-decoder
1132 (lambda (val)
1133 (prog1
1134 (auth-source-epa-extract-gpg-token
1136 filename)
1137 (setq token-decoder nil)))))
1138 (lambda ()
1139 (when token-decoder
1140 (setq lexv (funcall token-decoder lexv)))
1141 lexv))))
1142 (setq ret (plist-put ret
1143 (auth-source--symbol-keyword k)
1144 v))))
1145 ret))
1146 alist))
1148 (cl-defun auth-source-netrc-search (&rest spec
1149 &key backend require create
1150 type max host user port
1151 &allow-other-keys)
1152 "Given a property list SPEC, return search matches from the :backend.
1153 See `auth-source-search' for details on SPEC."
1154 ;; just in case, check that the type is correct (null or same as the backend)
1155 (cl-assert (or (null type) (eq type (oref backend type)))
1156 t "Invalid netrc search: %s %s")
1158 (let ((results (auth-source-netrc-normalize
1159 (auth-source-netrc-parse
1160 :max max
1161 :require require
1162 :file (oref backend source)
1163 :host (or host t)
1164 :user (or user t)
1165 :port (or port t))
1166 (oref backend source))))
1168 ;; if we need to create an entry AND none were found to match
1169 (when (and create
1170 (not results))
1172 ;; create based on the spec and record the value
1173 (setq results (or
1174 ;; if the user did not want to create the entry
1175 ;; in the file, it will be returned
1176 (apply (slot-value backend 'create-function) spec)
1177 ;; if not, we do the search again without :create
1178 ;; to get the updated data.
1180 ;; the result will be returned, even if the search fails
1181 (apply #'auth-source-netrc-search
1182 (plist-put spec :create nil)))))
1183 results))
1185 (defun auth-source-netrc-element-or-first (v)
1186 (if (listp v)
1187 (nth 0 v)
1190 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1191 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1193 (cl-defun auth-source-netrc-create (&rest spec
1194 &key backend host port create
1195 &allow-other-keys)
1196 (let* ((base-required '(host user port secret))
1197 ;; we know (because of an assertion in auth-source-search) that the
1198 ;; :create parameter is either t or a list (which includes nil)
1199 (create-extra (if (eq t create) nil create))
1200 (current-data (car (auth-source-search :max 1
1201 :host host
1202 :port port)))
1203 (required (append base-required create-extra))
1204 (file (oref backend source))
1205 (add "")
1206 ;; `valist' is an alist
1207 valist
1208 ;; `artificial' will be returned if no creation is needed
1209 artificial)
1211 ;; only for base required elements (defined as function parameters):
1212 ;; fill in the valist with whatever data we may have from the search
1213 ;; we complete the first value if it's a list and use the value otherwise
1214 (dolist (br base-required)
1215 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1216 (when val
1217 (let ((br-choice (cond
1218 ;; all-accepting choice (predicate is t)
1219 ((eq t val) nil)
1220 ;; just the value otherwise
1221 (t val))))
1222 (when br-choice
1223 (auth-source--aput valist br br-choice))))))
1225 ;; for extra required elements, see if the spec includes a value for them
1226 (dolist (er create-extra)
1227 (let ((k (auth-source--symbol-keyword er))
1228 (keys (cl-loop for i below (length spec) by 2
1229 collect (nth i spec))))
1230 (when (memq k keys)
1231 (auth-source--aput valist er (plist-get spec k)))))
1233 ;; for each required element
1234 (dolist (r required)
1235 (let* ((data (auth-source--aget valist r))
1236 ;; take the first element if the data is a list
1237 (data (or (auth-source-netrc-element-or-first data)
1238 (plist-get current-data
1239 (auth-source--symbol-keyword r))))
1240 ;; this is the default to be offered
1241 (given-default (auth-source--aget
1242 auth-source-creation-defaults r))
1243 ;; the default supplementals are simple:
1244 ;; for the user, try `given-default' and then (user-login-name);
1245 ;; otherwise take `given-default'
1246 (default (cond
1247 ((and (not given-default) (eq r 'user))
1248 (user-login-name))
1249 (t given-default)))
1250 (printable-defaults (list
1251 (cons 'user
1253 (auth-source-netrc-element-or-first
1254 (auth-source--aget valist 'user))
1255 (plist-get artificial :user)
1256 "[any user]"))
1257 (cons 'host
1259 (auth-source-netrc-element-or-first
1260 (auth-source--aget valist 'host))
1261 (plist-get artificial :host)
1262 "[any host]"))
1263 (cons 'port
1265 (auth-source-netrc-element-or-first
1266 (auth-source--aget valist 'port))
1267 (plist-get artificial :port)
1268 "[any port]"))))
1269 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1270 (cl-case r
1271 (secret "%p password for %u@%h: ")
1272 (user "%p user name for %h: ")
1273 (host "%p host name for user %u: ")
1274 (port "%p port for %u@%h: "))
1275 (format "Enter %s (%%u@%%h:%%p): " r)))
1276 (prompt (auth-source-format-prompt
1277 prompt
1278 `((?u ,(auth-source--aget printable-defaults 'user))
1279 (?h ,(auth-source--aget printable-defaults 'host))
1280 (?p ,(auth-source--aget printable-defaults 'port))))))
1282 ;; Store the data, prompting for the password if needed.
1283 (setq data (or data
1284 (if (eq r 'secret)
1285 ;; Special case prompt for passwords.
1286 ;; 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)))
1287 ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1288 (let* ((ep (format "Use GPG password tokens in %s?" file))
1289 (gpg-encrypt
1290 (cond
1291 ((eq auth-source-netrc-use-gpg-tokens 'never)
1292 'never)
1293 ((listp auth-source-netrc-use-gpg-tokens)
1294 (let ((check (copy-sequence
1295 auth-source-netrc-use-gpg-tokens))
1296 item ret)
1297 (while check
1298 (setq item (pop check))
1299 (when (or (eq (car item) t)
1300 (string-match (car item) file))
1301 (setq ret (cdr item))
1302 (setq check nil)))
1303 ;; FIXME: `ret' unused.
1304 ;; Should we return it here?
1306 (t 'never)))
1307 (plain (or (eval default) (read-passwd prompt))))
1308 ;; ask if we don't know what to do (in which case
1309 ;; auth-source-netrc-use-gpg-tokens must be a list)
1310 (unless gpg-encrypt
1311 (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1312 ;; TODO: save the defcustom now? or ask?
1313 (setq auth-source-netrc-use-gpg-tokens
1314 (cons `(,file ,gpg-encrypt)
1315 auth-source-netrc-use-gpg-tokens)))
1316 (if (eq gpg-encrypt 'gpg)
1317 (auth-source-epa-make-gpg-token plain file)
1318 plain))
1319 (if (stringp default)
1320 (read-string (if (string-match ": *\\'" prompt)
1321 (concat (substring prompt 0 (match-beginning 0))
1322 " (default " default "): ")
1323 (concat prompt "(default " default ") "))
1324 nil nil default)
1325 (eval default)))))
1327 (when data
1328 (setq artificial (plist-put artificial
1329 (auth-source--symbol-keyword r)
1330 (if (eq r 'secret)
1331 (let ((data data))
1332 (lambda () data))
1333 data))))
1335 ;; When r is not an empty string...
1336 (when (and (stringp data)
1337 (< 0 (length data)))
1338 ;; this function is not strictly necessary but I think it
1339 ;; makes the code clearer -tzz
1340 (let ((printer (lambda ()
1341 ;; append the key (the symbol name of r)
1342 ;; and the value in r
1343 (format "%s%s %s"
1344 ;; prepend a space
1345 (if (zerop (length add)) "" " ")
1346 ;; remap auth-source tokens to netrc
1347 (cl-case r
1348 (user "login")
1349 (host "machine")
1350 (secret "password")
1351 (port "port") ; redundant but clearer
1352 (t (symbol-name r)))
1353 (if (string-match "[\"# ]" data)
1354 (format "%S" data)
1355 data)))))
1356 (setq add (concat add (funcall printer)))))))
1358 (plist-put
1359 artificial
1360 :save-function
1361 (let ((file file)
1362 (add add))
1363 (lambda () (auth-source-netrc-saver file add))))
1365 (list artificial)))
1367 (defun auth-source-netrc-saver (file add)
1368 "Save a line ADD in FILE, prompting along the way.
1369 Respects `auth-source-save-behavior'. Uses
1370 `auth-source-netrc-cache' to avoid prompting more than once."
1371 (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1372 (cached (assoc key auth-source-netrc-cache)))
1374 (if cached
1375 (auth-source-do-trivia
1376 "auth-source-netrc-saver: found previous run for key %s, returning"
1377 key)
1378 (with-temp-buffer
1379 (when (file-exists-p file)
1380 (insert-file-contents file))
1381 (when auth-source-gpg-encrypt-to
1382 ;; (see bug#7487) making `epa-file-encrypt-to' local to
1383 ;; this buffer lets epa-file skip the key selection query
1384 ;; (see the `local-variable-p' check in
1385 ;; `epa-file-write-region').
1386 (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1387 (make-local-variable 'epa-file-encrypt-to))
1388 (if (listp auth-source-gpg-encrypt-to)
1389 (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1390 ;; we want the new data to be found first, so insert at beginning
1391 (goto-char (point-min))
1393 ;; Ask AFTER we've successfully opened the file.
1394 (let ((prompt (format "Save auth info to file %s? " file))
1395 (done (not (eq auth-source-save-behavior 'ask)))
1396 (bufname "*auth-source Help*")
1398 (while (not done)
1399 (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1400 (cl-case k
1401 (?y (setq done t))
1402 (?? (save-excursion
1403 (with-output-to-temp-buffer bufname
1404 (princ
1405 (concat "(y)es, save\n"
1406 "(n)o but use the info\n"
1407 "(N)o and don't ask to save again\n"
1408 "(e)dit the line\n"
1409 "(?) for help as you can see.\n"))
1410 ;; Why? Doesn't with-output-to-temp-buffer already do
1411 ;; the exact same thing anyway? --Stef
1412 (set-buffer standard-output)
1413 (help-mode))))
1414 (?n (setq add ""
1415 done t))
1417 (setq add ""
1418 done t)
1419 (customize-save-variable 'auth-source-save-behavior nil))
1420 (?e (setq add (read-string "Line to add: " add)))
1421 (t nil)))
1423 (when (get-buffer-window bufname)
1424 (delete-window (get-buffer-window bufname)))
1426 ;; Make sure the info is not saved.
1427 (when (null auth-source-save-behavior)
1428 (setq add ""))
1430 (when (< 0 (length add))
1431 (progn
1432 (unless (bolp)
1433 (insert "\n"))
1434 (insert add "\n")
1435 (write-region (point-min) (point-max) file nil 'silent)
1436 ;; Make the .authinfo file non-world-readable.
1437 (set-file-modes file #o600)
1438 (auth-source-do-debug
1439 "auth-source-netrc-create: wrote 1 new line to %s"
1440 file)
1441 (message "Saved new authentication information to %s" file)
1442 nil))))
1443 (auth-source--aput auth-source-netrc-cache key "ran"))))
1445 ;;; Backend specific parsing: Secrets API backend
1447 (defun auth-source-secrets-listify-pattern (pattern)
1448 "Convert a pattern with lists to a list of string patterns.
1450 auth-source patterns can have values of the form :foo (\"bar\"
1451 \"qux\"), which means to match any secret with :foo equal to
1452 \"bar\" or :foo equal to \"qux\". The secrets backend supports
1453 only string values for patterns, so this routine returns a list
1454 of patterns that is equivalent to the single original pattern
1455 when interpreted such that if a secret matches any pattern in the
1456 list, it matches the original pattern."
1457 (if (null pattern)
1458 '(nil)
1459 (let* ((key (pop pattern))
1460 (value (pop pattern))
1461 (tails (auth-source-secrets-listify-pattern pattern))
1462 (heads (if (stringp value)
1463 (list (list key value))
1464 (mapcar (lambda (v) (list key v)) value))))
1465 (cl-loop for h in heads
1466 nconc (cl-loop for tl in tails collect (append h tl))))))
1468 (cl-defun auth-source-secrets-search (&rest spec
1469 &key backend create delete label max
1470 &allow-other-keys)
1471 "Search the Secrets API; spec is like `auth-source'.
1473 The :label key specifies the item's label. It is the only key
1474 that can specify a substring. Any :label value besides a string
1475 will allow any label.
1477 All other search keys must match exactly. If you need substring
1478 matching, do a wider search and narrow it down yourself.
1480 You'll get back all the properties of the token as a plist.
1482 Here's an example that looks for the first item in the `Login'
1483 Secrets collection:
1485 (let ((auth-sources \\='(\"secrets:Login\")))
1486 (auth-source-search :max 1)
1488 Here's another that looks for the first item in the `Login'
1489 Secrets collection whose label contains `gnus':
1491 (let ((auth-sources \\='(\"secrets:Login\")))
1492 (auth-source-search :max 1 :label \"gnus\")
1494 And this one looks for the first item in the `Login' Secrets
1495 collection that's a Google Chrome entry for the git.gnus.org site
1496 authentication tokens:
1498 (let ((auth-sources \\='(\"secrets:Login\")))
1499 (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1502 ;; TODO
1503 (cl-assert (not create) nil
1504 "The Secrets API auth-source backend doesn't support creation yet")
1505 ;; TODO
1506 ;; (secrets-delete-item coll elt)
1507 (cl-assert (not delete) nil
1508 "The Secrets API auth-source backend doesn't support deletion yet")
1510 (let* ((coll (oref backend source))
1511 (max (or max 5000)) ; sanity check: default to stop at 5K
1512 (ignored-keys '(:create :delete :max :backend :label :require :type))
1513 (search-keys (cl-loop for i below (length spec) by 2
1514 unless (memq (nth i spec) ignored-keys)
1515 collect (nth i spec)))
1516 ;; build a search spec without the ignored keys
1517 ;; if a search key is nil or t (match anything), we skip it
1518 (search-specs (auth-source-secrets-listify-pattern
1519 (apply #'append (mapcar
1520 (lambda (k)
1521 (if (or (null (plist-get spec k))
1522 (eq t (plist-get spec k)))
1524 (list k (plist-get spec k))))
1525 search-keys))))
1526 ;; needed keys (always including host, login, port, and secret)
1527 (returned-keys (delete-dups (append
1528 '(:host :login :port :secret)
1529 search-keys)))
1530 (items
1531 (cl-loop
1532 for search-spec in search-specs
1533 nconc
1534 (cl-loop for item in (apply #'secrets-search-items coll search-spec)
1535 unless (and (stringp label)
1536 (not (string-match label item)))
1537 collect item)))
1538 ;; TODO: respect max in `secrets-search-items', not after the fact
1539 (items (butlast items (- (length items) max)))
1540 ;; convert the item name to a full plist
1541 (items (mapcar (lambda (item)
1542 (append
1543 ;; make an entry for the secret (password) element
1544 (list
1545 :secret
1546 (let ((v (secrets-get-secret coll item)))
1547 (lambda () v)))
1548 ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1549 (apply #'append
1550 (mapcar (lambda (entry)
1551 (list (car entry) (cdr entry)))
1552 (secrets-get-attributes coll item)))))
1553 items))
1554 ;; ensure each item has each key in `returned-keys'
1555 (items (mapcar (lambda (plist)
1556 (append
1557 (apply #'append
1558 (mapcar (lambda (req)
1559 (if (plist-get plist req)
1561 (list req nil)))
1562 returned-keys))
1563 plist))
1564 items)))
1565 items))
1567 (defun auth-source-secrets-create (&rest spec)
1568 ;; TODO
1569 ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1570 (debug spec))
1572 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1574 (cl-defun auth-source-macos-keychain-search (&rest spec
1575 &key backend create delete type max
1576 &allow-other-keys)
1577 "Search the macOS Keychain; spec is like `auth-source'.
1579 All search keys must match exactly. If you need substring
1580 matching, do a wider search and narrow it down yourself.
1582 You'll get back all the properties of the token as a plist.
1584 The :type key is either `macos-keychain-internet' or
1585 `macos-keychain-generic'.
1587 For the internet keychain type, the :label key searches the
1588 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1589 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1590 and :port maps to \"-P PORT\" or \"-r PROT\"
1591 \(note PROT has to be a 4-character string).
1593 For the generic keychain type, the :label key searches the item's
1594 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1595 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1596 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1598 Here's an example that looks for the first item in the default
1599 generic macOS Keychain:
1601 (let ((auth-sources \\='(macos-keychain-generic)))
1602 (auth-source-search :max 1)
1604 Here's another that looks for the first item in the internet
1605 macOS Keychain collection whose label is `gnus':
1607 (let ((auth-sources \\='(macos-keychain-internet)))
1608 (auth-source-search :max 1 :label \"gnus\")
1610 And this one looks for the first item in the internet keychain
1611 entries for git.gnus.org:
1613 (let ((auth-sources \\='(macos-keychain-internet\")))
1614 (auth-source-search :max 1 :host \"git.gnus.org\"))
1616 ;; TODO
1617 (cl-assert (not create) nil
1618 "The macOS Keychain auth-source backend doesn't support creation yet")
1619 ;; TODO
1620 ;; (macos-keychain-delete-item coll elt)
1621 (cl-assert (not delete) nil
1622 "The macOS Keychain auth-source backend doesn't support deletion yet")
1624 (let* ((coll (oref backend source))
1625 (max (or max 5000)) ; sanity check: default to stop at 5K
1626 ;; Filter out ignored keys from the spec
1627 (ignored-keys '(:create :delete :max :backend :label :host :port))
1628 ;; Build a search spec without the ignored keys
1629 ;; FIXME make this loop a function? it's used in at least 3 places
1630 (search-keys (cl-loop for i below (length spec) by 2
1631 unless (memq (nth i spec) ignored-keys)
1632 collect (nth i spec)))
1633 ;; If a search key value is nil or t (match anything), we skip it
1634 (search-spec (apply #'append (mapcar
1635 (lambda (k)
1636 (if (or (null (plist-get spec k))
1637 (eq t (plist-get spec k)))
1639 (list k (plist-get spec k))))
1640 search-keys)))
1641 ;; needed keys (always including host, login, port, and secret)
1642 (returned-keys (delete-dups (append
1643 '(:host :login :port :secret)
1644 search-keys)))
1645 ;; Extract host and port from spec
1646 (hosts (plist-get spec :host))
1647 (hosts (if (and hosts (listp hosts)) hosts `(,hosts)))
1648 (ports (plist-get spec :port))
1649 (ports (if (and ports (listp ports)) ports `(,ports)))
1650 ;; Loop through all combinations of host/port and pass each of these to
1651 ;; auth-source-macos-keychain-search-items
1652 (items (catch 'match
1653 (dolist (host hosts)
1654 (dolist (port ports)
1655 (let* ((port (if port (format "%S" port)))
1656 (items (apply #'auth-source-macos-keychain-search-items
1657 coll
1658 type
1660 host port
1661 search-spec)))
1662 (when items
1663 (throw 'match items)))))))
1665 ;; ensure each item has each key in `returned-keys'
1666 (items (mapcar (lambda (plist)
1667 (append
1668 (apply #'append
1669 (mapcar (lambda (req)
1670 (if (plist-get plist req)
1672 (list req nil)))
1673 returned-keys))
1674 plist))
1675 items)))
1676 items))
1679 (defun auth-source--decode-octal-string (string)
1680 "Convert octal string to utf-8 string. E.g: 'a\134b' to 'a\b'"
1681 (let ((list (string-to-list string))
1682 (size (length string)))
1683 (decode-coding-string
1684 (apply #'unibyte-string
1685 (cl-loop for i = 0 then (+ i (if (eq (nth i list) ?\\) 4 1))
1686 for var = (nth i list)
1687 while (< i size)
1688 if (eq var ?\\)
1689 collect (string-to-number
1690 (concat (cl-subseq list (+ i 1) (+ i 4))) 8)
1691 else
1692 collect var))
1693 'utf-8)))
1695 (cl-defun auth-source-macos-keychain-search-items (coll _type _max host port
1696 &key label type user
1697 &allow-other-keys)
1698 (let* ((keychain-generic (eq type 'macos-keychain-generic))
1699 (args `(,(if keychain-generic
1700 "find-generic-password"
1701 "find-internet-password")
1702 "-g"))
1703 (ret (list :type type)))
1704 (when label
1705 (setq args (append args (list "-l" label))))
1706 (when host
1707 (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1708 (when user
1709 (setq args (append args (list "-a" user))))
1711 (when port
1712 (if keychain-generic
1713 (setq args (append args (list "-s" port)))
1714 (setq args (append args (list
1715 (if (string-match "[0-9]+" port) "-P" "-r")
1716 port)))))
1718 (unless (equal coll "default")
1719 (setq args (append args (list coll))))
1721 (with-temp-buffer
1722 (apply #'call-process "/usr/bin/security" nil t nil args)
1723 (goto-char (point-min))
1724 (while (not (eobp))
1725 (cond
1726 ((looking-at "^password: \\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1727 (setq ret (auth-source-macos-keychain-result-append
1729 keychain-generic
1730 "secret"
1731 (let ((v (auth-source--decode-octal-string
1732 (match-string 1))))
1733 (lambda () v)))))
1734 ;; TODO: check if this is really the label
1735 ;; match 0x00000007 <blob>="AppleID"
1736 ((looking-at
1737 "^[ ]+0x00000007 <blob>=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1738 (setq ret (auth-source-macos-keychain-result-append
1740 keychain-generic
1741 "label"
1742 (auth-source--decode-octal-string (match-string 1)))))
1743 ;; match "crtr"<uint32>="aapl"
1744 ;; match "svce"<blob>="AppleID"
1745 ((looking-at
1746 "^[ ]+\"\\([a-z]+\\)\"[^=]+=\\(?:0x[0-9A-F]+\\)? *\"\\(.+\\)\"")
1747 (setq ret (auth-source-macos-keychain-result-append
1749 keychain-generic
1750 (auth-source--decode-octal-string (match-string 1))
1751 (auth-source--decode-octal-string (match-string 2))))))
1752 (forward-line)))
1753 ;; return `ret' iff it has the :secret key
1754 (and (plist-get ret :secret) (list ret))))
1756 (defun auth-source-macos-keychain-result-append (result generic k v)
1757 (push v result)
1758 (push (auth-source--symbol-keyword
1759 (cond
1760 ((equal k "acct") "user")
1761 ;; for generic keychains, creator is host, service is port
1762 ((and generic (equal k "crtr")) "host")
1763 ((and generic (equal k "svce")) "port")
1764 ;; for internet keychains, protocol is port, server is host
1765 ((and (not generic) (equal k "ptcl")) "port")
1766 ((and (not generic) (equal k "srvr")) "host")
1767 (t k)))
1768 result))
1770 (defun auth-source-macos-keychain-create (&rest spec)
1771 ;; TODO
1772 (debug spec))
1774 ;;; Backend specific parsing: PLSTORE backend
1776 (cl-defun auth-source-plstore-search (&rest spec
1777 &key backend create delete max
1778 &allow-other-keys)
1779 "Search the PLSTORE; spec is like `auth-source'."
1780 (let* ((store (oref backend data))
1781 (max (or max 5000)) ; sanity check: default to stop at 5K
1782 (ignored-keys '(:create :delete :max :backend :label :require :type))
1783 (search-keys (cl-loop for i below (length spec) by 2
1784 unless (memq (nth i spec) ignored-keys)
1785 collect (nth i spec)))
1786 ;; build a search spec without the ignored keys
1787 ;; if a search key is nil or t (match anything), we skip it
1788 (search-spec (apply #'append (mapcar
1789 (lambda (k)
1790 (let ((v (plist-get spec k)))
1791 (if (or (null v)
1792 (eq t v))
1794 (if (stringp v)
1795 (setq v (list v)))
1796 (list k v))))
1797 search-keys)))
1798 ;; needed keys (always including host, login, port, and secret)
1799 (returned-keys (delete-dups (append
1800 '(:host :login :port :secret)
1801 search-keys)))
1802 (items (plstore-find store search-spec))
1803 (item-names (mapcar #'car items))
1804 (items (butlast items (- (length items) max)))
1805 ;; convert the item to a full plist
1806 (items (mapcar (lambda (item)
1807 (let* ((plist (copy-tree (cdr item)))
1808 (secret (plist-member plist :secret)))
1809 (if secret
1810 (setcar
1811 (cdr secret)
1812 (let ((v (car (cdr secret))))
1813 (lambda () v))))
1814 plist))
1815 items))
1816 ;; ensure each item has each key in `returned-keys'
1817 (items (mapcar (lambda (plist)
1818 (append
1819 (apply #'append
1820 (mapcar (lambda (req)
1821 (if (plist-get plist req)
1823 (list req nil)))
1824 returned-keys))
1825 plist))
1826 items)))
1827 (cond
1828 ;; if we need to create an entry AND none were found to match
1829 ((and create
1830 (not items))
1832 ;; create based on the spec and record the value
1833 (setq items (or
1834 ;; if the user did not want to create the entry
1835 ;; in the file, it will be returned
1836 (apply (slot-value backend 'create-function) spec)
1837 ;; if not, we do the search again without :create
1838 ;; to get the updated data.
1840 ;; the result will be returned, even if the search fails
1841 (apply #'auth-source-plstore-search
1842 (plist-put spec :create nil)))))
1843 ((and delete
1844 item-names)
1845 (dolist (item-name item-names)
1846 (plstore-delete store item-name))
1847 (plstore-save store)))
1848 items))
1850 (cl-defun auth-source-plstore-create (&rest spec
1851 &key backend host port create
1852 &allow-other-keys)
1853 (let* ((base-required '(host user port secret))
1854 (base-secret '(secret))
1855 ;; we know (because of an assertion in auth-source-search) that the
1856 ;; :create parameter is either t or a list (which includes nil)
1857 (create-extra (if (eq t create) nil create))
1858 (current-data (car (auth-source-search :max 1
1859 :host host
1860 :port port)))
1861 (required (append base-required create-extra))
1862 ;; `valist' is an alist
1863 valist
1864 ;; `artificial' will be returned if no creation is needed
1865 artificial
1866 secret-artificial)
1868 ;; only for base required elements (defined as function parameters):
1869 ;; fill in the valist with whatever data we may have from the search
1870 ;; we complete the first value if it's a list and use the value otherwise
1871 (dolist (br base-required)
1872 (let ((val (plist-get spec (auth-source--symbol-keyword br))))
1873 (when val
1874 (let ((br-choice (cond
1875 ;; all-accepting choice (predicate is t)
1876 ((eq t val) nil)
1877 ;; just the value otherwise
1878 (t val))))
1879 (when br-choice
1880 (auth-source--aput valist br br-choice))))))
1882 ;; for extra required elements, see if the spec includes a value for them
1883 (dolist (er create-extra)
1884 (let ((k (auth-source--symbol-keyword er))
1885 (keys (cl-loop for i below (length spec) by 2
1886 collect (nth i spec))))
1887 (when (memq k keys)
1888 (auth-source--aput valist er (plist-get spec k)))))
1890 ;; for each required element
1891 (dolist (r required)
1892 (let* ((data (auth-source--aget valist r))
1893 ;; take the first element if the data is a list
1894 (data (or (auth-source-netrc-element-or-first data)
1895 (plist-get current-data
1896 (auth-source--symbol-keyword r))))
1897 ;; this is the default to be offered
1898 (given-default (auth-source--aget
1899 auth-source-creation-defaults r))
1900 ;; the default supplementals are simple:
1901 ;; for the user, try `given-default' and then (user-login-name);
1902 ;; otherwise take `given-default'
1903 (default (cond
1904 ((and (not given-default) (eq r 'user))
1905 (user-login-name))
1906 (t given-default)))
1907 (printable-defaults (list
1908 (cons 'user
1910 (auth-source-netrc-element-or-first
1911 (auth-source--aget valist 'user))
1912 (plist-get artificial :user)
1913 "[any user]"))
1914 (cons 'host
1916 (auth-source-netrc-element-or-first
1917 (auth-source--aget valist 'host))
1918 (plist-get artificial :host)
1919 "[any host]"))
1920 (cons 'port
1922 (auth-source-netrc-element-or-first
1923 (auth-source--aget valist 'port))
1924 (plist-get artificial :port)
1925 "[any port]"))))
1926 (prompt (or (auth-source--aget auth-source-creation-prompts r)
1927 (cl-case r
1928 (secret "%p password for %u@%h: ")
1929 (user "%p user name for %h: ")
1930 (host "%p host name for user %u: ")
1931 (port "%p port for %u@%h: "))
1932 (format "Enter %s (%%u@%%h:%%p): " r)))
1933 (prompt (auth-source-format-prompt
1934 prompt
1935 `((?u ,(auth-source--aget printable-defaults 'user))
1936 (?h ,(auth-source--aget printable-defaults 'host))
1937 (?p ,(auth-source--aget printable-defaults 'port))))))
1939 ;; Store the data, prompting for the password if needed.
1940 (setq data (or data
1941 (if (eq r 'secret)
1942 (or (eval default) (read-passwd prompt))
1943 (if (stringp default)
1944 (read-string
1945 (if (string-match ": *\\'" prompt)
1946 (concat (substring prompt 0 (match-beginning 0))
1947 " (default " default "): ")
1948 (concat prompt "(default " default ") "))
1949 nil nil default)
1950 (eval default)))))
1952 (when data
1953 (if (member r base-secret)
1954 (setq secret-artificial
1955 (plist-put secret-artificial
1956 (auth-source--symbol-keyword r)
1957 data))
1958 (setq artificial (plist-put artificial
1959 (auth-source--symbol-keyword r)
1960 data))))))
1961 (plstore-put (oref backend data)
1962 (sha1 (format "%s@%s:%s"
1963 (plist-get artificial :user)
1964 (plist-get artificial :host)
1965 (plist-get artificial :port)))
1966 artificial secret-artificial)
1967 (if (y-or-n-p (format "Save auth info to file %s? "
1968 (plstore-get-file (oref backend data))))
1969 (plstore-save (oref backend data)))))
1971 ;;; older API
1973 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1975 ;; deprecate the old interface
1976 (make-obsolete 'auth-source-user-or-password
1977 'auth-source-search "Emacs 24.1")
1978 (make-obsolete 'auth-source-forget-user-or-password
1979 'auth-source-forget "Emacs 24.1")
1981 (defun auth-source-user-or-password
1982 (mode host port &optional username create-missing delete-existing)
1983 "Find MODE (string or list of strings) matching HOST and PORT.
1985 DEPRECATED in favor of `auth-source-search'!
1987 USERNAME is optional and will be used as \"login\" in a search
1988 across the Secret Service API (see secrets.el) if the resulting
1989 items don't have a username. This means that if you search for
1990 username \"joe\" and it matches an item but the item doesn't have
1991 a :user attribute, the username \"joe\" will be returned.
1993 A non nil DELETE-EXISTING means deleting any matching password
1994 entry in the respective sources. This is useful only when
1995 CREATE-MISSING is non nil as well; the intended use case is to
1996 remove wrong password entries.
1998 If no matching entry is found, and CREATE-MISSING is non nil,
1999 the password will be retrieved interactively, and it will be
2000 stored in the password database which matches best (see
2001 `auth-sources').
2003 MODE can be \"login\" or \"password\"."
2004 (auth-source-do-debug
2005 "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2006 mode host port username)
2008 (let* ((listy (listp mode))
2009 (mode (if listy mode (list mode)))
2010 ;; (cname (if username
2011 ;; (format "%s %s:%s %s" mode host port username)
2012 ;; (format "%s %s:%s" mode host port)))
2013 (search (list :host host :port port))
2014 (search (if username (append search (list :user username)) search))
2015 (search (if create-missing
2016 (append search (list :create t))
2017 search))
2018 (search (if delete-existing
2019 (append search (list :delete t))
2020 search))
2021 ;; (found (if (not delete-existing)
2022 ;; (gethash cname auth-source-cache)
2023 ;; (remhash cname auth-source-cache)
2024 ;; nil)))
2025 (found nil))
2026 (if found
2027 (progn
2028 (auth-source-do-debug
2029 "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2030 mode
2031 ;; don't show the password
2032 (if (and (member "password" mode) t)
2033 "SECRET"
2034 found)
2035 host port username)
2036 found) ; return the found data
2037 ;; else, if not found, search with a max of 1
2038 (let ((choice (nth 0 (apply #'auth-source-search
2039 (append '(:max 1) search)))))
2040 (when choice
2041 (dolist (m mode)
2042 (cond
2043 ((equal "password" m)
2044 (push (if (plist-get choice :secret)
2045 (funcall (plist-get choice :secret))
2046 nil) found))
2047 ((equal "login" m)
2048 (push (plist-get choice :user) found)))))
2049 (setq found (nreverse found))
2050 (setq found (if listy found (car-safe found)))))
2052 found))
2054 (defun auth-source-user-and-password (host &optional user)
2055 (let* ((auth-info (car
2056 (if user
2057 (auth-source-search
2058 :host host
2059 :user user
2060 :max 1
2061 :require '(:user :secret)
2062 :create nil)
2063 (auth-source-search
2064 :host host
2065 :max 1
2066 :require '(:user :secret)
2067 :create nil))))
2068 (user (plist-get auth-info :user))
2069 (password (plist-get auth-info :secret)))
2070 (when (functionp password)
2071 (setq password (funcall password)))
2072 (list user password auth-info)))
2074 (provide 'auth-source)
2076 ;;; auth-source.el ends here