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