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