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