Misc changes made in Emacs trunk
[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 ;; with thanks to org-mode
1069 (defsubst auth-source-current-line (&optional pos)
1070   (save-excursion
1071     (and pos (goto-char pos))
1072     ;; works also in narrowed buffer, because we start at 1, not point-min
1073     (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1074
1075 (defun auth-source-netrc-parse-entries(check max)
1076   "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1077   (let ((adder (lambda(check alist all)
1078                  (when (and
1079                         alist
1080                         (> max (length all))
1081                         (funcall check alist))
1082                    (push alist all))
1083                  all))
1084         item item2 all alist default)
1085     (while (setq item (auth-source-netrc-parse-one))
1086       (setq default (equal item "default"))
1087       ;; We're starting a new machine.  Save the old one.
1088       (when (and alist
1089                  (or default
1090                      (equal item "machine")))
1091         ;; (auth-source-do-trivia
1092         ;;  "auth-source-netrc-parse-entries: got entry %S" alist)
1093         (setq all (funcall adder check alist all)
1094               alist nil))
1095       ;; In default entries, we don't have a next token.
1096       ;; We store them as ("machine" . t)
1097       (if default
1098           (push (cons "machine" t) alist)
1099         ;; Not a default entry.  Grab the next item.
1100         (when (setq item2 (auth-source-netrc-parse-one))
1101           ;; Did we get a "machine" value?
1102           (if (equal item2 "machine")
1103               (progn
1104                 (gnus-error 1
1105                  "%s: Unexpected 'machine' token at line %d"
1106                  "auth-source-netrc-parse-entries"
1107                  (auth-source-current-line))
1108                 (forward-line 1))
1109             (push (cons item item2) alist)))))
1110
1111     ;; Clean up: if there's an entry left over, use it.
1112     (when alist
1113       (setq all (funcall adder check alist all))
1114       ;; (auth-source-do-trivia
1115       ;;  "auth-source-netrc-parse-entries: got2 entry %S" alist)
1116       )
1117     (nreverse all)))
1118
1119 (defvar auth-source-passphrase-alist nil)
1120
1121 (defun auth-source-token-passphrase-callback-function (context key-id file)
1122   (let* ((file (file-truename file))
1123          (entry (assoc file auth-source-passphrase-alist))
1124          passphrase)
1125     ;; return the saved passphrase, calling a function if needed
1126     (or (copy-sequence (if (functionp (cdr entry))
1127                            (funcall (cdr entry))
1128                          (cdr entry)))
1129         (progn
1130           (unless entry
1131             (setq entry (list file))
1132             (push entry auth-source-passphrase-alist))
1133           (setq passphrase
1134                 (read-passwd
1135                  (format "Passphrase for %s tokens: " file)
1136                  t))
1137           (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1138                           (lambda () p)))
1139           passphrase))))
1140
1141 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1142 (defun auth-source-epa-extract-gpg-token (secret file)
1143   "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1144 FILE is the file from which we obtained this token."
1145   (when (string-match "^gpg:\\(.+\\)" secret)
1146     (setq secret (base64-decode-string (match-string 1 secret))))
1147   (let ((context (epg-make-context 'OpenPGP))
1148         plain)
1149     (epg-context-set-passphrase-callback
1150      context
1151      (cons #'auth-source-token-passphrase-callback-function
1152            file))
1153     (epg-decrypt-string context secret)))
1154
1155 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1156 (defun auth-source-epa-make-gpg-token (secret file)
1157   (let ((context (epg-make-context 'OpenPGP))
1158         (pp-escape-newlines nil)
1159         cipher)
1160     (epg-context-set-armor context t)
1161     (epg-context-set-passphrase-callback
1162      context
1163      (cons #'auth-source-token-passphrase-callback-function
1164            file))
1165     (setq cipher (epg-encrypt-string context secret nil))
1166     (with-temp-buffer
1167       (insert cipher)
1168       (base64-encode-region (point-min) (point-max) t)
1169       (concat "gpg:" (buffer-substring-no-properties
1170                       (point-min)
1171                       (point-max))))))
1172
1173 (defun auth-source-netrc-normalize (alist filename)
1174   (mapcar (lambda (entry)
1175             (let (ret item)
1176               (while (setq item (pop entry))
1177                 (let ((k (car item))
1178                       (v (cdr item)))
1179
1180                   ;; apply key aliases
1181                   (setq k (cond ((member k '("machine")) "host")
1182                                 ((member k '("login" "account")) "user")
1183                                 ((member k '("protocol")) "port")
1184                                 ((member k '("password")) "secret")
1185                                 (t k)))
1186
1187                   ;; send back the secret in a function (lexical binding)
1188                   (when (equal k "secret")
1189                     (setq v (lexical-let ((lexv v)
1190                                           (token-decoder nil))
1191                               (when (string-match "^gpg:" lexv)
1192                                 ;; it's a GPG token: create a token decoder
1193                                 ;; which unsets itself once
1194                                 (setq token-decoder
1195                                       (lambda (val)
1196                                         (prog1
1197                                             (auth-source-epa-extract-gpg-token
1198                                              val
1199                                              filename)
1200                                           (setq token-decoder nil)))))
1201                               (lambda ()
1202                                 (when token-decoder
1203                                   (setq lexv (funcall token-decoder lexv)))
1204                                 lexv))))
1205                   (setq ret (plist-put ret
1206                                        (intern (concat ":" k))
1207                                        v))))
1208               ret))
1209           alist))
1210
1211 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1212 ;; (funcall secret)
1213
1214 (defun* auth-source-netrc-search (&rest
1215                                   spec
1216                                   &key backend require create delete
1217                                   type max host user port
1218                                   &allow-other-keys)
1219   "Given a property list SPEC, return search matches from the :backend.
1220 See `auth-source-search' for details on SPEC."
1221   ;; just in case, check that the type is correct (null or same as the backend)
1222   (assert (or (null type) (eq type (oref backend type)))
1223           t "Invalid netrc search: %s %s")
1224
1225   (let ((results (auth-source-netrc-normalize
1226                   (auth-source-netrc-parse
1227                    :max max
1228                    :require require
1229                    :delete delete
1230                    :file (oref backend source)
1231                    :host (or host t)
1232                    :user (or user t)
1233                    :port (or port t))
1234                   (oref backend source))))
1235
1236     ;; if we need to create an entry AND none were found to match
1237     (when (and create
1238                (not results))
1239
1240       ;; create based on the spec and record the value
1241       (setq results (or
1242                      ;; if the user did not want to create the entry
1243                      ;; in the file, it will be returned
1244                      (apply (slot-value backend 'create-function) spec)
1245                      ;; if not, we do the search again without :create
1246                      ;; to get the updated data.
1247
1248                      ;; the result will be returned, even if the search fails
1249                      (apply 'auth-source-netrc-search
1250                             (plist-put spec :create nil)))))
1251     results))
1252
1253 (defun auth-source-netrc-element-or-first (v)
1254   (if (listp v)
1255       (nth 0 v)
1256     v))
1257
1258 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1259 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1260
1261 (defun* auth-source-netrc-create (&rest spec
1262                                         &key backend
1263                                         secret host user port create
1264                                         &allow-other-keys)
1265   (let* ((base-required '(host user port secret))
1266          ;; we know (because of an assertion in auth-source-search) that the
1267          ;; :create parameter is either t or a list (which includes nil)
1268          (create-extra (if (eq t create) nil create))
1269          (current-data (car (auth-source-search :max 1
1270                                                 :host host
1271                                                 :port port)))
1272          (required (append base-required create-extra))
1273          (file (oref backend source))
1274          (add "")
1275          ;; `valist' is an alist
1276          valist
1277          ;; `artificial' will be returned if no creation is needed
1278          artificial)
1279
1280     ;; only for base required elements (defined as function parameters):
1281     ;; fill in the valist with whatever data we may have from the search
1282     ;; we complete the first value if it's a list and use the value otherwise
1283     (dolist (br base-required)
1284       (when (symbol-value br)
1285         (let ((br-choice (cond
1286                           ;; all-accepting choice (predicate is t)
1287                           ((eq t (symbol-value br)) nil)
1288                           ;; just the value otherwise
1289                           (t (symbol-value br)))))
1290           (when br-choice
1291             (auth-source--aput valist br br-choice)))))
1292
1293     ;; for extra required elements, see if the spec includes a value for them
1294     (dolist (er create-extra)
1295       (let ((name (concat ":" (symbol-name er)))
1296             (keys (loop for i below (length spec) by 2
1297                         collect (nth i spec))))
1298         (dolist (k keys)
1299           (when (equal (symbol-name k) name)
1300             (auth-source--aput valist er (plist-get spec k))))))
1301
1302     ;; for each required element
1303     (dolist (r required)
1304       (let* ((data (auth-source--aget valist r))
1305              ;; take the first element if the data is a list
1306              (data (or (auth-source-netrc-element-or-first data)
1307                        (plist-get current-data
1308                                   (intern (format ":%s" r) obarray))))
1309              ;; this is the default to be offered
1310              (given-default (auth-source--aget
1311                              auth-source-creation-defaults r))
1312              ;; the default supplementals are simple:
1313              ;; for the user, try `given-default' and then (user-login-name);
1314              ;; otherwise take `given-default'
1315              (default (cond
1316                        ((and (not given-default) (eq r 'user))
1317                         (user-login-name))
1318                        (t given-default)))
1319              (printable-defaults (list
1320                                   (cons 'user
1321                                         (or
1322                                          (auth-source-netrc-element-or-first
1323                                           (auth-source--aget valist 'user))
1324                                          (plist-get artificial :user)
1325                                          "[any user]"))
1326                                   (cons 'host
1327                                         (or
1328                                          (auth-source-netrc-element-or-first
1329                                           (auth-source--aget valist 'host))
1330                                          (plist-get artificial :host)
1331                                          "[any host]"))
1332                                   (cons 'port
1333                                         (or
1334                                          (auth-source-netrc-element-or-first
1335                                           (auth-source--aget valist 'port))
1336                                          (plist-get artificial :port)
1337                                          "[any port]"))))
1338              (prompt (or (auth-source--aget auth-source-creation-prompts r)
1339                          (case r
1340                            (secret "%p password for %u@%h: ")
1341                            (user "%p user name for %h: ")
1342                            (host "%p host name for user %u: ")
1343                            (port "%p port for %u@%h: "))
1344                          (format "Enter %s (%%u@%%h:%%p): " r)))
1345              (prompt (auth-source-format-prompt
1346                       prompt
1347                       `((?u ,(auth-source--aget printable-defaults 'user))
1348                         (?h ,(auth-source--aget printable-defaults 'host))
1349                         (?p ,(auth-source--aget printable-defaults 'port))))))
1350
1351         ;; Store the data, prompting for the password if needed.
1352         (setq data (or data
1353                        (if (eq r 'secret)
1354                            ;; Special case prompt for passwords.
1355                            ;; 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)))
1356                            ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1357                            (let* ((ep (format "Use GPG password tokens in %s?" file))
1358                                   (gpg-encrypt
1359                                    (cond
1360                                     ((eq auth-source-netrc-use-gpg-tokens 'never)
1361                                      'never)
1362                                     ((listp auth-source-netrc-use-gpg-tokens)
1363                                      (let ((check (copy-sequence
1364                                                    auth-source-netrc-use-gpg-tokens))
1365                                            item ret)
1366                                        (while check
1367                                          (setq item (pop check))
1368                                          (when (or (eq (car item) t)
1369                                                    (string-match (car item) file))
1370                                            (setq ret (cdr item))
1371                                            (setq check nil)))))
1372                                     (t 'never)))
1373                                   (plain (or (eval default) (read-passwd prompt))))
1374                              ;; ask if we don't know what to do (in which case
1375                              ;; auth-source-netrc-use-gpg-tokens must be a list)
1376                              (unless gpg-encrypt
1377                                (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1378                                ;; TODO: save the defcustom now? or ask?
1379                                (setq auth-source-netrc-use-gpg-tokens
1380                                      (cons `(,file ,gpg-encrypt)
1381                                            auth-source-netrc-use-gpg-tokens)))
1382                              (if (eq gpg-encrypt 'gpg)
1383                                  (auth-source-epa-make-gpg-token plain file)
1384                                plain))
1385                          (if (stringp default)
1386                              (read-string (if (string-match ": *\\'" prompt)
1387                                               (concat (substring prompt 0 (match-beginning 0))
1388                                                       " (default " default "): ")
1389                                             (concat prompt "(default " default ") "))
1390                                           nil nil default)
1391                            (eval default)))))
1392
1393         (when data
1394           (setq artificial (plist-put artificial
1395                                       (intern (concat ":" (symbol-name r)))
1396                                       (if (eq r 'secret)
1397                                           (lexical-let ((data data))
1398                                             (lambda () data))
1399                                         data))))
1400
1401         ;; When r is not an empty string...
1402         (when (and (stringp data)
1403                    (< 0 (length data)))
1404           ;; this function is not strictly necessary but I think it
1405           ;; makes the code clearer -tzz
1406           (let ((printer (lambda ()
1407                            ;; append the key (the symbol name of r)
1408                            ;; and the value in r
1409                            (format "%s%s %s"
1410                                    ;; prepend a space
1411                                    (if (zerop (length add)) "" " ")
1412                                    ;; remap auth-source tokens to netrc
1413                                    (case r
1414                                      (user   "login")
1415                                      (host   "machine")
1416                                      (secret "password")
1417                                      (port   "port") ; redundant but clearer
1418                                      (t (symbol-name r)))
1419                                    (if (string-match "[\"# ]" data)
1420                                        (format "%S" data)
1421                                      data)))))
1422             (setq add (concat add (funcall printer)))))))
1423
1424     (plist-put
1425      artificial
1426      :save-function
1427      (lexical-let ((file file)
1428                    (add add))
1429        (lambda () (auth-source-netrc-saver file add))))
1430
1431     (list artificial)))
1432
1433 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1434 (defun auth-source-netrc-saver (file add)
1435   "Save a line ADD in FILE, prompting along the way.
1436 Respects `auth-source-save-behavior'.  Uses
1437 `auth-source-netrc-cache' to avoid prompting more than once."
1438   (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1439          (cached (assoc key auth-source-netrc-cache)))
1440
1441     (if cached
1442         (auth-source-do-trivia
1443          "auth-source-netrc-saver: found previous run for key %s, returning"
1444          key)
1445       (with-temp-buffer
1446         (when (file-exists-p file)
1447           (insert-file-contents file))
1448         (when auth-source-gpg-encrypt-to
1449           ;; (see bug#7487) making `epa-file-encrypt-to' local to
1450           ;; this buffer lets epa-file skip the key selection query
1451           ;; (see the `local-variable-p' check in
1452           ;; `epa-file-write-region').
1453           (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1454             (make-local-variable 'epa-file-encrypt-to))
1455           (if (listp auth-source-gpg-encrypt-to)
1456               (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1457         ;; we want the new data to be found first, so insert at beginning
1458         (goto-char (point-min))
1459
1460         ;; Ask AFTER we've successfully opened the file.
1461         (let ((prompt (format "Save auth info to file %s? " file))
1462               (done (not (eq auth-source-save-behavior 'ask)))
1463               (bufname "*auth-source Help*")
1464               k)
1465           (while (not done)
1466             (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1467             (case k
1468               (?y (setq done t))
1469               (?? (save-excursion
1470                     (with-output-to-temp-buffer bufname
1471                       (princ
1472                        (concat "(y)es, save\n"
1473                                "(n)o but use the info\n"
1474                                "(N)o and don't ask to save again\n"
1475                                "(e)dit the line\n"
1476                                "(?) for help as you can see.\n"))
1477                       ;; Why?  Doesn't with-output-to-temp-buffer already do
1478                       ;; the exact same thing anyway?  --Stef
1479                       (set-buffer standard-output)
1480                       (help-mode))))
1481               (?n (setq add ""
1482                         done t))
1483               (?N
1484                (setq add ""
1485                      done t)
1486                (customize-save-variable 'auth-source-save-behavior nil))
1487               (?e (setq add (read-string "Line to add: " add)))
1488               (t nil)))
1489
1490           (when (get-buffer-window bufname)
1491             (delete-window (get-buffer-window bufname)))
1492
1493           ;; Make sure the info is not saved.
1494           (when (null auth-source-save-behavior)
1495             (setq add ""))
1496
1497           (when (< 0 (length add))
1498             (progn
1499               (unless (bolp)
1500                 (insert "\n"))
1501               (insert add "\n")
1502               (write-region (point-min) (point-max) file nil 'silent)
1503               ;; Make the .authinfo file non-world-readable.
1504               (set-file-modes file #o600)
1505               (auth-source-do-debug
1506                "auth-source-netrc-create: wrote 1 new line to %s"
1507                file)
1508               (message "Saved new authentication information to %s" file)
1509               nil))))
1510       (auth-source--aput auth-source-netrc-cache key "ran"))))
1511
1512 ;;; Backend specific parsing: Secrets API backend
1513
1514 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1515 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1516 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1517 ;; (let ((auth-sources '(default))) (auth-source-search))
1518 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1519 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1520
1521 (defun* auth-source-secrets-search (&rest
1522                                     spec
1523                                     &key backend create delete label
1524                                     type max host user port
1525                                     &allow-other-keys)
1526   "Search the Secrets API; spec is like `auth-source'.
1527
1528 The :label key specifies the item's label.  It is the only key
1529 that can specify a substring.  Any :label value besides a string
1530 will allow any label.
1531
1532 All other search keys must match exactly.  If you need substring
1533 matching, do a wider search and narrow it down yourself.
1534
1535 You'll get back all the properties of the token as a plist.
1536
1537 Here's an example that looks for the first item in the 'Login'
1538 Secrets collection:
1539
1540  \(let ((auth-sources '(\"secrets:Login\")))
1541     (auth-source-search :max 1)
1542
1543 Here's another that looks for the first item in the 'Login'
1544 Secrets collection whose label contains 'gnus':
1545
1546  \(let ((auth-sources '(\"secrets:Login\")))
1547     (auth-source-search :max 1 :label \"gnus\")
1548
1549 And this one looks for the first item in the 'Login' Secrets
1550 collection that's a Google Chrome entry for the git.gnus.org site
1551 authentication tokens:
1552
1553  \(let ((auth-sources '(\"secrets:Login\")))
1554     (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1555 "
1556
1557   ;; TODO
1558   (assert (not create) nil
1559           "The Secrets API auth-source backend doesn't support creation yet")
1560   ;; TODO
1561   ;; (secrets-delete-item coll elt)
1562   (assert (not delete) nil
1563           "The Secrets API auth-source backend doesn't support deletion yet")
1564
1565   (let* ((coll (oref backend source))
1566          (max (or max 5000))     ; sanity check: default to stop at 5K
1567          (ignored-keys '(:create :delete :max :backend :label :require :type))
1568          (search-keys (loop for i below (length spec) by 2
1569                             unless (memq (nth i spec) ignored-keys)
1570                             collect (nth i spec)))
1571          ;; build a search spec without the ignored keys
1572          ;; if a search key is nil or t (match anything), we skip it
1573          (search-spec (apply 'append (mapcar
1574                                       (lambda (k)
1575                                         (if (or (null (plist-get spec k))
1576                                                 (eq t (plist-get spec k)))
1577                                             nil
1578                                           (list k (plist-get spec k))))
1579                                       search-keys)))
1580          ;; needed keys (always including host, login, port, and secret)
1581          (returned-keys (mm-delete-duplicates (append
1582                                                '(:host :login :port :secret)
1583                                                search-keys)))
1584          (items (loop for item in (apply 'secrets-search-items coll search-spec)
1585                       unless (and (stringp label)
1586                                   (not (string-match label item)))
1587                       collect item))
1588          ;; TODO: respect max in `secrets-search-items', not after the fact
1589          (items (butlast items (- (length items) max)))
1590          ;; convert the item name to a full plist
1591          (items (mapcar (lambda (item)
1592                           (append
1593                            ;; make an entry for the secret (password) element
1594                            (list
1595                             :secret
1596                             (lexical-let ((v (secrets-get-secret coll item)))
1597                               (lambda () v)))
1598                            ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1599                            (apply 'append
1600                                   (mapcar (lambda (entry)
1601                                             (list (car entry) (cdr entry)))
1602                                           (secrets-get-attributes coll item)))))
1603                         items))
1604          ;; ensure each item has each key in `returned-keys'
1605          (items (mapcar (lambda (plist)
1606                           (append
1607                            (apply 'append
1608                                   (mapcar (lambda (req)
1609                                             (if (plist-get plist req)
1610                                                 nil
1611                                               (list req nil)))
1612                                           returned-keys))
1613                            plist))
1614                         items)))
1615     items))
1616
1617 (defun* auth-source-secrets-create (&rest
1618                                     spec
1619                                     &key backend type max host user port
1620                                     &allow-other-keys)
1621   ;; TODO
1622   ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1623   (debug spec))
1624
1625 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1626
1627 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1628 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1629 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1630 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1631
1632 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1633 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1634 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1635 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1636
1637 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1638 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1639
1640 (defun* auth-source-macos-keychain-search (&rest
1641                                     spec
1642                                     &key backend create delete label
1643                                     type max host user port
1644                                     &allow-other-keys)
1645   "Search the MacOS Keychain; spec is like `auth-source'.
1646
1647 All search keys must match exactly.  If you need substring
1648 matching, do a wider search and narrow it down yourself.
1649
1650 You'll get back all the properties of the token as a plist.
1651
1652 The :type key is either 'macos-keychain-internet or
1653 'macos-keychain-generic.
1654
1655 For the internet keychain type, the :label key searches the
1656 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1657 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1658 and :port maps to \"-P PORT\" or \"-r PROT\"
1659 (note PROT has to be a 4-character string).
1660
1661 For the generic keychain type, the :label key searches the item's
1662 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1663 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1664 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1665
1666 Here's an example that looks for the first item in the default
1667 generic MacOS Keychain:
1668
1669  \(let ((auth-sources '(macos-keychain-generic)))
1670     (auth-source-search :max 1)
1671
1672 Here's another that looks for the first item in the internet
1673 MacOS Keychain collection whose label is 'gnus':
1674
1675  \(let ((auth-sources '(macos-keychain-internet)))
1676     (auth-source-search :max 1 :label \"gnus\")
1677
1678 And this one looks for the first item in the internet keychain
1679 entries for git.gnus.org:
1680
1681  \(let ((auth-sources '(macos-keychain-internet\")))
1682     (auth-source-search :max 1 :host \"git.gnus.org\"))
1683 "
1684   ;; TODO
1685   (assert (not create) nil
1686           "The MacOS Keychain auth-source backend doesn't support creation yet")
1687   ;; TODO
1688   ;; (macos-keychain-delete-item coll elt)
1689   (assert (not delete) nil
1690           "The MacOS Keychain auth-source backend doesn't support deletion yet")
1691
1692   (let* ((coll (oref backend source))
1693          (max (or max 5000))     ; sanity check: default to stop at 5K
1694          (ignored-keys '(:create :delete :max :backend :label))
1695          (search-keys (loop for i below (length spec) by 2
1696                             unless (memq (nth i spec) ignored-keys)
1697                             collect (nth i spec)))
1698          ;; build a search spec without the ignored keys
1699          ;; if a search key is nil or t (match anything), we skip it
1700          (search-spec (apply 'append (mapcar
1701                                       (lambda (k)
1702                                         (if (or (null (plist-get spec k))
1703                                                 (eq t (plist-get spec k)))
1704                                             nil
1705                                           (list k (plist-get spec k))))
1706                                       search-keys)))
1707          ;; needed keys (always including host, login, port, and secret)
1708          (returned-keys (mm-delete-duplicates (append
1709                                                '(:host :login :port :secret)
1710                                                search-keys)))
1711          (items (apply 'auth-source-macos-keychain-search-items
1712                        coll
1713                        type
1714                        max
1715                        search-spec))
1716
1717          ;; ensure each item has each key in `returned-keys'
1718          (items (mapcar (lambda (plist)
1719                           (append
1720                            (apply 'append
1721                                   (mapcar (lambda (req)
1722                                             (if (plist-get plist req)
1723                                                 nil
1724                                               (list req nil)))
1725                                           returned-keys))
1726                            plist))
1727                         items)))
1728     items))
1729
1730 (defun* auth-source-macos-keychain-search-items (coll type max
1731                                                       &rest spec
1732                                                       &key label type
1733                                                       host user port
1734                                                       &allow-other-keys)
1735
1736   (let* ((keychain-generic (eq type 'macos-keychain-generic))
1737          (args `(,(if keychain-generic
1738                       "find-generic-password"
1739                     "find-internet-password")
1740                  "-g"))
1741          (ret (list :type type)))
1742     (when label
1743       (setq args (append args (list "-l" label))))
1744     (when host
1745       (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1746     (when user
1747       (setq args (append args (list "-a" user))))
1748
1749     (when port
1750       (if keychain-generic
1751           (setq args (append args (list "-s" port)))
1752         (setq args (append args (list
1753                                  (if (string-match "[0-9]+" port) "-P" "-r")
1754                                  port)))))
1755
1756       (unless (equal coll "default")
1757         (setq args (append args (list coll))))
1758
1759       (with-temp-buffer
1760         (apply 'call-process "/usr/bin/security" nil t nil args)
1761         (goto-char (point-min))
1762         (while (not (eobp))
1763           (cond
1764            ((looking-at "^password: \"\\(.+\\)\"$")
1765             (auth-source-macos-keychain-result-append
1766              ret
1767              keychain-generic
1768              "secret"
1769              (lexical-let ((v (match-string 1)))
1770                (lambda () v))))
1771            ;; TODO: check if this is really the label
1772            ;; match 0x00000007 <blob>="AppleID"
1773            ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1774             (auth-source-macos-keychain-result-append
1775              ret
1776              keychain-generic
1777              "label"
1778              (match-string 1)))
1779            ;; match "crtr"<uint32>="aapl"
1780            ;; match "svce"<blob>="AppleID"
1781            ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1782             (auth-source-macos-keychain-result-append
1783              ret
1784              keychain-generic
1785              (match-string 1)
1786              (match-string 2))))
1787             (forward-line)))
1788       ;; return `ret' iff it has the :secret key
1789       (and (plist-get ret :secret) (list ret))))
1790
1791 (defun auth-source-macos-keychain-result-append (result generic k v)
1792   (push v result)
1793   (setq k (cond
1794            ((equal k "acct") "user")
1795            ;; for generic keychains, creator is host, service is port
1796            ((and generic (equal k "crtr")) "host")
1797            ((and generic (equal k "svce")) "port")
1798            ;; for internet keychains, protocol is port, server is host
1799            ((and (not generic) (equal k "ptcl")) "port")
1800            ((and (not generic) (equal k "srvr")) "host")
1801            (t k)))
1802
1803   (push (intern (format ":%s" k)) result))
1804
1805 (defun* auth-source-macos-keychain-create (&rest
1806                                            spec
1807                                            &key backend type max host user port
1808                                            &allow-other-keys)
1809   ;; TODO
1810   (debug spec))
1811
1812 ;;; Backend specific parsing: PLSTORE backend
1813
1814 (defun* auth-source-plstore-search (&rest
1815                                     spec
1816                                     &key backend create delete label
1817                                     type max host user port
1818                                     &allow-other-keys)
1819   "Search the PLSTORE; spec is like `auth-source'."
1820   (let* ((store (oref backend data))
1821          (max (or max 5000))     ; sanity check: default to stop at 5K
1822          (ignored-keys '(:create :delete :max :backend :label :require :type))
1823          (search-keys (loop for i below (length spec) by 2
1824                             unless (memq (nth i spec) ignored-keys)
1825                             collect (nth i spec)))
1826          ;; build a search spec without the ignored keys
1827          ;; if a search key is nil or t (match anything), we skip it
1828          (search-spec (apply 'append (mapcar
1829                                       (lambda (k)
1830                                         (let ((v (plist-get spec k)))
1831                                           (if (or (null v)
1832                                                   (eq t v))
1833                                               nil
1834                                             (if (stringp v)
1835                                                 (setq v (list v)))
1836                                             (list k v))))
1837                                       search-keys)))
1838          ;; needed keys (always including host, login, port, and secret)
1839          (returned-keys (mm-delete-duplicates (append
1840                                                '(:host :login :port :secret)
1841                                                search-keys)))
1842          (items (plstore-find store search-spec))
1843          (item-names (mapcar #'car items))
1844          (items (butlast items (- (length items) max)))
1845          ;; convert the item to a full plist
1846          (items (mapcar (lambda (item)
1847                           (let* ((plist (copy-tree (cdr item)))
1848                                  (secret (plist-member plist :secret)))
1849                             (if secret
1850                                 (setcar
1851                                  (cdr secret)
1852                                  (lexical-let ((v (car (cdr secret))))
1853                                    (lambda () v))))
1854                             plist))
1855                         items))
1856          ;; ensure each item has each key in `returned-keys'
1857          (items (mapcar (lambda (plist)
1858                           (append
1859                            (apply 'append
1860                                   (mapcar (lambda (req)
1861                                             (if (plist-get plist req)
1862                                                 nil
1863                                               (list req nil)))
1864                                           returned-keys))
1865                            plist))
1866                         items)))
1867     (cond
1868      ;; if we need to create an entry AND none were found to match
1869      ((and create
1870            (not items))
1871
1872       ;; create based on the spec and record the value
1873       (setq items (or
1874                    ;; if the user did not want to create the entry
1875                    ;; in the file, it will be returned
1876                    (apply (slot-value backend 'create-function) spec)
1877                    ;; if not, we do the search again without :create
1878                    ;; to get the updated data.
1879
1880                    ;; the result will be returned, even if the search fails
1881                    (apply 'auth-source-plstore-search
1882                           (plist-put spec :create nil)))))
1883      ((and delete
1884            item-names)
1885       (dolist (item-name item-names)
1886         (plstore-delete store item-name))
1887       (plstore-save store)))
1888     items))
1889
1890 (defun* auth-source-plstore-create (&rest spec
1891                                           &key backend
1892                                           secret host user port create
1893                                           &allow-other-keys)
1894   (let* ((base-required '(host user port secret))
1895          (base-secret '(secret))
1896          ;; we know (because of an assertion in auth-source-search) that the
1897          ;; :create parameter is either t or a list (which includes nil)
1898          (create-extra (if (eq t create) nil create))
1899          (current-data (car (auth-source-search :max 1
1900                                                 :host host
1901                                                 :port port)))
1902          (required (append base-required create-extra))
1903          (file (oref backend source))
1904          (add "")
1905          ;; `valist' is an alist
1906          valist
1907          ;; `artificial' will be returned if no creation is needed
1908          artificial
1909          secret-artificial)
1910
1911     ;; only for base required elements (defined as function parameters):
1912     ;; fill in the valist with whatever data we may have from the search
1913     ;; we complete the first value if it's a list and use the value otherwise
1914     (dolist (br base-required)
1915       (when (symbol-value br)
1916         (let ((br-choice (cond
1917                           ;; all-accepting choice (predicate is t)
1918                           ((eq t (symbol-value br)) nil)
1919                           ;; just the value otherwise
1920                           (t (symbol-value br)))))
1921           (when br-choice
1922             (auth-source--aput valist br br-choice)))))
1923
1924     ;; for extra required elements, see if the spec includes a value for them
1925     (dolist (er create-extra)
1926       (let ((name (concat ":" (symbol-name er)))
1927             (keys (loop for i below (length spec) by 2
1928                         collect (nth i spec))))
1929         (dolist (k keys)
1930           (when (equal (symbol-name k) name)
1931             (auth-source--aput valist er (plist-get spec k))))))
1932
1933     ;; for each required element
1934     (dolist (r required)
1935       (let* ((data (auth-source--aget valist r))
1936              ;; take the first element if the data is a list
1937              (data (or (auth-source-netrc-element-or-first data)
1938                        (plist-get current-data
1939                                   (intern (format ":%s" r) obarray))))
1940              ;; this is the default to be offered
1941              (given-default (auth-source--aget
1942                              auth-source-creation-defaults r))
1943              ;; the default supplementals are simple:
1944              ;; for the user, try `given-default' and then (user-login-name);
1945              ;; otherwise take `given-default'
1946              (default (cond
1947                        ((and (not given-default) (eq r 'user))
1948                         (user-login-name))
1949                        (t given-default)))
1950              (printable-defaults (list
1951                                   (cons 'user
1952                                         (or
1953                                          (auth-source-netrc-element-or-first
1954                                           (auth-source--aget valist 'user))
1955                                          (plist-get artificial :user)
1956                                          "[any user]"))
1957                                   (cons 'host
1958                                         (or
1959                                          (auth-source-netrc-element-or-first
1960                                           (auth-source--aget valist 'host))
1961                                          (plist-get artificial :host)
1962                                          "[any host]"))
1963                                   (cons 'port
1964                                         (or
1965                                          (auth-source-netrc-element-or-first
1966                                           (auth-source--aget valist 'port))
1967                                          (plist-get artificial :port)
1968                                          "[any port]"))))
1969              (prompt (or (auth-source--aget auth-source-creation-prompts r)
1970                          (case r
1971                            (secret "%p password for %u@%h: ")
1972                            (user "%p user name for %h: ")
1973                            (host "%p host name for user %u: ")
1974                            (port "%p port for %u@%h: "))
1975                          (format "Enter %s (%%u@%%h:%%p): " r)))
1976              (prompt (auth-source-format-prompt
1977                       prompt
1978                       `((?u ,(auth-source--aget printable-defaults 'user))
1979                         (?h ,(auth-source--aget printable-defaults 'host))
1980                         (?p ,(auth-source--aget printable-defaults 'port))))))
1981
1982         ;; Store the data, prompting for the password if needed.
1983         (setq data (or data
1984                        (if (eq r 'secret)
1985                            (or (eval default) (read-passwd prompt))
1986                          (if (stringp default)
1987                              (read-string
1988                               (if (string-match ": *\\'" prompt)
1989                                   (concat (substring prompt 0 (match-beginning 0))
1990                                           " (default " default "): ")
1991                                 (concat prompt "(default " default ") "))
1992                               nil nil default)
1993                            (eval default)))))
1994
1995         (when data
1996           (if (member r base-secret)
1997               (setq secret-artificial
1998                     (plist-put secret-artificial
1999                                (intern (concat ":" (symbol-name r)))
2000                                data))
2001             (setq artificial (plist-put artificial
2002                                         (intern (concat ":" (symbol-name r)))
2003                                         data))))))
2004     (plstore-put (oref backend data)
2005                  (sha1 (format "%s@%s:%s"
2006                                (plist-get artificial :user)
2007                                (plist-get artificial :host)
2008                                (plist-get artificial :port)))
2009                  artificial secret-artificial)
2010     (if (y-or-n-p (format "Save auth info to file %s? "
2011                           (plstore-get-file (oref backend data))))
2012         (plstore-save (oref backend data)))))
2013
2014 ;;; older API
2015
2016 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2017
2018 ;; deprecate the old interface
2019 (make-obsolete 'auth-source-user-or-password
2020                'auth-source-search "Emacs 24.1")
2021 (make-obsolete 'auth-source-forget-user-or-password
2022                'auth-source-forget "Emacs 24.1")
2023
2024 (defun auth-source-user-or-password
2025   (mode host port &optional username create-missing delete-existing)
2026   "Find MODE (string or list of strings) matching HOST and PORT.
2027
2028 DEPRECATED in favor of `auth-source-search'!
2029
2030 USERNAME is optional and will be used as \"login\" in a search
2031 across the Secret Service API (see secrets.el) if the resulting
2032 items don't have a username.  This means that if you search for
2033 username \"joe\" and it matches an item but the item doesn't have
2034 a :user attribute, the username \"joe\" will be returned.
2035
2036 A non nil DELETE-EXISTING means deleting any matching password
2037 entry in the respective sources.  This is useful only when
2038 CREATE-MISSING is non nil as well; the intended use case is to
2039 remove wrong password entries.
2040
2041 If no matching entry is found, and CREATE-MISSING is non nil,
2042 the password will be retrieved interactively, and it will be
2043 stored in the password database which matches best (see
2044 `auth-sources').
2045
2046 MODE can be \"login\" or \"password\"."
2047   (auth-source-do-debug
2048    "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2049    mode host port username)
2050
2051   (let* ((listy (listp mode))
2052          (mode (if listy mode (list mode)))
2053          (cname (if username
2054                     (format "%s %s:%s %s" mode host port username)
2055                   (format "%s %s:%s" mode host port)))
2056          (search (list :host host :port port))
2057          (search (if username (append search (list :user username)) search))
2058          (search (if create-missing
2059                      (append search (list :create t))
2060                    search))
2061          (search (if delete-existing
2062                      (append search (list :delete t))
2063                    search))
2064          ;; (found (if (not delete-existing)
2065          ;;            (gethash cname auth-source-cache)
2066          ;;          (remhash cname auth-source-cache)
2067          ;;          nil)))
2068          (found nil))
2069     (if found
2070         (progn
2071           (auth-source-do-debug
2072            "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2073            mode
2074            ;; don't show the password
2075            (if (and (member "password" mode) t)
2076                "SECRET"
2077              found)
2078            host port username)
2079           found)                        ; return the found data
2080       ;; else, if not found, search with a max of 1
2081       (let ((choice (nth 0 (apply 'auth-source-search
2082                                   (append '(:max 1) search)))))
2083         (when choice
2084           (dolist (m mode)
2085             (cond
2086              ((equal "password" m)
2087               (push (if (plist-get choice :secret)
2088                         (funcall (plist-get choice :secret))
2089                       nil) found))
2090              ((equal "login" m)
2091               (push (plist-get choice :user) found)))))
2092         (setq found (nreverse found))
2093         (setq found (if listy found (car-safe found)))))
2094
2095     found))
2096
2097 (defun auth-source-user-and-password (host &optional user)
2098   (let* ((auth-info (car
2099                      (if user
2100                          (auth-source-search
2101                           :host host
2102                           :user "yourusername"
2103                           :max 1
2104                           :require '(:user :secret)
2105                           :create nil)
2106                        (auth-source-search
2107                         :host host
2108                         :max 1
2109                         :require '(:user :secret)
2110                         :create nil))))
2111          (user (plist-get auth-info :user))
2112          (password (plist-get auth-info :secret)))
2113     (when (functionp password)
2114       (setq password (funcall password)))
2115     (list user password auth-info)))
2116
2117 (provide 'auth-source)
2118
2119 ;;; auth-source.el ends here