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