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