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