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