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