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