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