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