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