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