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