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