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