Misc url-cookie tidy-up.
[bpt/emacs.git] / lisp / url / url-cookie.el
1 ;;; url-cookie.el --- URL cookie support
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2004, 2005, 2006, 2007, 2008,
4 ;; 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Keywords: comm, data, processes, hypermedia
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 ;;; Code:
26
27 (require 'url-util)
28 (require 'url-parse)
29
30 (defgroup url-cookie nil
31 "URL cookies."
32 :prefix "url-"
33 :prefix "url-cookie-"
34 :group 'url)
35
36 ;; A cookie is stored internally as a vector of 7 slots
37 ;; [ cookie NAME VALUE EXPIRES LOCALPART DOMAIN SECURE ]
38
39 (defstruct (url-cookie
40 (:constructor url-cookie-create)
41 (:copier nil)
42 ;; For compatibility with a previous version which did not use
43 ;; defstruct, and also in order to make sure that the printed
44 ;; representation does not depend on CL internals, we use an
45 ;; explicitly managed tag.
46 (:type vector))
47 (tag 'cookie :read-only t)
48 name value expires localpart domain secure)
49
50 (defvar url-cookie-storage nil "Where cookies are stored.")
51 (defvar url-cookie-secure-storage nil "Where secure cookies are stored.")
52 (defcustom url-cookie-file nil
53 "File where cookies are stored on disk."
54 :type '(choice (const :tag "Default" :value nil) file)
55 :group 'url-file
56 :group 'url-cookie)
57
58 (defcustom url-cookie-confirmation nil
59 "If non-nil, confirmation by the user is required to accept HTTP cookies."
60 :type 'boolean
61 :group 'url-cookie)
62
63 (defcustom url-cookie-multiple-line nil
64 "If nil, HTTP requests put all cookies for the server on one line.
65 Some web servers, such as http://www.hotmail.com/, only accept cookies
66 when they are on one line. This is broken behavior, but just try
67 telling Microsoft that."
68 :type 'boolean
69 :group 'url-cookie)
70
71 (defvar url-cookies-changed-since-last-save nil
72 "Whether the cookies list has changed since the last save operation.")
73
74 (defun url-cookie-parse-file (&optional fname)
75 "Load FNAME, default `url-cookie-file'."
76 ;; It's completely normal for the cookies file not to exist yet.
77 (load (or fname url-cookie-file) t t))
78
79 (declare-function url-cookie-p "url-cookie" t t) ; defstruct
80
81 (defun url-cookie-clean-up (&optional secure)
82 (let ((var (if secure 'url-cookie-secure-storage 'url-cookie-storage))
83 new new-cookies)
84 (dolist (cur (symbol-value var))
85 (setq new-cookies nil)
86 (dolist (cur-cookie (cdr cur))
87 (or (not (url-cookie-p cur-cookie))
88 (url-cookie-expired-p cur-cookie)
89 (null (url-cookie-expires cur-cookie))
90 (setq new-cookies (cons cur-cookie new-cookies))))
91 (when new-cookies
92 (setcdr cur new-cookies)
93 (setq new (cons cur new))))
94 (set var new)))
95
96 (defun url-cookie-write-file (&optional fname)
97 (when url-cookies-changed-since-last-save
98 (or fname (setq fname (expand-file-name url-cookie-file)))
99 (if (condition-case nil
100 (progn
101 (url-make-private-file fname)
102 nil)
103 (error t))
104 (message "Error accessing cookie file `%s'" fname)
105 (url-cookie-clean-up)
106 (url-cookie-clean-up t)
107 (with-temp-buffer
108 (insert ";; Emacs-W3 HTTP cookies file\n"
109 ";; Automatically generated file!!! DO NOT EDIT!!!\n\n"
110 "(setq url-cookie-storage\n '")
111 (pp url-cookie-storage (current-buffer))
112 (insert ")\n(setq url-cookie-secure-storage\n '")
113 (pp url-cookie-secure-storage (current-buffer))
114 (insert ")\n")
115 (insert "\f\n;; Local Variables:\n"
116 ";; version-control: never\n"
117 ";; no-byte-compile: t\n"
118 ";; End:\n")
119 (set (make-local-variable 'version-control) 'never)
120 (write-file fname))
121 (setq url-cookies-changed-since-last-save nil))))
122
123 (defun url-cookie-store (name value &optional expires domain localpart secure)
124 "Store a cookie."
125 (let ((storage (if secure url-cookie-secure-storage url-cookie-storage))
126 tmp found-domain)
127 ;; First, look for a matching domain.
128 (if (setq found-domain (assoc domain storage))
129 ;; Need to either stick the new cookie in existing domain storage
130 ;; or possibly replace an existing cookie if the names match.
131 (unless (dolist (cur (setq storage (cdr found-domain)) tmp)
132 (and (equal localpart (url-cookie-localpart cur))
133 (equal name (url-cookie-name cur))
134 (progn
135 (setf (url-cookie-expires cur) expires)
136 (setf (url-cookie-value cur) value)
137 (setq tmp t))))
138 ;; New cookie.
139 (setcdr found-domain (cons
140 (url-cookie-create :name name
141 :value value
142 :expires expires
143 :domain domain
144 :localpart localpart
145 :secure secure)
146 (cdr found-domain))))
147 ;; Need to add a new top-level domain.
148 (setq tmp (url-cookie-create :name name
149 :value value
150 :expires expires
151 :domain domain
152 :localpart localpart
153 :secure secure))
154 (cond (storage
155 (setcdr storage (cons (list domain tmp) (cdr storage))))
156 (secure
157 (setq url-cookie-secure-storage (list (list domain tmp))))
158 (t
159 (setq url-cookie-storage (list (list domain tmp))))))))
160
161 (defun url-cookie-expired-p (cookie)
162 "Return non-nil if COOKIE is expired."
163 (let ((exp (url-cookie-expires cookie)))
164 (and exp (> (float-time) (float-time (date-to-time exp))))))
165
166 (defun url-cookie-retrieve (host &optional localpart secure)
167 "Retrieve all cookies for a specified HOST and LOCALPART."
168 (let ((storage (if secure
169 (append url-cookie-secure-storage url-cookie-storage)
170 url-cookie-storage))
171 (case-fold-search t)
172 cookies retval localpart-match)
173 (dolist (cur storage)
174 (setq cookies (cdr cur))
175 (if (and (car cur)
176 (string-match
177 (concat "^.*"
178 (regexp-quote
179 ;; Remove the dot from wildcard domains
180 ;; before matching.
181 (if (eq ?. (aref (car cur) 0))
182 (substring (car cur) 1)
183 (car cur)))
184 "$") host))
185 ;; The domains match - a possible hit!
186 (dolist (cur cookies)
187 (and (if (and (stringp
188 (setq localpart-match (url-cookie-localpart cur)))
189 (stringp localpart))
190 (string-match (concat "^" (regexp-quote localpart-match))
191 localpart)
192 (equal localpart localpart-match))
193 (not (url-cookie-expired-p cur))
194 (setq retval (cons cur retval))))))
195 retval))
196
197 (defun url-cookie-generate-header-lines (host localpart secure)
198 (let ((cookies (url-cookie-retrieve host localpart secure))
199 retval chunk)
200 ;; Have to sort this for sending most specific cookies first.
201 (setq cookies (and cookies
202 (sort cookies
203 (lambda (x y)
204 (> (length (url-cookie-localpart x))
205 (length (url-cookie-localpart y)))))))
206 (dolist (cur cookies)
207 (setq chunk (format "%s=%s" (url-cookie-name cur) (url-cookie-value cur))
208 retval (if (and url-cookie-multiple-line
209 (< 80 (+ (length retval) (length chunk) 4)))
210 (concat retval "\r\nCookie: " chunk)
211 (if retval
212 (concat retval "; " chunk)
213 (concat "Cookie: " chunk)))))
214 (if retval
215 (concat retval "\r\n")
216 "")))
217
218 (defvar url-cookie-two-dot-domains
219 (concat "\\.\\("
220 (mapconcat 'identity (list "com" "edu" "net" "org" "gov" "mil" "int")
221 "\\|")
222 "\\)$")
223 "A regexp of top level domains that only require two matching
224 '.'s in the domain name in order to set a cookie.")
225
226 (defcustom url-cookie-trusted-urls nil
227 "A list of regular expressions matching URLs to always accept cookies from."
228 :type '(repeat regexp)
229 :group 'url-cookie)
230
231 (defcustom url-cookie-untrusted-urls nil
232 "A list of regular expressions matching URLs to never accept cookies from."
233 :type '(repeat regexp)
234 :group 'url-cookie)
235
236 (defun url-cookie-host-can-set-p (host domain)
237 (let ((numdots 0)
238 (last nil)
239 (case-fold-search t)
240 (mindots 3))
241 (while (setq last (string-match "\\." domain last))
242 (setq numdots (1+ numdots)
243 last (1+ last)))
244 (if (string-match url-cookie-two-dot-domains domain)
245 (setq mindots 2))
246 (cond
247 ((string= host domain) ; Apparently netscape lets you do this
248 t)
249 ((>= numdots mindots) ; We have enough dots in domain name
250 ;; Need to check and make sure the host is actually _in_ the
251 ;; domain it wants to set a cookie for though.
252 (string-match (concat (regexp-quote
253 ;; Remove the dot from wildcard domains
254 ;; before matching.
255 (if (eq ?. (aref domain 0))
256 (substring domain 1)
257 domain))
258 "$") host))
259 (t
260 nil))))
261
262 (defun url-cookie-handle-set-cookie (str)
263 (setq url-cookies-changed-since-last-save t)
264 (let* ((args (url-parse-args str t))
265 (case-fold-search t)
266 (secure (and (assoc-string "secure" args t) t))
267 (domain (or (cdr-safe (assoc-string "domain" args t))
268 (url-host url-current-object)))
269 (current-url (url-view-url t))
270 (trusted url-cookie-trusted-urls)
271 (untrusted url-cookie-untrusted-urls)
272 (expires (cdr-safe (assoc-string "expires" args t)))
273 (localpart (or (cdr-safe (assoc-string "path" args t))
274 (file-name-directory
275 (url-filename url-current-object))))
276 (rest nil))
277 (dolist (this args)
278 (or (member (downcase (car this)) '("secure" "domain" "expires" "path"))
279 (setq rest (cons this rest))))
280
281 ;; Sometimes we get dates that the timezone package cannot handle very
282 ;; gracefully - take care of this here, instead of in url-cookie-expired-p
283 ;; to speed things up.
284 (and expires
285 (string-match
286 (concat "^[^,]+, +\\(..\\)-\\(...\\)-\\(..\\) +"
287 "\\(..:..:..\\) +\\[*\\([^\]]+\\)\\]*$")
288 expires)
289 (setq expires (concat (match-string 1 expires) " "
290 (match-string 2 expires) " "
291 (match-string 3 expires) " "
292 (match-string 4 expires) " ["
293 (match-string 5 expires) "]")))
294
295 ;; This one is for older Emacs/XEmacs variants that don't
296 ;; understand this format without tenths of a second in it.
297 ;; Wednesday, 30-Dec-2037 16:00:00 GMT
298 ;; - vs -
299 ;; Wednesday, 30-Dec-2037 16:00:00.00 GMT
300 (and expires
301 (string-match
302 "\\([0-9]+\\)-\\([A-Za-z]+\\)-\\([0-9]+\\)[ \t]+\\([0-9]+:[0-9]+:[0-9]+\\)\\(\\.[0-9]+\\)*[ \t]+\\([-+a-zA-Z0-9]+\\)"
303 expires)
304 (setq expires (concat (match-string 1 expires) "-" ; day
305 (match-string 2 expires) "-" ; month
306 (match-string 3 expires) " " ; year
307 (match-string 4 expires) ".00 " ; hour:minutes:seconds
308 (match-string 6 expires)))) ":" ; timezone
309
310 (while (consp trusted)
311 (if (string-match (car trusted) current-url)
312 (setq trusted (- (match-end 0) (match-beginning 0)))
313 (pop trusted)))
314 (while (consp untrusted)
315 (if (string-match (car untrusted) current-url)
316 (setq untrusted (- (match-end 0) (match-beginning 0)))
317 (pop untrusted)))
318 (and trusted untrusted
319 ;; Choose the more specific match.
320 (set (if (> trusted untrusted) 'untrusted 'trusted) nil))
321 (cond
322 (untrusted
323 ;; The site was explicity marked as untrusted by the user.
324 nil)
325 ((or (eq url-privacy-level 'paranoid)
326 (and (listp url-privacy-level) (memq 'cookies url-privacy-level)))
327 ;; User never wants cookies.
328 nil)
329 ((and url-cookie-confirmation
330 (not trusted)
331 (save-window-excursion
332 (with-output-to-temp-buffer "*Cookie Warning*"
333 (mapcar
334 (lambda (x)
335 (princ (format "%s - %s" (car x) (cdr x)))) rest))
336 (prog1
337 (not (funcall url-confirmation-func
338 (format "Allow %s to set these cookies? "
339 (url-host url-current-object))))
340 (if (get-buffer "*Cookie Warning*")
341 (kill-buffer "*Cookie Warning*")))))
342 ;; User wants to be asked, and declined.
343 nil)
344 ((url-cookie-host-can-set-p (url-host url-current-object) domain)
345 ;; Cookie is accepted by the user, and passes our security checks.
346 (dolist (cur rest)
347 (url-cookie-store (car cur) (cdr cur) expires domain localpart secure)))
348 (t
349 (url-lazy-message "%s tried to set a cookie for domain %s - rejected."
350 (url-host url-current-object) domain)))))
351
352 (defvar url-cookie-timer nil)
353
354 (defcustom url-cookie-save-interval 3600
355 "The number of seconds between automatic saves of cookies.
356 Default is 1 hour. Note that if you change this variable outside of
357 the `customize' interface after `url-do-setup' has been run, you need
358 to run the `url-cookie-setup-save-timer' function manually."
359 :set #'(lambda (var val)
360 (set-default var val)
361 (if (bound-and-true-p url-setup-done)
362 (url-cookie-setup-save-timer)))
363 :type 'integer
364 :group 'url-cookie)
365
366 (defun url-cookie-setup-save-timer ()
367 "Reset the cookie saver timer."
368 (interactive)
369 (ignore-errors (cancel-timer url-cookie-timer))
370 (setq url-cookie-timer nil)
371 (if url-cookie-save-interval
372 (setq url-cookie-timer (run-at-time url-cookie-save-interval
373 url-cookie-save-interval
374 #'url-cookie-write-file))))
375
376 (provide 'url-cookie)
377
378 ;;; url-cookie.el ends here