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