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