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