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