1 ;;; url-http.el --- HTTP retrieval routines
3 ;; Copyright (C) 1999, 2001, 2004-2016 Free Software Foundation, Inc.
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: comm, data, processes
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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)
64 (autoload 'url-cache-create-filename "url-cache")
66 (defconst url-http-default-port 80 "Default HTTP port.")
67 (defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
68 (defalias 'url-http-expand-file-name 'url-default-expander)
70 (defvar url-http-real-basic-auth-storage nil)
71 (defvar url-http-proxy-basic-auth-storage nil)
73 (defvar url-http-open-connections (make-hash-table :test 'equal
75 "A hash table of all open network connections.")
77 (defvar url-http-version "1.1"
78 "What version of HTTP we advertise, as a string.
79 Valid values are 1.1 and 1.0.
80 This is only useful when debugging the HTTP subsystem.
82 Setting this to 1.0 will tell servers not to send chunked encoding,
83 and other HTTP/1.1 specific features.")
85 (defvar url-http-attempt-keepalives t
86 "Whether to use a single TCP connection multiple times in HTTP.
87 This is only useful when debugging the HTTP subsystem. Setting to
88 nil will explicitly close the connection to the server after every
91 (defconst url-http-codes
92 '((100 continue "Continue with request")
93 (101 switching-protocols "Switching protocols")
94 (102 processing "Processing (Added by DAV)")
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")
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")
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.")
140 (defconst url-https-default-port 443 "Default HTTPS port.")
143 ;; These are all macros so that they are hidden from external sight
144 ;; when the file is byte-compiled.
146 ;; This allows us to expose just the entry points we want.
148 ;; These routines will allow us to implement persistent HTTP
150 (defsubst url-http-debug (&rest args)
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)
157 (set-process-sentinel proc nil)
158 (set-process-filter proc nil)))
159 (error "Transfer interrupted!")))
160 (apply 'url-debug 'http args))
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)
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))
181 (defun url-http-find-free-connection (host port &optional gateway-method)
182 (let ((conns (gethash (cons host port) url-http-open-connections))
184 (while (and conns (not connection))
185 (if (not (memq (process-status (car conns)) '(run open connect)))
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))
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)
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.
203 (let ((proc (url-open-stream host buf
205 (url-host url-using-proxy)
208 (url-port url-using-proxy)
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
218 (when (get-buffer-process buf)
219 (set-process-query-on-exit-flag (get-buffer-process buf) nil))
223 (url-http-mark-connection-as-busy host port connection))))
225 (defun url-http--user-agent-default-string ()
226 "Compute a default User-Agent string based on `url-privacy-level'."
227 (let ((package-info (when url-package-name
228 (format "%s/%s" url-package-name url-package-version)))
229 (emacs-info (unless (and (listp url-privacy-level)
230 (memq 'emacs url-privacy-level))
231 (format "Emacs/%s" emacs-version)))
232 (os-info (unless (and (listp url-privacy-level)
233 (memq 'os url-privacy-level))
234 (format "(%s; %s)" url-system-type url-os-type)))
235 (url-info (format "URL/%s" url-version)))
236 (string-join (delq nil (list package-info url-info
240 ;; Building an HTTP request
241 (defun url-http-user-agent-string ()
242 "Compute a User-Agent string.
243 The string is based on `url-privacy-level' and `url-user-agent'."
245 (or (eq url-privacy-level 'paranoid)
246 (and (listp url-privacy-level)
247 (memq 'agent url-privacy-level))))
251 ((functionp url-user-agent) (funcall url-user-agent))
252 ((stringp url-user-agent) url-user-agent)
253 ((eq url-user-agent 'default) (url-http--user-agent-default-string))))))
254 (if ua-string (format "User-Agent: %s\r\n" (string-trim ua-string)) "")))
256 (defun url-http-create-request (&optional ref-url)
257 "Create an HTTP request for `url-http-target-url', referred to by REF-URL."
258 (let* ((extra-headers)
260 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
261 (using-proxy url-http-proxy)
262 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
263 url-http-extra-headers))
266 (let ((url-basic-auth-storage
267 'url-http-proxy-basic-auth-storage))
268 (url-get-authentication url-http-proxy nil 'any nil))))
269 (real-fname (url-filename url-http-target-url))
270 (host (url-host url-http-target-url))
271 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers))
273 (url-get-authentication (or
274 (and (boundp 'proxy-info)
276 url-http-target-url) nil 'any nil))))
277 (if (equal "" real-fname)
278 (setq real-fname "/"))
279 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
281 (setq auth (concat "Authorization: " auth "\r\n")))
283 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
285 ;; Protection against stupid values in the referrer
286 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
287 (string= ref-url "")))
290 ;; We do not want to expose the referrer if the user is paranoid.
291 (if (or (memq url-privacy-level '(low high paranoid))
292 (and (listp url-privacy-level)
293 (memq 'lastloc url-privacy-level)))
296 ;; url-http-extra-headers contains an assoc-list of
297 ;; header/value pairs that we need to put into the request.
298 (setq extra-headers (mapconcat
300 (concat (car x) ": " (cdr x)))
301 url-http-extra-headers "\r\n"))
302 (if (not (equal extra-headers ""))
303 (setq extra-headers (concat extra-headers "\r\n")))
305 ;; This was done with a call to `format'. Concatenating parts has
306 ;; the advantage of keeping the parts of each header together and
307 ;; allows us to elide null lines directly, at the cost of making
308 ;; the layout less clear.
310 ;; We used to concat directly, but if one of the strings happens
311 ;; to being multibyte (even if it only contains pure ASCII) then
312 ;; every string gets converted with `string-MAKE-multibyte' which
313 ;; turns the 127-255 codes into things like latin-1 accented chars
314 ;; (it would work right if it used `string-TO-multibyte' instead).
315 ;; So to avoid the problem we force every string to be unibyte.
317 ;; FIXME: Instead of `string-AS-unibyte' we'd want
318 ;; `string-to-unibyte', so as to properly signal an error if one
319 ;; of the strings contains a multibyte char.
324 (or url-http-method "GET") " "
325 (if using-proxy (url-recreate-url url-http-target-url) real-fname)
326 " HTTP/" url-http-version "\r\n"
327 ;; Version of MIME we speak
328 "MIME-Version: 1.0\r\n"
329 ;; (maybe) Try to keep the connection open
330 "Connection: " (if (or using-proxy
331 (not url-http-attempt-keepalives))
332 "close" "keep-alive") "\r\n"
333 ;; HTTP extensions we support
334 (if url-extensions-header
336 "Extension: %s\r\n" url-extensions-header))
337 ;; Who we want to talk to
338 (if (/= (url-port url-http-target-url)
339 (url-scheme-get-property
340 (url-type url-http-target-url) 'default-port))
342 "Host: %s:%d\r\n" (puny-encode-domain host)
343 (url-port url-http-target-url))
344 (format "Host: %s\r\n" (puny-encode-domain host)))
346 (if url-personal-mail-address
348 "From: " url-personal-mail-address "\r\n"))
349 ;; Encodings we understand
350 (if (or url-mime-encoding-string
351 ;; MS-Windows loads zlib dynamically, so recheck
352 ;; in case they made it available since
353 ;; initialization in url-vars.el.
354 (and (eq 'system-type 'windows-nt)
355 (fboundp 'zlib-available-p)
357 (setq url-mime-encoding-string "gzip")))
359 "Accept-encoding: " url-mime-encoding-string "\r\n"))
360 (if url-mime-charset-string
362 "Accept-charset: " url-mime-charset-string "\r\n"))
363 ;; Languages we understand
364 (if url-mime-language-string
366 "Accept-language: " url-mime-language-string "\r\n"))
367 ;; Types we understand
368 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
370 (url-http-user-agent-string)
371 ;; Proxy Authorization
376 (when (url-use-cookies url-http-target-url)
377 (url-cookie-generate-header-lines
379 (equal "https" (url-type url-http-target-url))))
381 (if (and (not no-cache)
382 (member url-http-method '("GET" nil)))
383 (let ((tm (url-is-cached url-http-target-url)))
385 (concat "If-modified-since: "
386 (url-get-normalized-date tm) "\r\n"))))
389 "Referer: " ref-url "\r\n"))
394 "Content-length: " (number-to-string
395 (length url-http-data))
402 (url-http-debug "Request is: \n%s" request)
406 (defun url-http-clean-headers ()
407 "Remove trailing \r from header lines.
408 This allows us to use `mail-fetch-field', etc.
409 Return the number of characters removed."
410 (let ((end (marker-position url-http-end-of-headers)))
411 (goto-char (point-min))
412 (while (re-search-forward "\r$" url-http-end-of-headers t)
414 (- end url-http-end-of-headers)))
416 (defun url-http-handle-authentication (proxy)
417 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
418 (let ((auths (or (nreverse
420 (if proxy "proxy-authenticate" "www-authenticate")
424 (url (url-recreate-url url-current-object))
425 (auth-url (url-recreate-url
426 (if (and proxy (boundp 'url-http-proxy))
428 url-current-object)))
429 (url-basic-auth-storage (if proxy
430 ;; Cheating, but who cares? :)
431 'url-http-proxy-basic-auth-storage
432 'url-http-real-basic-auth-storage))
436 ;; find strongest supported auth
437 (dolist (this-auth auths)
438 (setq this-auth (url-eat-trailing-space
439 (url-strip-leading-spaces
442 (downcase (if (string-match "[ \t]" this-auth)
443 (substring this-auth 0 (match-beginning 0))
445 (registered (url-auth-registered this-type))
446 (this-strength (cddr registered)))
447 (when (and registered (> this-strength strength))
450 strength this-strength))))
452 (if (not (url-auth-registered type))
455 (goto-char (point-max))
456 (insert "<hr>Sorry, but I do not know how to handle " (or type auth url "")
457 " authentication. If you'd like to write it,"
458 " please use M-x report-emacs-bug RET.<hr>")
459 ;; We used to set a `status' var (declared "special") but I can't
460 ;; find the corresponding let-binding, so it's probably an error.
461 ;; FIXME: Maybe it was supposed to set `success', i.e. to return t?
463 nil) ;; Not success yet.
465 (let* ((args (url-parse-args (subst-char-in-string ?, ?\; auth)))
466 (auth (url-get-authentication auth-url
467 (cdr-safe (assoc "realm" args))
471 (push (cons (if proxy "Proxy-Authorization" "Authorization") auth)
472 url-http-extra-headers)
473 (let ((url-request-method url-http-method)
474 (url-request-data url-http-data)
475 (url-request-extra-headers url-http-extra-headers))
476 (url-retrieve-internal url url-callback-function
477 url-callback-arguments))
478 nil))))) ;; Not success yet.
480 (defun url-http-parse-response ()
481 "Parse just the response code."
482 (if (not url-http-end-of-headers)
483 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
484 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
485 (goto-char (point-min))
486 (skip-chars-forward " \t\n") ; Skip any blank crap
487 (skip-chars-forward "HTTP/") ; Skip HTTP Version
488 (setq url-http-response-version
489 (buffer-substring (point)
491 (skip-chars-forward "[0-9].")
493 (setq url-http-response-status (read (current-buffer))))
495 (defun url-http-handle-cookies ()
496 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
497 The buffer must already be narrowed to the headers, so `mail-fetch-field' will
499 (let ((cookies (nreverse (mail-fetch-field "Set-Cookie" nil nil t)))
500 (cookies2 (nreverse (mail-fetch-field "Set-Cookie2" nil nil t))))
501 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
502 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
504 (url-cookie-handle-set-cookie (pop cookies)))
506 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
510 (declare-function gnutls-peer-status "gnutls.c" (proc))
511 (declare-function gnutls-negotiate "gnutls.el")
513 (defun url-http-parse-headers ()
514 "Parse and handle HTTP specific headers.
515 Return t if and only if the current buffer is still active and
516 should be shown to the user."
517 ;; The comments after each status code handled are taken from RFC
519 (url-http-mark-connection-as-free (url-host url-current-object)
520 (url-port url-current-object)
522 ;; Pass the https certificate on to the caller.
523 (when (gnutls-available-p)
524 (let ((status (gnutls-peer-status url-http-process)))
526 (plist-get (car url-callback-arguments) :peer))
527 (setcar url-callback-arguments
528 (plist-put (car url-callback-arguments)
530 (if (or (not (boundp 'url-http-end-of-headers))
531 (not url-http-end-of-headers))
532 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
533 (goto-char (point-min))
534 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
535 (url-http-parse-response)
536 (mail-narrow-to-head)
537 ;;(narrow-to-region (point-min) url-http-end-of-headers)
538 (let ((connection (mail-fetch-field "Connection")))
539 ;; In HTTP 1.0, keep the connection only if there is a
540 ;; "Connection: keep-alive" header.
541 ;; In HTTP 1.1 (and greater), keep the connection unless there is a
542 ;; "Connection: close" header
544 ((string= url-http-response-version "1.0")
545 (unless (and connection
546 (string= (downcase connection) "keep-alive"))
547 (delete-process url-http-process)))
549 (when (and connection
550 (string= (downcase connection) "close"))
551 (delete-process url-http-process)))))
552 (let* ((buffer (current-buffer))
553 (class (/ url-http-response-status 100))
555 ;; other status symbols: jewelry and luxury cars
556 (status-symbol (cadr (assq url-http-response-status url-http-codes))))
557 (url-http-debug "Parsed HTTP headers: class=%d status=%d"
558 class url-http-response-status)
559 (when (url-use-cookies url-http-target-url)
560 (url-http-handle-cookies))
563 ;; Classes of response codes
565 ;; 5xx = Server Error
566 ;; 4xx = Client Error
569 ;; 1xx = Informational
570 (1 ; Information messages
571 ;; 100 = Continue with request
572 ;; 101 = Switching protocols
573 ;; 102 = Processing (Added by DAV)
574 (url-mark-buffer-as-dead buffer)
575 (error "HTTP responses in class 1xx not supported (%d)"
576 url-http-response-status))
581 ;; 203 Non-authoritative information
584 ;; 206 Partial content
585 ;; 207 Multi-status (Added by DAV)
587 ((or `no-content `reset-content)
588 ;; No new data, just stay at the same document
589 (url-mark-buffer-as-dead buffer))
591 ;; Generic success for all others. Store in the cache, and
592 ;; mark it as successful.
594 (if (and url-automatic-caching (equal url-http-method "GET"))
595 (url-store-in-cache buffer))))
598 ;; 300 Multiple choices
599 ;; 301 Moved permanently
604 ;; 307 Temporary redirect
605 (let ((redirect-uri (or (mail-fetch-field "Location")
606 (mail-fetch-field "URI"))))
608 (`multiple-choices ; 300
609 ;; Quoth the spec (section 10.3.1)
610 ;; -------------------------------
611 ;; The requested resource corresponds to any one of a set of
612 ;; representations, each with its own specific location and
613 ;; agent-driven negotiation information is being provided so
614 ;; that the user can select a preferred representation and
615 ;; redirect its request to that location.
617 ;; If the server has a preferred choice of representation, it
618 ;; SHOULD include the specific URI for that representation in
619 ;; the Location field; user agents MAY use the Location field
620 ;; value for automatic redirection.
621 ;; -------------------------------
622 ;; We do not support agent-driven negotiation, so we just
623 ;; redirect to the preferred URI if one is provided.
626 ;; The response to the request can be found under a different
627 ;; URI and SHOULD be retrieved using a GET method on that
629 (setq url-http-method "GET"
632 ;; The 304 response MUST NOT contain a message-body.
633 (url-http-debug "Extracting document from cache... (%s)"
634 (url-cache-create-filename (url-view-url t)))
635 (url-cache-extract (url-cache-create-filename (url-view-url t)))
636 (setq redirect-uri nil
639 ;; The requested resource MUST be accessed through the
640 ;; proxy given by the Location field. The Location field
641 ;; gives the URI of the proxy. The recipient is expected
642 ;; to repeat this single request via the proxy. 305
643 ;; responses MUST only be generated by origin servers.
644 (error "Redirection thru a proxy server not supported: %s"
647 ;; Treat everything like '300'
650 ;; Clean off any whitespace and/or <...> cruft.
651 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
652 (setq redirect-uri (match-string 1 redirect-uri)))
653 (if (string-match "^<\\(.*\\)>$" redirect-uri)
654 (setq redirect-uri (match-string 1 redirect-uri)))
656 ;; Some stupid sites (like sourceforge) send a
657 ;; non-fully-qualified URL (ie: /), which royally confuses
659 (if (not (string-match url-nonrelative-link redirect-uri))
660 ;; Be careful to use the real target URL, otherwise we may
661 ;; compute the redirection relative to the URL of the proxy.
663 (url-expand-file-name redirect-uri url-http-target-url)))
664 ;; Do not automatically include an authorization header in the
665 ;; redirect. If needed it will be regenerated by the relevant
666 ;; auth scheme when the new request happens.
667 (setq url-http-extra-headers
668 (cl-remove "Authorization"
669 url-http-extra-headers :key 'car :test 'equal))
670 (let ((url-request-method url-http-method)
671 (url-request-data url-http-data)
672 (url-request-extra-headers url-http-extra-headers))
673 ;; Check existing number of redirects
674 (if (or (< url-max-redirections 0)
675 (and (> url-max-redirections 0)
676 (let ((events (car url-callback-arguments))
679 (if (eq (car events) :redirect)
680 (setq old-redirects (1+ old-redirects)))
681 (and (setq events (cdr events))
682 (setq events (cdr events))))
683 (< old-redirects url-max-redirections))))
684 ;; url-max-redirections hasn't been reached, so go
685 ;; ahead and redirect.
687 ;; Remember that the request was redirected.
688 (setf (car url-callback-arguments)
689 (nconc (list :redirect redirect-uri)
690 (car url-callback-arguments)))
691 ;; Put in the current buffer a forwarding pointer to the new
692 ;; destination buffer.
693 ;; FIXME: This is a hack to fix url-retrieve-synchronously
694 ;; without changing the API. Instead url-retrieve should
695 ;; either simply not return the "destination" buffer, or it
696 ;; should take an optional `dest-buf' argument.
697 (set (make-local-variable 'url-redirect-buffer)
698 (url-retrieve-internal
699 redirect-uri url-callback-function
700 url-callback-arguments
701 (url-silent url-current-object)
702 (not (url-use-cookies url-current-object))))
703 (url-mark-buffer-as-dead buffer))
704 ;; We hit url-max-redirections, so issue an error and
706 (url-http-debug "Maximum redirections reached")
707 (setf (car url-callback-arguments)
708 (nconc (list :error (list 'error 'http-redirect-limit
710 (car url-callback-arguments)))
711 (setq success t))))))
715 ;; 402 Payment required
718 ;; 405 Method not allowed
719 ;; 406 Not acceptable
720 ;; 407 Proxy authentication required
721 ;; 408 Request time-out
724 ;; 411 Length required
725 ;; 412 Precondition failed
726 ;; 413 Request entity too large
727 ;; 414 Request-URI too large
728 ;; 415 Unsupported media type
729 ;; 416 Requested range not satisfiable
730 ;; 417 Expectation failed
731 ;; 422 Unprocessable Entity (Added by DAV)
733 ;; 424 Failed Dependency
737 ;; The request requires user authentication. The response
738 ;; MUST include a WWW-Authenticate header field containing a
739 ;; challenge applicable to the requested resource. The
740 ;; client MAY repeat the request with a suitable
741 ;; Authorization header field.
742 (url-http-handle-authentication nil))
743 (`payment-required ; 402
744 ;; This code is reserved for future use
745 (url-mark-buffer-as-dead buffer)
746 (error "Somebody wants you to give them money"))
748 ;; The server understood the request, but is refusing to
749 ;; fulfill it. Authorization will not help and the request
750 ;; SHOULD NOT be repeated.
755 (`method-not-allowed ; 405
756 ;; The method specified in the Request-Line is not allowed
757 ;; for the resource identified by the Request-URI. The
758 ;; response MUST include an Allow header containing a list of
759 ;; valid methods for the requested resource.
761 (`not-acceptable ; 406
762 ;; The resource identified by the request is only capable of
763 ;; generating response entities which have content
764 ;; characteristics not acceptable according to the accept
765 ;; headers sent in the request.
767 (`proxy-authentication-required ; 407
768 ;; This code is similar to 401 (Unauthorized), but indicates
769 ;; that the client must first authenticate itself with the
770 ;; proxy. The proxy MUST return a Proxy-Authenticate header
771 ;; field containing a challenge applicable to the proxy for
772 ;; the requested resource.
773 (url-http-handle-authentication t))
774 (`request-timeout ; 408
775 ;; The client did not produce a request within the time that
776 ;; the server was prepared to wait. The client MAY repeat
777 ;; the request without modifications at any later time.
780 ;; The request could not be completed due to a conflict with
781 ;; the current state of the resource. This code is only
782 ;; allowed in situations where it is expected that the user
783 ;; might be able to resolve the conflict and resubmit the
784 ;; request. The response body SHOULD include enough
785 ;; information for the user to recognize the source of the
789 ;; The requested resource is no longer available at the
790 ;; server and no forwarding address is known.
792 (`length-required ; 411
793 ;; The server refuses to accept the request without a defined
794 ;; Content-Length. The client MAY repeat the request if it
795 ;; adds a valid Content-Length header field containing the
796 ;; length of the message-body in the request message.
798 ;; NOTE - this will never happen because
799 ;; `url-http-create-request' automatically calculates the
802 (`precondition-failed ; 412
803 ;; The precondition given in one or more of the
804 ;; request-header fields evaluated to false when it was
805 ;; tested on the server.
807 ((or `request-entity-too-large `request-uri-too-large) ; 413 414
808 ;; The server is refusing to process a request because the
809 ;; request entity|URI is larger than the server is willing or
812 (`unsupported-media-type ; 415
813 ;; The server is refusing to service the request because the
814 ;; entity of the request is in a format not supported by the
815 ;; requested resource for the requested method.
817 (`requested-range-not-satisfiable ; 416
818 ;; A server SHOULD return a response with this status code if
819 ;; a request included a Range request-header field, and none
820 ;; of the range-specifier values in this field overlap the
821 ;; current extent of the selected resource, and the request
822 ;; did not include an If-Range request-header field.
824 (`expectation-failed ; 417
825 ;; The expectation given in an Expect request-header field
826 ;; could not be met by this server, or, if the server is a
827 ;; proxy, the server has unambiguous evidence that the
828 ;; request could not be met by the next-hop server.
831 ;; The request could not be understood by the server due to
832 ;; malformed syntax. The client SHOULD NOT repeat the
833 ;; request without modifications.
835 ;; Tell the callback that an error occurred, and what the
838 (setf (car url-callback-arguments)
839 (nconc (list :error (list 'error 'http url-http-response-status))
840 (car url-callback-arguments)))))
842 ;; 500 Internal server error
843 ;; 501 Not implemented
845 ;; 503 Service unavailable
846 ;; 504 Gateway time-out
847 ;; 505 HTTP version not supported
848 ;; 507 Insufficient storage
850 (pcase url-http-response-status
851 (`not-implemented ; 501
852 ;; The server does not support the functionality required to
853 ;; fulfill the request.
856 ;; The server, while acting as a gateway or proxy, received
857 ;; an invalid response from the upstream server it accessed
858 ;; in attempting to fulfill the request.
860 (`service-unavailable ; 503
861 ;; The server is currently unable to handle the request due
862 ;; to a temporary overloading or maintenance of the server.
863 ;; The implication is that this is a temporary condition
864 ;; which will be alleviated after some delay. If known, the
865 ;; length of the delay MAY be indicated in a Retry-After
866 ;; header. If no Retry-After is given, the client SHOULD
867 ;; handle the response as it would for a 500 response.
869 (`gateway-timeout ; 504
870 ;; The server, while acting as a gateway or proxy, did not
871 ;; receive a timely response from the upstream server
872 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
873 ;; auxiliary server (e.g. DNS) it needed to access in
874 ;; attempting to complete the request.
876 (`http-version-not-supported ; 505
877 ;; The server does not support, or refuses to support, the
878 ;; HTTP protocol version that was used in the request
881 (`insufficient-storage ; 507 (DAV)
882 ;; The method could not be performed on the resource
883 ;; because the server is unable to store the representation
884 ;; needed to successfully complete the request. This
885 ;; condition is considered to be temporary. If the request
886 ;; which received this status code was the result of a user
887 ;; action, the request MUST NOT be repeated until it is
888 ;; requested by a separate user action.
890 ;; Tell the callback that an error occurred, and what the
893 (setf (car url-callback-arguments)
894 (nconc (list :error (list 'error 'http url-http-response-status))
895 (car url-callback-arguments)))))
897 (error "Unknown class of HTTP response code: %d (%d)"
898 class url-http-response-status)))
900 (url-mark-buffer-as-dead buffer)
901 (url-handle-content-transfer-encoding))
902 (url-http-debug "Finished parsing HTTP headers: %S" success)
904 (goto-char (point-min))
907 (declare-function zlib-decompress-region "decompress.c" (start end))
909 (defun url-handle-content-transfer-encoding ()
910 (let ((encoding (mail-fetch-field "content-encoding")))
912 (fboundp 'zlib-available-p)
914 (equal (downcase encoding) "gzip"))
917 (goto-char (point-min))
918 (when (search-forward "\n\n")
919 (zlib-decompress-region (point) (point-max)))))))
922 (defun url-http-activate-callback ()
923 "Activate callback specified when this buffer was created."
924 (url-http-mark-connection-as-free (url-host url-current-object)
925 (url-port url-current-object)
927 (url-http-debug "Activating callback in buffer (%s): %S %S"
928 (buffer-name) url-callback-function url-callback-arguments)
929 (apply url-callback-function url-callback-arguments))
933 ;; These unfortunately cannot be macros... please ignore them!
934 (defun url-http-idle-sentinel (proc why)
935 "Remove (now defunct) process PROC from the list of open connections."
936 (maphash (lambda (key val)
938 (puthash key (delq proc val) url-http-open-connections)))
939 url-http-open-connections))
941 (defun url-http-end-of-document-sentinel (proc why)
942 ;; Sentinel used to handle (i) terminated old HTTP/0.9 connections,
943 ;; and (ii) closed connection due to reusing a HTTP connection which
944 ;; we believed was still alive, but which the server closed on us.
945 ;; We handle case (ii) by calling `url-http' again.
946 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
947 (process-buffer proc))
948 (url-http-idle-sentinel proc why)
949 (when (buffer-name (process-buffer proc))
950 (with-current-buffer (process-buffer proc)
951 (goto-char (point-min))
952 (cond ((not (looking-at "HTTP/"))
953 (if url-http-no-retry
954 ;; HTTP/0.9 just gets passed back no matter what
955 (url-http-activate-callback)
956 ;; Call `url-http' again if our connection expired.
958 (let ((url-request-method url-http-method)
959 (url-request-extra-headers url-http-extra-headers)
960 (url-request-data url-http-data)
961 (url-using-proxy (url-find-proxy-for-url
963 (url-host url-current-object))))
964 (when url-using-proxy
965 (setq url-using-proxy
966 (url-generic-parse-url url-using-proxy)))
967 (url-http url-current-object url-callback-function
968 url-callback-arguments (current-buffer)))))
969 ((url-http-parse-headers)
970 (url-http-activate-callback))))))
972 (defun url-http-simple-after-change-function (st nd length)
973 ;; Function used when we do NOT know how long the document is going to be
974 ;; Just _very_ simple 'downloaded %d' type of info.
975 (url-lazy-message "Reading %s..." (file-size-human-readable nd)))
977 (defun url-http-content-length-after-change-function (st nd length)
978 "Function used when we DO know how long the document is going to be.
979 More sophisticated percentage downloaded, etc.
980 Also does minimal parsing of HTTP headers and will actually cause
981 the callback to be triggered."
982 (if url-http-content-type
983 (url-display-percentage
984 "Reading [%s]... %s of %s (%d%%)"
985 (url-percentage (- nd url-http-end-of-headers)
986 url-http-content-length)
987 url-http-content-type
988 (file-size-human-readable (- nd url-http-end-of-headers))
989 (file-size-human-readable url-http-content-length)
990 (url-percentage (- nd url-http-end-of-headers)
991 url-http-content-length))
992 (url-display-percentage
993 "Reading... %s of %s (%d%%)"
994 (url-percentage (- nd url-http-end-of-headers)
995 url-http-content-length)
996 (file-size-human-readable (- nd url-http-end-of-headers))
997 (file-size-human-readable url-http-content-length)
998 (url-percentage (- nd url-http-end-of-headers)
999 url-http-content-length)))
1001 (if (> (- nd url-http-end-of-headers) url-http-content-length)
1003 ;; Found the end of the document! Wheee!
1004 (url-display-percentage nil nil)
1005 (url-lazy-message "Reading... done.")
1006 (if (url-http-parse-headers)
1007 (url-http-activate-callback)))))
1009 (defun url-http-chunked-encoding-after-change-function (st nd length)
1010 "Function used when dealing with chunked encoding.
1011 Cannot give a sophisticated percentage, but we need a different
1012 function to look for the special 0-length chunk that signifies
1013 the end of the document."
1016 (let ((read-next-chunk t)
1017 (case-fold-search t)
1019 (no-initial-crlf nil))
1020 ;; We need to loop thru looking for more chunks even within
1021 ;; one after-change-function call.
1022 (while read-next-chunk
1023 (setq no-initial-crlf (= 0 url-http-chunked-counter))
1024 (if url-http-content-type
1025 (url-display-percentage nil
1026 "Reading [%s]... chunk #%d"
1027 url-http-content-type url-http-chunked-counter)
1028 (url-display-percentage nil
1029 "Reading... chunk #%d"
1030 url-http-chunked-counter))
1031 (url-http-debug "Reading chunk %d (%d %d %d)"
1032 url-http-chunked-counter st nd length)
1033 (setq regexp (if no-initial-crlf
1034 "\\([0-9a-z]+\\).*\r?\n"
1035 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
1037 (if url-http-chunked-start
1038 ;; We know how long the chunk is supposed to be, skip over
1039 ;; leading crap if possible.
1040 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
1042 (url-http-debug "Got to the end of chunk #%d!"
1043 url-http-chunked-counter)
1044 (goto-char (+ url-http-chunked-start
1045 url-http-chunked-length)))
1046 (url-http-debug "Still need %d bytes to hit end of chunk"
1047 (- (+ url-http-chunked-start
1048 url-http-chunked-length)
1050 (setq read-next-chunk nil)))
1051 (if (not read-next-chunk)
1052 (url-http-debug "Still spinning for next chunk...")
1053 (if no-initial-crlf (skip-chars-forward "\r\n"))
1054 (if (not (looking-at regexp))
1056 ;; Must not have received the entirety of the chunk header,
1057 ;; need to spin some more.
1058 (url-http-debug "Did not see start of chunk @ %d!" (point))
1059 (setq read-next-chunk nil))
1060 (add-text-properties (match-beginning 0) (match-end 0)
1066 (setq url-http-chunked-length (string-to-number (buffer-substring
1070 url-http-chunked-counter (1+ url-http-chunked-counter)
1071 url-http-chunked-start (set-marker
1072 (or url-http-chunked-start
1075 ; (if (not url-http-debug)
1076 (delete-region (match-beginning 0) (match-end 0));)
1077 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1078 url-http-chunked-counter url-http-chunked-length
1079 (marker-position url-http-chunked-start))
1080 (if (= 0 url-http-chunked-length)
1082 ;; Found the end of the document! Wheee!
1083 (url-http-debug "Saw end of stream chunk!")
1084 (setq read-next-chunk nil)
1085 (url-display-percentage nil nil)
1086 ;; Every chunk, even the last 0-length one, is
1087 ;; terminated by CRLF. Skip it.
1088 (when (looking-at "\r?\n")
1089 (url-http-debug "Removing terminator of last chunk")
1090 (delete-region (match-beginning 0) (match-end 0)))
1091 (if (re-search-forward "^\r?\n" nil t)
1092 (url-http-debug "Saw end of trailers..."))
1093 (if (url-http-parse-headers)
1094 (url-http-activate-callback))))))))))
1096 (defun url-http-wait-for-headers-change-function (st nd length)
1097 ;; This will wait for the headers to arrive and then splice in the
1098 ;; next appropriate after-change-function, etc.
1099 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1101 (let ((end-of-headers nil)
1103 (process-buffer (current-buffer))
1104 (content-length nil))
1106 (goto-char (point-min))
1107 (if (and (looking-at ".*\n") ; have one line at least
1108 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1109 ;; Not HTTP/x.y data, must be 0.9
1110 ;; God, I wish this could die.
1111 (setq end-of-headers t
1112 url-http-end-of-headers 0
1114 ;; Blank line at end of headers.
1115 (when (re-search-forward "^\r?\n" nil t)
1117 ;; Saw the end of the headers
1118 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1119 (setq url-http-end-of-headers (set-marker (make-marker)
1122 (setq nd (- nd (url-http-clean-headers)))))
1124 (if (not end-of-headers)
1125 ;; Haven't seen the end of the headers yet, need to wait
1126 ;; for more data to arrive.
1129 (url-http-parse-response)
1130 (mail-narrow-to-head)
1131 (setq url-http-transfer-encoding (mail-fetch-field
1132 "transfer-encoding")
1133 url-http-content-type (mail-fetch-field "content-type"))
1134 (if (mail-fetch-field "content-length")
1135 (setq url-http-content-length
1136 (string-to-number (mail-fetch-field "content-length"))))
1138 (when url-http-transfer-encoding
1139 (setq url-http-transfer-encoding
1140 (downcase url-http-transfer-encoding)))
1143 ((null url-http-response-status)
1144 ;; We got back a headerless malformed response from the
1146 (url-http-activate-callback))
1147 ((or (= url-http-response-status 204)
1148 (= url-http-response-status 205))
1149 (url-http-debug "%d response must have headers only (%s)."
1150 url-http-response-status (buffer-name))
1151 (when (url-http-parse-headers)
1152 (url-http-activate-callback)))
1153 ((string= "HEAD" url-http-method)
1154 ;; A HEAD request is _ALWAYS_ terminated by the header
1155 ;; information, regardless of any entity headers,
1156 ;; according to section 4.4 of the HTTP/1.1 draft.
1157 (url-http-debug "HEAD request must have headers only (%s)."
1159 (when (url-http-parse-headers)
1160 (url-http-activate-callback)))
1161 ((string= "CONNECT" url-http-method)
1162 ;; A CONNECT request is finished, but we cannot stick this
1163 ;; back on the free connection list
1164 (url-http-debug "CONNECT request must have headers only.")
1165 (when (url-http-parse-headers)
1166 (url-http-activate-callback)))
1167 ((equal url-http-response-status 304)
1168 ;; Only allowed to have a header section. We have to handle
1169 ;; this here instead of in url-http-parse-headers because if
1170 ;; you have a cached copy of something without a known
1171 ;; content-length, and try to retrieve it from the cache, we'd
1172 ;; fall into the 'being dumb' section and wait for the
1173 ;; connection to terminate, which means we'd wait for 10
1174 ;; seconds for the keep-alives to time out on some servers.
1175 (when (url-http-parse-headers)
1176 (url-http-activate-callback)))
1178 ;; HTTP/0.9 always signaled end-of-connection by closing the
1181 "Saw HTTP/0.9 response, connection closed means end of document.")
1182 (setq url-http-after-change-function
1183 'url-http-simple-after-change-function))
1184 ((equal url-http-transfer-encoding "chunked")
1185 (url-http-debug "Saw chunked encoding.")
1186 (setq url-http-after-change-function
1187 'url-http-chunked-encoding-after-change-function)
1188 (when (> nd url-http-end-of-headers)
1190 "Calling initial chunked-encoding for extra data at end of headers")
1191 (url-http-chunked-encoding-after-change-function
1192 (marker-position url-http-end-of-headers) nd
1193 (- nd url-http-end-of-headers))))
1194 ((integerp url-http-content-length)
1196 "Got a content-length, being smart about document end.")
1197 (setq url-http-after-change-function
1198 'url-http-content-length-after-change-function)
1200 ((= 0 url-http-content-length)
1201 ;; We got a NULL body! Activate the callback
1204 "Got 0-length content-length, activating callback immediately.")
1205 (when (url-http-parse-headers)
1206 (url-http-activate-callback)))
1207 ((> nd url-http-end-of-headers)
1208 ;; Have some leftover data
1209 (url-http-debug "Calling initial content-length for extra data at end of headers")
1210 (url-http-content-length-after-change-function
1211 (marker-position url-http-end-of-headers)
1213 (- nd url-http-end-of-headers)))
1217 (url-http-debug "No content-length, being dumb.")
1218 (setq url-http-after-change-function
1219 'url-http-simple-after-change-function)))))
1220 ;; We are still at the beginning of the buffer... must just be
1221 ;; waiting for a response.
1222 (url-http-debug "Spinning waiting for headers...")
1223 (when (eq process-buffer (current-buffer))
1224 (goto-char (point-max)))))
1226 (defun url-http (url callback cbargs &optional retry-buffer gateway-method)
1227 "Retrieve URL via HTTP asynchronously.
1228 URL must be a parsed URL. See `url-generic-parse-url' for details.
1230 When retrieval is completed, execute the function CALLBACK,
1231 passing it an updated value of CBARGS as arguments. The first
1232 element in CBARGS should be a plist describing what has happened
1233 so far during the request, as described in the docstring of
1234 `url-retrieve' (if in doubt, specify nil). The current buffer
1235 then CALLBACK is executed is the retrieval buffer.
1237 Optional arg RETRY-BUFFER, if non-nil, specifies the buffer of a
1238 previous `url-http' call, which is being re-attempted.
1240 Optional arg GATEWAY-METHOD specifies the gateway to be used,
1241 overriding the value of `url-gateway-method'.
1243 The return value of this function is the retrieval buffer."
1244 (cl-check-type url vector "Need a pre-parsed URL.")
1245 (let* ((host (url-host (or url-using-proxy url)))
1246 (port (url-port (or url-using-proxy url)))
1247 (nsm-noninteractive (or url-request-noninteractive
1248 (and (boundp 'url-http-noninteractive)
1249 url-http-noninteractive)))
1250 (connection (url-http-find-free-connection (url-host url)
1253 (mime-accept-string url-mime-accept-string)
1254 (buffer (or retry-buffer
1255 (generate-new-buffer
1256 (format " *http %s:%d*" (url-host url) (url-port url))))))
1257 (if (not connection)
1258 ;; Failed to open the connection for some reason
1260 (kill-buffer buffer)
1262 (error "Could not create connection to %s:%d" (url-host url)
1264 (with-current-buffer buffer
1265 (mm-disable-multibyte)
1266 (setq url-current-object url
1267 mode-line-format "%b [%s]")
1269 (dolist (var '(url-http-end-of-headers
1270 url-http-content-type
1271 url-http-content-length
1272 url-http-transfer-encoding
1273 url-http-after-change-function
1274 url-http-response-version
1275 url-http-response-status
1276 url-http-chunked-length
1277 url-http-chunked-counter
1278 url-http-chunked-start
1279 url-callback-function
1280 url-callback-arguments
1284 url-http-extra-headers
1285 url-http-noninteractive
1289 url-http-connection-opened
1290 url-mime-accept-string
1292 (set (make-local-variable var) nil))
1294 (setq url-http-method (or url-request-method "GET")
1295 url-http-extra-headers url-request-extra-headers
1296 url-http-noninteractive url-request-noninteractive
1297 url-http-data url-request-data
1298 url-http-process connection
1299 url-http-chunked-length nil
1300 url-http-chunked-start nil
1301 url-http-chunked-counter 0
1302 url-callback-function callback
1303 url-callback-arguments cbargs
1304 url-http-after-change-function 'url-http-wait-for-headers-change-function
1305 url-http-target-url url-current-object
1306 url-http-no-retry retry-buffer
1307 url-http-connection-opened nil
1308 url-mime-accept-string mime-accept-string
1309 url-http-proxy url-using-proxy)
1311 (set-process-buffer connection buffer)
1312 (set-process-filter connection 'url-http-generic-filter)
1313 (pcase (process-status connection)
1315 ;; Asynchronous connection
1316 (set-process-sentinel connection 'url-http-async-sentinel))
1318 ;; Asynchronous connection failed
1319 (error "Could not create connection to %s:%d" (url-host url)
1322 (if (and url-http-proxy (string= "https"
1323 (url-type url-current-object)))
1324 (url-https-proxy-connect connection)
1325 (set-process-sentinel connection
1326 'url-http-end-of-document-sentinel)
1327 (process-send-string connection (url-http-create-request)))))))
1330 (defun url-https-proxy-connect (connection)
1331 (setq url-http-after-change-function 'url-https-proxy-after-change-function)
1332 (process-send-string connection (format (concat "CONNECT %s:%d HTTP/1.1\r\n"
1335 (url-host url-current-object)
1336 (or (url-port url-current-object)
1337 url-https-default-port)
1338 (url-host url-current-object))))
1340 (defun url-https-proxy-after-change-function (st nd length)
1341 (let* ((process-buffer (current-buffer))
1342 (proc (get-buffer-process process-buffer)))
1343 (goto-char (point-min))
1344 (when (re-search-forward "^\r?\n" nil t)
1346 ;; Saw the end of the headers
1347 (setq url-http-end-of-headers (set-marker (make-marker) (point)))
1348 (url-http-parse-response)
1350 ((null url-http-response-status)
1351 ;; We got back a headerless malformed response from the
1353 (url-http-activate-callback)
1354 (error "Malformed response from proxy, fail!"))
1355 ((= url-http-response-status 200)
1356 (if (gnutls-available-p)
1358 (let ((tls-connection (gnutls-negotiate
1360 :hostname (url-host url-current-object)
1361 :verify-error nil)))
1362 ;; check certificate validity
1363 (setq tls-connection
1364 (nsm-verify-connection tls-connection
1365 (url-host url-current-object)
1366 (url-port url-current-object)))
1367 (with-current-buffer process-buffer (erase-buffer))
1368 (set-process-buffer tls-connection process-buffer)
1369 (setq url-http-after-change-function
1370 'url-http-wait-for-headers-change-function)
1371 (set-process-filter tls-connection 'url-http-generic-filter)
1372 (process-send-string tls-connection
1373 (url-http-create-request)))
1375 (url-http-activate-callback)
1376 (error "gnutls-error: %s" e))
1378 (url-http-activate-callback)
1379 (error "error: %s" e)))
1380 (error "error: gnutls support needed!")))
1382 (message "error response: %d" url-http-response-status)
1383 (url-http-activate-callback))))))
1385 (defun url-http-async-sentinel (proc why)
1386 ;; We are performing an asynchronous connection, and a status change
1388 (when (buffer-name (process-buffer proc))
1389 (with-current-buffer (process-buffer proc)
1391 (url-http-connection-opened
1392 (setq url-http-no-retry t)
1393 (url-http-end-of-document-sentinel proc why))
1394 ((string= (substring why 0 4) "open")
1395 (setq url-http-connection-opened t)
1396 (if (and url-http-proxy (string= "https" (url-type url-current-object)))
1397 (url-https-proxy-connect proc)
1398 (condition-case error
1399 (process-send-string proc (url-http-create-request))
1401 (setq url-http-connection-opened nil)
1402 (message "HTTP error: %s" error)))))
1404 (setf (car url-callback-arguments)
1405 (nconc (list :error (list 'error 'connection-failed why
1406 :host (url-host (or url-http-proxy url-current-object))
1407 :service (url-port (or url-http-proxy url-current-object))))
1408 (car url-callback-arguments)))
1409 (url-http-activate-callback))))))
1411 ;; Since Emacs 19/20 does not allow you to change the
1412 ;; `after-change-functions' hook in the midst of running them, we fake
1413 ;; an after change by hooking into the process filter and inserting
1414 ;; the data ourselves. This is slightly less efficient, but there
1415 ;; were tons of weird ways the after-change code was biting us in the
1417 ;; FIXME this can probably be simplified since the above is no longer true.
1418 (defun url-http-generic-filter (proc data)
1419 ;; Sometimes we get a zero-length data chunk after the process has
1420 ;; been changed to 'free', which means it has no buffer associated
1421 ;; with it. Do nothing if there is no buffer, or 0 length data.
1422 (and (process-buffer proc)
1423 (/= (length data) 0)
1424 (with-current-buffer (process-buffer proc)
1425 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1426 (funcall url-http-after-change-function
1429 (goto-char (point-max))
1434 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1435 ;;; file-name-handler stuff from here on out
1436 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1437 (defalias 'url-http-symbol-value-in-buffer
1438 (if (fboundp 'symbol-value-in-buffer)
1439 'symbol-value-in-buffer
1440 (lambda (symbol buffer &optional unbound-value)
1441 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1442 (with-current-buffer buffer
1443 (if (not (boundp symbol))
1445 (symbol-value symbol))))))
1447 (defun url-http-head (url)
1448 (let ((url-request-method "HEAD")
1449 (url-request-data nil))
1450 (url-retrieve-synchronously url)))
1452 (defun url-http-file-exists-p (url)
1453 (let ((buffer (url-http-head url)))
1455 (let ((status (url-http-symbol-value-in-buffer 'url-http-response-status
1458 (and (integerp status)
1459 (>= status 200) (< status 300))
1460 (kill-buffer buffer))))))
1462 (defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1464 (defun url-http-head-file-attributes (url &optional id-format)
1465 (let ((buffer (url-http-head url)))
1469 nil ;dir / link / normal file
1470 1 ;number of links to file.
1472 nil nil nil ;atime ; mtime ; ctime
1473 (url-http-symbol-value-in-buffer 'url-http-content-length
1475 (eval-when-compile (make-string 10 ?-))
1476 nil nil nil) ;whether gid would change ; inode ; device.
1477 (kill-buffer buffer)))))
1479 (declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
1481 (defun url-http-file-attributes (url &optional id-format)
1482 (if (url-dav-supported-p url)
1483 (url-dav-file-attributes url id-format)
1484 (url-http-head-file-attributes url id-format)))
1486 (defun url-http-options (url)
1487 "Return a property list describing options available for URL.
1488 This list is retrieved using the `OPTIONS' HTTP method.
1490 Property list members:
1493 A list of symbols specifying what HTTP methods the resource
1497 A list of numbers specifying what DAV protocol/schema versions are
1501 A list of supported DASL search types supported (string form)
1504 A list of the units available for use in partial document fetches.
1507 The `Platform For Privacy Protection' description for the resource.
1508 Currently this is just the raw header contents. This is likely to
1509 change once P3P is formally supported by the URL package or
1511 (let* ((url-request-method "OPTIONS")
1512 (url-request-data nil)
1513 (buffer (url-retrieve-synchronously url))
1516 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1517 'url-http-response-status buffer 0) 100)))
1518 ;; Only parse the options if we got a 2xx response code!
1519 (with-current-buffer buffer
1522 (mail-narrow-to-head)
1524 ;; Figure out what methods are supported.
1525 (when (setq header (mail-fetch-field "allow"))
1526 (setq options (plist-put
1528 (mapcar 'intern (split-string header "[ ,]+")))))
1531 (when (setq header (mail-fetch-field "dav"))
1532 (setq options (plist-put
1535 (mapcar 'string-to-number
1536 (split-string header "[, ]+"))))))
1539 (when (setq header (mail-fetch-field "dasl"))
1540 (setq options (plist-put
1542 (split-string header "[, ]+"))))
1544 ;; P3P - should get more detailed here. FIXME
1545 (when (setq header (mail-fetch-field "p3p"))
1546 (setq options (plist-put options 'p3p header)))
1548 ;; Check for whether they accept byte-range requests.
1549 (when (setq header (mail-fetch-field "accept-ranges"))
1550 (setq options (plist-put
1554 (split-string header "[, ]+"))))))
1556 (if buffer (kill-buffer buffer))
1559 ;; HTTPS. This used to be in url-https.el, but that file collides
1560 ;; with url-http.el on systems with 8-character file names.
1563 (defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
1565 ;; FIXME what is the point of this alias being an autoload?
1566 ;; Trying to use it will not cause url-http to be loaded,
1567 ;; since the full alias just gets dumped into loaddefs.el.
1569 ;;;###autoload (autoload 'url-default-expander "url-expand")
1571 (defalias 'url-https-expand-file-name 'url-default-expander)
1573 (defmacro url-https-create-secure-wrapper (method args)
1574 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1575 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
1576 (,(intern (format (if method "url-http-%s" "url-http") method))
1577 ,@(remove '&rest (remove '&optional (append args (if method nil '(nil 'tls))))))))
1579 ;;;###autoload (autoload 'url-https "url-http")
1580 (url-https-create-secure-wrapper nil (url callback cbargs))
1581 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1582 (url-https-create-secure-wrapper file-exists-p (url))
1583 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1584 (url-https-create-secure-wrapper file-readable-p (url))
1585 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1586 (url-https-create-secure-wrapper file-attributes (url &optional id-format))
1590 ;;; url-http.el ends here