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