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