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