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