Fix default prompt and repeated saver query bugs.
[gnus] / lisp / auth-source.el
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
2
3 ;; Copyright (C) 2008-2011 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 (require 'assoc)
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 (defvar secrets-enabled)
70
71 (defgroup auth-source nil
72   "Authentication sources."
73   :version "23.1" ;; No Gnus
74   :group 'gnus)
75
76 ;;;###autoload
77 (defcustom auth-source-cache-expiry 7200
78   "How many seconds passwords are cached, or nil to disable
79 expiring.  Overrides `password-cache-expiry' through a
80 let-binding."
81   :group 'auth-source
82   :type '(choice (const :tag "Never" nil)
83                  (const :tag "All Day" 86400)
84                  (const :tag "2 Hours" 7200)
85                  (const :tag "30 Minutes" 1800)
86                  (integer :tag "Seconds")))
87
88 (defclass auth-source-backend ()
89   ((type :initarg :type
90          :initform 'netrc
91          :type symbol
92          :custom symbol
93          :documentation "The backend type.")
94    (source :initarg :source
95            :type string
96            :custom string
97            :documentation "The backend source.")
98    (host :initarg :host
99          :initform t
100          :type t
101          :custom string
102          :documentation "The backend host.")
103    (user :initarg :user
104          :initform t
105          :type t
106          :custom string
107          :documentation "The backend user.")
108    (port :initarg :port
109          :initform t
110          :type t
111          :custom string
112          :documentation "The backend protocol.")
113    (create-function :initarg :create-function
114                     :initform ignore
115                     :type function
116                     :custom function
117                     :documentation "The create function.")
118    (search-function :initarg :search-function
119                     :initform ignore
120                     :type function
121                     :custom function
122                     :documentation "The search function.")))
123
124 (defcustom auth-source-protocols '((imap "imap" "imaps" "143" "993")
125                                    (pop3 "pop3" "pop" "pop3s" "110" "995")
126                                    (ssh  "ssh" "22")
127                                    (sftp "sftp" "115")
128                                    (smtp "smtp" "25"))
129   "List of authentication protocols and their names"
130
131   :group 'auth-source
132   :version "23.2" ;; No Gnus
133   :type '(repeat :tag "Authentication Protocols"
134                  (cons :tag "Protocol Entry"
135                        (symbol :tag "Protocol")
136                        (repeat :tag "Names"
137                                (string :tag "Name")))))
138
139 ;;; generate all the protocols in a format Customize can use
140 ;;; TODO: generate on the fly from auth-source-protocols
141 (defconst auth-source-protocols-customize
142   (mapcar (lambda (a)
143             (let ((p (car-safe a)))
144               (list 'const
145                     :tag (upcase (symbol-name p))
146                     p)))
147           auth-source-protocols))
148
149 (defvar auth-source-creation-defaults nil
150   "Defaults for creating token values.  Usually let-bound.")
151
152 (defvar auth-source-creation-prompts nil
153   "Default prompts for token values.  Usually let-bound.")
154
155 (make-obsolete 'auth-source-hide-passwords nil "Emacs 24.1")
156
157 (defcustom auth-source-save-behavior 'ask
158   "If set, auth-source will respect it for save behavior."
159   :group 'auth-source
160   :version "23.2" ;; No Gnus
161   :type `(choice
162           :tag "auth-source new token save behavior"
163           (const :tag "Always save" t)
164           (const :tag "Never save" nil)
165           (const :tag "Ask" ask)))
166
167 (defvar auth-source-magic "auth-source-magic ")
168
169 (defcustom auth-source-do-cache t
170   "Whether auth-source should cache information with `password-cache'."
171   :group 'auth-source
172   :version "23.2" ;; No Gnus
173   :type `boolean)
174
175 (defcustom auth-source-debug nil
176   "Whether auth-source should log debug messages.
177
178 If the value is nil, debug messages are not logged.
179
180 If the value is t, debug messages are logged with `message'.  In
181 that case, your authentication data will be in the clear (except
182 for passwords).
183
184 If the value is a function, debug messages are logged by calling
185  that function using the same arguments as `message'."
186   :group 'auth-source
187   :version "23.2" ;; No Gnus
188   :type `(choice
189           :tag "auth-source debugging mode"
190           (const :tag "Log using `message' to the *Messages* buffer" t)
191           (const :tag "Log all trivia with `message' to the *Messages* buffer"
192                  trivia)
193           (function :tag "Function that takes arguments like `message'")
194           (const :tag "Don't log anything" nil)))
195
196 (defcustom auth-sources '("~/.authinfo.gpg" "~/.authinfo" "~/.netrc")
197   "List of authentication sources.
198
199 The default will get login and password information from
200 \"~/.authinfo.gpg\", which you should set up with the EPA/EPG
201 packages to be encrypted.  If that file doesn't exist, it will
202 try the unencrypted version \"~/.authinfo\" and the famous
203 \"~/.netrc\" file.
204
205 See the auth.info manual for details.
206
207 Each entry is the authentication type with optional properties.
208
209 It's best to customize this with `M-x customize-variable' because the choices
210 can get pretty complex."
211   :group 'auth-source
212   :version "24.1" ;; No Gnus
213   :type `(repeat :tag "Authentication Sources"
214                  (choice
215                   (string :tag "Just a file")
216                   (const :tag "Default Secrets API Collection" 'default)
217                   (const :tag "Login Secrets API Collection" "secrets:Login")
218                   (const :tag "Temp Secrets API Collection" "secrets:session")
219                   (list :tag "Source definition"
220                         (const :format "" :value :source)
221                         (choice :tag "Authentication backend choice"
222                                 (string :tag "Authentication Source (file)")
223                                 (list
224                                  :tag "Secret Service API/KWallet/GNOME Keyring"
225                                  (const :format "" :value :secrets)
226                                  (choice :tag "Collection to use"
227                                          (string :tag "Collection name")
228                                          (const :tag "Default" 'default)
229                                          (const :tag "Login" "Login")
230                                          (const
231                                           :tag "Temporary" "session"))))
232                         (repeat :tag "Extra Parameters" :inline t
233                                 (choice :tag "Extra parameter"
234                                         (list
235                                          :tag "Host"
236                                          (const :format "" :value :host)
237                                          (choice :tag "Host (machine) choice"
238                                                  (const :tag "Any" t)
239                                                  (regexp
240                                                   :tag "Regular expression")))
241                                         (list
242                                          :tag "Protocol"
243                                          (const :format "" :value :port)
244                                          (choice
245                                           :tag "Protocol"
246                                           (const :tag "Any" t)
247                                           ,@auth-source-protocols-customize))
248                                         (list :tag "User" :inline t
249                                               (const :format "" :value :user)
250                                               (choice :tag "Personality/Username"
251                                                       (const :tag "Any" t)
252                                                       (string :tag "Name")))))))))
253
254 (defcustom auth-source-gpg-encrypt-to t
255   "List of recipient keys that `authinfo.gpg' encrypted to.
256 If the value is not a list, symmetric encryption will be used."
257   :group 'auth-source
258   :version "24.1" ;; No Gnus
259   :type '(choice (const :tag "Symmetric encryption" t)
260                  (repeat :tag "Recipient public keys"
261                          (string :tag "Recipient public key"))))
262
263 ;; temp for debugging
264 ;; (unintern 'auth-source-protocols)
265 ;; (unintern 'auth-sources)
266 ;; (customize-variable 'auth-sources)
267 ;; (setq auth-sources nil)
268 ;; (format "%S" auth-sources)
269 ;; (customize-variable 'auth-source-protocols)
270 ;; (setq auth-source-protocols nil)
271 ;; (format "%S" auth-source-protocols)
272 ;; (auth-source-pick nil :host "a" :port 'imap)
273 ;; (auth-source-user-or-password "login" "imap.myhost.com" 'imap)
274 ;; (auth-source-user-or-password "password" "imap.myhost.com" 'imap)
275 ;; (auth-source-user-or-password-imap "login" "imap.myhost.com")
276 ;; (auth-source-user-or-password-imap "password" "imap.myhost.com")
277 ;; (auth-source-protocol-defaults 'imap)
278
279 ;; (let ((auth-source-debug 'debug)) (auth-source-do-debug "hello"))
280 ;; (let ((auth-source-debug t)) (auth-source-do-debug "hello"))
281 ;; (let ((auth-source-debug nil)) (auth-source-do-debug "hello"))
282 (defun auth-source-do-debug (&rest msg)
283   (when auth-source-debug
284     (apply 'auth-source-do-warn msg)))
285
286 (defun auth-source-do-trivia (&rest msg)
287   (when (or (eq auth-source-debug 'trivia)
288             (functionp auth-source-debug))
289     (apply 'auth-source-do-warn msg)))
290
291 (defun auth-source-do-warn (&rest msg)
292   (apply
293     ;; set logger to either the function in auth-source-debug or 'message
294     ;; note that it will be 'message if auth-source-debug is nil
295    (if (functionp auth-source-debug)
296        auth-source-debug
297      'message)
298    msg))
299
300
301 ;;; (auth-source-read-char-choice "enter choice? " '(?a ?b ?q))
302 (defun auth-source-read-char-choice (prompt choices)
303   "Read one of CHOICES by `read-char-choice', or `read-char'.
304 `dropdown-list' support is disabled because it doesn't work reliably.
305 Only one of CHOICES will be returned.  The PROMPT is augmented
306 with \"[a/b/c] \" if CHOICES is '\(?a ?b ?c\)."
307   (when choices
308     (let* ((prompt-choices
309             (apply 'concat (loop for c in choices
310                                  collect (format "%c/" c))))
311            (prompt-choices (concat "[" (substring prompt-choices 0 -1) "] "))
312            (full-prompt (concat prompt prompt-choices))
313            k)
314
315       (while (not (memq k choices))
316         (setq k (cond
317                  ((fboundp 'read-char-choice)
318                   (read-char-choice full-prompt choices))
319                  (t (message "%s" full-prompt)
320                     (setq k (read-char))))))
321       k)))
322
323 ;; (auth-source-pick nil :host "any" :port 'imap :user "joe")
324 ;; (auth-source-pick t :host "any" :port 'imap :user "joe")
325 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
326 ;;                   (:source (:secrets "session") :host t :port t :user "joe")
327 ;;                   (:source (:secrets "Login") :host t :port t)
328 ;;                   (:source "~/.authinfo.gpg" :host t :port t)))
329
330 ;; (setq auth-sources '((:source (:secrets default) :host t :port t :user "joe")
331 ;;                   (:source (:secrets "session") :host t :port t :user "joe")
332 ;;                   (:source (:secrets "Login") :host t :port t)
333 ;;                   ))
334
335 ;; (setq auth-sources '((:source "~/.authinfo.gpg" :host t :port t)))
336
337 ;; (auth-source-backend-parse "myfile.gpg")
338 ;; (auth-source-backend-parse 'default)
339 ;; (auth-source-backend-parse "secrets:Login")
340
341 (defun auth-source-backend-parse (entry)
342   "Creates an auth-source-backend from an ENTRY in `auth-sources'."
343   (auth-source-backend-parse-parameters
344    entry
345    (cond
346     ;; take 'default and recurse to get it as a Secrets API default collection
347     ;; matching any user, host, and protocol
348     ((eq entry 'default)
349      (auth-source-backend-parse '(:source (:secrets default))))
350     ;; take secrets:XYZ and recurse to get it as Secrets API collection "XYZ"
351     ;; matching any user, host, and protocol
352     ((and (stringp entry) (string-match "^secrets:\\(.+\\)" entry))
353      (auth-source-backend-parse `(:source (:secrets ,(match-string 1 entry)))))
354     ;; take just a file name and recurse to get it as a netrc file
355     ;; matching any user, host, and protocol
356     ((stringp entry)
357      (auth-source-backend-parse `(:source ,entry)))
358
359     ;; a file name with parameters
360     ((stringp (plist-get entry :source))
361      (auth-source-backend
362       (plist-get entry :source)
363       :source (plist-get entry :source)
364       :type 'netrc
365       :search-function 'auth-source-netrc-search
366       :create-function 'auth-source-netrc-create))
367
368     ;; the Secrets API.  We require the package, in order to have a
369     ;; defined value for `secrets-enabled'.
370     ((and
371       (not (null (plist-get entry :source))) ; the source must not be nil
372       (listp (plist-get entry :source))      ; and it must be a list
373       (require 'secrets nil t)               ; and we must load the Secrets API
374       secrets-enabled)                       ; and that API must be enabled
375
376      ;; the source is either the :secrets key in ENTRY or
377      ;; if that's missing or nil, it's "session"
378      (let ((source (or (plist-get (plist-get entry :source) :secrets)
379                        "session")))
380
381        ;; if the source is a symbol, we look for the alias named so,
382        ;; and if that alias is missing, we use "Login"
383        (when (symbolp source)
384          (setq source (or (secrets-get-alias (symbol-name source))
385                           "Login")))
386
387        (if (featurep 'secrets)
388            (auth-source-backend
389             (format "Secrets API (%s)" source)
390             :source source
391             :type 'secrets
392             :search-function 'auth-source-secrets-search
393             :create-function 'auth-source-secrets-create)
394          (auth-source-do-warn
395           "auth-source-backend-parse: no Secrets API, ignoring spec: %S" entry)
396          (auth-source-backend
397           (format "Ignored Secrets API (%s)" source)
398           :source ""
399           :type 'ignore))))
400
401     ;; none of them
402     (t
403      (auth-source-do-warn
404       "auth-source-backend-parse: invalid backend spec: %S" entry)
405      (auth-source-backend
406       "Empty"
407       :source ""
408       :type 'ignore)))))
409
410 (defun auth-source-backend-parse-parameters (entry backend)
411   "Fills in the extra auth-source-backend parameters of ENTRY.
412 Using the plist ENTRY, get the :host, :port, and :user search
413 parameters."
414   (let ((entry (if (stringp entry)
415                    nil
416                  entry))
417         val)
418     (when (setq val (plist-get entry :host))
419       (oset backend host val))
420     (when (setq val (plist-get entry :user))
421       (oset backend user val))
422     (when (setq val (plist-get entry :port))
423       (oset backend port val)))
424   backend)
425
426 ;; (mapcar 'auth-source-backend-parse auth-sources)
427
428 (defun* auth-source-search (&rest spec
429                                   &key type max host user port secret
430                                   require create delete
431                                   &allow-other-keys)
432   "Search or modify authentication backends according to SPEC.
433
434 This function parses `auth-sources' for matches of the SPEC
435 plist.  It can optionally create or update an authentication
436 token if requested.  A token is just a standard Emacs property
437 list with a :secret property that can be a function; all the
438 other properties will always hold scalar values.
439
440 Typically the :secret property, if present, contains a password.
441
442 Common search keys are :max, :host, :port, and :user.  In
443 addition, :create specifies how tokens will be or created.
444 Finally, :type can specify which backend types you want to check.
445
446 A string value is always matched literally.  A symbol is matched
447 as its string value, literally.  All the SPEC values can be
448 single values (symbol or string) or lists thereof (in which case
449 any of the search terms matches).
450
451 :create t means to create a token if possible.
452
453 A new token will be created if no matching tokens were found.
454 The new token will have only the keys the backend requires.  For
455 the netrc backend, for instance, that's the user, host, and
456 port keys.
457
458 Here's an example:
459
460 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
461                                         (A    . \"default A\"))))
462   (auth-source-search :host \"mine\" :type 'netrc :max 1
463                       :P \"pppp\" :Q \"qqqq\"
464                       :create t))
465
466 which says:
467
468 \"Search for any entry matching host 'mine' in backends of type
469  'netrc', maximum one result.
470
471  Create a new entry if you found none.  The netrc backend will
472  automatically require host, user, and port.  The host will be
473  'mine'.  We prompt for the user with default 'defaultUser' and
474  for the port without a default.  We will not prompt for A, Q,
475  or P.  The resulting token will only have keys user, host, and
476  port.\"
477
478 :create '(A B C) also means to create a token if possible.
479
480 The behavior is like :create t but if the list contains any
481 parameter, that parameter will be required in the resulting
482 token.  The value for that parameter will be obtained from the
483 search parameters or from user input.  If any queries are needed,
484 the alist `auth-source-creation-defaults' will be checked for the
485 default value.  If the user, host, or port are missing, the alist
486 `auth-source-creation-prompts' will be used to look up the
487 prompts IN THAT ORDER (so the 'user prompt will be queried first,
488 then 'host, then 'port, and finally 'secret).  Each prompt string
489 can use %u, %h, and %p to show the user, host, and port.
490
491 Here's an example:
492
493 \(let ((auth-source-creation-defaults '((user . \"defaultUser\")
494                                         (A    . \"default A\")))
495        (auth-source-creation-prompts
496         '((password . \"Enter IMAP password for %h:%p: \"))))
497   (auth-source-search :host '(\"nonesuch\" \"twosuch\") :type 'netrc :max 1
498                       :P \"pppp\" :Q \"qqqq\"
499                       :create '(A B Q)))
500
501 which says:
502
503 \"Search for any entry matching host 'nonesuch'
504  or 'twosuch' in backends of type 'netrc', maximum one result.
505
506  Create a new entry if you found none.  The netrc backend will
507  automatically require host, user, and port.  The host will be
508  'nonesuch' and Q will be 'qqqq'.  We prompt for the password
509  with the shown prompt.  We will not prompt for Q.  The resulting
510  token will have keys user, host, port, A, B, and Q.  It will not
511  have P with any value, even though P is used in the search to
512  find only entries that have P set to 'pppp'.\"
513
514 When multiple values are specified in the search parameter, the
515 user is prompted for which one.  So :host (X Y Z) would ask the
516 user to choose between X, Y, and Z.
517
518 This creation can fail if the search was not specific enough to
519 create a new token (it's up to the backend to decide that).  You
520 should `catch' the backend-specific error as usual.  Some
521 backends (netrc, at least) will prompt the user rather than throw
522 an error.
523
524 :require (A B C) means that only results that contain those
525 tokens will be returned.  Thus for instance requiring :secret
526 will ensure that any results will actually have a :secret
527 property.
528
529 :delete t means to delete any found entries.  nil by default.
530 Use `auth-source-delete' in ELisp code instead of calling
531 `auth-source-search' directly with this parameter.
532
533 :type (X Y Z) will check only those backend types.  'netrc and
534 'secrets are the only ones supported right now.
535
536 :max N means to try to return at most N items (defaults to 1).
537 When 0 the function will return just t or nil to indicate if any
538 matches were found.  More than N items may be returned, depending
539 on the search and the backend.
540
541 :host (X Y Z) means to match only hosts X, Y, or Z according to
542 the match rules above.  Defaults to t.
543
544 :user (X Y Z) means to match only users X, Y, or Z according to
545 the match rules above.  Defaults to t.
546
547 :port (P Q R) means to match only protocols P, Q, or R.
548 Defaults to t.
549
550 :K (V1 V2 V3) for any other key K will match values V1, V2, or
551 V3 (note the match rules above).
552
553 The return value is a list with at most :max tokens.  Each token
554 is a plist with keys :backend :host :port :user, plus any other
555 keys provided by the backend (notably :secret).  But note the
556 exception for :max 0, which see above.
557
558 The token can hold a :save-function key.  If you call that, the
559 user will be prompted to save the data to the backend.  You can't
560 request that this should happen right after creation, because
561 `auth-source-search' has no way of knowing if the token is
562 actually useful.  So the caller must arrange to call this function.
563
564 The token's :secret key can hold a function.  In that case you
565 must call it to obtain the actual value."
566   (let* ((backends (mapcar 'auth-source-backend-parse auth-sources))
567          (max (or max 1))
568          (ignored-keys '(:require :create :delete :max))
569          (keys (loop for i below (length spec) by 2
570                      unless (memq (nth i spec) ignored-keys)
571                      collect (nth i spec)))
572          (cached (auth-source-remembered-p spec))
573          ;; note that we may have cached results but found is still nil
574          ;; (there were no results from the search)
575          (found (auth-source-recall spec))
576          filtered-backends accessor-key backend)
577
578     (if (and cached auth-source-do-cache)
579         (auth-source-do-debug
580          "auth-source-search: found %d CACHED results matching %S"
581          (length found) spec)
582
583       (assert
584        (or (eq t create) (listp create)) t
585        "Invalid auth-source :create parameter (must be t or a list): %s %s")
586
587       (assert
588        (listp require) t
589        "Invalid auth-source :require parameter (must be a list): %s")
590
591       (setq filtered-backends (copy-sequence backends))
592       (dolist (backend backends)
593         (dolist (key keys)
594           ;; ignore invalid slots
595           (condition-case signal
596               (unless (eval `(auth-source-search-collection
597                               (plist-get spec key)
598                               (oref backend ,key)))
599                 (setq filtered-backends (delq backend filtered-backends))
600                 (return))
601             (invalid-slot-name))))
602
603       (auth-source-do-trivia
604        "auth-source-search: found %d backends matching %S"
605        (length filtered-backends) spec)
606
607       ;; (debug spec "filtered" filtered-backends)
608       ;; First go through all the backends without :create, so we can
609       ;; query them all.
610       (setq found (auth-source-search-backends filtered-backends
611                                                spec
612                                                ;; to exit early
613                                                max
614                                                ;; create is always nil here
615                                                nil delete
616                                                require))
617
618       (auth-source-do-debug
619        "auth-source-search: found %d results (max %d) matching %S"
620        (length found) max spec)
621
622       ;; If we didn't find anything, then we allow the backend(s) to
623       ;; create the entries.
624       (when (and create
625                  (not found))
626         (setq found (auth-source-search-backends filtered-backends
627                                                  spec
628                                                  ;; to exit early
629                                                  max
630                                                  create delete
631                                                  require))
632         (auth-source-do-debug
633          "auth-source-search: CREATED %d results (max %d) matching %S"
634          (length found) max spec))
635
636       ;; note we remember the lack of result too, if it's applicable
637       (when auth-source-do-cache
638         (auth-source-remember spec found)))
639
640       found))
641
642 (defun auth-source-search-backends (backends spec max create delete require)
643   (let (matches)
644     (dolist (backend backends)
645       (when (> max (length matches))   ; when we need more matches...
646         (let* ((bmatches (apply
647                           (slot-value backend 'search-function)
648                           :backend backend
649                           ;; note we're overriding whatever the spec
650                           ;; has for :require, :create, and :delete
651                           :require require
652                           :create create
653                           :delete delete
654                           spec)))
655           (when bmatches
656             (auth-source-do-trivia
657              "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
658              (length bmatches) max
659              (slot-value backend :type)
660              (slot-value backend :source)
661              spec)
662             (setq matches (append matches bmatches))))))
663     matches))
664
665 ;;; (auth-source-search :max 1)
666 ;;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
667 ;;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
668 ;;; (auth-source-search :host "nonesuch" :type 'secrets)
669
670 (defun* auth-source-delete (&rest spec
671                                   &key delete
672                                   &allow-other-keys)
673   "Delete entries from the authentication backends according to SPEC.
674 Calls `auth-source-search' with the :delete property in SPEC set to t.
675 The backend may not actually delete the entries.
676
677 Returns the deleted entries."
678   (auth-source-search (plist-put spec :delete t)))
679
680 (defun auth-source-search-collection (collection value)
681   "Returns t is VALUE is t or COLLECTION is t or contains VALUE."
682   (when (and (atom collection) (not (eq t collection)))
683     (setq collection (list collection)))
684
685   ;; (debug :collection collection :value value)
686   (or (eq collection t)
687       (eq value t)
688       (equal collection value)
689       (member value collection)))
690
691 (defun auth-source-forget-all-cached ()
692   "Forget all cached auth-source data."
693   (interactive)
694   (loop for sym being the symbols of password-data
695         ;; when the symbol name starts with auth-source-magic
696         when (string-match (concat "^" auth-source-magic)
697                            (symbol-name sym))
698         ;; remove that key
699         do (password-cache-remove (symbol-name sym))))
700
701 (defun auth-source-remember (spec found)
702   "Remember FOUND search results for SPEC."
703   (let ((password-cache-expiry auth-source-cache-expiry))
704     (password-cache-add
705      (concat auth-source-magic (format "%S" spec)) found)))
706
707 (defun auth-source-recall (spec)
708   "Recall FOUND search results for SPEC."
709   (password-read-from-cache
710    (concat auth-source-magic (format "%S" spec))))
711
712 (defun auth-source-remembered-p (spec)
713   "Check if SPEC is remembered."
714   (password-in-cache-p
715    (concat auth-source-magic (format "%S" spec))))
716
717 (defun auth-source-forget (spec)
718   "Forget any cached data matching SPEC exactly.
719
720 This is the same SPEC you passed to `auth-source-search'.
721 Returns t or nil for forgotten or not found."
722   (password-cache-remove (concat auth-source-magic (format "%S" spec))))
723
724 ;;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
725
726 ;;; (auth-source-remember '(:host "wedd") '(4 5 6))
727 ;;; (auth-source-remembered-p '(:host "wedd"))
728 ;;; (auth-source-remember '(:host "xedd") '(1 2 3))
729 ;;; (auth-source-remembered-p '(:host "xedd"))
730 ;;; (auth-source-remembered-p '(:host "zedd"))
731 ;;; (auth-source-recall '(:host "xedd"))
732 ;;; (auth-source-recall '(:host t))
733 ;;; (auth-source-forget+ :host t)
734
735 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
736   "Forget any cached data matching SPEC.  Returns forgotten count.
737
738 This is not a full `auth-source-search' spec but works similarly.
739 For instance, \(:host \"myhost\" \"yourhost\") would find all the
740 cached data that was found with a search for those two hosts,
741 while \(:host t) would find all host entries."
742   (let ((count 0)
743         sname)
744     (loop for sym being the symbols of password-data
745           ;; when the symbol name matches with auth-source-magic
746           when (and (setq sname (symbol-name sym))
747                     (string-match (concat "^" auth-source-magic "\\(.+\\)")
748                                   sname)
749                     ;; and the spec matches what was stored in the cache
750                     (auth-source-specmatchp spec (read (match-string 1 sname))))
751           ;; remove that key
752           do (progn
753                (password-cache-remove sname)
754                (incf count)))
755     count))
756
757 (defun auth-source-specmatchp (spec stored)
758   (let ((keys (loop for i below (length spec) by 2
759                    collect (nth i spec))))
760     (not (eq
761           (dolist (key keys)
762             (unless (auth-source-search-collection (plist-get stored key)
763                                                    (plist-get spec key))
764               (return 'no)))
765           'no))))
766
767 ;;; (auth-source-pick-first-password :host "z.lifelogs.com")
768 ;;; (auth-source-pick-first-password :port "imap")
769 (defun auth-source-pick-first-password (&rest spec)
770   "Pick the first secret found from applying SPEC to `auth-source-search'."
771   (let* ((result (nth 0 (apply 'auth-source-search (plist-put spec :max 1))))
772          (secret (plist-get result :secret)))
773
774     (if (functionp secret)
775         (funcall secret)
776       secret)))
777
778 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
779 (defun auth-source-format-prompt (prompt alist)
780   "Format PROMPT using %x (for any character x) specifiers in ALIST."
781   (dolist (cell alist)
782     (let ((c (nth 0 cell))
783           (v (nth 1 cell)))
784       (when (and c v)
785         (setq prompt (replace-regexp-in-string (format "%%%c" c)
786                                                (format "%s" v)
787                                                prompt)))))
788   prompt)
789
790 (defun auth-source-ensure-strings (values)
791   (unless (listp values)
792     (setq values (list values)))
793   (mapcar (lambda (value)
794             (if (numberp value)
795                 (format "%s" value)
796               value))
797           values))
798
799 ;;; Backend specific parsing: netrc/authinfo backend
800
801 (defvar auth-source-netrc-cache nil)
802
803 ;;; (auth-source-netrc-parse "~/.authinfo.gpg")
804 (defun* auth-source-netrc-parse (&rest
805                                  spec
806                                  &key file max host user port delete require
807                                  &allow-other-keys)
808   "Parse FILE and return a list of all entries in the file.
809 Note that the MAX parameter is used so we can exit the parse early."
810   (if (listp file)
811       ;; We got already parsed contents; just return it.
812       file
813     (when (file-exists-p file)
814       (setq port (auth-source-ensure-strings port))
815       (with-temp-buffer
816         (let* ((tokens '("machine" "host" "default" "login" "user"
817                          "password" "account" "macdef" "force"
818                          "port" "protocol"))
819                (max (or max 5000))       ; sanity check: default to stop at 5K
820                (modified 0)
821                (cached (cdr-safe (assoc file auth-source-netrc-cache)))
822                (cached-mtime (plist-get cached :mtime))
823                (cached-secrets (plist-get cached :secret))
824                alist elem result pair)
825
826           (if (and (functionp cached-secrets)
827                    (equal cached-mtime
828                           (nth 5 (file-attributes file))))
829               (progn
830                 (auth-source-do-trivia
831                  "auth-source-netrc-parse: using CACHED file data for %s"
832                  file)
833                 (insert (funcall cached-secrets)))
834             (insert-file-contents file)
835             ;; cache all netrc files (used to be just .gpg files)
836             ;; Store the contents of the file heavily encrypted in memory.
837             ;; (note for the irony-impaired: they are just obfuscated)
838             (aput 'auth-source-netrc-cache file
839                   (list :mtime (nth 5 (file-attributes file))
840                         :secret (lexical-let ((v (rot13-string
841                                                   (base64-encode-string
842                                                    (buffer-string)))))
843                                   (lambda () (base64-decode-string
844                                          (rot13-string v)))))))
845           (goto-char (point-min))
846           ;; Go through the file, line by line.
847           (while (and (not (eobp))
848                       (> max 0))
849
850             (narrow-to-region (point) (point-at-eol))
851             ;; For each line, get the tokens and values.
852             (while (not (eobp))
853               (skip-chars-forward "\t ")
854               ;; Skip lines that begin with a "#".
855               (if (eq (char-after) ?#)
856                   (goto-char (point-max))
857                 (unless (eobp)
858                   (setq elem
859                         (if (= (following-char) ?\")
860                             (read (current-buffer))
861                           (buffer-substring
862                            (point) (progn (skip-chars-forward "^\t ")
863                                           (point)))))
864                   (cond
865                    ((equal elem "macdef")
866                     ;; We skip past the macro definition.
867                     (widen)
868                     (while (and (zerop (forward-line 1))
869                                 (looking-at "$")))
870                     (narrow-to-region (point) (point)))
871                    ((member elem tokens)
872                     ;; Tokens that don't have a following value are ignored,
873                     ;; except "default".
874                     (when (and pair (or (cdr pair)
875                                         (equal (car pair) "default")))
876                       (push pair alist))
877                     (setq pair (list elem)))
878                    (t
879                     ;; Values that haven't got a preceding token are ignored.
880                     (when pair
881                       (setcdr pair elem)
882                       (push pair alist)
883                       (setq pair nil)))))))
884
885             (when (and alist
886                        (> max 0)
887                        (auth-source-search-collection
888                         host
889                         (or
890                          (aget alist "machine")
891                          (aget alist "host")
892                          t))
893                        (auth-source-search-collection
894                         user
895                         (or
896                          (aget alist "login")
897                          (aget alist "account")
898                          (aget alist "user")
899                          t))
900                        (auth-source-search-collection
901                         port
902                         (or
903                          (aget alist "port")
904                          (aget alist "protocol")
905                          t))
906                        (or
907                         ;; the required list of keys is nil, or
908                         (null require)
909                         ;; every element of require is in the normalized list
910                         (let ((normalized (nth 0 (auth-source-netrc-normalize
911                                                  (list alist)))))
912                           (loop for req in require
913                                 always (plist-get normalized req)))))
914               (decf max)
915               (push (nreverse alist) result)
916               ;; to delete a line, we just comment it out
917               (when delete
918                 (goto-char (point-min))
919                 (insert "#")
920                 (incf modified)))
921             (setq alist nil
922                   pair nil)
923             (widen)
924             (forward-line 1))
925
926           (when (< 0 modified)
927             (when auth-source-gpg-encrypt-to
928               ;; (see bug#7487) making `epa-file-encrypt-to' local to
929               ;; this buffer lets epa-file skip the key selection query
930               ;; (see the `local-variable-p' check in
931               ;; `epa-file-write-region').
932               (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
933                 (make-local-variable 'epa-file-encrypt-to))
934               (if (listp auth-source-gpg-encrypt-to)
935                   (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
936
937             ;; ask AFTER we've successfully opened the file
938             (when (y-or-n-p (format "Save file %s? (%d deletions)"
939                                     file modified))
940               (write-region (point-min) (point-max) file nil 'silent)
941               (auth-source-do-debug
942                "auth-source-netrc-parse: modified %d lines in %s"
943                modified file)))
944
945           (nreverse result))))))
946
947 (defun auth-source-netrc-normalize (alist)
948   (mapcar (lambda (entry)
949             (let (ret item)
950               (while (setq item (pop entry))
951                 (let ((k (car item))
952                       (v (cdr item)))
953
954                   ;; apply key aliases
955                   (setq k (cond ((member k '("machine")) "host")
956                                 ((member k '("login" "account")) "user")
957                                 ((member k '("protocol")) "port")
958                                 ((member k '("password")) "secret")
959                                 (t k)))
960
961                   ;; send back the secret in a function (lexical binding)
962                   (when (equal k "secret")
963                     (setq v (lexical-let ((v v))
964                               (lambda () v))))
965
966                   (setq ret (plist-put ret
967                                        (intern (concat ":" k))
968                                        v))
969                   ))
970               ret))
971           alist))
972
973 ;;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
974 ;;; (funcall secret)
975
976 (defun* auth-source-netrc-search (&rest
977                                   spec
978                                   &key backend require create delete
979                                   type max host user port
980                                   &allow-other-keys)
981 "Given a property list SPEC, return search matches from the :backend.
982 See `auth-source-search' for details on SPEC."
983   ;; just in case, check that the type is correct (null or same as the backend)
984   (assert (or (null type) (eq type (oref backend type)))
985           t "Invalid netrc search: %s %s")
986
987   (let ((results (auth-source-netrc-normalize
988                   (auth-source-netrc-parse
989                    :max max
990                    :require require
991                    :delete delete
992                    :file (oref backend source)
993                    :host (or host t)
994                    :user (or user t)
995                    :port (or port t)))))
996
997     ;; if we need to create an entry AND none were found to match
998     (when (and create
999                (not results))
1000
1001       ;; create based on the spec and record the value
1002       (setq results (or
1003                      ;; if the user did not want to create the entry
1004                      ;; in the file, it will be returned
1005                      (apply (slot-value backend 'create-function) spec)
1006                      ;; if not, we do the search again without :create
1007                      ;; to get the updated data.
1008
1009                      ;; the result will be returned, even if the search fails
1010                      (apply 'auth-source-netrc-search
1011                             (plist-put spec :create nil)))))
1012     results))
1013
1014 (defun auth-source-netrc-element-or-first (v)
1015   (if (listp v)
1016       (nth 0 v)
1017     v))
1018
1019 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1020 ;;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1021
1022 (defun* auth-source-netrc-create (&rest spec
1023                                         &key backend
1024                                         secret host user port create
1025                                         &allow-other-keys)
1026   (let* ((base-required '(host user port secret))
1027          ;; we know (because of an assertion in auth-source-search) that the
1028          ;; :create parameter is either t or a list (which includes nil)
1029          (create-extra (if (eq t create) nil create))
1030          (required (append base-required create-extra))
1031          (file (oref backend source))
1032          (add "")
1033          ;; `valist' is an alist
1034          valist
1035          ;; `artificial' will be returned if no creation is needed
1036          artificial)
1037
1038     ;; only for base required elements (defined as function parameters):
1039     ;; fill in the valist with whatever data we may have from the search
1040     ;; we complete the first value if it's a list and use the value otherwise
1041     (dolist (br base-required)
1042       (when (symbol-value br)
1043         (let ((br-choice (cond
1044                           ;; all-accepting choice (predicate is t)
1045                           ((eq t (symbol-value br)) nil)
1046                           ;; just the value otherwise
1047                           (t (symbol-value br)))))
1048           (when br-choice
1049             (aput 'valist br br-choice)))))
1050
1051     ;; for extra required elements, see if the spec includes a value for them
1052     (dolist (er create-extra)
1053       (let ((name (concat ":" (symbol-name er)))
1054             (keys (loop for i below (length spec) by 2
1055                         collect (nth i spec))))
1056         (dolist (k keys)
1057           (when (equal (symbol-name k) name)
1058             (aput 'valist er (plist-get spec k))))))
1059
1060     ;; for each required element
1061     (dolist (r required)
1062       (let* ((data (aget valist r))
1063              ;; take the first element if the data is a list
1064              (data (auth-source-netrc-element-or-first data))
1065              ;; this is the default to be offered
1066              (given-default (aget auth-source-creation-defaults r))
1067              ;; the default supplementals are simple:
1068              ;; for the user, try `given-default' and then (user-login-name);
1069              ;; otherwise take `given-default'
1070              (default (cond
1071                        ((and (not given-default) (eq r 'user))
1072                         (user-login-name))
1073                        (t given-default)))
1074              (printable-defaults (list
1075                                   (cons 'user
1076                                         (or
1077                                          (auth-source-netrc-element-or-first
1078                                           (aget valist 'user))
1079                                          (plist-get artificial :user)
1080                                          "[any user]"))
1081                                   (cons 'host
1082                                         (or
1083                                          (auth-source-netrc-element-or-first
1084                                           (aget valist 'host))
1085                                          (plist-get artificial :host)
1086                                          "[any host]"))
1087                                   (cons 'port
1088                                         (or
1089                                          (auth-source-netrc-element-or-first
1090                                           (aget valist 'port))
1091                                          (plist-get artificial :port)
1092                                          "[any port]"))))
1093              (prompt (or (aget auth-source-creation-prompts r)
1094                          (case r
1095                            (secret "%p password for %u@%h: ")
1096                            (user "%p user name for %h: ")
1097                            (host "%p host name for user %u: ")
1098                            (port "%p port for %u@%h: "))
1099                          (format "Enter %s (%%u@%%h:%%p): " r)))
1100              (prompt (auth-source-format-prompt
1101                       prompt
1102                       `((?u ,(aget printable-defaults 'user))
1103                         (?h ,(aget printable-defaults 'host))
1104                         (?p ,(aget printable-defaults 'port))))))
1105
1106         ;; store the data, prompting for the password if needed
1107         (setq data
1108               (cond
1109                ((and (null data) (eq r 'secret))
1110                 ;; special case prompt for passwords
1111                 (read-passwd prompt))
1112                ((null data)
1113                 (read-string prompt nil nil default))
1114                (t (or data default))))
1115
1116         (when data
1117           (setq artificial (plist-put artificial
1118                                       (intern (concat ":" (symbol-name r)))
1119                                       (if (eq r 'secret)
1120                                           (lexical-let ((data data))
1121                                             (lambda () data))
1122                                         data))))
1123
1124         ;; when r is not an empty string...
1125         (when (and (stringp data)
1126                    (< 0 (length data)))
1127           ;; this function is not strictly necessary but I think it
1128           ;; makes the code clearer -tzz
1129           (let ((printer (lambda ()
1130                            ;; append the key (the symbol name of r)
1131                            ;; and the value in r
1132                            (format "%s%s %S"
1133                                    ;; prepend a space
1134                                    (if (zerop (length add)) "" " ")
1135                                    ;; remap auth-source tokens to netrc
1136                                    (case r
1137                                      ('user   "login")
1138                                      ('host   "machine")
1139                                      ('secret "password")
1140                                      ('port   "port") ; redundant but clearer
1141                                      (t (symbol-name r)))
1142                                    ;; the value will be printed in %S format
1143                                    data))))
1144             (setq add (concat add (funcall printer)))))))
1145
1146     (plist-put
1147      artificial
1148      :save-function
1149      (lexical-let ((file file)
1150                    (add add))
1151        (lambda () (auth-source-netrc-saver file add))))
1152
1153     (list artificial)))
1154
1155 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1156 (defun auth-source-netrc-saver (file add)
1157   "Save a line ADD in FILE, prompting along the way.
1158 Respects `auth-source-save-behavior'.  Uses
1159 `auth-source-netrc-cache' to avoid prompting more than once."
1160   (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1161          (cached (assoc key auth-source-netrc-cache)))
1162
1163     (if cached
1164         (auth-source-do-trivia
1165          "auth-source-netrc-saver: found previous run for key %s, returning"
1166          key)
1167       (with-temp-buffer
1168         (when (file-exists-p file)
1169           (insert-file-contents file))
1170         (when auth-source-gpg-encrypt-to
1171           ;; (see bug#7487) making `epa-file-encrypt-to' local to
1172           ;; this buffer lets epa-file skip the key selection query
1173           ;; (see the `local-variable-p' check in
1174           ;; `epa-file-write-region').
1175           (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1176             (make-local-variable 'epa-file-encrypt-to))
1177           (if (listp auth-source-gpg-encrypt-to)
1178               (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1179         ;; we want the new data to be found first, so insert at beginning
1180         (goto-char (point-min))
1181
1182         ;; ask AFTER we've successfully opened the file
1183         (let ((prompt (format "Save auth info to file %s? " file))
1184               (done (not (eq auth-source-save-behavior 'ask)))
1185               (bufname "*auth-source Help*")
1186               k)
1187           (while (not done)
1188             (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1189             (case k
1190               (?y (setq done t))
1191               (?? (save-excursion
1192                     (with-output-to-temp-buffer bufname
1193                       (princ
1194                        (concat "(y)es, save\n"
1195                                "(n)o but use the info\n"
1196                                "(N)o and don't ask to save again\n"
1197                                "(e)dit the line\n"
1198                                "(?) for help as you can see.\n"))
1199                       (set-buffer standard-output)
1200                       (help-mode))))
1201               (?n (setq add ""
1202                         done t))
1203               (?N (setq add ""
1204                         done t
1205                         auth-source-save-behavior nil))
1206               (?e (setq add (read-string "Line to add: " add)))
1207               (t nil)))
1208
1209           (when (get-buffer-window bufname)
1210             (delete-window (get-buffer-window bufname)))
1211
1212           ;; make sure the info is not saved
1213           (when (null auth-source-save-behavior)
1214             (setq add ""))
1215
1216           (when (< 0 (length add))
1217             (progn
1218               (unless (bolp)
1219                 (insert "\n"))
1220               (insert add "\n")
1221               (write-region (point-min) (point-max) file nil 'silent)
1222               (auth-source-do-debug
1223                "auth-source-netrc-create: wrote 1 new line to %s"
1224                file)
1225               (message "Saved new authentication information to %s" file)
1226               nil))))
1227       (aput 'auth-source-netrc-cache key "ran"))))
1228
1229 ;;; Backend specific parsing: Secrets API backend
1230
1231 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1232 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1233 ;;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1234 ;;; (let ((auth-sources '(default))) (auth-source-search))
1235 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1236 ;;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1237
1238 (defun* auth-source-secrets-search (&rest
1239                                     spec
1240                                     &key backend create delete label
1241                                     type max host user port
1242                                     &allow-other-keys)
1243   "Search the Secrets API; spec is like `auth-source'.
1244
1245 The :label key specifies the item's label.  It is the only key
1246 that can specify a substring.  Any :label value besides a string
1247 will allow any label.
1248
1249 All other search keys must match exactly.  If you need substring
1250 matching, do a wider search and narrow it down yourself.
1251
1252 You'll get back all the properties of the token as a plist.
1253
1254 Here's an example that looks for the first item in the 'Login'
1255 Secrets collection:
1256
1257  \(let ((auth-sources '(\"secrets:Login\")))
1258     (auth-source-search :max 1)
1259
1260 Here's another that looks for the first item in the 'Login'
1261 Secrets collection whose label contains 'gnus':
1262
1263  \(let ((auth-sources '(\"secrets:Login\")))
1264     (auth-source-search :max 1 :label \"gnus\")
1265
1266 And this one looks for the first item in the 'Login' Secrets
1267 collection that's a Google Chrome entry for the git.gnus.org site
1268 authentication tokens:
1269
1270  \(let ((auth-sources '(\"secrets:Login\")))
1271     (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1272 "
1273
1274   ;; TODO
1275   (assert (not create) nil
1276           "The Secrets API auth-source backend doesn't support creation yet")
1277   ;; TODO
1278   ;; (secrets-delete-item coll elt)
1279   (assert (not delete) nil
1280           "The Secrets API auth-source backend doesn't support deletion yet")
1281
1282   (let* ((coll (oref backend source))
1283          (max (or max 5000))     ; sanity check: default to stop at 5K
1284          (ignored-keys '(:create :delete :max :backend :label))
1285          (search-keys (loop for i below (length spec) by 2
1286                             unless (memq (nth i spec) ignored-keys)
1287                             collect (nth i spec)))
1288          ;; build a search spec without the ignored keys
1289          ;; if a search key is nil or t (match anything), we skip it
1290          (search-spec (apply 'append (mapcar
1291                                       (lambda (k)
1292                                         (if (or (null (plist-get spec k))
1293                                                 (eq t (plist-get spec k)))
1294                                             nil
1295                                           (list k (plist-get spec k))))
1296                               search-keys)))
1297          ;; needed keys (always including host, login, port, and secret)
1298          (returned-keys (mm-delete-duplicates (append
1299                                                '(:host :login :port :secret)
1300                                                search-keys)))
1301          (items (loop for item in (apply 'secrets-search-items coll search-spec)
1302                       unless (and (stringp label)
1303                                   (not (string-match label item)))
1304                       collect item))
1305          ;; TODO: respect max in `secrets-search-items', not after the fact
1306          (items (butlast items (- (length items) max)))
1307          ;; convert the item name to a full plist
1308          (items (mapcar (lambda (item)
1309                           (append
1310                            ;; make an entry for the secret (password) element
1311                            (list
1312                             :secret
1313                             (lexical-let ((v (secrets-get-secret coll item)))
1314                               (lambda () v)))
1315                            ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1316                            (apply 'append
1317                                   (mapcar (lambda (entry)
1318                                             (list (car entry) (cdr entry)))
1319                                           (secrets-get-attributes coll item)))))
1320                         items))
1321          ;; ensure each item has each key in `returned-keys'
1322          (items (mapcar (lambda (plist)
1323                           (append
1324                            (apply 'append
1325                                   (mapcar (lambda (req)
1326                                             (if (plist-get plist req)
1327                                                 nil
1328                                               (list req nil)))
1329                                           returned-keys))
1330                            plist))
1331                         items)))
1332     items))
1333
1334 (defun* auth-source-secrets-create (&rest
1335                                     spec
1336                                     &key backend type max host user port
1337                                     &allow-other-keys)
1338   ;; TODO
1339   ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1340   (debug spec))
1341
1342 ;;; older API
1343
1344 ;;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
1345
1346 ;; deprecate the old interface
1347 (make-obsolete 'auth-source-user-or-password
1348                'auth-source-search "Emacs 24.1")
1349 (make-obsolete 'auth-source-forget-user-or-password
1350                'auth-source-forget "Emacs 24.1")
1351
1352 (defun auth-source-user-or-password
1353   (mode host port &optional username create-missing delete-existing)
1354   "Find MODE (string or list of strings) matching HOST and PORT.
1355
1356 DEPRECATED in favor of `auth-source-search'!
1357
1358 USERNAME is optional and will be used as \"login\" in a search
1359 across the Secret Service API (see secrets.el) if the resulting
1360 items don't have a username.  This means that if you search for
1361 username \"joe\" and it matches an item but the item doesn't have
1362 a :user attribute, the username \"joe\" will be returned.
1363
1364 A non nil DELETE-EXISTING means deleting any matching password
1365 entry in the respective sources.  This is useful only when
1366 CREATE-MISSING is non nil as well; the intended use case is to
1367 remove wrong password entries.
1368
1369 If no matching entry is found, and CREATE-MISSING is non nil,
1370 the password will be retrieved interactively, and it will be
1371 stored in the password database which matches best (see
1372 `auth-sources').
1373
1374 MODE can be \"login\" or \"password\"."
1375   (auth-source-do-debug
1376    "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
1377    mode host port username)
1378
1379   (let* ((listy (listp mode))
1380          (mode (if listy mode (list mode)))
1381          (cname (if username
1382                     (format "%s %s:%s %s" mode host port username)
1383                   (format "%s %s:%s" mode host port)))
1384          (search (list :host host :port port))
1385          (search (if username (append search (list :user username)) search))
1386          (search (if create-missing
1387                      (append search (list :create t))
1388                    search))
1389          (search (if delete-existing
1390                      (append search (list :delete t))
1391                    search))
1392          ;; (found (if (not delete-existing)
1393          ;;            (gethash cname auth-source-cache)
1394          ;;          (remhash cname auth-source-cache)
1395          ;;          nil)))
1396          (found nil))
1397     (if found
1398         (progn
1399           (auth-source-do-debug
1400            "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
1401            mode
1402            ;; don't show the password
1403            (if (and (member "password" mode) t)
1404                "SECRET"
1405              found)
1406            host port username)
1407           found)                        ; return the found data
1408       ;; else, if not found, search with a max of 1
1409       (let ((choice (nth 0 (apply 'auth-source-search
1410                                   (append '(:max 1) search)))))
1411         (when choice
1412           (dolist (m mode)
1413             (cond
1414              ((equal "password" m)
1415               (push (if (plist-get choice :secret)
1416                       (funcall (plist-get choice :secret))
1417                     nil) found))
1418              ((equal "login" m)
1419               (push (plist-get choice :user) found)))))
1420         (setq found (nreverse found))
1421         (setq found (if listy found (car-safe found)))))
1422
1423         found))
1424
1425 (provide 'auth-source)
1426
1427 ;;; auth-source.el ends here