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