Allow ^substr, substr=, ~word in mairix searches via the form widget.
[bpt/emacs.git] / lisp / url / url-http.el
CommitLineData
8c8b8430 1;;; url-http.el --- HTTP retrieval routines
b43eb9ab 2
acaf905b 3;; Copyright (C) 1999, 2001, 2004-2012 Free Software Foundation, Inc.
b43eb9ab 4
8c8b8430 5;; Author: Bill Perry <wmperry@gnu.org>
8c8b8430 6;; Keywords: comm, data, processes
3f19601e 7
b43eb9ab
SM
8;; This file is part of GNU Emacs.
9;;
4936186e 10;; GNU Emacs is free software: you can redistribute it and/or modify
b43eb9ab 11;; it under the terms of the GNU General Public License as published by
4936186e
GM
12;; the Free Software Foundation, either version 3 of the License, or
13;; (at your option) any later version.
14
b43eb9ab
SM
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.
4936186e 19
b43eb9ab 20;; You should have received a copy of the GNU General Public License
4936186e 21;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
8c8b8430 22
b43eb9ab
SM
23;;; Commentary:
24
25;;; Code:
8c8b8430 26
12f1edc8
SM
27(eval-when-compile (require 'cl))
28(defvar url-http-extra-headers)
29(defvar url-http-target-url)
62bfb5bb 30(defvar url-http-proxy)
b3cd7f61 31(defvar url-http-connection-opened)
8c8b8430
SM
32(require 'url-gw)
33(require 'url-util)
34(require 'url-parse)
35(require 'url-cookie)
36(require 'mail-parse)
37(require 'url-auth)
55d1d8b7 38(require 'url)
8c8b8430 39(autoload 'url-cache-create-filename "url-cache")
8c8b8430
SM
40
41(defconst url-http-default-port 80 "Default HTTP port.")
42(defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
43(defalias 'url-http-expand-file-name 'url-default-expander)
44
45(defvar url-http-real-basic-auth-storage nil)
46(defvar url-http-proxy-basic-auth-storage nil)
47
48(defvar url-http-open-connections (make-hash-table :test 'equal
49 :size 17)
50 "A hash table of all open network connections.")
51
52(defvar url-http-version "1.1"
53 "What version of HTTP we advertise, as a string.
54Valid values are 1.1 and 1.0.
55This is only useful when debugging the HTTP subsystem.
56
57Setting this to 1.0 will tell servers not to send chunked encoding,
55d1d8b7 58and other HTTP/1.1 specific features.")
8c8b8430
SM
59
60(defvar url-http-attempt-keepalives t
61 "Whether to use a single TCP connection multiple times in HTTP.
62This is only useful when debugging the HTTP subsystem. Setting to
55d1d8b7
SM
63nil will explicitly close the connection to the server after every
64request.")
8c8b8430 65
1e9d758c
TZ
66(defconst url-http-codes
67 '((100 continue "Continue with request")
68 (101 switching-protocols "Switching protocols")
69 (102 processing "Processing (Added by DAV)")
70 (200 OK "OK")
71 (201 created "Created")
72 (202 accepted "Accepted")
73 (203 non-authoritative "Non-authoritative information")
74 (204 no-content "No content")
75 (205 reset-content "Reset content")
76 (206 partial-content "Partial content")
77 (207 multi-status "Multi-status (Added by DAV)")
78 (300 multiple-choices "Multiple choices")
79 (301 moved-permanently "Moved permanently")
80 (302 found "Found")
81 (303 see-other "See other")
82 (304 not-modified "Not modified")
83 (305 use-proxy "Use proxy")
84 (307 temporary-redirect "Temporary redirect")
85 (400 bad-request "Bad Request")
86 (401 unauthorized "Unauthorized")
87 (402 payment-required "Payment required")
88 (403 forbidden "Forbidden")
89 (404 not-found "Not found")
90 (405 method-not-allowed "Method not allowed")
91 (406 not-acceptable "Not acceptable")
92 (407 proxy-authentication-required "Proxy authentication required")
93 (408 request-timeout "Request time-out")
94 (409 conflict "Conflict")
95 (410 gone "Gone")
96 (411 length-required "Length required")
97 (412 precondition-failed "Precondition failed")
98 (413 request-entity-too-large "Request entity too large")
99 (414 request-uri-too-large "Request-URI too large")
100 (415 unsupported-media-type "Unsupported media type")
101 (416 requested-range-not-satisfiable "Requested range not satisfiable")
102 (417 expectation-failed "Expectation failed")
103 (422 unprocessable-entity "Unprocessable Entity (Added by DAV)")
104 (423 locked "Locked")
105 (424 failed-Dependency "Failed Dependency")
106 (500 internal-server-error "Internal server error")
107 (501 not-implemented "Not implemented")
108 (502 bad-gateway "Bad gateway")
109 (503 service-unavailable "Service unavailable")
110 (504 gateway-timeout "Gateway time-out")
111 (505 http-version-not-supported "HTTP version not supported")
112 (507 insufficient-storage "Insufficient storage")
113"The HTTP return codes and their text."))
114
8c8b8430
SM
115;(eval-when-compile
116;; These are all macros so that they are hidden from external sight
117;; when the file is byte-compiled.
118;;
119;; This allows us to expose just the entry points we want.
120
121;; These routines will allow us to implement persistent HTTP
122;; connections.
123(defsubst url-http-debug (&rest args)
124 (if quit-flag
125 (let ((proc (get-buffer-process (current-buffer))))
126 ;; The user hit C-g, honor it! Some things can get in an
127 ;; incredibly tight loop (chunked encoding)
128 (if proc
129 (progn
130 (set-process-sentinel proc nil)
131 (set-process-filter proc nil)))
132 (error "Transfer interrupted!")))
133 (apply 'url-debug 'http args))
134
135(defun url-http-mark-connection-as-busy (host port proc)
136 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
8ae85a27 137 (set-process-query-on-exit-flag proc t)
8c8b8430
SM
138 (puthash (cons host port)
139 (delq proc (gethash (cons host port) url-http-open-connections))
140 url-http-open-connections)
141 proc)
142
143(defun url-http-mark-connection-as-free (host port proc)
144 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
db8d5936 145 (when (memq (process-status proc) '(open run connect))
5695d1dd
CY
146 (set-process-buffer proc nil)
147 (set-process-sentinel proc 'url-http-idle-sentinel)
8ae85a27 148 (set-process-query-on-exit-flag proc nil)
5695d1dd
CY
149 (puthash (cons host port)
150 (cons proc (gethash (cons host port) url-http-open-connections))
151 url-http-open-connections))
8c8b8430
SM
152 nil)
153
154(defun url-http-find-free-connection (host port)
155 (let ((conns (gethash (cons host port) url-http-open-connections))
156 (found nil))
157 (while (and conns (not found))
db8d5936 158 (if (not (memq (process-status (car conns)) '(run open connect)))
8c8b8430
SM
159 (progn
160 (url-http-debug "Cleaning up dead process: %s:%d %S"
161 host port (car conns))
162 (url-http-idle-sentinel (car conns) nil))
163 (setq found (car conns))
164 (url-http-debug "Found existing connection: %s:%d %S" host port found))
165 (pop conns))
166 (if found
167 (url-http-debug "Reusing existing connection: %s:%d" host port)
168 (url-http-debug "Contacting host: %s:%d" host port))
169 (url-lazy-message "Contacting host: %s:%d" host port)
55d1d8b7
SM
170 (url-http-mark-connection-as-busy
171 host port
172 (or found
173 (let ((buf (generate-new-buffer " *url-http-temp*")))
174 ;; `url-open-stream' needs a buffer in which to do things
175 ;; like authentication. But we use another buffer afterwards.
8dff56de
SM
176 (unwind-protect
177 (let ((proc (url-open-stream host buf host port)))
dfea17e0
MH
178 ;; url-open-stream might return nil.
179 (when (processp proc)
180 ;; Drop the temp buffer link before killing the buffer.
181 (set-process-buffer proc nil))
bedeb7fd 182 proc)
ad87170f
LMI
183 ;; If there was an error on connect, make sure we don't
184 ;; get queried.
185 (when (get-buffer-process buf)
186 (set-process-query-on-exit-flag (get-buffer-process buf) nil))
55d1d8b7 187 (kill-buffer buf)))))))
8c8b8430
SM
188
189;; Building an HTTP request
190(defun url-http-user-agent-string ()
191 (if (or (eq url-privacy-level 'paranoid)
192 (and (listp url-privacy-level)
193 (memq 'agent url-privacy-level)))
194 ""
195 (format "User-Agent: %sURL/%s%s\r\n"
196 (if url-package-name
197 (concat url-package-name "/" url-package-version " ")
198 "")
199 url-version
200 (cond
201 ((and url-os-type url-system-type)
202 (concat " (" url-os-type "; " url-system-type ")"))
203 ((or url-os-type url-system-type)
204 (concat " (" (or url-system-type url-os-type) ")"))
205 (t "")))))
206
9450f124
MH
207(defun url-http-create-request (&optional ref-url)
208 "Create an HTTP request for `url-http-target-url', referred to by REF-URL."
d1ce47b0 209 (declare (special proxy-info
8ea88265
MH
210 url-http-method url-http-data
211 url-http-extra-headers))
8c8b8430
SM
212 (let* ((extra-headers)
213 (request nil)
8ea88265 214 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
62bfb5bb 215 (using-proxy url-http-proxy)
8c8b8430 216 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
8ea88265 217 url-http-extra-headers))
9450f124 218 (not using-proxy))
8c8b8430
SM
219 nil
220 (let ((url-basic-auth-storage
221 'url-http-proxy-basic-auth-storage))
9450f124
MH
222 (url-get-authentication url-http-target-url nil 'any nil))))
223 (real-fname (concat (url-filename url-http-target-url)
224 (url-recreate-url-attributes url-http-target-url)))
225 (host (url-host url-http-target-url))
8ea88265 226 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers))
8c8b8430
SM
227 nil
228 (url-get-authentication (or
229 (and (boundp 'proxy-info)
230 proxy-info)
9450f124 231 url-http-target-url) nil 'any nil))))
8c8b8430
SM
232 (if (equal "" real-fname)
233 (setq real-fname "/"))
234 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
235 (if auth
236 (setq auth (concat "Authorization: " auth "\r\n")))
237 (if proxy-auth
238 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
239
fac916bf 240 ;; Protection against stupid values in the referrer
8c8b8430
SM
241 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
242 (string= ref-url "")))
243 (setq ref-url nil))
244
fac916bf 245 ;; We do not want to expose the referrer if the user is paranoid.
8c8b8430
SM
246 (if (or (memq url-privacy-level '(low high paranoid))
247 (and (listp url-privacy-level)
248 (memq 'lastloc url-privacy-level)))
249 (setq ref-url nil))
250
8ea88265 251 ;; url-http-extra-headers contains an assoc-list of
8c8b8430
SM
252 ;; header/value pairs that we need to put into the request.
253 (setq extra-headers (mapconcat
254 (lambda (x)
255 (concat (car x) ": " (cdr x)))
8ea88265 256 url-http-extra-headers "\r\n"))
8c8b8430
SM
257 (if (not (equal extra-headers ""))
258 (setq extra-headers (concat extra-headers "\r\n")))
259
fe3c5669 260 ;; This was done with a call to `format'. Concatenating parts has
1430e7f9 261 ;; the advantage of keeping the parts of each header together and
8c8b8430
SM
262 ;; allows us to elide null lines directly, at the cost of making
263 ;; the layout less clear.
264 (setq request
1430e7f9
SM
265 ;; We used to concat directly, but if one of the strings happens
266 ;; to being multibyte (even if it only contains pure ASCII) then
267 ;; every string gets converted with `string-MAKE-multibyte' which
268 ;; turns the 127-255 codes into things like latin-1 accented chars
269 ;; (it would work right if it used `string-TO-multibyte' instead).
270 ;; So to avoid the problem we force every string to be unibyte.
271 (mapconcat
272 ;; FIXME: Instead of `string-AS-unibyte' we'd want
273 ;; `string-to-unibyte', so as to properly signal an error if one
274 ;; of the strings contains a multibyte char.
275 'string-as-unibyte
276 (delq nil
277 (list
278 ;; The request
8ea88265 279 (or url-http-method "GET") " "
9450f124 280 (if using-proxy (url-recreate-url url-http-target-url) real-fname)
1430e7f9
SM
281 " HTTP/" url-http-version "\r\n"
282 ;; Version of MIME we speak
283 "MIME-Version: 1.0\r\n"
284 ;; (maybe) Try to keep the connection open
9450f124 285 "Connection: " (if (or using-proxy
1430e7f9
SM
286 (not url-http-attempt-keepalives))
287 "close" "keep-alive") "\r\n"
288 ;; HTTP extensions we support
289 (if url-extensions-header
290 (format
291 "Extension: %s\r\n" url-extensions-header))
292 ;; Who we want to talk to
9450f124 293 (if (/= (url-port url-http-target-url)
1430e7f9 294 (url-scheme-get-property
9450f124 295 (url-type url-http-target-url) 'default-port))
1430e7f9 296 (format
9450f124 297 "Host: %s:%d\r\n" host (url-port url-http-target-url))
1430e7f9
SM
298 (format "Host: %s\r\n" host))
299 ;; Who its from
300 (if url-personal-mail-address
301 (concat
302 "From: " url-personal-mail-address "\r\n"))
303 ;; Encodings we understand
304 (if url-mime-encoding-string
305 (concat
306 "Accept-encoding: " url-mime-encoding-string "\r\n"))
307 (if url-mime-charset-string
308 (concat
309 "Accept-charset: " url-mime-charset-string "\r\n"))
310 ;; Languages we understand
311 (if url-mime-language-string
312 (concat
313 "Accept-language: " url-mime-language-string "\r\n"))
314 ;; Types we understand
315 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
316 ;; User agent
317 (url-http-user-agent-string)
318 ;; Proxy Authorization
319 proxy-auth
320 ;; Authorization
321 auth
322 ;; Cookies
aacaa419
LI
323 (when (url-use-cookies url-http-target-url)
324 (url-cookie-generate-header-lines
325 host real-fname
326 (equal "https" (url-type url-http-target-url))))
1430e7f9
SM
327 ;; If-modified-since
328 (if (and (not no-cache)
8ea88265 329 (member url-http-method '("GET" nil)))
9450f124 330 (let ((tm (url-is-cached url-http-target-url)))
1430e7f9
SM
331 (if tm
332 (concat "If-modified-since: "
333 (url-get-normalized-date tm) "\r\n"))))
334 ;; Whence we came
335 (if ref-url (concat
336 "Referer: " ref-url "\r\n"))
337 extra-headers
338 ;; Length of data
8ea88265 339 (if url-http-data
1430e7f9
SM
340 (concat
341 "Content-length: " (number-to-string
8ea88265 342 (length url-http-data))
1430e7f9
SM
343 "\r\n"))
344 ;; End request
345 "\r\n"
346 ;; Any data
b02ba905
CW
347 url-http-data
348 ;; If `url-http-data' is nil, avoid two CRLFs (Bug#8931).
349 (if url-http-data "\r\n")))
1430e7f9 350 ""))
8c8b8430
SM
351 (url-http-debug "Request is: \n%s" request)
352 request))
353
354;; Parsing routines
355(defun url-http-clean-headers ()
356 "Remove trailing \r from header lines.
d7c5e162
AS
357This allows us to use `mail-fetch-field', etc.
358Return the number of characters removed."
8c8b8430 359 (declare (special url-http-end-of-headers))
d7c5e162
AS
360 (let ((end (marker-position url-http-end-of-headers)))
361 (goto-char (point-min))
362 (while (re-search-forward "\r$" url-http-end-of-headers t)
363 (replace-match ""))
364 (- end url-http-end-of-headers)))
8c8b8430
SM
365
366(defun url-http-handle-authentication (proxy)
367 (declare (special status success url-http-method url-http-data
368 url-callback-function url-callback-arguments))
369 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
8917392a
MH
370 (let ((auths (or (nreverse
371 (mail-fetch-field
372 (if proxy "proxy-authenticate" "www-authenticate")
373 nil nil t))
374 '("basic")))
8c8b8430
SM
375 (type nil)
376 (url (url-recreate-url url-current-object))
c98f55ca
CY
377 (auth-url (url-recreate-url
378 (if (and proxy (boundp 'url-http-proxy))
379 url-http-proxy
380 url-current-object)))
381 (url-basic-auth-storage (if proxy
382 ;; Cheating, but who cares? :)
383 'url-http-proxy-basic-auth-storage
384 'url-http-real-basic-auth-storage))
385b64c5
MH
385 auth
386 (strength 0))
8c8b8430 387
385b64c5
MH
388 ;; find strongest supported auth
389 (dolist (this-auth auths)
d1ce47b0
JB
390 (setq this-auth (url-eat-trailing-space
391 (url-strip-leading-spaces
385b64c5 392 this-auth)))
d1ce47b0 393 (let* ((this-type
385b64c5
MH
394 (if (string-match "[ \t]" this-auth)
395 (downcase (substring this-auth 0 (match-beginning 0)))
396 (downcase this-auth)))
397 (registered (url-auth-registered this-type))
398 (this-strength (cddr registered)))
399 (when (and registered (> this-strength strength))
400 (setq auth this-auth
401 type this-type
402 strength this-strength))))
8c8b8430
SM
403
404 (if (not (url-auth-registered type))
405 (progn
406 (widen)
407 (goto-char (point-max))
408 (insert "<hr>Sorry, but I do not know how to handle " type
409 " authentication. If you'd like to write it,"
410 " send it to " url-bug-address ".<hr>")
411 (setq status t))
12f1edc8 412 (let* ((args (url-parse-args (subst-char-in-string ?, ?\; auth)))
c98f55ca
CY
413 (auth (url-get-authentication auth-url
414 (cdr-safe (assoc "realm" args))
12f1edc8 415 type t args)))
8c8b8430
SM
416 (if (not auth)
417 (setq success t)
418 (push (cons (if proxy "Proxy-Authorization" "Authorization") auth)
419 url-http-extra-headers)
420 (let ((url-request-method url-http-method)
421 (url-request-data url-http-data)
422 (url-request-extra-headers url-http-extra-headers))
5695d1dd
CY
423 (url-retrieve-internal url url-callback-function
424 url-callback-arguments)))))))
8c8b8430
SM
425
426(defun url-http-parse-response ()
427 "Parse just the response code."
b9b172ac
MH
428 (declare (special url-http-end-of-headers url-http-response-status
429 url-http-response-version))
8c8b8430
SM
430 (if (not url-http-end-of-headers)
431 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
432 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
433 (goto-char (point-min))
434 (skip-chars-forward " \t\n") ; Skip any blank crap
435 (skip-chars-forward "HTTP/") ; Skip HTTP Version
b9b172ac
MH
436 (setq url-http-response-version
437 (buffer-substring (point)
438 (progn
439 (skip-chars-forward "[0-9].")
440 (point))))
8c8b8430
SM
441 (setq url-http-response-status (read (current-buffer))))
442
443(defun url-http-handle-cookies ()
444 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
55d1d8b7 445The buffer must already be narrowed to the headers, so `mail-fetch-field' will
8c8b8430 446work correctly."
8c33dc13
CY
447 (let ((cookies (nreverse (mail-fetch-field "Set-Cookie" nil nil t)))
448 (cookies2 (nreverse (mail-fetch-field "Set-Cookie2" nil nil t))))
8c8b8430
SM
449 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
450 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
451 (while cookies
452 (url-cookie-handle-set-cookie (pop cookies)))
453;;; (while cookies2
454;;; (url-cookie-handle-set-cookie2 (pop cookies)))
455 )
456 )
457
458(defun url-http-parse-headers ()
459 "Parse and handle HTTP specific headers.
460Return t if and only if the current buffer is still active and
461should be shown to the user."
462 ;; The comments after each status code handled are taken from RFC
463 ;; 2616 (HTTP/1.1)
464 (declare (special url-http-end-of-headers url-http-response-status
b9b172ac 465 url-http-response-version
8c8b8430
SM
466 url-http-method url-http-data url-http-process
467 url-callback-function url-callback-arguments))
468
469 (url-http-mark-connection-as-free (url-host url-current-object)
470 (url-port url-current-object)
471 url-http-process)
472
473 (if (or (not (boundp 'url-http-end-of-headers))
474 (not url-http-end-of-headers))
475 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
476 (goto-char (point-min))
477 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
478 (url-http-parse-response)
479 (mail-narrow-to-head)
480 ;;(narrow-to-region (point-min) url-http-end-of-headers)
48abdb63 481 (let ((connection (mail-fetch-field "Connection")))
b9b172ac
MH
482 ;; In HTTP 1.0, keep the connection only if there is a
483 ;; "Connection: keep-alive" header.
484 ;; In HTTP 1.1 (and greater), keep the connection unless there is a
485 ;; "Connection: close" header
d1ce47b0 486 (cond
b9b172ac
MH
487 ((string= url-http-response-version "1.0")
488 (unless (and connection
489 (string= (downcase connection) "keep-alive"))
48abdb63 490 (delete-process url-http-process)))
b9b172ac
MH
491 (t
492 (when (and connection
493 (string= (downcase connection) "close"))
494 (delete-process url-http-process)))))
72f25299
GM
495 (let ((buffer (current-buffer))
496 (class nil)
1e9d758c
TZ
497 (success nil)
498 ;; other status symbols: jewelry and luxury cars
0ed082fe 499 (status-symbol (cadr (assq url-http-response-status url-http-codes)))
4ac3a65c 500 ;; The filename part of a URL could be in remote file syntax,
c48763bb
MA
501 ;; see Bug#6717 for an example. We disable file name
502 ;; handlers, therefore.
503 (file-name-handler-alist nil))
8c8b8430
SM
504 (setq class (/ url-http-response-status 100))
505 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status)
aacaa419
LI
506 (when (url-use-cookies url-http-target-url)
507 (url-http-handle-cookies))
8c8b8430
SM
508
509 (case class
510 ;; Classes of response codes
511 ;;
512 ;; 5xx = Server Error
513 ;; 4xx = Client Error
514 ;; 3xx = Redirection
515 ;; 2xx = Successful
516 ;; 1xx = Informational
517 (1 ; Information messages
518 ;; 100 = Continue with request
519 ;; 101 = Switching protocols
520 ;; 102 = Processing (Added by DAV)
72f25299 521 (url-mark-buffer-as-dead buffer)
8c8b8430
SM
522 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status))
523 (2 ; Success
524 ;; 200 Ok
525 ;; 201 Created
526 ;; 202 Accepted
527 ;; 203 Non-authoritative information
528 ;; 204 No content
529 ;; 205 Reset content
530 ;; 206 Partial content
531 ;; 207 Multi-status (Added by DAV)
1e9d758c
TZ
532 (case status-symbol
533 ((no-content reset-content)
8c8b8430 534 ;; No new data, just stay at the same document
72f25299 535 (url-mark-buffer-as-dead buffer)
8c8b8430
SM
536 (setq success t))
537 (otherwise
538 ;; Generic success for all others. Store in the cache, and
539 ;; mark it as successful.
540 (widen)
76bad534 541 (if (and url-automatic-caching (equal url-http-method "GET"))
72f25299 542 (url-store-in-cache buffer))
8c8b8430
SM
543 (setq success t))))
544 (3 ; Redirection
545 ;; 300 Multiple choices
546 ;; 301 Moved permanently
547 ;; 302 Found
548 ;; 303 See other
549 ;; 304 Not modified
550 ;; 305 Use proxy
551 ;; 307 Temporary redirect
552 (let ((redirect-uri (or (mail-fetch-field "Location")
553 (mail-fetch-field "URI"))))
1e9d758c
TZ
554 (case status-symbol
555 (multiple-choices ; 300
8c8b8430
SM
556 ;; Quoth the spec (section 10.3.1)
557 ;; -------------------------------
558 ;; The requested resource corresponds to any one of a set of
559 ;; representations, each with its own specific location and
560 ;; agent-driven negotiation information is being provided so
561 ;; that the user can select a preferred representation and
562 ;; redirect its request to that location.
563 ;; [...]
564 ;; If the server has a preferred choice of representation, it
565 ;; SHOULD include the specific URI for that representation in
566 ;; the Location field; user agents MAY use the Location field
567 ;; value for automatic redirection.
568 ;; -------------------------------
569 ;; We do not support agent-driven negotiation, so we just
570 ;; redirect to the preferred URI if one is provided.
571 nil)
1e9d758c 572 ((moved-permanently found temporary-redirect) ; 301 302 307
8c8b8430
SM
573 ;; If the 301|302 status code is received in response to a
574 ;; request other than GET or HEAD, the user agent MUST NOT
575 ;; automatically redirect the request unless it can be
576 ;; confirmed by the user, since this might change the
577 ;; conditions under which the request was issued.
98fdd2b8
CY
578 (unless (member url-http-method '("HEAD" "GET"))
579 (setq redirect-uri nil)))
1e9d758c 580 (see-other ; 303
8c8b8430
SM
581 ;; The response to the request can be found under a different
582 ;; URI and SHOULD be retrieved using a GET method on that
583 ;; resource.
584 (setq url-http-method "GET"
585 url-http-data nil))
1e9d758c 586 (not-modified ; 304
8c8b8430
SM
587 ;; The 304 response MUST NOT contain a message-body.
588 (url-http-debug "Extracting document from cache... (%s)"
589 (url-cache-create-filename (url-view-url t)))
590 (url-cache-extract (url-cache-create-filename (url-view-url t)))
591 (setq redirect-uri nil
592 success t))
1e9d758c 593 (use-proxy ; 305
8c8b8430
SM
594 ;; The requested resource MUST be accessed through the
595 ;; proxy given by the Location field. The Location field
596 ;; gives the URI of the proxy. The recipient is expected
597 ;; to repeat this single request via the proxy. 305
598 ;; responses MUST only be generated by origin servers.
599 (error "Redirection thru a proxy server not supported: %s"
600 redirect-uri))
601 (otherwise
602 ;; Treat everything like '300'
603 nil))
604 (when redirect-uri
605 ;; Clean off any whitespace and/or <...> cruft.
606 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
607 (setq redirect-uri (match-string 1 redirect-uri)))
608 (if (string-match "^<\\(.*\\)>$" redirect-uri)
609 (setq redirect-uri (match-string 1 redirect-uri)))
610
611 ;; Some stupid sites (like sourceforge) send a
612 ;; non-fully-qualified URL (ie: /), which royally confuses
613 ;; the URL library.
614 (if (not (string-match url-nonrelative-link redirect-uri))
12f1edc8
SM
615 ;; Be careful to use the real target URL, otherwise we may
616 ;; compute the redirection relative to the URL of the proxy.
617 (setq redirect-uri
618 (url-expand-file-name redirect-uri url-http-target-url)))
619 (let ((url-request-method url-http-method)
8c8b8430
SM
620 (url-request-data url-http-data)
621 (url-request-extra-headers url-http-extra-headers))
58aba814
CY
622 ;; Check existing number of redirects
623 (if (or (< url-max-redirections 0)
624 (and (> url-max-redirections 0)
625 (let ((events (car url-callback-arguments))
626 (old-redirects 0))
627 (while events
628 (if (eq (car events) :redirect)
629 (setq old-redirects (1+ old-redirects)))
630 (and (setq events (cdr events))
631 (setq events (cdr events))))
632 (< old-redirects url-max-redirections))))
633 ;; url-max-redirections hasn't been reached, so go
634 ;; ahead and redirect.
635 (progn
636 ;; Remember that the request was redirected.
637 (setf (car url-callback-arguments)
638 (nconc (list :redirect redirect-uri)
639 (car url-callback-arguments)))
640 ;; Put in the current buffer a forwarding pointer to the new
641 ;; destination buffer.
642 ;; FIXME: This is a hack to fix url-retrieve-synchronously
643 ;; without changing the API. Instead url-retrieve should
644 ;; either simply not return the "destination" buffer, or it
645 ;; should take an optional `dest-buf' argument.
646 (set (make-local-variable 'url-redirect-buffer)
647 (url-retrieve-internal
648 redirect-uri url-callback-function
08b8ba9f 649 url-callback-arguments
3b8eb822 650 (url-silent url-current-object)
3647f557 651 (not (url-use-cookies url-current-object))))
72f25299 652 (url-mark-buffer-as-dead buffer))
58aba814
CY
653 ;; We hit url-max-redirections, so issue an error and
654 ;; stop redirecting.
655 (url-http-debug "Maximum redirections reached")
656 (setf (car url-callback-arguments)
657 (nconc (list :error (list 'error 'http-redirect-limit
658 redirect-uri))
659 (car url-callback-arguments)))
660 (setq success t))))))
8c8b8430
SM
661 (4 ; Client error
662 ;; 400 Bad Request
663 ;; 401 Unauthorized
664 ;; 402 Payment required
665 ;; 403 Forbidden
666 ;; 404 Not found
667 ;; 405 Method not allowed
668 ;; 406 Not acceptable
669 ;; 407 Proxy authentication required
670 ;; 408 Request time-out
671 ;; 409 Conflict
672 ;; 410 Gone
673 ;; 411 Length required
674 ;; 412 Precondition failed
675 ;; 413 Request entity too large
676 ;; 414 Request-URI too large
677 ;; 415 Unsupported media type
678 ;; 416 Requested range not satisfiable
679 ;; 417 Expectation failed
680 ;; 422 Unprocessable Entity (Added by DAV)
681 ;; 423 Locked
682 ;; 424 Failed Dependency
1e9d758c
TZ
683 (case status-symbol
684 (unauthorized ; 401
8c8b8430
SM
685 ;; The request requires user authentication. The response
686 ;; MUST include a WWW-Authenticate header field containing a
687 ;; challenge applicable to the requested resource. The
688 ;; client MAY repeat the request with a suitable
689 ;; Authorization header field.
690 (url-http-handle-authentication nil))
1e9d758c 691 (payment-required ; 402
8c8b8430 692 ;; This code is reserved for future use
72f25299 693 (url-mark-buffer-as-dead buffer)
8c8b8430 694 (error "Somebody wants you to give them money"))
1e9d758c 695 (forbidden ; 403
8c8b8430
SM
696 ;; The server understood the request, but is refusing to
697 ;; fulfill it. Authorization will not help and the request
698 ;; SHOULD NOT be repeated.
699 (setq success t))
1e9d758c 700 (not-found ; 404
8c8b8430
SM
701 ;; Not found
702 (setq success t))
1e9d758c 703 (method-not-allowed ; 405
8c8b8430
SM
704 ;; The method specified in the Request-Line is not allowed
705 ;; for the resource identified by the Request-URI. The
706 ;; response MUST include an Allow header containing a list of
707 ;; valid methods for the requested resource.
708 (setq success t))
1e9d758c 709 (not-acceptable ; 406
8c8b8430
SM
710 ;; The resource identified by the request is only capable of
711 ;; generating response entities which have content
da6062e6 712 ;; characteristics not acceptable according to the accept
8c8b8430
SM
713 ;; headers sent in the request.
714 (setq success t))
1e9d758c 715 (proxy-authentication-required ; 407
8c8b8430
SM
716 ;; This code is similar to 401 (Unauthorized), but indicates
717 ;; that the client must first authenticate itself with the
718 ;; proxy. The proxy MUST return a Proxy-Authenticate header
719 ;; field containing a challenge applicable to the proxy for
720 ;; the requested resource.
721 (url-http-handle-authentication t))
1e9d758c 722 (request-timeout ; 408
8c8b8430
SM
723 ;; The client did not produce a request within the time that
724 ;; the server was prepared to wait. The client MAY repeat
725 ;; the request without modifications at any later time.
726 (setq success t))
1e9d758c 727 (conflict ; 409
8c8b8430
SM
728 ;; The request could not be completed due to a conflict with
729 ;; the current state of the resource. This code is only
730 ;; allowed in situations where it is expected that the user
53964682 731 ;; might be able to resolve the conflict and resubmit the
8c8b8430
SM
732 ;; request. The response body SHOULD include enough
733 ;; information for the user to recognize the source of the
734 ;; conflict.
735 (setq success t))
1e9d758c 736 (gone ; 410
8c8b8430
SM
737 ;; The requested resource is no longer available at the
738 ;; server and no forwarding address is known.
739 (setq success t))
1e9d758c 740 (length-required ; 411
8c8b8430
SM
741 ;; The server refuses to accept the request without a defined
742 ;; Content-Length. The client MAY repeat the request if it
743 ;; adds a valid Content-Length header field containing the
744 ;; length of the message-body in the request message.
745 ;;
746 ;; NOTE - this will never happen because
747 ;; `url-http-create-request' automatically calculates the
748 ;; content-length.
749 (setq success t))
1e9d758c 750 (precondition-failed ; 412
8c8b8430
SM
751 ;; The precondition given in one or more of the
752 ;; request-header fields evaluated to false when it was
753 ;; tested on the server.
754 (setq success t))
1e9d758c 755 ((request-entity-too-large request-uri-too-large) ; 413 414
8c8b8430
SM
756 ;; The server is refusing to process a request because the
757 ;; request entity|URI is larger than the server is willing or
758 ;; able to process.
759 (setq success t))
1e9d758c 760 (unsupported-media-type ; 415
8c8b8430
SM
761 ;; The server is refusing to service the request because the
762 ;; entity of the request is in a format not supported by the
763 ;; requested resource for the requested method.
764 (setq success t))
1e9d758c 765 (requested-range-not-satisfiable ; 416
8c8b8430
SM
766 ;; A server SHOULD return a response with this status code if
767 ;; a request included a Range request-header field, and none
768 ;; of the range-specifier values in this field overlap the
769 ;; current extent of the selected resource, and the request
770 ;; did not include an If-Range request-header field.
771 (setq success t))
1e9d758c 772 (expectation-failed ; 417
8c8b8430
SM
773 ;; The expectation given in an Expect request-header field
774 ;; could not be met by this server, or, if the server is a
775 ;; proxy, the server has unambiguous evidence that the
776 ;; request could not be met by the next-hop server.
777 (setq success t))
778 (otherwise
779 ;; The request could not be understood by the server due to
780 ;; malformed syntax. The client SHOULD NOT repeat the
781 ;; request without modifications.
5695d1dd
CY
782 (setq success t)))
783 ;; Tell the callback that an error occurred, and what the
784 ;; status code was.
785 (when success
786 (setf (car url-callback-arguments)
787 (nconc (list :error (list 'error 'http url-http-response-status))
788 (car url-callback-arguments)))))
8c8b8430
SM
789 (5
790 ;; 500 Internal server error
791 ;; 501 Not implemented
792 ;; 502 Bad gateway
793 ;; 503 Service unavailable
794 ;; 504 Gateway time-out
795 ;; 505 HTTP version not supported
796 ;; 507 Insufficient storage
797 (setq success t)
798 (case url-http-response-status
1e9d758c 799 (not-implemented ; 501
8c8b8430
SM
800 ;; The server does not support the functionality required to
801 ;; fulfill the request.
802 nil)
1e9d758c 803 (bad-gateway ; 502
8c8b8430
SM
804 ;; The server, while acting as a gateway or proxy, received
805 ;; an invalid response from the upstream server it accessed
806 ;; in attempting to fulfill the request.
807 nil)
1e9d758c 808 (service-unavailable ; 503
8c8b8430
SM
809 ;; The server is currently unable to handle the request due
810 ;; to a temporary overloading or maintenance of the server.
811 ;; The implication is that this is a temporary condition
812 ;; which will be alleviated after some delay. If known, the
813 ;; length of the delay MAY be indicated in a Retry-After
814 ;; header. If no Retry-After is given, the client SHOULD
815 ;; handle the response as it would for a 500 response.
816 nil)
1e9d758c 817 (gateway-timeout ; 504
8c8b8430
SM
818 ;; The server, while acting as a gateway or proxy, did not
819 ;; receive a timely response from the upstream server
820 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
821 ;; auxiliary server (e.g. DNS) it needed to access in
822 ;; attempting to complete the request.
823 nil)
1e9d758c 824 (http-version-not-supported ; 505
8c8b8430
SM
825 ;; The server does not support, or refuses to support, the
826 ;; HTTP protocol version that was used in the request
827 ;; message.
828 nil)
1e9d758c 829 (insufficient-storage ; 507 (DAV)
8c8b8430
SM
830 ;; The method could not be performed on the resource
831 ;; because the server is unable to store the representation
832 ;; needed to successfully complete the request. This
833 ;; condition is considered to be temporary. If the request
834 ;; which received this status code was the result of a user
835 ;; action, the request MUST NOT be repeated until it is
836 ;; requested by a separate user action.
5695d1dd
CY
837 nil))
838 ;; Tell the callback that an error occurred, and what the
839 ;; status code was.
840 (when success
841 (setf (car url-callback-arguments)
842 (nconc (list :error (list 'error 'http url-http-response-status))
843 (car url-callback-arguments)))))
8c8b8430
SM
844 (otherwise
845 (error "Unknown class of HTTP response code: %d (%d)"
846 class url-http-response-status)))
847 (if (not success)
72f25299 848 (url-mark-buffer-as-dead buffer))
8c8b8430
SM
849 (url-http-debug "Finished parsing HTTP headers: %S" success)
850 (widen)
851 success))
852
853;; Miscellaneous
854(defun url-http-activate-callback ()
855 "Activate callback specified when this buffer was created."
856 (declare (special url-http-process
857 url-callback-function
858 url-callback-arguments))
859 (url-http-mark-connection-as-free (url-host url-current-object)
860 (url-port url-current-object)
861 url-http-process)
862 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
863 (apply url-callback-function url-callback-arguments))
864
865;; )
866
867;; These unfortunately cannot be macros... please ignore them!
868(defun url-http-idle-sentinel (proc why)
d1ce47b0 869 "Remove (now defunct) process PROC from the list of open connections."
8c8b8430
SM
870 (maphash (lambda (key val)
871 (if (memq proc val)
872 (puthash key (delq proc val) url-http-open-connections)))
873 url-http-open-connections))
874
875(defun url-http-end-of-document-sentinel (proc why)
876 ;; Sentinel used for old HTTP/0.9 or connections we know are going
877 ;; to die as the 'end of document' notifier.
878 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
879 (process-buffer proc))
880 (url-http-idle-sentinel proc why)
b0e0b216
LMI
881 (when (buffer-name (process-buffer proc))
882 (with-current-buffer (process-buffer proc)
883 (goto-char (point-min))
884 (if (not (looking-at "HTTP/"))
885 ;; HTTP/0.9 just gets passed back no matter what
886 (url-http-activate-callback)
887 (if (url-http-parse-headers)
888 (url-http-activate-callback))))))
8c8b8430
SM
889
890(defun url-http-simple-after-change-function (st nd length)
891 ;; Function used when we do NOT know how long the document is going to be
892 ;; Just _very_ simple 'downloaded %d' type of info.
893 (declare (special url-http-end-of-headers))
894 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
895
896(defun url-http-content-length-after-change-function (st nd length)
897 "Function used when we DO know how long the document is going to be.
898More sophisticated percentage downloaded, etc.
899Also does minimal parsing of HTTP headers and will actually cause
900the callback to be triggered."
901 (declare (special url-current-object
902 url-http-end-of-headers
903 url-http-content-length
904 url-http-content-type
905 url-http-process))
906 (if url-http-content-type
907 (url-display-percentage
908 "Reading [%s]... %s of %s (%d%%)"
909 (url-percentage (- nd url-http-end-of-headers)
910 url-http-content-length)
911 url-http-content-type
912 (url-pretty-length (- nd url-http-end-of-headers))
913 (url-pretty-length url-http-content-length)
914 (url-percentage (- nd url-http-end-of-headers)
915 url-http-content-length))
916 (url-display-percentage
917 "Reading... %s of %s (%d%%)"
918 (url-percentage (- nd url-http-end-of-headers)
919 url-http-content-length)
920 (url-pretty-length (- nd url-http-end-of-headers))
921 (url-pretty-length url-http-content-length)
922 (url-percentage (- nd url-http-end-of-headers)
923 url-http-content-length)))
924
925 (if (> (- nd url-http-end-of-headers) url-http-content-length)
926 (progn
927 ;; Found the end of the document! Wheee!
928 (url-display-percentage nil nil)
f0d64cfc 929 (url-lazy-message "Reading... done.")
8c8b8430
SM
930 (if (url-http-parse-headers)
931 (url-http-activate-callback)))))
932
933(defun url-http-chunked-encoding-after-change-function (st nd length)
934 "Function used when dealing with 'chunked' encoding.
935Cannot give a sophisticated percentage, but we need a different
936function to look for the special 0-length chunk that signifies
937the end of the document."
938 (declare (special url-current-object
939 url-http-end-of-headers
940 url-http-content-type
941 url-http-chunked-length
942 url-http-chunked-counter
943 url-http-process url-http-chunked-start))
944 (save-excursion
945 (goto-char st)
946 (let ((read-next-chunk t)
947 (case-fold-search t)
948 (regexp nil)
949 (no-initial-crlf nil))
950 ;; We need to loop thru looking for more chunks even within
951 ;; one after-change-function call.
952 (while read-next-chunk
953 (setq no-initial-crlf (= 0 url-http-chunked-counter))
954 (if url-http-content-type
955 (url-display-percentage nil
956 "Reading [%s]... chunk #%d"
957 url-http-content-type url-http-chunked-counter)
958 (url-display-percentage nil
959 "Reading... chunk #%d"
960 url-http-chunked-counter))
961 (url-http-debug "Reading chunk %d (%d %d %d)"
962 url-http-chunked-counter st nd length)
963 (setq regexp (if no-initial-crlf
964 "\\([0-9a-z]+\\).*\r?\n"
965 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
966
967 (if url-http-chunked-start
968 ;; We know how long the chunk is supposed to be, skip over
969 ;; leading crap if possible.
970 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
971 (progn
972 (url-http-debug "Got to the end of chunk #%d!"
973 url-http-chunked-counter)
974 (goto-char (+ url-http-chunked-start
975 url-http-chunked-length)))
976 (url-http-debug "Still need %d bytes to hit end of chunk"
977 (- (+ url-http-chunked-start
978 url-http-chunked-length)
979 nd))
980 (setq read-next-chunk nil)))
981 (if (not read-next-chunk)
982 (url-http-debug "Still spinning for next chunk...")
983 (if no-initial-crlf (skip-chars-forward "\r\n"))
984 (if (not (looking-at regexp))
985 (progn
986 ;; Must not have received the entirety of the chunk header,
987 ;; need to spin some more.
988 (url-http-debug "Did not see start of chunk @ %d!" (point))
989 (setq read-next-chunk nil))
990 (add-text-properties (match-beginning 0) (match-end 0)
991 (list 'start-open t
992 'end-open t
993 'chunked-encoding t
cc38a294 994 'face 'cursor
8c8b8430 995 'invisible t))
216d3806
JB
996 (setq url-http-chunked-length (string-to-number (buffer-substring
997 (match-beginning 1)
998 (match-end 1))
999 16)
8c8b8430
SM
1000 url-http-chunked-counter (1+ url-http-chunked-counter)
1001 url-http-chunked-start (set-marker
1002 (or url-http-chunked-start
1003 (make-marker))
1004 (match-end 0)))
1005; (if (not url-http-debug)
1006 (delete-region (match-beginning 0) (match-end 0));)
1007 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1008 url-http-chunked-counter url-http-chunked-length
1009 (marker-position url-http-chunked-start))
1010 (if (= 0 url-http-chunked-length)
1011 (progn
1012 ;; Found the end of the document! Wheee!
1013 (url-http-debug "Saw end of stream chunk!")
1014 (setq read-next-chunk nil)
1015 (url-display-percentage nil nil)
84f089d3
MH
1016 ;; Every chunk, even the last 0-length one, is
1017 ;; terminated by CRLF. Skip it.
1018 (when (looking-at "\r?\n")
1019 (url-http-debug "Removing terminator of last chunk")
1020 (delete-region (match-beginning 0) (match-end 0)))
8c8b8430 1021 (if (re-search-forward "^\r*$" nil t)
63db9644 1022 (url-http-debug "Saw end of trailers..."))
8c8b8430
SM
1023 (if (url-http-parse-headers)
1024 (url-http-activate-callback))))))))))
1025
1026(defun url-http-wait-for-headers-change-function (st nd length)
1027 ;; This will wait for the headers to arrive and then splice in the
1028 ;; next appropriate after-change-function, etc.
1029 (declare (special url-current-object
1030 url-http-end-of-headers
1031 url-http-content-type
1032 url-http-content-length
1033 url-http-transfer-encoding
1034 url-callback-function
1035 url-callback-arguments
1036 url-http-process
1037 url-http-method
1038 url-http-after-change-function
1039 url-http-response-status))
1040 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1041 (buffer-name))
b301d174
LI
1042 (let ((end-of-headers nil)
1043 (old-http nil)
1044 (process-buffer (current-buffer))
1045 (content-length nil))
1046 (when (not (bobp))
57babe17
MH
1047 (goto-char (point-min))
1048 (if (and (looking-at ".*\n") ; have one line at least
1049 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1050 ;; Not HTTP/x.y data, must be 0.9
1051 ;; God, I wish this could die.
1052 (setq end-of-headers t
1053 url-http-end-of-headers 0
1054 old-http t)
1055 (when (re-search-forward "^\r*$" nil t)
1056 ;; Saw the end of the headers
1057 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1058 (setq url-http-end-of-headers (set-marker (make-marker)
1059 (point))
1060 end-of-headers t)
d7c5e162 1061 (setq nd (- nd (url-http-clean-headers)))))
8c8b8430 1062
d23832a2 1063 (if (not end-of-headers)
57babe17
MH
1064 ;; Haven't seen the end of the headers yet, need to wait
1065 ;; for more data to arrive.
1066 nil
9aec558a
LMI
1067 (unless old-http
1068 (url-http-parse-response)
1069 (mail-narrow-to-head)
1070 (setq url-http-transfer-encoding (mail-fetch-field
1071 "transfer-encoding")
1072 url-http-content-type (mail-fetch-field "content-type"))
1073 (if (mail-fetch-field "content-length")
1074 (setq url-http-content-length
1075 (string-to-number (mail-fetch-field "content-length"))))
1076 (widen))
57babe17
MH
1077 (when url-http-transfer-encoding
1078 (setq url-http-transfer-encoding
1079 (downcase url-http-transfer-encoding)))
8c8b8430 1080
57babe17 1081 (cond
10472dd0
LMI
1082 ((null url-http-response-status)
1083 ;; We got back a headerless malformed response from the
1084 ;; server.
1085 (url-http-activate-callback))
57babe17
MH
1086 ((or (= url-http-response-status 204)
1087 (= url-http-response-status 205))
1088 (url-http-debug "%d response must have headers only (%s)."
1089 url-http-response-status (buffer-name))
1090 (when (url-http-parse-headers)
1091 (url-http-activate-callback)))
1092 ((string= "HEAD" url-http-method)
1093 ;; A HEAD request is _ALWAYS_ terminated by the header
1094 ;; information, regardless of any entity headers,
1095 ;; according to section 4.4 of the HTTP/1.1 draft.
1096 (url-http-debug "HEAD request must have headers only (%s)."
1097 (buffer-name))
1098 (when (url-http-parse-headers)
1099 (url-http-activate-callback)))
1100 ((string= "CONNECT" url-http-method)
1101 ;; A CONNECT request is finished, but we cannot stick this
da6062e6 1102 ;; back on the free connection list
57babe17
MH
1103 (url-http-debug "CONNECT request must have headers only.")
1104 (when (url-http-parse-headers)
1105 (url-http-activate-callback)))
1106 ((equal url-http-response-status 304)
1107 ;; Only allowed to have a header section. We have to handle
1108 ;; this here instead of in url-http-parse-headers because if
1109 ;; you have a cached copy of something without a known
1110 ;; content-length, and try to retrieve it from the cache, we'd
1111 ;; fall into the 'being dumb' section and wait for the
1112 ;; connection to terminate, which means we'd wait for 10
1113 ;; seconds for the keep-alives to time out on some servers.
1114 (when (url-http-parse-headers)
1115 (url-http-activate-callback)))
1116 (old-http
1117 ;; HTTP/0.9 always signaled end-of-connection by closing the
1118 ;; connection.
1119 (url-http-debug
1120 "Saw HTTP/0.9 response, connection closed means end of document.")
1121 (setq url-http-after-change-function
1122 'url-http-simple-after-change-function))
1123 ((equal url-http-transfer-encoding "chunked")
1124 (url-http-debug "Saw chunked encoding.")
1125 (setq url-http-after-change-function
1126 'url-http-chunked-encoding-after-change-function)
1127 (when (> nd url-http-end-of-headers)
8c8b8430 1128 (url-http-debug
57babe17
MH
1129 "Calling initial chunked-encoding for extra data at end of headers")
1130 (url-http-chunked-encoding-after-change-function
1131 (marker-position url-http-end-of-headers) nd
1132 (- nd url-http-end-of-headers))))
1133 ((integerp url-http-content-length)
1134 (url-http-debug
1135 "Got a content-length, being smart about document end.")
1136 (setq url-http-after-change-function
1137 'url-http-content-length-after-change-function)
1138 (cond
1139 ((= 0 url-http-content-length)
1140 ;; We got a NULL body! Activate the callback
1141 ;; immediately!
8c8b8430 1142 (url-http-debug
57babe17
MH
1143 "Got 0-length content-length, activating callback immediately.")
1144 (when (url-http-parse-headers)
1145 (url-http-activate-callback)))
1146 ((> nd url-http-end-of-headers)
1147 ;; Have some leftover data
1148 (url-http-debug "Calling initial content-length for extra data at end of headers")
1149 (url-http-content-length-after-change-function
1150 (marker-position url-http-end-of-headers)
1151 nd
1152 (- nd url-http-end-of-headers)))
8c8b8430 1153 (t
57babe17
MH
1154 nil)))
1155 (t
1156 (url-http-debug "No content-length, being dumb.")
1157 (setq url-http-after-change-function
1158 'url-http-simple-after-change-function)))))
8c8b8430
SM
1159 ;; We are still at the beginning of the buffer... must just be
1160 ;; waiting for a response.
b301d174
LI
1161 (url-http-debug "Spinning waiting for headers...")
1162 (when (eq process-buffer (current-buffer))
1163 (goto-char (point-max)))))
8c8b8430
SM
1164
1165;;;###autoload
1166(defun url-http (url callback cbargs)
1167 "Retrieve URL via HTTP asynchronously.
1168URL must be a parsed URL. See `url-generic-parse-url' for details.
1169When retrieval is completed, the function CALLBACK is executed with
1170CBARGS as the arguments."
1171 (check-type url vector "Need a pre-parsed URL.")
1172 (declare (special url-current-object
1173 url-http-end-of-headers
1174 url-http-content-type
1175 url-http-content-length
1176 url-http-transfer-encoding
1177 url-http-after-change-function
1178 url-callback-function
1179 url-callback-arguments
b0c9af93 1180 url-show-status
8c8b8430
SM
1181 url-http-method
1182 url-http-extra-headers
1183 url-http-data
1184 url-http-chunked-length
1185 url-http-chunked-start
1186 url-http-chunked-counter
9450f124 1187 url-http-process))
62bfb5bb
MH
1188 (let* ((host (url-host (or url-using-proxy url)))
1189 (port (url-port (or url-using-proxy url)))
1190 (connection (url-http-find-free-connection host port))
1191 (buffer (generate-new-buffer (format " *http %s:%d*" host port))))
8c8b8430
SM
1192 (if (not connection)
1193 ;; Failed to open the connection for some reason
1194 (progn
1195 (kill-buffer buffer)
1196 (setq buffer nil)
62bfb5bb 1197 (error "Could not create connection to %s:%d" host port))
12f1edc8 1198 (with-current-buffer buffer
8c8b8430
SM
1199 (mm-disable-multibyte)
1200 (setq url-current-object url
1201 mode-line-format "%b [%s]")
1202
1203 (dolist (var '(url-http-end-of-headers
1204 url-http-content-type
1205 url-http-content-length
1206 url-http-transfer-encoding
1207 url-http-after-change-function
b9b172ac 1208 url-http-response-version
8c8b8430
SM
1209 url-http-response-status
1210 url-http-chunked-length
1211 url-http-chunked-counter
1212 url-http-chunked-start
1213 url-callback-function
1214 url-callback-arguments
b0c9af93 1215 url-show-status
8c8b8430
SM
1216 url-http-process
1217 url-http-method
1218 url-http-extra-headers
cacfe88b 1219 url-http-data
62bfb5bb 1220 url-http-target-url
b3cd7f61 1221 url-http-connection-opened
62bfb5bb 1222 url-http-proxy))
8c8b8430
SM
1223 (set (make-local-variable var) nil))
1224
1225 (setq url-http-method (or url-request-method "GET")
1226 url-http-extra-headers url-request-extra-headers
1227 url-http-data url-request-data
1228 url-http-process connection
1229 url-http-chunked-length nil
1230 url-http-chunked-start nil
1231 url-http-chunked-counter 0
1232 url-callback-function callback
1233 url-callback-arguments cbargs
cacfe88b 1234 url-http-after-change-function 'url-http-wait-for-headers-change-function
62bfb5bb 1235 url-http-target-url url-current-object
b3cd7f61 1236 url-http-connection-opened nil
62bfb5bb 1237 url-http-proxy url-using-proxy)
8c8b8430
SM
1238
1239 (set-process-buffer connection buffer)
8c8b8430 1240 (set-process-filter connection 'url-http-generic-filter)
5695d1dd
CY
1241 (let ((status (process-status connection)))
1242 (cond
1243 ((eq status 'connect)
1244 ;; Asynchronous connection
1245 (set-process-sentinel connection 'url-http-async-sentinel))
1246 ((eq status 'failed)
1247 ;; Asynchronous connection failed
62bfb5bb 1248 (error "Could not create connection to %s:%d" host port))
5695d1dd
CY
1249 (t
1250 (set-process-sentinel connection 'url-http-end-of-document-sentinel)
9450f124 1251 (process-send-string connection (url-http-create-request)))))))
8c8b8430
SM
1252 buffer))
1253
5695d1dd
CY
1254(defun url-http-async-sentinel (proc why)
1255 (declare (special url-callback-arguments))
1256 ;; We are performing an asynchronous connection, and a status change
1257 ;; has occurred.
6ca26f1d
LMI
1258 (when (buffer-name (process-buffer proc))
1259 (with-current-buffer (process-buffer proc)
1260 (cond
1261 (url-http-connection-opened
1262 (url-http-end-of-document-sentinel proc why))
1263 ((string= (substring why 0 4) "open")
1264 (setq url-http-connection-opened t)
122d9463
LMI
1265 (condition-case error
1266 (process-send-string proc (url-http-create-request))
1267 (file-error
1268 (setq url-http-connection-opened nil)
1269 (message "HTTP error: %s" error))))
6ca26f1d
LMI
1270 (t
1271 (setf (car url-callback-arguments)
1272 (nconc (list :error (list 'error 'connection-failed why
1273 :host (url-host (or url-http-proxy url-current-object))
1274 :service (url-port (or url-http-proxy url-current-object))))
1275 (car url-callback-arguments)))
1276 (url-http-activate-callback))))))
5695d1dd 1277
8c8b8430
SM
1278;; Since Emacs 19/20 does not allow you to change the
1279;; `after-change-functions' hook in the midst of running them, we fake
1280;; an after change by hooking into the process filter and inserting
1281;; the data ourselves. This is slightly less efficient, but there
1282;; were tons of weird ways the after-change code was biting us in the
1283;; shorts.
12421f1c 1284;; FIXME this can probably be simplified since the above is no longer true.
8c8b8430
SM
1285(defun url-http-generic-filter (proc data)
1286 ;; Sometimes we get a zero-length data chunk after the process has
1287 ;; been changed to 'free', which means it has no buffer associated
1288 ;; with it. Do nothing if there is no buffer, or 0 length data.
1289 (declare (special url-http-after-change-function))
1290 (and (process-buffer proc)
1291 (/= (length data) 0)
12f1edc8 1292 (with-current-buffer (process-buffer proc)
8c8b8430
SM
1293 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1294 (funcall url-http-after-change-function
1295 (point-max)
1296 (progn
1297 (goto-char (point-max))
1298 (insert data)
1299 (point-max))
1300 (length data)))))
1301
1302;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1303;;; file-name-handler stuff from here on out
1304;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8dff56de
SM
1305(defalias 'url-http-symbol-value-in-buffer
1306 (if (fboundp 'symbol-value-in-buffer)
1307 'symbol-value-in-buffer
1308 (lambda (symbol buffer &optional unbound-value)
8c8b8430 1309 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
12f1edc8 1310 (with-current-buffer buffer
8dff56de
SM
1311 (if (not (boundp symbol))
1312 unbound-value
1313 (symbol-value symbol))))))
8c8b8430
SM
1314
1315(defun url-http-head (url)
1316 (let ((url-request-method "HEAD")
1317 (url-request-data nil))
1318 (url-retrieve-synchronously url)))
1319
1320;;;###autoload
1321(defun url-http-file-exists-p (url)
b43eb9ab 1322 (let ((status nil)
8c8b8430
SM
1323 (exists nil)
1324 (buffer (url-http-head url)))
1325 (if (not buffer)
1326 (setq exists nil)
1327 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1328 buffer 500)
d10a6bf1
RS
1329 exists (and (integerp status)
1330 (>= status 200) (< status 300)))
8c8b8430
SM
1331 (kill-buffer buffer))
1332 exists))
1333
1334;;;###autoload
1335(defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1336
3f19601e 1337(defun url-http-head-file-attributes (url &optional id-format)
162fbe11 1338 (let ((buffer (url-http-head url)))
8c8b8430 1339 (when buffer
162fbe11
SM
1340 (prog1
1341 (list
1342 nil ;dir / link / normal file
1343 1 ;number of links to file.
1344 0 0 ;uid ; gid
1345 nil nil nil ;atime ; mtime ; ctime
1346 (url-http-symbol-value-in-buffer 'url-http-content-length
1347 buffer -1)
1348 (eval-when-compile (make-string 10 ?-))
1349 nil nil nil) ;whether gid would change ; inode ; device.
1350 (kill-buffer buffer)))))
8c8b8430 1351
f9c9a239 1352(declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
153ef845 1353
8c8b8430 1354;;;###autoload
3f19601e 1355(defun url-http-file-attributes (url &optional id-format)
8c8b8430 1356 (if (url-dav-supported-p url)
3f19601e
SM
1357 (url-dav-file-attributes url id-format)
1358 (url-http-head-file-attributes url id-format)))
8c8b8430
SM
1359
1360;;;###autoload
1361(defun url-http-options (url)
55d1d8b7 1362 "Return a property list describing options available for URL.
8c8b8430
SM
1363This list is retrieved using the `OPTIONS' HTTP method.
1364
1365Property list members:
1366
1367methods
1368 A list of symbols specifying what HTTP methods the resource
1369 supports.
1370
1371dav
1372 A list of numbers specifying what DAV protocol/schema versions are
1373 supported.
1374
1375dasl
1376 A list of supported DASL search types supported (string form)
1377
1378ranges
1379 A list of the units available for use in partial document fetches.
1380
1381p3p
1382 The `Platform For Privacy Protection' description for the resource.
1383 Currently this is just the raw header contents. This is likely to
1384 change once P3P is formally supported by the URL package or
55d1d8b7 1385 Emacs/W3."
8c8b8430
SM
1386 (let* ((url-request-method "OPTIONS")
1387 (url-request-data nil)
1388 (buffer (url-retrieve-synchronously url))
1389 (header nil)
1390 (options nil))
1391 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1392 'url-http-response-status buffer 0) 100)))
1393 ;; Only parse the options if we got a 2xx response code!
12f1edc8 1394 (with-current-buffer buffer
8c8b8430
SM
1395 (save-restriction
1396 (save-match-data
8c8b8430
SM
1397 (mail-narrow-to-head)
1398
1399 ;; Figure out what methods are supported.
1400 (when (setq header (mail-fetch-field "allow"))
1401 (setq options (plist-put
1402 options 'methods
1403 (mapcar 'intern (split-string header "[ ,]+")))))
1404
1405 ;; Check for DAV
1406 (when (setq header (mail-fetch-field "dav"))
1407 (setq options (plist-put
1408 options 'dav
1409 (delq 0
1410 (mapcar 'string-to-number
1411 (split-string header "[, ]+"))))))
1412
1413 ;; Now for DASL
1414 (when (setq header (mail-fetch-field "dasl"))
1415 (setq options (plist-put
1416 options 'dasl
1417 (split-string header "[, ]+"))))
1418
1419 ;; P3P - should get more detailed here. FIXME
1420 (when (setq header (mail-fetch-field "p3p"))
1421 (setq options (plist-put options 'p3p header)))
1422
1423 ;; Check for whether they accept byte-range requests.
1424 (when (setq header (mail-fetch-field "accept-ranges"))
1425 (setq options (plist-put
1426 options 'ranges
1427 (delq 'none
1428 (mapcar 'intern
1429 (split-string header "[, ]+"))))))
1430 ))))
1431 (if buffer (kill-buffer buffer))
1432 options))
1433
9c51663a
MH
1434;; HTTPS. This used to be in url-https.el, but that file collides
1435;; with url-http.el on systems with 8-character file names.
1436(require 'tls)
1437
1438;;;###autoload
1439(defconst url-https-default-port 443 "Default HTTPS port.")
1440;;;###autoload
1441(defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
b7270504
GM
1442
1443;; FIXME what is the point of this alias being an autoload?
1444;; Trying to use it will not cause url-http to be loaded,
1445;; since the full alias just gets dumped into loaddefs.el.
1446
e77e9cf4 1447;;;###autoload (autoload 'url-default-expander "url-expand")
9c51663a 1448;;;###autoload
e77e9cf4 1449(defalias 'url-https-expand-file-name 'url-default-expander)
9c51663a
MH
1450
1451(defmacro url-https-create-secure-wrapper (method args)
1452 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1453 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
784f5416 1454 (let ((url-gateway-method 'tls))
9c51663a
MH
1455 (,(intern (format (if method "url-http-%s" "url-http") method))
1456 ,@(remove '&rest (remove '&optional args))))))
1457
1458;;;###autoload (autoload 'url-https "url-http")
1459(url-https-create-secure-wrapper nil (url callback cbargs))
1460;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1461(url-https-create-secure-wrapper file-exists-p (url))
1462;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1463(url-https-create-secure-wrapper file-readable-p (url))
1464;;;###autoload (autoload 'url-https-file-attributes "url-http")
1465(url-https-create-secure-wrapper file-attributes (url &optional id-format))
1466
8c8b8430
SM
1467(provide 'url-http)
1468
1469;;; url-http.el ends here