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