Port 'movemail' again to Solaris and similar hosts.
[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)
09100633 30(defvar url-http-no-retry)
62bfb5bb 31(defvar url-http-proxy)
b3cd7f61 32(defvar url-http-connection-opened)
8c8b8430
SM
33(require 'url-gw)
34(require 'url-util)
35(require 'url-parse)
36(require 'url-cookie)
37(require 'mail-parse)
38(require 'url-auth)
55d1d8b7 39(require 'url)
8c8b8430 40(autoload 'url-cache-create-filename "url-cache")
8c8b8430
SM
41
42(defconst url-http-default-port 80 "Default HTTP port.")
43(defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
44(defalias 'url-http-expand-file-name 'url-default-expander)
45
46(defvar url-http-real-basic-auth-storage nil)
47(defvar url-http-proxy-basic-auth-storage nil)
48
49(defvar url-http-open-connections (make-hash-table :test 'equal
50 :size 17)
51 "A hash table of all open network connections.")
52
53(defvar url-http-version "1.1"
54 "What version of HTTP we advertise, as a string.
55Valid values are 1.1 and 1.0.
56This is only useful when debugging the HTTP subsystem.
57
58Setting this to 1.0 will tell servers not to send chunked encoding,
55d1d8b7 59and other HTTP/1.1 specific features.")
8c8b8430
SM
60
61(defvar url-http-attempt-keepalives t
62 "Whether to use a single TCP connection multiple times in HTTP.
63This is only useful when debugging the HTTP subsystem. Setting to
55d1d8b7
SM
64nil will explicitly close the connection to the server after every
65request.")
8c8b8430 66
1e9d758c
TZ
67(defconst url-http-codes
68 '((100 continue "Continue with request")
69 (101 switching-protocols "Switching protocols")
70 (102 processing "Processing (Added by DAV)")
71 (200 OK "OK")
72 (201 created "Created")
73 (202 accepted "Accepted")
74 (203 non-authoritative "Non-authoritative information")
75 (204 no-content "No content")
76 (205 reset-content "Reset content")
77 (206 partial-content "Partial content")
78 (207 multi-status "Multi-status (Added by DAV)")
79 (300 multiple-choices "Multiple choices")
80 (301 moved-permanently "Moved permanently")
81 (302 found "Found")
82 (303 see-other "See other")
83 (304 not-modified "Not modified")
84 (305 use-proxy "Use proxy")
85 (307 temporary-redirect "Temporary redirect")
86 (400 bad-request "Bad Request")
87 (401 unauthorized "Unauthorized")
88 (402 payment-required "Payment required")
89 (403 forbidden "Forbidden")
90 (404 not-found "Not found")
91 (405 method-not-allowed "Method not allowed")
92 (406 not-acceptable "Not acceptable")
93 (407 proxy-authentication-required "Proxy authentication required")
94 (408 request-timeout "Request time-out")
95 (409 conflict "Conflict")
96 (410 gone "Gone")
97 (411 length-required "Length required")
98 (412 precondition-failed "Precondition failed")
99 (413 request-entity-too-large "Request entity too large")
100 (414 request-uri-too-large "Request-URI too large")
101 (415 unsupported-media-type "Unsupported media type")
102 (416 requested-range-not-satisfiable "Requested range not satisfiable")
103 (417 expectation-failed "Expectation failed")
104 (422 unprocessable-entity "Unprocessable Entity (Added by DAV)")
105 (423 locked "Locked")
106 (424 failed-Dependency "Failed Dependency")
107 (500 internal-server-error "Internal server error")
108 (501 not-implemented "Not implemented")
109 (502 bad-gateway "Bad gateway")
110 (503 service-unavailable "Service unavailable")
111 (504 gateway-timeout "Gateway time-out")
112 (505 http-version-not-supported "HTTP version not supported")
9979ea1c
LL
113 (507 insufficient-storage "Insufficient storage"))
114 "The HTTP return codes and their text.")
1e9d758c 115
8c8b8430
SM
116;(eval-when-compile
117;; These are all macros so that they are hidden from external sight
118;; when the file is byte-compiled.
119;;
120;; This allows us to expose just the entry points we want.
121
122;; These routines will allow us to implement persistent HTTP
123;; connections.
124(defsubst url-http-debug (&rest args)
125 (if quit-flag
126 (let ((proc (get-buffer-process (current-buffer))))
127 ;; The user hit C-g, honor it! Some things can get in an
128 ;; incredibly tight loop (chunked encoding)
129 (if proc
130 (progn
131 (set-process-sentinel proc nil)
132 (set-process-filter proc nil)))
133 (error "Transfer interrupted!")))
134 (apply 'url-debug 'http args))
135
136(defun url-http-mark-connection-as-busy (host port proc)
137 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
8ae85a27 138 (set-process-query-on-exit-flag proc t)
8c8b8430
SM
139 (puthash (cons host port)
140 (delq proc (gethash (cons host port) url-http-open-connections))
141 url-http-open-connections)
142 proc)
143
144(defun url-http-mark-connection-as-free (host port proc)
145 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
db8d5936 146 (when (memq (process-status proc) '(open run connect))
5695d1dd
CY
147 (set-process-buffer proc nil)
148 (set-process-sentinel proc 'url-http-idle-sentinel)
8ae85a27 149 (set-process-query-on-exit-flag proc nil)
5695d1dd
CY
150 (puthash (cons host port)
151 (cons proc (gethash (cons host port) url-http-open-connections))
152 url-http-open-connections))
8c8b8430
SM
153 nil)
154
155(defun url-http-find-free-connection (host port)
156 (let ((conns (gethash (cons host port) url-http-open-connections))
179f6911
DSM
157 (connection nil))
158 (while (and conns (not connection))
db8d5936 159 (if (not (memq (process-status (car conns)) '(run open connect)))
8c8b8430
SM
160 (progn
161 (url-http-debug "Cleaning up dead process: %s:%d %S"
162 host port (car conns))
163 (url-http-idle-sentinel (car conns) nil))
179f6911
DSM
164 (setq connection (car conns))
165 (url-http-debug "Found existing connection: %s:%d %S" host port connection))
8c8b8430 166 (pop conns))
179f6911 167 (if connection
8c8b8430
SM
168 (url-http-debug "Reusing existing connection: %s:%d" host port)
169 (url-http-debug "Contacting host: %s:%d" host port))
170 (url-lazy-message "Contacting host: %s:%d" host port)
179f6911
DSM
171
172 (unless connection
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.
176 (unwind-protect
177 (let ((proc (url-open-stream host buf host port)))
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)
182 (setq connection proc)))
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))
187 (kill-buffer buf))))
188
189 (if connection
190 (url-http-mark-connection-as-busy host port connection))))
8c8b8430
SM
191
192;; Building an HTTP request
193(defun url-http-user-agent-string ()
194 (if (or (eq url-privacy-level 'paranoid)
195 (and (listp url-privacy-level)
196 (memq 'agent url-privacy-level)))
197 ""
198 (format "User-Agent: %sURL/%s%s\r\n"
199 (if url-package-name
200 (concat url-package-name "/" url-package-version " ")
201 "")
202 url-version
203 (cond
204 ((and url-os-type url-system-type)
205 (concat " (" url-os-type "; " url-system-type ")"))
206 ((or url-os-type url-system-type)
207 (concat " (" (or url-system-type url-os-type) ")"))
208 (t "")))))
209
9450f124
MH
210(defun url-http-create-request (&optional ref-url)
211 "Create an HTTP request for `url-http-target-url', referred to by REF-URL."
d1ce47b0 212 (declare (special proxy-info
8ea88265
MH
213 url-http-method url-http-data
214 url-http-extra-headers))
8c8b8430
SM
215 (let* ((extra-headers)
216 (request nil)
8ea88265 217 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
62bfb5bb 218 (using-proxy url-http-proxy)
8c8b8430 219 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
8ea88265 220 url-http-extra-headers))
9450f124 221 (not using-proxy))
8c8b8430
SM
222 nil
223 (let ((url-basic-auth-storage
224 'url-http-proxy-basic-auth-storage))
9450f124 225 (url-get-authentication url-http-target-url nil 'any nil))))
ce7b18ec 226 (real-fname (url-filename url-http-target-url))
9450f124 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)
09100633
CY
878 ;; Sentinel used to handle (i) terminated old HTTP/0.9 connections,
879 ;; and (ii) closed connection due to reusing a HTTP connection which
880 ;; we believed was still alive, but which the server closed on us.
881 ;; We handle case (ii) by calling `url-http' again.
8c8b8430
SM
882 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
883 (process-buffer proc))
884 (url-http-idle-sentinel proc why)
b0e0b216
LMI
885 (when (buffer-name (process-buffer proc))
886 (with-current-buffer (process-buffer proc)
887 (goto-char (point-min))
09100633
CY
888 (cond ((not (looking-at "HTTP/"))
889 (if url-http-no-retry
890 ;; HTTP/0.9 just gets passed back no matter what
891 (url-http-activate-callback)
892 ;; Call `url-http' again if our connection expired.
893 (erase-buffer)
894 (url-http url-current-object url-callback-function
895 url-callback-arguments (current-buffer))))
896 ((url-http-parse-headers)
897 (url-http-activate-callback))))))
8c8b8430
SM
898
899(defun url-http-simple-after-change-function (st nd length)
900 ;; Function used when we do NOT know how long the document is going to be
901 ;; Just _very_ simple 'downloaded %d' type of info.
902 (declare (special url-http-end-of-headers))
903 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
904
905(defun url-http-content-length-after-change-function (st nd length)
906 "Function used when we DO know how long the document is going to be.
907More sophisticated percentage downloaded, etc.
908Also does minimal parsing of HTTP headers and will actually cause
909the callback to be triggered."
910 (declare (special url-current-object
911 url-http-end-of-headers
912 url-http-content-length
913 url-http-content-type
914 url-http-process))
915 (if url-http-content-type
916 (url-display-percentage
917 "Reading [%s]... %s of %s (%d%%)"
918 (url-percentage (- nd url-http-end-of-headers)
919 url-http-content-length)
920 url-http-content-type
921 (url-pretty-length (- nd url-http-end-of-headers))
922 (url-pretty-length url-http-content-length)
923 (url-percentage (- nd url-http-end-of-headers)
924 url-http-content-length))
925 (url-display-percentage
926 "Reading... %s of %s (%d%%)"
927 (url-percentage (- nd url-http-end-of-headers)
928 url-http-content-length)
929 (url-pretty-length (- nd url-http-end-of-headers))
930 (url-pretty-length url-http-content-length)
931 (url-percentage (- nd url-http-end-of-headers)
932 url-http-content-length)))
933
934 (if (> (- nd url-http-end-of-headers) url-http-content-length)
935 (progn
936 ;; Found the end of the document! Wheee!
937 (url-display-percentage nil nil)
f0d64cfc 938 (url-lazy-message "Reading... done.")
8c8b8430
SM
939 (if (url-http-parse-headers)
940 (url-http-activate-callback)))))
941
942(defun url-http-chunked-encoding-after-change-function (st nd length)
943 "Function used when dealing with 'chunked' encoding.
944Cannot give a sophisticated percentage, but we need a different
945function to look for the special 0-length chunk that signifies
946the end of the document."
947 (declare (special url-current-object
948 url-http-end-of-headers
949 url-http-content-type
950 url-http-chunked-length
951 url-http-chunked-counter
952 url-http-process url-http-chunked-start))
953 (save-excursion
954 (goto-char st)
955 (let ((read-next-chunk t)
956 (case-fold-search t)
957 (regexp nil)
958 (no-initial-crlf nil))
959 ;; We need to loop thru looking for more chunks even within
960 ;; one after-change-function call.
961 (while read-next-chunk
962 (setq no-initial-crlf (= 0 url-http-chunked-counter))
963 (if url-http-content-type
964 (url-display-percentage nil
965 "Reading [%s]... chunk #%d"
966 url-http-content-type url-http-chunked-counter)
967 (url-display-percentage nil
968 "Reading... chunk #%d"
969 url-http-chunked-counter))
970 (url-http-debug "Reading chunk %d (%d %d %d)"
971 url-http-chunked-counter st nd length)
972 (setq regexp (if no-initial-crlf
973 "\\([0-9a-z]+\\).*\r?\n"
974 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
975
976 (if url-http-chunked-start
977 ;; We know how long the chunk is supposed to be, skip over
978 ;; leading crap if possible.
979 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
980 (progn
981 (url-http-debug "Got to the end of chunk #%d!"
982 url-http-chunked-counter)
983 (goto-char (+ url-http-chunked-start
984 url-http-chunked-length)))
985 (url-http-debug "Still need %d bytes to hit end of chunk"
986 (- (+ url-http-chunked-start
987 url-http-chunked-length)
988 nd))
989 (setq read-next-chunk nil)))
990 (if (not read-next-chunk)
991 (url-http-debug "Still spinning for next chunk...")
992 (if no-initial-crlf (skip-chars-forward "\r\n"))
993 (if (not (looking-at regexp))
994 (progn
995 ;; Must not have received the entirety of the chunk header,
996 ;; need to spin some more.
997 (url-http-debug "Did not see start of chunk @ %d!" (point))
998 (setq read-next-chunk nil))
999 (add-text-properties (match-beginning 0) (match-end 0)
1000 (list 'start-open t
1001 'end-open t
1002 'chunked-encoding t
cc38a294 1003 'face 'cursor
8c8b8430 1004 'invisible t))
216d3806
JB
1005 (setq url-http-chunked-length (string-to-number (buffer-substring
1006 (match-beginning 1)
1007 (match-end 1))
1008 16)
8c8b8430
SM
1009 url-http-chunked-counter (1+ url-http-chunked-counter)
1010 url-http-chunked-start (set-marker
1011 (or url-http-chunked-start
1012 (make-marker))
1013 (match-end 0)))
1014; (if (not url-http-debug)
1015 (delete-region (match-beginning 0) (match-end 0));)
1016 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1017 url-http-chunked-counter url-http-chunked-length
1018 (marker-position url-http-chunked-start))
1019 (if (= 0 url-http-chunked-length)
1020 (progn
1021 ;; Found the end of the document! Wheee!
1022 (url-http-debug "Saw end of stream chunk!")
1023 (setq read-next-chunk nil)
1024 (url-display-percentage nil nil)
84f089d3
MH
1025 ;; Every chunk, even the last 0-length one, is
1026 ;; terminated by CRLF. Skip it.
1027 (when (looking-at "\r?\n")
1028 (url-http-debug "Removing terminator of last chunk")
1029 (delete-region (match-beginning 0) (match-end 0)))
8c8b8430 1030 (if (re-search-forward "^\r*$" nil t)
63db9644 1031 (url-http-debug "Saw end of trailers..."))
8c8b8430
SM
1032 (if (url-http-parse-headers)
1033 (url-http-activate-callback))))))))))
1034
1035(defun url-http-wait-for-headers-change-function (st nd length)
1036 ;; This will wait for the headers to arrive and then splice in the
1037 ;; next appropriate after-change-function, etc.
1038 (declare (special url-current-object
1039 url-http-end-of-headers
1040 url-http-content-type
1041 url-http-content-length
1042 url-http-transfer-encoding
1043 url-callback-function
1044 url-callback-arguments
1045 url-http-process
1046 url-http-method
1047 url-http-after-change-function
1048 url-http-response-status))
1049 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1050 (buffer-name))
b301d174
LI
1051 (let ((end-of-headers nil)
1052 (old-http nil)
1053 (process-buffer (current-buffer))
1054 (content-length nil))
1055 (when (not (bobp))
57babe17
MH
1056 (goto-char (point-min))
1057 (if (and (looking-at ".*\n") ; have one line at least
1058 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1059 ;; Not HTTP/x.y data, must be 0.9
1060 ;; God, I wish this could die.
1061 (setq end-of-headers t
1062 url-http-end-of-headers 0
1063 old-http t)
1064 (when (re-search-forward "^\r*$" nil t)
1065 ;; Saw the end of the headers
1066 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1067 (setq url-http-end-of-headers (set-marker (make-marker)
1068 (point))
1069 end-of-headers t)
d7c5e162 1070 (setq nd (- nd (url-http-clean-headers)))))
8c8b8430 1071
d23832a2 1072 (if (not end-of-headers)
57babe17
MH
1073 ;; Haven't seen the end of the headers yet, need to wait
1074 ;; for more data to arrive.
1075 nil
9aec558a
LMI
1076 (unless old-http
1077 (url-http-parse-response)
1078 (mail-narrow-to-head)
1079 (setq url-http-transfer-encoding (mail-fetch-field
1080 "transfer-encoding")
1081 url-http-content-type (mail-fetch-field "content-type"))
1082 (if (mail-fetch-field "content-length")
1083 (setq url-http-content-length
1084 (string-to-number (mail-fetch-field "content-length"))))
1085 (widen))
57babe17
MH
1086 (when url-http-transfer-encoding
1087 (setq url-http-transfer-encoding
1088 (downcase url-http-transfer-encoding)))
8c8b8430 1089
57babe17 1090 (cond
10472dd0
LMI
1091 ((null url-http-response-status)
1092 ;; We got back a headerless malformed response from the
1093 ;; server.
1094 (url-http-activate-callback))
57babe17
MH
1095 ((or (= url-http-response-status 204)
1096 (= url-http-response-status 205))
1097 (url-http-debug "%d response must have headers only (%s)."
1098 url-http-response-status (buffer-name))
1099 (when (url-http-parse-headers)
1100 (url-http-activate-callback)))
1101 ((string= "HEAD" url-http-method)
1102 ;; A HEAD request is _ALWAYS_ terminated by the header
1103 ;; information, regardless of any entity headers,
1104 ;; according to section 4.4 of the HTTP/1.1 draft.
1105 (url-http-debug "HEAD request must have headers only (%s)."
1106 (buffer-name))
1107 (when (url-http-parse-headers)
1108 (url-http-activate-callback)))
1109 ((string= "CONNECT" url-http-method)
1110 ;; A CONNECT request is finished, but we cannot stick this
da6062e6 1111 ;; back on the free connection list
57babe17
MH
1112 (url-http-debug "CONNECT request must have headers only.")
1113 (when (url-http-parse-headers)
1114 (url-http-activate-callback)))
1115 ((equal url-http-response-status 304)
1116 ;; Only allowed to have a header section. We have to handle
1117 ;; this here instead of in url-http-parse-headers because if
1118 ;; you have a cached copy of something without a known
1119 ;; content-length, and try to retrieve it from the cache, we'd
1120 ;; fall into the 'being dumb' section and wait for the
1121 ;; connection to terminate, which means we'd wait for 10
1122 ;; seconds for the keep-alives to time out on some servers.
1123 (when (url-http-parse-headers)
1124 (url-http-activate-callback)))
1125 (old-http
1126 ;; HTTP/0.9 always signaled end-of-connection by closing the
1127 ;; connection.
1128 (url-http-debug
1129 "Saw HTTP/0.9 response, connection closed means end of document.")
1130 (setq url-http-after-change-function
1131 'url-http-simple-after-change-function))
1132 ((equal url-http-transfer-encoding "chunked")
1133 (url-http-debug "Saw chunked encoding.")
1134 (setq url-http-after-change-function
1135 'url-http-chunked-encoding-after-change-function)
1136 (when (> nd url-http-end-of-headers)
8c8b8430 1137 (url-http-debug
57babe17
MH
1138 "Calling initial chunked-encoding for extra data at end of headers")
1139 (url-http-chunked-encoding-after-change-function
1140 (marker-position url-http-end-of-headers) nd
1141 (- nd url-http-end-of-headers))))
1142 ((integerp url-http-content-length)
1143 (url-http-debug
1144 "Got a content-length, being smart about document end.")
1145 (setq url-http-after-change-function
1146 'url-http-content-length-after-change-function)
1147 (cond
1148 ((= 0 url-http-content-length)
1149 ;; We got a NULL body! Activate the callback
1150 ;; immediately!
8c8b8430 1151 (url-http-debug
57babe17
MH
1152 "Got 0-length content-length, activating callback immediately.")
1153 (when (url-http-parse-headers)
1154 (url-http-activate-callback)))
1155 ((> nd url-http-end-of-headers)
1156 ;; Have some leftover data
1157 (url-http-debug "Calling initial content-length for extra data at end of headers")
1158 (url-http-content-length-after-change-function
1159 (marker-position url-http-end-of-headers)
1160 nd
1161 (- nd url-http-end-of-headers)))
8c8b8430 1162 (t
57babe17
MH
1163 nil)))
1164 (t
1165 (url-http-debug "No content-length, being dumb.")
1166 (setq url-http-after-change-function
1167 'url-http-simple-after-change-function)))))
8c8b8430
SM
1168 ;; We are still at the beginning of the buffer... must just be
1169 ;; waiting for a response.
b301d174
LI
1170 (url-http-debug "Spinning waiting for headers...")
1171 (when (eq process-buffer (current-buffer))
1172 (goto-char (point-max)))))
8c8b8430
SM
1173
1174;;;###autoload
09100633 1175(defun url-http (url callback cbargs &optional retry-buffer)
8c8b8430
SM
1176 "Retrieve URL via HTTP asynchronously.
1177URL must be a parsed URL. See `url-generic-parse-url' for details.
1178When retrieval is completed, the function CALLBACK is executed with
09100633
CY
1179CBARGS as the arguments.
1180
1181Optional arg RETRY-BUFFER, if non-nil, specifies the buffer of a
1182previous `url-http' call, which is being re-attempted."
8c8b8430
SM
1183 (check-type url vector "Need a pre-parsed URL.")
1184 (declare (special url-current-object
1185 url-http-end-of-headers
1186 url-http-content-type
1187 url-http-content-length
1188 url-http-transfer-encoding
1189 url-http-after-change-function
1190 url-callback-function
1191 url-callback-arguments
b0c9af93 1192 url-show-status
8c8b8430
SM
1193 url-http-method
1194 url-http-extra-headers
1195 url-http-data
1196 url-http-chunked-length
1197 url-http-chunked-start
1198 url-http-chunked-counter
9450f124 1199 url-http-process))
62bfb5bb
MH
1200 (let* ((host (url-host (or url-using-proxy url)))
1201 (port (url-port (or url-using-proxy url)))
1202 (connection (url-http-find-free-connection host port))
09100633
CY
1203 (buffer (or retry-buffer
1204 (generate-new-buffer (format " *http %s:%d*" host port)))))
8c8b8430
SM
1205 (if (not connection)
1206 ;; Failed to open the connection for some reason
1207 (progn
1208 (kill-buffer buffer)
1209 (setq buffer nil)
62bfb5bb 1210 (error "Could not create connection to %s:%d" host port))
12f1edc8 1211 (with-current-buffer buffer
8c8b8430
SM
1212 (mm-disable-multibyte)
1213 (setq url-current-object url
1214 mode-line-format "%b [%s]")
1215
1216 (dolist (var '(url-http-end-of-headers
1217 url-http-content-type
1218 url-http-content-length
1219 url-http-transfer-encoding
1220 url-http-after-change-function
b9b172ac 1221 url-http-response-version
8c8b8430
SM
1222 url-http-response-status
1223 url-http-chunked-length
1224 url-http-chunked-counter
1225 url-http-chunked-start
1226 url-callback-function
1227 url-callback-arguments
b0c9af93 1228 url-show-status
8c8b8430
SM
1229 url-http-process
1230 url-http-method
1231 url-http-extra-headers
cacfe88b 1232 url-http-data
62bfb5bb 1233 url-http-target-url
09100633 1234 url-http-no-retry
b3cd7f61 1235 url-http-connection-opened
62bfb5bb 1236 url-http-proxy))
8c8b8430
SM
1237 (set (make-local-variable var) nil))
1238
1239 (setq url-http-method (or url-request-method "GET")
1240 url-http-extra-headers url-request-extra-headers
1241 url-http-data url-request-data
1242 url-http-process connection
1243 url-http-chunked-length nil
1244 url-http-chunked-start nil
1245 url-http-chunked-counter 0
1246 url-callback-function callback
1247 url-callback-arguments cbargs
cacfe88b 1248 url-http-after-change-function 'url-http-wait-for-headers-change-function
62bfb5bb 1249 url-http-target-url url-current-object
09100633 1250 url-http-no-retry retry-buffer
b3cd7f61 1251 url-http-connection-opened nil
62bfb5bb 1252 url-http-proxy url-using-proxy)
8c8b8430
SM
1253
1254 (set-process-buffer connection buffer)
8c8b8430 1255 (set-process-filter connection 'url-http-generic-filter)
5695d1dd
CY
1256 (let ((status (process-status connection)))
1257 (cond
1258 ((eq status 'connect)
1259 ;; Asynchronous connection
1260 (set-process-sentinel connection 'url-http-async-sentinel))
1261 ((eq status 'failed)
1262 ;; Asynchronous connection failed
62bfb5bb 1263 (error "Could not create connection to %s:%d" host port))
5695d1dd
CY
1264 (t
1265 (set-process-sentinel connection 'url-http-end-of-document-sentinel)
9450f124 1266 (process-send-string connection (url-http-create-request)))))))
8c8b8430
SM
1267 buffer))
1268
5695d1dd
CY
1269(defun url-http-async-sentinel (proc why)
1270 (declare (special url-callback-arguments))
1271 ;; We are performing an asynchronous connection, and a status change
1272 ;; has occurred.
6ca26f1d
LMI
1273 (when (buffer-name (process-buffer proc))
1274 (with-current-buffer (process-buffer proc)
1275 (cond
1276 (url-http-connection-opened
09100633 1277 (setq url-http-no-retry t)
6ca26f1d
LMI
1278 (url-http-end-of-document-sentinel proc why))
1279 ((string= (substring why 0 4) "open")
1280 (setq url-http-connection-opened t)
122d9463
LMI
1281 (condition-case error
1282 (process-send-string proc (url-http-create-request))
1283 (file-error
1284 (setq url-http-connection-opened nil)
1285 (message "HTTP error: %s" error))))
6ca26f1d
LMI
1286 (t
1287 (setf (car url-callback-arguments)
1288 (nconc (list :error (list 'error 'connection-failed why
1289 :host (url-host (or url-http-proxy url-current-object))
1290 :service (url-port (or url-http-proxy url-current-object))))
1291 (car url-callback-arguments)))
1292 (url-http-activate-callback))))))
5695d1dd 1293
8c8b8430
SM
1294;; Since Emacs 19/20 does not allow you to change the
1295;; `after-change-functions' hook in the midst of running them, we fake
1296;; an after change by hooking into the process filter and inserting
1297;; the data ourselves. This is slightly less efficient, but there
1298;; were tons of weird ways the after-change code was biting us in the
1299;; shorts.
12421f1c 1300;; FIXME this can probably be simplified since the above is no longer true.
8c8b8430
SM
1301(defun url-http-generic-filter (proc data)
1302 ;; Sometimes we get a zero-length data chunk after the process has
1303 ;; been changed to 'free', which means it has no buffer associated
1304 ;; with it. Do nothing if there is no buffer, or 0 length data.
1305 (declare (special url-http-after-change-function))
1306 (and (process-buffer proc)
1307 (/= (length data) 0)
12f1edc8 1308 (with-current-buffer (process-buffer proc)
8c8b8430
SM
1309 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1310 (funcall url-http-after-change-function
1311 (point-max)
1312 (progn
1313 (goto-char (point-max))
1314 (insert data)
1315 (point-max))
1316 (length data)))))
1317
1318;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1319;;; file-name-handler stuff from here on out
1320;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
8dff56de
SM
1321(defalias 'url-http-symbol-value-in-buffer
1322 (if (fboundp 'symbol-value-in-buffer)
1323 'symbol-value-in-buffer
1324 (lambda (symbol buffer &optional unbound-value)
8c8b8430 1325 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
12f1edc8 1326 (with-current-buffer buffer
8dff56de
SM
1327 (if (not (boundp symbol))
1328 unbound-value
1329 (symbol-value symbol))))))
8c8b8430
SM
1330
1331(defun url-http-head (url)
1332 (let ((url-request-method "HEAD")
1333 (url-request-data nil))
1334 (url-retrieve-synchronously url)))
1335
1336;;;###autoload
1337(defun url-http-file-exists-p (url)
b43eb9ab 1338 (let ((status nil)
8c8b8430
SM
1339 (exists nil)
1340 (buffer (url-http-head url)))
1341 (if (not buffer)
1342 (setq exists nil)
1343 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1344 buffer 500)
d10a6bf1
RS
1345 exists (and (integerp status)
1346 (>= status 200) (< status 300)))
8c8b8430
SM
1347 (kill-buffer buffer))
1348 exists))
1349
1350;;;###autoload
1351(defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1352
3f19601e 1353(defun url-http-head-file-attributes (url &optional id-format)
162fbe11 1354 (let ((buffer (url-http-head url)))
8c8b8430 1355 (when buffer
162fbe11
SM
1356 (prog1
1357 (list
1358 nil ;dir / link / normal file
1359 1 ;number of links to file.
1360 0 0 ;uid ; gid
1361 nil nil nil ;atime ; mtime ; ctime
1362 (url-http-symbol-value-in-buffer 'url-http-content-length
1363 buffer -1)
1364 (eval-when-compile (make-string 10 ?-))
1365 nil nil nil) ;whether gid would change ; inode ; device.
1366 (kill-buffer buffer)))))
8c8b8430 1367
f9c9a239 1368(declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
153ef845 1369
8c8b8430 1370;;;###autoload
3f19601e 1371(defun url-http-file-attributes (url &optional id-format)
8c8b8430 1372 (if (url-dav-supported-p url)
3f19601e
SM
1373 (url-dav-file-attributes url id-format)
1374 (url-http-head-file-attributes url id-format)))
8c8b8430
SM
1375
1376;;;###autoload
1377(defun url-http-options (url)
55d1d8b7 1378 "Return a property list describing options available for URL.
8c8b8430
SM
1379This list is retrieved using the `OPTIONS' HTTP method.
1380
1381Property list members:
1382
1383methods
1384 A list of symbols specifying what HTTP methods the resource
1385 supports.
1386
1387dav
1388 A list of numbers specifying what DAV protocol/schema versions are
1389 supported.
1390
1391dasl
1392 A list of supported DASL search types supported (string form)
1393
1394ranges
1395 A list of the units available for use in partial document fetches.
1396
1397p3p
1398 The `Platform For Privacy Protection' description for the resource.
1399 Currently this is just the raw header contents. This is likely to
1400 change once P3P is formally supported by the URL package or
55d1d8b7 1401 Emacs/W3."
8c8b8430
SM
1402 (let* ((url-request-method "OPTIONS")
1403 (url-request-data nil)
1404 (buffer (url-retrieve-synchronously url))
1405 (header nil)
1406 (options nil))
1407 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1408 'url-http-response-status buffer 0) 100)))
1409 ;; Only parse the options if we got a 2xx response code!
12f1edc8 1410 (with-current-buffer buffer
8c8b8430
SM
1411 (save-restriction
1412 (save-match-data
8c8b8430
SM
1413 (mail-narrow-to-head)
1414
1415 ;; Figure out what methods are supported.
1416 (when (setq header (mail-fetch-field "allow"))
1417 (setq options (plist-put
1418 options 'methods
1419 (mapcar 'intern (split-string header "[ ,]+")))))
1420
1421 ;; Check for DAV
1422 (when (setq header (mail-fetch-field "dav"))
1423 (setq options (plist-put
1424 options 'dav
1425 (delq 0
1426 (mapcar 'string-to-number
1427 (split-string header "[, ]+"))))))
1428
1429 ;; Now for DASL
1430 (when (setq header (mail-fetch-field "dasl"))
1431 (setq options (plist-put
1432 options 'dasl
1433 (split-string header "[, ]+"))))
1434
1435 ;; P3P - should get more detailed here. FIXME
1436 (when (setq header (mail-fetch-field "p3p"))
1437 (setq options (plist-put options 'p3p header)))
1438
1439 ;; Check for whether they accept byte-range requests.
1440 (when (setq header (mail-fetch-field "accept-ranges"))
1441 (setq options (plist-put
1442 options 'ranges
1443 (delq 'none
1444 (mapcar 'intern
1445 (split-string header "[, ]+"))))))
1446 ))))
1447 (if buffer (kill-buffer buffer))
1448 options))
1449
9c51663a
MH
1450;; HTTPS. This used to be in url-https.el, but that file collides
1451;; with url-http.el on systems with 8-character file names.
1452(require 'tls)
1453
1454;;;###autoload
1455(defconst url-https-default-port 443 "Default HTTPS port.")
1456;;;###autoload
1457(defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
b7270504
GM
1458
1459;; FIXME what is the point of this alias being an autoload?
1460;; Trying to use it will not cause url-http to be loaded,
1461;; since the full alias just gets dumped into loaddefs.el.
1462
e77e9cf4 1463;;;###autoload (autoload 'url-default-expander "url-expand")
9c51663a 1464;;;###autoload
e77e9cf4 1465(defalias 'url-https-expand-file-name 'url-default-expander)
9c51663a
MH
1466
1467(defmacro url-https-create-secure-wrapper (method args)
1468 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1469 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
784f5416 1470 (let ((url-gateway-method 'tls))
9c51663a
MH
1471 (,(intern (format (if method "url-http-%s" "url-http") method))
1472 ,@(remove '&rest (remove '&optional args))))))
1473
1474;;;###autoload (autoload 'url-https "url-http")
1475(url-https-create-secure-wrapper nil (url callback cbargs))
1476;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1477(url-https-create-secure-wrapper file-exists-p (url))
1478;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1479(url-https-create-secure-wrapper file-readable-p (url))
1480;;;###autoload (autoload 'url-https-file-attributes "url-http")
1481(url-https-create-secure-wrapper file-attributes (url &optional id-format))
1482
8c8b8430
SM
1483(provide 'url-http)
1484
1485;;; url-http.el ends here