* auth-source.el (auth-source-epa-make-gpg-token):
[gnus] / lisp / auth-source.el
1 ;;; auth-source.el --- authentication sources for Gnus and Emacs
2
3 ;; Copyright (C) 2008-2015 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 `\\[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 if and how tokens will be 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 More than N items may be returned, depending on the search and
668 the backend.
669
670 When :max is 0 the function will return just t or nil to indicate
671 if any matches were found.
672
673 :host (X Y Z) means to match only hosts X, Y, or Z according to
674 the match rules above.  Defaults to t.
675
676 :user (X Y Z) means to match only users X, Y, or Z according to
677 the match rules above.  Defaults to t.
678
679 :port (P Q R) means to match only protocols P, Q, or R.
680 Defaults to t.
681
682 :K (V1 V2 V3) for any other key K will match values V1, V2, or
683 V3 (note the match rules above).
684
685 The return value is a list with at most :max tokens.  Each token
686 is a plist with keys :backend :host :port :user, plus any other
687 keys provided by the backend (notably :secret).  But note the
688 exception for :max 0, which see above.
689
690 The token can hold a :save-function key.  If you call that, the
691 user will be prompted to save the data to the backend.  You can't
692 request that this should happen right after creation, because
693 `auth-source-search' has no way of knowing if the token is
694 actually useful.  So the caller must arrange to call this function.
695
696 The token's :secret key can hold a function.  In that case you
697 must call it to obtain the actual value."
698   (let* ((backends (mapcar #'auth-source-backend-parse auth-sources))
699          (max (or max 1))
700          (ignored-keys '(:require :create :delete :max))
701          (keys (loop for i below (length spec) by 2
702                      unless (memq (nth i spec) ignored-keys)
703                      collect (nth i spec)))
704          (cached (auth-source-remembered-p spec))
705          ;; note that we may have cached results but found is still nil
706          ;; (there were no results from the search)
707          (found (auth-source-recall spec))
708          filtered-backends accessor-key backend)
709
710     (if (and cached auth-source-do-cache)
711         (auth-source-do-debug
712          "auth-source-search: found %d CACHED results matching %S"
713          (length found) spec)
714
715       (assert
716        (or (eq t create) (listp create)) t
717        "Invalid auth-source :create parameter (must be t or a list): %s %s")
718
719       (assert
720        (listp require) t
721        "Invalid auth-source :require parameter (must be a list): %s")
722
723       (setq filtered-backends (copy-sequence backends))
724       (dolist (backend backends)
725         (dolist (key keys)
726           ;; ignore invalid slots
727           (condition-case signal
728               (unless (eval `(auth-source-search-collection
729                               (plist-get spec key)
730                               (oref backend ,key)))
731                 (setq filtered-backends (delq backend filtered-backends))
732                 (return))
733             (invalid-slot-name))))
734
735       (auth-source-do-trivia
736        "auth-source-search: found %d backends matching %S"
737        (length filtered-backends) spec)
738
739       ;; (debug spec "filtered" filtered-backends)
740       ;; First go through all the backends without :create, so we can
741       ;; query them all.
742       (setq found (auth-source-search-backends filtered-backends
743                                                spec
744                                                ;; to exit early
745                                                max
746                                                ;; create is always nil here
747                                                nil delete
748                                                require))
749
750       (auth-source-do-debug
751        "auth-source-search: found %d results (max %d) matching %S"
752        (length found) max spec)
753
754       ;; If we didn't find anything, then we allow the backend(s) to
755       ;; create the entries.
756       (when (and create
757                  (not found))
758         (setq found (auth-source-search-backends filtered-backends
759                                                  spec
760                                                  ;; to exit early
761                                                  max
762                                                  create delete
763                                                  require))
764         (auth-source-do-debug
765          "auth-source-search: CREATED %d results (max %d) matching %S"
766          (length found) max spec))
767
768       ;; note we remember the lack of result too, if it's applicable
769       (when auth-source-do-cache
770         (auth-source-remember spec found)))
771
772     (if (zerop max)
773         (not (null found))
774       found)))
775
776 (defun auth-source-search-backends (backends spec max create delete require)
777   (let ((max (if (zerop max) 1 max)) ; stop with 1 match if we're asked for zero
778         matches)
779     (dolist (backend backends)
780       (when (> max (length matches)) ; if we need more matches...
781         (let* ((bmatches (apply
782                           (slot-value backend 'search-function)
783                           :backend backend
784                           :type (slot-value backend :type)
785                           ;; note we're overriding whatever the spec
786                           ;; has for :max, :require, :create, and :delete
787                           :max max
788                           :require require
789                           :create create
790                           :delete delete
791                           spec)))
792           (when bmatches
793             (auth-source-do-trivia
794              "auth-source-search-backend: got %d (max %d) in %s:%s matching %S"
795              (length bmatches) max
796              (slot-value backend :type)
797              (slot-value backend :source)
798              spec)
799             (setq matches (append matches bmatches))))))
800     matches))
801
802 ;; (auth-source-search :max 0)
803 ;; (auth-source-search :max 1)
804 ;; (funcall (plist-get (nth 0 (auth-source-search :max 1)) :secret))
805 ;; (auth-source-search :host "nonesuch" :type 'netrc :K 1)
806 ;; (auth-source-search :host "nonesuch" :type 'secrets)
807
808 (defun* auth-source-delete (&rest spec
809                                   &key delete
810                                   &allow-other-keys)
811   "Delete entries from the authentication backends according to SPEC.
812 Calls `auth-source-search' with the :delete property in SPEC set to t.
813 The backend may not actually delete the entries.
814
815 Returns the deleted entries."
816   (auth-source-search (plist-put spec :delete t)))
817
818 (defun auth-source-search-collection (collection value)
819   "Returns t is VALUE is t or COLLECTION is t or COLLECTION contains VALUE."
820   (when (and (atom collection) (not (eq t collection)))
821     (setq collection (list collection)))
822
823   ;; (debug :collection collection :value value)
824   (or (eq collection t)
825       (eq value t)
826       (equal collection value)
827       (member value collection)))
828
829 (defvar auth-source-netrc-cache nil)
830
831 (defun auth-source-forget-all-cached ()
832   "Forget all cached auth-source data."
833   (interactive)
834   (loop for sym being the symbols of password-data
835         ;; when the symbol name starts with auth-source-magic
836         when (string-match (concat "^" auth-source-magic)
837                            (symbol-name sym))
838         ;; remove that key
839         do (password-cache-remove (symbol-name sym)))
840   (setq auth-source-netrc-cache nil))
841
842 (defun auth-source-format-cache-entry (spec)
843   "Format SPEC entry to put it in the password cache."
844   (concat auth-source-magic (format "%S" spec)))
845
846 (defun auth-source-remember (spec found)
847   "Remember FOUND search results for SPEC."
848   (let ((password-cache-expiry auth-source-cache-expiry))
849     (password-cache-add
850      (auth-source-format-cache-entry spec) found)))
851
852 (defun auth-source-recall (spec)
853   "Recall FOUND search results for SPEC."
854   (password-read-from-cache (auth-source-format-cache-entry spec)))
855
856 (defun auth-source-remembered-p (spec)
857   "Check if SPEC is remembered."
858   (password-in-cache-p
859    (auth-source-format-cache-entry spec)))
860
861 (defun auth-source-forget (spec)
862   "Forget any cached data matching SPEC exactly.
863
864 This is the same SPEC you passed to `auth-source-search'.
865 Returns t or nil for forgotten or not found."
866   (password-cache-remove (auth-source-format-cache-entry spec)))
867
868 ;; (loop for sym being the symbols of password-data when (string-match (concat "^" auth-source-magic) (symbol-name sym)) collect (symbol-name sym))
869
870 ;; (auth-source-remember '(:host "wedd") '(4 5 6))
871 ;; (auth-source-remembered-p '(:host "wedd"))
872 ;; (auth-source-remember '(:host "xedd") '(1 2 3))
873 ;; (auth-source-remembered-p '(:host "xedd"))
874 ;; (auth-source-remembered-p '(:host "zedd"))
875 ;; (auth-source-recall '(:host "xedd"))
876 ;; (auth-source-recall '(:host t))
877 ;; (auth-source-forget+ :host t)
878
879 (defun* auth-source-forget+ (&rest spec &allow-other-keys)
880   "Forget any cached data matching SPEC.  Returns forgotten count.
881
882 This is not a full `auth-source-search' spec but works similarly.
883 For instance, \(:host \"myhost\" \"yourhost\") would find all the
884 cached data that was found with a search for those two hosts,
885 while \(:host t) would find all host entries."
886   (let ((count 0)
887         sname)
888     (loop for sym being the symbols of password-data
889           ;; when the symbol name matches with auth-source-magic
890           when (and (setq sname (symbol-name sym))
891                     (string-match (concat "^" auth-source-magic "\\(.+\\)")
892                                   sname)
893                     ;; and the spec matches what was stored in the cache
894                     (auth-source-specmatchp spec (read (match-string 1 sname))))
895           ;; remove that key
896           do (progn
897                (password-cache-remove sname)
898                (incf count)))
899     count))
900
901 (defun auth-source-specmatchp (spec stored)
902   (let ((keys (loop for i below (length spec) by 2
903                     collect (nth i spec))))
904     (not (eq
905           (dolist (key keys)
906             (unless (auth-source-search-collection (plist-get stored key)
907                                                    (plist-get spec key))
908               (return 'no)))
909           'no))))
910
911 ;; (auth-source-pick-first-password :host "z.lifelogs.com")
912 ;; (auth-source-pick-first-password :port "imap")
913 (defun auth-source-pick-first-password (&rest spec)
914   "Pick the first secret found from applying SPEC to `auth-source-search'."
915   (let* ((result (nth 0 (apply #'auth-source-search (plist-put spec :max 1))))
916          (secret (plist-get result :secret)))
917
918     (if (functionp secret)
919         (funcall secret)
920       secret)))
921
922 ;; (auth-source-format-prompt "test %u %h %p" '((?u "user") (?h "host")))
923 (defun auth-source-format-prompt (prompt alist)
924   "Format PROMPT using %x (for any character x) specifiers in ALIST."
925   (dolist (cell alist)
926     (let ((c (nth 0 cell))
927           (v (nth 1 cell)))
928       (when (and c v)
929         (setq prompt (replace-regexp-in-string (format "%%%c" c)
930                                                (format "%s" v)
931                                                prompt nil t)))))
932   prompt)
933
934 (defun auth-source-ensure-strings (values)
935   (unless (listp values)
936     (setq values (list values)))
937   (mapcar (lambda (value)
938             (if (numberp value)
939                 (format "%s" value)
940               value))
941           values))
942
943 ;;; Backend specific parsing: netrc/authinfo backend
944
945 (defun auth-source--aput-1 (alist key val)
946   (let ((seen ())
947         (rest alist))
948     (while (and (consp rest) (not (equal key (caar rest))))
949       (push (pop rest) seen))
950     (cons (cons key val)
951           (if (null rest) alist
952             (nconc (nreverse seen)
953                    (if (equal key (caar rest)) (cdr rest) rest))))))
954 (defmacro auth-source--aput (var key val)
955   `(setq ,var (auth-source--aput-1 ,var ,key ,val)))
956
957 (defun auth-source--aget (alist key)
958   (cdr (assoc key alist)))
959
960 ;; (auth-source-netrc-parse :file "~/.authinfo.gpg")
961 (defun* auth-source-netrc-parse (&rest
962                                  spec
963                                  &key file max host user port delete require
964                                  &allow-other-keys)
965   "Parse FILE and return a list of all entries in the file.
966 Note that the MAX parameter is used so we can exit the parse early."
967   (if (listp file)
968       ;; We got already parsed contents; just return it.
969       file
970     (when (file-exists-p file)
971       (setq port (auth-source-ensure-strings port))
972       (with-temp-buffer
973         (let* ((max (or max 5000))       ; sanity check: default to stop at 5K
974                (modified 0)
975                (cached (cdr-safe (assoc file auth-source-netrc-cache)))
976                (cached-mtime (plist-get cached :mtime))
977                (cached-secrets (plist-get cached :secret))
978                (check (lambda(alist)
979                         (and alist
980                              (auth-source-search-collection
981                               host
982                               (or
983                                (auth-source--aget alist "machine")
984                                (auth-source--aget alist "host")
985                                t))
986                              (auth-source-search-collection
987                               user
988                               (or
989                                (auth-source--aget alist "login")
990                                (auth-source--aget alist "account")
991                                (auth-source--aget alist "user")
992                                t))
993                              (auth-source-search-collection
994                               port
995                               (or
996                                (auth-source--aget alist "port")
997                                (auth-source--aget alist "protocol")
998                                t))
999                              (or
1000                               ;; the required list of keys is nil, or
1001                               (null require)
1002                               ;; every element of require is in n(ormalized)
1003                               (let ((n (nth 0 (auth-source-netrc-normalize
1004                                                (list alist) file))))
1005                                 (loop for req in require
1006                                       always (plist-get n req)))))))
1007                result)
1008
1009           (if (and (functionp cached-secrets)
1010                    (equal cached-mtime
1011                           (nth 5 (file-attributes file))))
1012               (progn
1013                 (auth-source-do-trivia
1014                  "auth-source-netrc-parse: using CACHED file data for %s"
1015                  file)
1016                 (insert (funcall cached-secrets)))
1017             (insert-file-contents file)
1018             ;; cache all netrc files (used to be just .gpg files)
1019             ;; Store the contents of the file heavily encrypted in memory.
1020             ;; (note for the irony-impaired: they are just obfuscated)
1021             (auth-source--aput
1022              auth-source-netrc-cache file
1023              (list :mtime (nth 5 (file-attributes file))
1024                    :secret (lexical-let ((v (mapcar #'1+ (buffer-string))))
1025                              (lambda () (apply #'string (mapcar #'1- v)))))))
1026           (goto-char (point-min))
1027           (let ((entries (auth-source-netrc-parse-entries check max))
1028                 alist)
1029             (while (setq alist (pop entries))
1030                 (push (nreverse alist) result)))
1031
1032           (when (< 0 modified)
1033             (when auth-source-gpg-encrypt-to
1034               ;; (see bug#7487) making `epa-file-encrypt-to' local to
1035               ;; this buffer lets epa-file skip the key selection query
1036               ;; (see the `local-variable-p' check in
1037               ;; `epa-file-write-region').
1038               (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1039                 (make-local-variable 'epa-file-encrypt-to))
1040               (if (listp auth-source-gpg-encrypt-to)
1041                   (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1042
1043             ;; ask AFTER we've successfully opened the file
1044             (when (y-or-n-p (format "Save file %s? (%d deletions)"
1045                                     file modified))
1046               (write-region (point-min) (point-max) file nil 'silent)
1047               (auth-source-do-debug
1048                "auth-source-netrc-parse: modified %d lines in %s"
1049                modified file)))
1050
1051           (nreverse result))))))
1052
1053 (defun auth-source-netrc-parse-next-interesting ()
1054   "Advance to the next interesting position in the current buffer."
1055   ;; If we're looking at a comment or are at the end of the line, move forward
1056   (while (or (looking-at "#")
1057              (and (eolp)
1058                   (not (eobp))))
1059     (forward-line 1))
1060   (skip-chars-forward "\t "))
1061
1062 (defun auth-source-netrc-parse-one ()
1063   "Read one thing from the current buffer."
1064   (auth-source-netrc-parse-next-interesting)
1065
1066   (when (or (looking-at "'\\([^']*\\)'")
1067             (looking-at "\"\\([^\"]*\\)\"")
1068             (looking-at "\\([^ \t\n]+\\)"))
1069     (forward-char (length (match-string 0)))
1070     (auth-source-netrc-parse-next-interesting)
1071     (match-string-no-properties 1)))
1072
1073 ;; with thanks to org-mode
1074 (defsubst auth-source-current-line (&optional pos)
1075   (save-excursion
1076     (and pos (goto-char pos))
1077     ;; works also in narrowed buffer, because we start at 1, not point-min
1078     (+ (if (bolp) 1 0) (count-lines 1 (point)))))
1079
1080 (defun auth-source-netrc-parse-entries(check max)
1081   "Parse up to MAX netrc entries, passed by CHECK, from the current buffer."
1082   (let ((adder (lambda(check alist all)
1083                  (when (and
1084                         alist
1085                         (> max (length all))
1086                         (funcall check alist))
1087                    (push alist all))
1088                  all))
1089         item item2 all alist default)
1090     (while (setq item (auth-source-netrc-parse-one))
1091       (setq default (equal item "default"))
1092       ;; We're starting a new machine.  Save the old one.
1093       (when (and alist
1094                  (or default
1095                      (equal item "machine")))
1096         ;; (auth-source-do-trivia
1097         ;;  "auth-source-netrc-parse-entries: got entry %S" alist)
1098         (setq all (funcall adder check alist all)
1099               alist nil))
1100       ;; In default entries, we don't have a next token.
1101       ;; We store them as ("machine" . t)
1102       (if default
1103           (push (cons "machine" t) alist)
1104         ;; Not a default entry.  Grab the next item.
1105         (when (setq item2 (auth-source-netrc-parse-one))
1106           ;; Did we get a "machine" value?
1107           (if (equal item2 "machine")
1108               (progn
1109                 (gnus-error 1
1110                  "%s: Unexpected `machine' token at line %d"
1111                  "auth-source-netrc-parse-entries"
1112                  (auth-source-current-line))
1113                 (forward-line 1))
1114             (push (cons item item2) alist)))))
1115
1116     ;; Clean up: if there's an entry left over, use it.
1117     (when alist
1118       (setq all (funcall adder check alist all))
1119       ;; (auth-source-do-trivia
1120       ;;  "auth-source-netrc-parse-entries: got2 entry %S" alist)
1121       )
1122     (nreverse all)))
1123
1124 (defvar auth-source-passphrase-alist nil)
1125
1126 (defun auth-source-token-passphrase-callback-function (context key-id file)
1127   (let* ((file (file-truename file))
1128          (entry (assoc file auth-source-passphrase-alist))
1129          passphrase)
1130     ;; return the saved passphrase, calling a function if needed
1131     (or (copy-sequence (if (functionp (cdr entry))
1132                            (funcall (cdr entry))
1133                          (cdr entry)))
1134         (progn
1135           (unless entry
1136             (setq entry (list file))
1137             (push entry auth-source-passphrase-alist))
1138           (setq passphrase
1139                 (read-passwd
1140                  (format "Passphrase for %s tokens: " file)
1141                  t))
1142           (setcdr entry (lexical-let ((p (copy-sequence passphrase)))
1143                           (lambda () p)))
1144           passphrase))))
1145
1146 ;; (auth-source-epa-extract-gpg-token "gpg:LS0tLS1CRUdJTiBQR1AgTUVTU0FHRS0tLS0tClZlcnNpb246IEdudVBHIHYxLjQuMTEgKEdOVS9MaW51eCkKCmpBMEVBd01DT25qMjB1ak9rZnRneVI3K21iNm9aZWhuLzRad3cySkdlbnVaKzRpeEswWDY5di9icDI1U1dsQT0KPS9yc2wKLS0tLS1FTkQgUEdQIE1FU1NBR0UtLS0tLQo=" "~/.netrc")
1147 (defun auth-source-epa-extract-gpg-token (secret file)
1148   "Pass either the decoded SECRET or the gpg:BASE64DATA version.
1149 FILE is the file from which we obtained this token."
1150   (when (string-match "^gpg:\\(.+\\)" secret)
1151     (setq secret (base64-decode-string (match-string 1 secret))))
1152   (let ((context (epg-make-context 'OpenPGP))
1153         plain)
1154     (epg-context-set-passphrase-callback
1155      context
1156      (cons #'auth-source-token-passphrase-callback-function
1157            file))
1158     (epg-decrypt-string context secret)))
1159
1160 ;; (insert (auth-source-epa-make-gpg-token "mysecret" "~/.netrc"))
1161 (defun auth-source-epa-make-gpg-token (secret file)
1162   (let ((context (epg-make-context 'OpenPGP))
1163         (pp-escape-newlines nil)
1164         cipher)
1165     (setf (epg-context-armor context) t)
1166     (epg-context-set-passphrase-callback
1167      context
1168      (cons #'auth-source-token-passphrase-callback-function
1169            file))
1170     (setq cipher (epg-encrypt-string context secret nil))
1171     (with-temp-buffer
1172       (insert cipher)
1173       (base64-encode-region (point-min) (point-max) t)
1174       (concat "gpg:" (buffer-substring-no-properties
1175                       (point-min)
1176                       (point-max))))))
1177
1178 (defun auth-source-netrc-normalize (alist filename)
1179   (mapcar (lambda (entry)
1180             (let (ret item)
1181               (while (setq item (pop entry))
1182                 (let ((k (car item))
1183                       (v (cdr item)))
1184
1185                   ;; apply key aliases
1186                   (setq k (cond ((member k '("machine")) "host")
1187                                 ((member k '("login" "account")) "user")
1188                                 ((member k '("protocol")) "port")
1189                                 ((member k '("password")) "secret")
1190                                 (t k)))
1191
1192                   ;; send back the secret in a function (lexical binding)
1193                   (when (equal k "secret")
1194                     (setq v (lexical-let ((lexv v)
1195                                           (token-decoder nil))
1196                               (when (string-match "^gpg:" lexv)
1197                                 ;; it's a GPG token: create a token decoder
1198                                 ;; which unsets itself once
1199                                 (setq token-decoder
1200                                       (lambda (val)
1201                                         (prog1
1202                                             (auth-source-epa-extract-gpg-token
1203                                              val
1204                                              filename)
1205                                           (setq token-decoder nil)))))
1206                               (lambda ()
1207                                 (when token-decoder
1208                                   (setq lexv (funcall token-decoder lexv)))
1209                                 lexv))))
1210                   (setq ret (plist-put ret
1211                                        (intern (concat ":" k))
1212                                        v))))
1213               ret))
1214           alist))
1215
1216 ;; (setq secret (plist-get (nth 0 (auth-source-search :host t :type 'netrc :K 1 :max 1)) :secret))
1217 ;; (funcall secret)
1218
1219 (defun* auth-source-netrc-search (&rest
1220                                   spec
1221                                   &key backend require create delete
1222                                   type max host user port
1223                                   &allow-other-keys)
1224   "Given a property list SPEC, return search matches from the :backend.
1225 See `auth-source-search' for details on SPEC."
1226   ;; just in case, check that the type is correct (null or same as the backend)
1227   (assert (or (null type) (eq type (oref backend type)))
1228           t "Invalid netrc search: %s %s")
1229
1230   (let ((results (auth-source-netrc-normalize
1231                   (auth-source-netrc-parse
1232                    :max max
1233                    :require require
1234                    :delete delete
1235                    :file (oref backend source)
1236                    :host (or host t)
1237                    :user (or user t)
1238                    :port (or port t))
1239                   (oref backend source))))
1240
1241     ;; if we need to create an entry AND none were found to match
1242     (when (and create
1243                (not results))
1244
1245       ;; create based on the spec and record the value
1246       (setq results (or
1247                      ;; if the user did not want to create the entry
1248                      ;; in the file, it will be returned
1249                      (apply (slot-value backend 'create-function) spec)
1250                      ;; if not, we do the search again without :create
1251                      ;; to get the updated data.
1252
1253                      ;; the result will be returned, even if the search fails
1254                      (apply #'auth-source-netrc-search
1255                             (plist-put spec :create nil)))))
1256     results))
1257
1258 (defun auth-source-netrc-element-or-first (v)
1259   (if (listp v)
1260       (nth 0 v)
1261     v))
1262
1263 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t)
1264 ;; (auth-source-search :host "nonesuch" :type 'netrc :max 1 :create t :create-extra-keys '((A "default A") (B)))
1265
1266 (defun* auth-source-netrc-create (&rest spec
1267                                         &key backend
1268                                         secret host user port create
1269                                         &allow-other-keys)
1270   (let* ((base-required '(host user port secret))
1271          ;; we know (because of an assertion in auth-source-search) that the
1272          ;; :create parameter is either t or a list (which includes nil)
1273          (create-extra (if (eq t create) nil create))
1274          (current-data (car (auth-source-search :max 1
1275                                                 :host host
1276                                                 :port port)))
1277          (required (append base-required create-extra))
1278          (file (oref backend source))
1279          (add "")
1280          ;; `valist' is an alist
1281          valist
1282          ;; `artificial' will be returned if no creation is needed
1283          artificial)
1284
1285     ;; only for base required elements (defined as function parameters):
1286     ;; fill in the valist with whatever data we may have from the search
1287     ;; we complete the first value if it's a list and use the value otherwise
1288     (dolist (br base-required)
1289       (when (symbol-value br)
1290         (let ((br-choice (cond
1291                           ;; all-accepting choice (predicate is t)
1292                           ((eq t (symbol-value br)) nil)
1293                           ;; just the value otherwise
1294                           (t (symbol-value br)))))
1295           (when br-choice
1296             (auth-source--aput valist br br-choice)))))
1297
1298     ;; for extra required elements, see if the spec includes a value for them
1299     (dolist (er create-extra)
1300       (let ((name (concat ":" (symbol-name er)))
1301             (keys (loop for i below (length spec) by 2
1302                         collect (nth i spec))))
1303         (dolist (k keys)
1304           (when (equal (symbol-name k) name)
1305             (auth-source--aput valist er (plist-get spec k))))))
1306
1307     ;; for each required element
1308     (dolist (r required)
1309       (let* ((data (auth-source--aget valist r))
1310              ;; take the first element if the data is a list
1311              (data (or (auth-source-netrc-element-or-first data)
1312                        (plist-get current-data
1313                                   (intern (format ":%s" r) obarray))))
1314              ;; this is the default to be offered
1315              (given-default (auth-source--aget
1316                              auth-source-creation-defaults r))
1317              ;; the default supplementals are simple:
1318              ;; for the user, try `given-default' and then (user-login-name);
1319              ;; otherwise take `given-default'
1320              (default (cond
1321                        ((and (not given-default) (eq r 'user))
1322                         (user-login-name))
1323                        (t given-default)))
1324              (printable-defaults (list
1325                                   (cons 'user
1326                                         (or
1327                                          (auth-source-netrc-element-or-first
1328                                           (auth-source--aget valist 'user))
1329                                          (plist-get artificial :user)
1330                                          "[any user]"))
1331                                   (cons 'host
1332                                         (or
1333                                          (auth-source-netrc-element-or-first
1334                                           (auth-source--aget valist 'host))
1335                                          (plist-get artificial :host)
1336                                          "[any host]"))
1337                                   (cons 'port
1338                                         (or
1339                                          (auth-source-netrc-element-or-first
1340                                           (auth-source--aget valist 'port))
1341                                          (plist-get artificial :port)
1342                                          "[any port]"))))
1343              (prompt (or (auth-source--aget auth-source-creation-prompts r)
1344                          (case r
1345                            (secret "%p password for %u@%h: ")
1346                            (user "%p user name for %h: ")
1347                            (host "%p host name for user %u: ")
1348                            (port "%p port for %u@%h: "))
1349                          (format "Enter %s (%%u@%%h:%%p): " r)))
1350              (prompt (auth-source-format-prompt
1351                       prompt
1352                       `((?u ,(auth-source--aget printable-defaults 'user))
1353                         (?h ,(auth-source--aget printable-defaults 'host))
1354                         (?p ,(auth-source--aget printable-defaults 'port))))))
1355
1356         ;; Store the data, prompting for the password if needed.
1357         (setq data (or data
1358                        (if (eq r 'secret)
1359                            ;; Special case prompt for passwords.
1360                            ;; TODO: make the default (setq auth-source-netrc-use-gpg-tokens `((,(if (boundp 'epa-file-auto-mode-alist-entry) (car (symbol-value 'epa-file-auto-mode-alist-entry)) "\\.gpg\\'") nil) (t gpg)))
1361                            ;; TODO: or maybe leave as (setq auth-source-netrc-use-gpg-tokens 'never)
1362                            (let* ((ep (format "Use GPG password tokens in %s?" file))
1363                                   (gpg-encrypt
1364                                    (cond
1365                                     ((eq auth-source-netrc-use-gpg-tokens 'never)
1366                                      'never)
1367                                     ((listp auth-source-netrc-use-gpg-tokens)
1368                                      (let ((check (copy-sequence
1369                                                    auth-source-netrc-use-gpg-tokens))
1370                                            item ret)
1371                                        (while check
1372                                          (setq item (pop check))
1373                                          (when (or (eq (car item) t)
1374                                                    (string-match (car item) file))
1375                                            (setq ret (cdr item))
1376                                            (setq check nil)))))
1377                                     (t 'never)))
1378                                   (plain (or (eval default) (read-passwd prompt))))
1379                              ;; ask if we don't know what to do (in which case
1380                              ;; auth-source-netrc-use-gpg-tokens must be a list)
1381                              (unless gpg-encrypt
1382                                (setq gpg-encrypt (if (y-or-n-p ep) 'gpg 'never))
1383                                ;; TODO: save the defcustom now? or ask?
1384                                (setq auth-source-netrc-use-gpg-tokens
1385                                      (cons `(,file ,gpg-encrypt)
1386                                            auth-source-netrc-use-gpg-tokens)))
1387                              (if (eq gpg-encrypt 'gpg)
1388                                  (auth-source-epa-make-gpg-token plain file)
1389                                plain))
1390                          (if (stringp default)
1391                              (read-string (if (string-match ": *\\'" prompt)
1392                                               (concat (substring prompt 0 (match-beginning 0))
1393                                                       " (default " default "): ")
1394                                             (concat prompt "(default " default ") "))
1395                                           nil nil default)
1396                            (eval default)))))
1397
1398         (when data
1399           (setq artificial (plist-put artificial
1400                                       (intern (concat ":" (symbol-name r)))
1401                                       (if (eq r 'secret)
1402                                           (lexical-let ((data data))
1403                                             (lambda () data))
1404                                         data))))
1405
1406         ;; When r is not an empty string...
1407         (when (and (stringp data)
1408                    (< 0 (length data)))
1409           ;; this function is not strictly necessary but I think it
1410           ;; makes the code clearer -tzz
1411           (let ((printer (lambda ()
1412                            ;; append the key (the symbol name of r)
1413                            ;; and the value in r
1414                            (format "%s%s %s"
1415                                    ;; prepend a space
1416                                    (if (zerop (length add)) "" " ")
1417                                    ;; remap auth-source tokens to netrc
1418                                    (case r
1419                                      (user   "login")
1420                                      (host   "machine")
1421                                      (secret "password")
1422                                      (port   "port") ; redundant but clearer
1423                                      (t (symbol-name r)))
1424                                    (if (string-match "[\"# ]" data)
1425                                        (format "%S" data)
1426                                      data)))))
1427             (setq add (concat add (funcall printer)))))))
1428
1429     (plist-put
1430      artificial
1431      :save-function
1432      (lexical-let ((file file)
1433                    (add add))
1434        (lambda () (auth-source-netrc-saver file add))))
1435
1436     (list artificial)))
1437
1438 ;;(funcall (plist-get (nth 0 (auth-source-search :host '("nonesuch2") :user "tzz" :port "imap" :create t :max 1)) :save-function))
1439 (defun auth-source-netrc-saver (file add)
1440   "Save a line ADD in FILE, prompting along the way.
1441 Respects `auth-source-save-behavior'.  Uses
1442 `auth-source-netrc-cache' to avoid prompting more than once."
1443   (let* ((key (format "%s %s" file (rfc2104-hash 'md5 64 16 file add)))
1444          (cached (assoc key auth-source-netrc-cache)))
1445
1446     (if cached
1447         (auth-source-do-trivia
1448          "auth-source-netrc-saver: found previous run for key %s, returning"
1449          key)
1450       (with-temp-buffer
1451         (when (file-exists-p file)
1452           (insert-file-contents file))
1453         (when auth-source-gpg-encrypt-to
1454           ;; (see bug#7487) making `epa-file-encrypt-to' local to
1455           ;; this buffer lets epa-file skip the key selection query
1456           ;; (see the `local-variable-p' check in
1457           ;; `epa-file-write-region').
1458           (unless (local-variable-p 'epa-file-encrypt-to (current-buffer))
1459             (make-local-variable 'epa-file-encrypt-to))
1460           (if (listp auth-source-gpg-encrypt-to)
1461               (setq epa-file-encrypt-to auth-source-gpg-encrypt-to)))
1462         ;; we want the new data to be found first, so insert at beginning
1463         (goto-char (point-min))
1464
1465         ;; Ask AFTER we've successfully opened the file.
1466         (let ((prompt (format "Save auth info to file %s? " file))
1467               (done (not (eq auth-source-save-behavior 'ask)))
1468               (bufname "*auth-source Help*")
1469               k)
1470           (while (not done)
1471             (setq k (auth-source-read-char-choice prompt '(?y ?n ?N ?e ??)))
1472             (case k
1473               (?y (setq done t))
1474               (?? (save-excursion
1475                     (with-output-to-temp-buffer bufname
1476                       (princ
1477                        (concat "(y)es, save\n"
1478                                "(n)o but use the info\n"
1479                                "(N)o and don't ask to save again\n"
1480                                "(e)dit the line\n"
1481                                "(?) for help as you can see.\n"))
1482                       ;; Why?  Doesn't with-output-to-temp-buffer already do
1483                       ;; the exact same thing anyway?  --Stef
1484                       (set-buffer standard-output)
1485                       (help-mode))))
1486               (?n (setq add ""
1487                         done t))
1488               (?N
1489                (setq add ""
1490                      done t)
1491                (customize-save-variable 'auth-source-save-behavior nil))
1492               (?e (setq add (read-string "Line to add: " add)))
1493               (t nil)))
1494
1495           (when (get-buffer-window bufname)
1496             (delete-window (get-buffer-window bufname)))
1497
1498           ;; Make sure the info is not saved.
1499           (when (null auth-source-save-behavior)
1500             (setq add ""))
1501
1502           (when (< 0 (length add))
1503             (progn
1504               (unless (bolp)
1505                 (insert "\n"))
1506               (insert add "\n")
1507               (write-region (point-min) (point-max) file nil 'silent)
1508               ;; Make the .authinfo file non-world-readable.
1509               (set-file-modes file #o600)
1510               (auth-source-do-debug
1511                "auth-source-netrc-create: wrote 1 new line to %s"
1512                file)
1513               (message "Saved new authentication information to %s" file)
1514               nil))))
1515       (auth-source--aput auth-source-netrc-cache key "ran"))))
1516
1517 ;;; Backend specific parsing: Secrets API backend
1518
1519 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :create t))
1520 ;; (let ((auth-sources '(default))) (auth-source-search :max 1 :delete t))
1521 ;; (let ((auth-sources '(default))) (auth-source-search :max 1))
1522 ;; (let ((auth-sources '(default))) (auth-source-search))
1523 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1))
1524 ;; (let ((auth-sources '("secrets:Login"))) (auth-source-search :max 1 :signon_realm "https://git.gnus.org/Git"))
1525
1526 (defun auth-source-secrets-listify-pattern (pattern)
1527   "Convert a pattern with lists to a list of string patterns.
1528
1529 auth-source patterns can have values of the form :foo (\"bar\"
1530 \"qux\"), which means to match any secret with :foo equal to
1531 \"bar\" or :foo equal to \"qux\".  The secrets backend supports
1532 only string values for patterns, so this routine returns a list
1533 of patterns that is equivalent to the single original pattern
1534 when interpreted such that if a secret matches any pattern in the
1535 list, it matches the original pattern."
1536   (if (null pattern)
1537       '(nil)
1538     (let* ((key (pop pattern))
1539            (value (pop pattern))
1540            (tails (auth-source-secrets-listify-pattern pattern))
1541            (heads (if (stringp value)
1542                       (list (list key value))
1543                     (mapcar (lambda (v) (list key v)) value))))
1544       (loop
1545          for h in heads
1546          nconc
1547            (loop
1548               for tl in tails
1549               collect (append h tl))))))
1550
1551 (defun* auth-source-secrets-search (&rest
1552                                     spec
1553                                     &key backend create delete label
1554                                     type max host user port
1555                                     &allow-other-keys)
1556   "Search the Secrets API; spec is like `auth-source'.
1557
1558 The :label key specifies the item's label.  It is the only key
1559 that can specify a substring.  Any :label value besides a string
1560 will allow any label.
1561
1562 All other search keys must match exactly.  If you need substring
1563 matching, do a wider search and narrow it down yourself.
1564
1565 You'll get back all the properties of the token as a plist.
1566
1567 Here's an example that looks for the first item in the `Login'
1568 Secrets collection:
1569
1570  (let ((auth-sources \\='(\"secrets:Login\")))
1571     (auth-source-search :max 1)
1572
1573 Here's another that looks for the first item in the `Login'
1574 Secrets collection whose label contains `gnus':
1575
1576  (let ((auth-sources \\='(\"secrets:Login\")))
1577     (auth-source-search :max 1 :label \"gnus\")
1578
1579 And this one looks for the first item in the `Login' Secrets
1580 collection that's a Google Chrome entry for the git.gnus.org site
1581 authentication tokens:
1582
1583  (let ((auth-sources \\='(\"secrets:Login\")))
1584     (auth-source-search :max 1 :signon_realm \"https://git.gnus.org/Git\"))
1585 "
1586
1587   ;; TODO
1588   (assert (not create) nil
1589           "The Secrets API auth-source backend doesn't support creation yet")
1590   ;; TODO
1591   ;; (secrets-delete-item coll elt)
1592   (assert (not delete) nil
1593           "The Secrets API auth-source backend doesn't support deletion yet")
1594
1595   (let* ((coll (oref backend source))
1596          (max (or max 5000))     ; sanity check: default to stop at 5K
1597          (ignored-keys '(:create :delete :max :backend :label :require :type))
1598          (search-keys (loop for i below (length spec) by 2
1599                             unless (memq (nth i spec) ignored-keys)
1600                             collect (nth i spec)))
1601          ;; build a search spec without the ignored keys
1602          ;; if a search key is nil or t (match anything), we skip it
1603          (search-specs (auth-source-secrets-listify-pattern
1604                         (apply #'append (mapcar
1605                                       (lambda (k)
1606                                         (if (or (null (plist-get spec k))
1607                                                 (eq t (plist-get spec k)))
1608                                             nil
1609                                           (list k (plist-get spec k))))
1610                                       search-keys))))
1611          ;; needed keys (always including host, login, port, and secret)
1612          (returned-keys (mm-delete-duplicates (append
1613                                                '(:host :login :port :secret)
1614                                                search-keys)))
1615          (items
1616           (loop for search-spec in search-specs
1617                nconc
1618                (loop for item in (apply #'secrets-search-items coll search-spec)
1619                   unless (and (stringp label)
1620                               (not (string-match label item)))
1621                   collect item)))
1622          ;; TODO: respect max in `secrets-search-items', not after the fact
1623          (items (butlast items (- (length items) max)))
1624          ;; convert the item name to a full plist
1625          (items (mapcar (lambda (item)
1626                           (append
1627                            ;; make an entry for the secret (password) element
1628                            (list
1629                             :secret
1630                             (lexical-let ((v (secrets-get-secret coll item)))
1631                               (lambda () v)))
1632                            ;; rewrite the entry from ((k1 v1) (k2 v2)) to plist
1633                            (apply #'append
1634                                   (mapcar (lambda (entry)
1635                                             (list (car entry) (cdr entry)))
1636                                           (secrets-get-attributes coll item)))))
1637                         items))
1638          ;; ensure each item has each key in `returned-keys'
1639          (items (mapcar (lambda (plist)
1640                           (append
1641                            (apply #'append
1642                                   (mapcar (lambda (req)
1643                                             (if (plist-get plist req)
1644                                                 nil
1645                                               (list req nil)))
1646                                           returned-keys))
1647                            plist))
1648                         items)))
1649     items))
1650
1651 (defun* auth-source-secrets-create (&rest
1652                                     spec
1653                                     &key backend type max host user port
1654                                     &allow-other-keys)
1655   ;; TODO
1656   ;; (apply 'secrets-create-item (auth-get-source entry) name passwd spec)
1657   (debug spec))
1658
1659 ;;; Backend specific parsing: Mac OS Keychain (using /usr/bin/security) backend
1660
1661 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :create t))
1662 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1 :delete t))
1663 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search :max 1))
1664 ;; (let ((auth-sources '(macos-keychain-internet))) (auth-source-search))
1665
1666 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :create t))
1667 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1 :delete t))
1668 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search :max 1))
1669 ;; (let ((auth-sources '(macos-keychain-generic))) (auth-source-search))
1670
1671 ;; (let ((auth-sources '("macos-keychain-internet:/Users/tzz/Library/Keychains/login.keychain"))) (auth-source-search :max 1))
1672 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1 :host "git.gnus.org"))
1673 ;; (let ((auth-sources '("macos-keychain-generic:Login"))) (auth-source-search :max 1))
1674
1675 (defun* auth-source-macos-keychain-search (&rest
1676                                     spec
1677                                     &key backend create delete label
1678                                     type max host user port
1679                                     &allow-other-keys)
1680   "Search the MacOS Keychain; spec is like `auth-source'.
1681
1682 All search keys must match exactly.  If you need substring
1683 matching, do a wider search and narrow it down yourself.
1684
1685 You'll get back all the properties of the token as a plist.
1686
1687 The :type key is either `macos-keychain-internet' or
1688 `macos-keychain-generic'.
1689
1690 For the internet keychain type, the :label key searches the
1691 item's labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1692 Similarly, :host maps to \"-s HOST\", :user maps to \"-a USER\",
1693 and :port maps to \"-P PORT\" or \"-r PROT\"
1694 (note PROT has to be a 4-character string).
1695
1696 For the generic keychain type, the :label key searches the item's
1697 labels (\"-l LABEL\" passed to \"/usr/bin/security\").
1698 Similarly, :host maps to \"-c HOST\" (the \"creator\" keychain
1699 field), :user maps to \"-a USER\", and :port maps to \"-s PORT\".
1700
1701 Here's an example that looks for the first item in the default
1702 generic MacOS Keychain:
1703
1704  (let ((auth-sources \\='(macos-keychain-generic)))
1705     (auth-source-search :max 1)
1706
1707 Here's another that looks for the first item in the internet
1708 MacOS Keychain collection whose label is `gnus':
1709
1710  (let ((auth-sources \\='(macos-keychain-internet)))
1711     (auth-source-search :max 1 :label \"gnus\")
1712
1713 And this one looks for the first item in the internet keychain
1714 entries for git.gnus.org:
1715
1716  (let ((auth-sources \\='(macos-keychain-internet\")))
1717     (auth-source-search :max 1 :host \"git.gnus.org\"))
1718 "
1719   ;; TODO
1720   (assert (not create) nil
1721           "The MacOS Keychain auth-source backend doesn't support creation yet")
1722   ;; TODO
1723   ;; (macos-keychain-delete-item coll elt)
1724   (assert (not delete) nil
1725           "The MacOS Keychain auth-source backend doesn't support deletion yet")
1726
1727   (let* ((coll (oref backend source))
1728          (max (or max 5000))     ; sanity check: default to stop at 5K
1729          (ignored-keys '(:create :delete :max :backend :label))
1730          (search-keys (loop for i below (length spec) by 2
1731                             unless (memq (nth i spec) ignored-keys)
1732                             collect (nth i spec)))
1733          ;; build a search spec without the ignored keys
1734          ;; if a search key is nil or t (match anything), we skip it
1735          (search-spec (apply #'append (mapcar
1736                                       (lambda (k)
1737                                         (if (or (null (plist-get spec k))
1738                                                 (eq t (plist-get spec k)))
1739                                             nil
1740                                           (list k (plist-get spec k))))
1741                                       search-keys)))
1742          ;; needed keys (always including host, login, port, and secret)
1743          (returned-keys (mm-delete-duplicates (append
1744                                                '(:host :login :port :secret)
1745                                                search-keys)))
1746          (items (apply #'auth-source-macos-keychain-search-items
1747                        coll
1748                        type
1749                        max
1750                        search-spec))
1751
1752          ;; ensure each item has each key in `returned-keys'
1753          (items (mapcar (lambda (plist)
1754                           (append
1755                            (apply #'append
1756                                   (mapcar (lambda (req)
1757                                             (if (plist-get plist req)
1758                                                 nil
1759                                               (list req nil)))
1760                                           returned-keys))
1761                            plist))
1762                         items)))
1763     items))
1764
1765 (defun* auth-source-macos-keychain-search-items (coll type max
1766                                                       &rest spec
1767                                                       &key label type
1768                                                       host user port
1769                                                       &allow-other-keys)
1770
1771   (let* ((keychain-generic (eq type 'macos-keychain-generic))
1772          (args `(,(if keychain-generic
1773                       "find-generic-password"
1774                     "find-internet-password")
1775                  "-g"))
1776          (ret (list :type type)))
1777     (when label
1778       (setq args (append args (list "-l" label))))
1779     (when host
1780       (setq args (append args (list (if keychain-generic "-c" "-s") host))))
1781     (when user
1782       (setq args (append args (list "-a" user))))
1783
1784     (when port
1785       (if keychain-generic
1786           (setq args (append args (list "-s" port)))
1787         (setq args (append args (list
1788                                  (if (string-match "[0-9]+" port) "-P" "-r")
1789                                  port)))))
1790
1791       (unless (equal coll "default")
1792         (setq args (append args (list coll))))
1793
1794       (with-temp-buffer
1795         (apply #'call-process "/usr/bin/security" nil t nil args)
1796         (goto-char (point-min))
1797         (while (not (eobp))
1798           (cond
1799            ((looking-at "^password: \"\\(.+\\)\"$")
1800             (setq ret (auth-source-macos-keychain-result-append
1801                        ret
1802                        keychain-generic
1803                        "secret"
1804                        (lexical-let ((v (match-string 1)))
1805                          (lambda () v)))))
1806            ;; TODO: check if this is really the label
1807            ;; match 0x00000007 <blob>="AppleID"
1808            ((looking-at "^[ ]+0x00000007 <blob>=\"\\(.+\\)\"")
1809             (setq ret (auth-source-macos-keychain-result-append
1810                        ret
1811                        keychain-generic
1812                        "label"
1813                        (match-string 1))))
1814            ;; match "crtr"<uint32>="aapl"
1815            ;; match "svce"<blob>="AppleID"
1816            ((looking-at "^[ ]+\"\\([a-z]+\\)\"[^=]+=\"\\(.+\\)\"")
1817             (setq ret (auth-source-macos-keychain-result-append
1818                        ret
1819                        keychain-generic
1820                        (match-string 1)
1821                        (match-string 2)))))
1822           (forward-line)))
1823       ;; return `ret' iff it has the :secret key
1824       (and (plist-get ret :secret) (list ret))))
1825
1826 (defun auth-source-macos-keychain-result-append (result generic k v)
1827   (push v result)
1828   (setq k (cond
1829            ((equal k "acct") "user")
1830            ;; for generic keychains, creator is host, service is port
1831            ((and generic (equal k "crtr")) "host")
1832            ((and generic (equal k "svce")) "port")
1833            ;; for internet keychains, protocol is port, server is host
1834            ((and (not generic) (equal k "ptcl")) "port")
1835            ((and (not generic) (equal k "srvr")) "host")
1836            (t k)))
1837
1838   (push (intern (format ":%s" k)) result))
1839
1840 (defun* auth-source-macos-keychain-create (&rest
1841                                            spec
1842                                            &key backend type max host user port
1843                                            &allow-other-keys)
1844   ;; TODO
1845   (debug spec))
1846
1847 ;;; Backend specific parsing: PLSTORE backend
1848
1849 (defun* auth-source-plstore-search (&rest
1850                                     spec
1851                                     &key backend create delete label
1852                                     type max host user port
1853                                     &allow-other-keys)
1854   "Search the PLSTORE; spec is like `auth-source'."
1855   (let* ((store (oref backend data))
1856          (max (or max 5000))     ; sanity check: default to stop at 5K
1857          (ignored-keys '(:create :delete :max :backend :label :require :type))
1858          (search-keys (loop for i below (length spec) by 2
1859                             unless (memq (nth i spec) ignored-keys)
1860                             collect (nth i spec)))
1861          ;; build a search spec without the ignored keys
1862          ;; if a search key is nil or t (match anything), we skip it
1863          (search-spec (apply #'append (mapcar
1864                                       (lambda (k)
1865                                         (let ((v (plist-get spec k)))
1866                                           (if (or (null v)
1867                                                   (eq t v))
1868                                               nil
1869                                             (if (stringp v)
1870                                                 (setq v (list v)))
1871                                             (list k v))))
1872                                       search-keys)))
1873          ;; needed keys (always including host, login, port, and secret)
1874          (returned-keys (mm-delete-duplicates (append
1875                                                '(:host :login :port :secret)
1876                                                search-keys)))
1877          (items (plstore-find store search-spec))
1878          (item-names (mapcar #'car items))
1879          (items (butlast items (- (length items) max)))
1880          ;; convert the item to a full plist
1881          (items (mapcar (lambda (item)
1882                           (let* ((plist (copy-tree (cdr item)))
1883                                  (secret (plist-member plist :secret)))
1884                             (if secret
1885                                 (setcar
1886                                  (cdr secret)
1887                                  (lexical-let ((v (car (cdr secret))))
1888                                    (lambda () v))))
1889                             plist))
1890                         items))
1891          ;; ensure each item has each key in `returned-keys'
1892          (items (mapcar (lambda (plist)
1893                           (append
1894                            (apply #'append
1895                                   (mapcar (lambda (req)
1896                                             (if (plist-get plist req)
1897                                                 nil
1898                                               (list req nil)))
1899                                           returned-keys))
1900                            plist))
1901                         items)))
1902     (cond
1903      ;; if we need to create an entry AND none were found to match
1904      ((and create
1905            (not items))
1906
1907       ;; create based on the spec and record the value
1908       (setq items (or
1909                    ;; if the user did not want to create the entry
1910                    ;; in the file, it will be returned
1911                    (apply (slot-value backend 'create-function) spec)
1912                    ;; if not, we do the search again without :create
1913                    ;; to get the updated data.
1914
1915                    ;; the result will be returned, even if the search fails
1916                    (apply #'auth-source-plstore-search
1917                           (plist-put spec :create nil)))))
1918      ((and delete
1919            item-names)
1920       (dolist (item-name item-names)
1921         (plstore-delete store item-name))
1922       (plstore-save store)))
1923     items))
1924
1925 (defun* auth-source-plstore-create (&rest spec
1926                                           &key backend
1927                                           secret host user port create
1928                                           &allow-other-keys)
1929   (let* ((base-required '(host user port secret))
1930          (base-secret '(secret))
1931          ;; we know (because of an assertion in auth-source-search) that the
1932          ;; :create parameter is either t or a list (which includes nil)
1933          (create-extra (if (eq t create) nil create))
1934          (current-data (car (auth-source-search :max 1
1935                                                 :host host
1936                                                 :port port)))
1937          (required (append base-required create-extra))
1938          (file (oref backend source))
1939          (add "")
1940          ;; `valist' is an alist
1941          valist
1942          ;; `artificial' will be returned if no creation is needed
1943          artificial
1944          secret-artificial)
1945
1946     ;; only for base required elements (defined as function parameters):
1947     ;; fill in the valist with whatever data we may have from the search
1948     ;; we complete the first value if it's a list and use the value otherwise
1949     (dolist (br base-required)
1950       (when (symbol-value br)
1951         (let ((br-choice (cond
1952                           ;; all-accepting choice (predicate is t)
1953                           ((eq t (symbol-value br)) nil)
1954                           ;; just the value otherwise
1955                           (t (symbol-value br)))))
1956           (when br-choice
1957             (auth-source--aput valist br br-choice)))))
1958
1959     ;; for extra required elements, see if the spec includes a value for them
1960     (dolist (er create-extra)
1961       (let ((name (concat ":" (symbol-name er)))
1962             (keys (loop for i below (length spec) by 2
1963                         collect (nth i spec))))
1964         (dolist (k keys)
1965           (when (equal (symbol-name k) name)
1966             (auth-source--aput valist er (plist-get spec k))))))
1967
1968     ;; for each required element
1969     (dolist (r required)
1970       (let* ((data (auth-source--aget valist r))
1971              ;; take the first element if the data is a list
1972              (data (or (auth-source-netrc-element-or-first data)
1973                        (plist-get current-data
1974                                   (intern (format ":%s" r) obarray))))
1975              ;; this is the default to be offered
1976              (given-default (auth-source--aget
1977                              auth-source-creation-defaults r))
1978              ;; the default supplementals are simple:
1979              ;; for the user, try `given-default' and then (user-login-name);
1980              ;; otherwise take `given-default'
1981              (default (cond
1982                        ((and (not given-default) (eq r 'user))
1983                         (user-login-name))
1984                        (t given-default)))
1985              (printable-defaults (list
1986                                   (cons 'user
1987                                         (or
1988                                          (auth-source-netrc-element-or-first
1989                                           (auth-source--aget valist 'user))
1990                                          (plist-get artificial :user)
1991                                          "[any user]"))
1992                                   (cons 'host
1993                                         (or
1994                                          (auth-source-netrc-element-or-first
1995                                           (auth-source--aget valist 'host))
1996                                          (plist-get artificial :host)
1997                                          "[any host]"))
1998                                   (cons 'port
1999                                         (or
2000                                          (auth-source-netrc-element-or-first
2001                                           (auth-source--aget valist 'port))
2002                                          (plist-get artificial :port)
2003                                          "[any port]"))))
2004              (prompt (or (auth-source--aget auth-source-creation-prompts r)
2005                          (case r
2006                            (secret "%p password for %u@%h: ")
2007                            (user "%p user name for %h: ")
2008                            (host "%p host name for user %u: ")
2009                            (port "%p port for %u@%h: "))
2010                          (format "Enter %s (%%u@%%h:%%p): " r)))
2011              (prompt (auth-source-format-prompt
2012                       prompt
2013                       `((?u ,(auth-source--aget printable-defaults 'user))
2014                         (?h ,(auth-source--aget printable-defaults 'host))
2015                         (?p ,(auth-source--aget printable-defaults 'port))))))
2016
2017         ;; Store the data, prompting for the password if needed.
2018         (setq data (or data
2019                        (if (eq r 'secret)
2020                            (or (eval default) (read-passwd prompt))
2021                          (if (stringp default)
2022                              (read-string
2023                               (if (string-match ": *\\'" prompt)
2024                                   (concat (substring prompt 0 (match-beginning 0))
2025                                           " (default " default "): ")
2026                                 (concat prompt "(default " default ") "))
2027                               nil nil default)
2028                            (eval default)))))
2029
2030         (when data
2031           (if (member r base-secret)
2032               (setq secret-artificial
2033                     (plist-put secret-artificial
2034                                (intern (concat ":" (symbol-name r)))
2035                                data))
2036             (setq artificial (plist-put artificial
2037                                         (intern (concat ":" (symbol-name r)))
2038                                         data))))))
2039     (plstore-put (oref backend data)
2040                  (sha1 (format "%s@%s:%s"
2041                                (plist-get artificial :user)
2042                                (plist-get artificial :host)
2043                                (plist-get artificial :port)))
2044                  artificial secret-artificial)
2045     (if (y-or-n-p (format "Save auth info to file %s? "
2046                           (plstore-get-file (oref backend data))))
2047         (plstore-save (oref backend data)))))
2048
2049 ;;; older API
2050
2051 ;; (auth-source-user-or-password '("login" "password") "imap.myhost.com" t "tzz")
2052
2053 ;; deprecate the old interface
2054 (make-obsolete 'auth-source-user-or-password
2055                'auth-source-search "Emacs 24.1")
2056 (make-obsolete 'auth-source-forget-user-or-password
2057                'auth-source-forget "Emacs 24.1")
2058
2059 (defun auth-source-user-or-password
2060   (mode host port &optional username create-missing delete-existing)
2061   "Find MODE (string or list of strings) matching HOST and PORT.
2062
2063 DEPRECATED in favor of `auth-source-search'!
2064
2065 USERNAME is optional and will be used as \"login\" in a search
2066 across the Secret Service API (see secrets.el) if the resulting
2067 items don't have a username.  This means that if you search for
2068 username \"joe\" and it matches an item but the item doesn't have
2069 a :user attribute, the username \"joe\" will be returned.
2070
2071 A non nil DELETE-EXISTING means deleting any matching password
2072 entry in the respective sources.  This is useful only when
2073 CREATE-MISSING is non nil as well; the intended use case is to
2074 remove wrong password entries.
2075
2076 If no matching entry is found, and CREATE-MISSING is non nil,
2077 the password will be retrieved interactively, and it will be
2078 stored in the password database which matches best (see
2079 `auth-sources').
2080
2081 MODE can be \"login\" or \"password\"."
2082   (auth-source-do-debug
2083    "auth-source-user-or-password: DEPRECATED get %s for %s (%s) + user=%s"
2084    mode host port username)
2085
2086   (let* ((listy (listp mode))
2087          (mode (if listy mode (list mode)))
2088          (cname (if username
2089                     (format "%s %s:%s %s" mode host port username)
2090                   (format "%s %s:%s" mode host port)))
2091          (search (list :host host :port port))
2092          (search (if username (append search (list :user username)) search))
2093          (search (if create-missing
2094                      (append search (list :create t))
2095                    search))
2096          (search (if delete-existing
2097                      (append search (list :delete t))
2098                    search))
2099          ;; (found (if (not delete-existing)
2100          ;;            (gethash cname auth-source-cache)
2101          ;;          (remhash cname auth-source-cache)
2102          ;;          nil)))
2103          (found nil))
2104     (if found
2105         (progn
2106           (auth-source-do-debug
2107            "auth-source-user-or-password: DEPRECATED cached %s=%s for %s (%s) + %s"
2108            mode
2109            ;; don't show the password
2110            (if (and (member "password" mode) t)
2111                "SECRET"
2112              found)
2113            host port username)
2114           found)                        ; return the found data
2115       ;; else, if not found, search with a max of 1
2116       (let ((choice (nth 0 (apply #'auth-source-search
2117                                   (append '(:max 1) search)))))
2118         (when choice
2119           (dolist (m mode)
2120             (cond
2121              ((equal "password" m)
2122               (push (if (plist-get choice :secret)
2123                         (funcall (plist-get choice :secret))
2124                       nil) found))
2125              ((equal "login" m)
2126               (push (plist-get choice :user) found)))))
2127         (setq found (nreverse found))
2128         (setq found (if listy found (car-safe found)))))
2129
2130     found))
2131
2132 (defun auth-source-user-and-password (host &optional user)
2133   (let* ((auth-info (car
2134                      (if user
2135                          (auth-source-search
2136                           :host host
2137                           :user "yourusername"
2138                           :max 1
2139                           :require '(:user :secret)
2140                           :create nil)
2141                        (auth-source-search
2142                         :host host
2143                         :max 1
2144                         :require '(:user :secret)
2145                         :create nil))))
2146          (user (plist-get auth-info :user))
2147          (password (plist-get auth-info :secret)))
2148     (when (functionp password)
2149       (setq password (funcall password)))
2150     (list user password auth-info)))
2151
2152 (provide 'auth-source)
2153
2154 ;;; auth-source.el ends here