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