1 ;;; url-http.el --- HTTP retrieval routines
3 ;; Copyright (C) 1999, 2001, 2004, 2005, 2006 Free Software Foundation, Inc.
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Keywords: comm, data, processes
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
29 (eval-when-compile (require 'cl))
30 (defvar url-http-extra-headers)
31 (defvar url-http-target-url)
39 (autoload 'url-cache-create-filename "url-cache")
41 (defconst url-http-default-port 80 "Default HTTP port.")
42 (defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
43 (defalias 'url-http-expand-file-name 'url-default-expander)
45 (defvar url-http-real-basic-auth-storage nil)
46 (defvar url-http-proxy-basic-auth-storage nil)
48 (defvar url-http-open-connections (make-hash-table :test 'equal
50 "A hash table of all open network connections.")
52 (defvar url-http-version "1.1"
53 "What version of HTTP we advertise, as a string.
54 Valid values are 1.1 and 1.0.
55 This is only useful when debugging the HTTP subsystem.
57 Setting this to 1.0 will tell servers not to send chunked encoding,
58 and other HTTP/1.1 specific features.")
60 (defvar url-http-attempt-keepalives t
61 "Whether to use a single TCP connection multiple times in HTTP.
62 This is only useful when debugging the HTTP subsystem. Setting to
63 nil will explicitly close the connection to the server after every
67 ;; These are all macros so that they are hidden from external sight
68 ;; when the file is byte-compiled.
70 ;; This allows us to expose just the entry points we want.
72 ;; These routines will allow us to implement persistent HTTP
74 (defsubst url-http-debug (&rest args)
76 (let ((proc (get-buffer-process (current-buffer))))
77 ;; The user hit C-g, honor it! Some things can get in an
78 ;; incredibly tight loop (chunked encoding)
81 (set-process-sentinel proc nil)
82 (set-process-filter proc nil)))
83 (error "Transfer interrupted!")))
84 (apply 'url-debug 'http args))
86 (defun url-http-mark-connection-as-busy (host port proc)
87 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
88 (puthash (cons host port)
89 (delq proc (gethash (cons host port) url-http-open-connections))
90 url-http-open-connections)
93 (defun url-http-mark-connection-as-free (host port proc)
94 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
95 (when (memq (process-status proc) '(open run))
96 (set-process-buffer proc nil)
97 (set-process-sentinel proc 'url-http-idle-sentinel)
98 (puthash (cons host port)
99 (cons proc (gethash (cons host port) url-http-open-connections))
100 url-http-open-connections))
103 (defun url-http-find-free-connection (host port)
104 (let ((conns (gethash (cons host port) url-http-open-connections))
106 (while (and conns (not found))
107 (if (not (memq (process-status (car conns)) '(run open)))
109 (url-http-debug "Cleaning up dead process: %s:%d %S"
110 host port (car conns))
111 (url-http-idle-sentinel (car conns) nil))
112 (setq found (car conns))
113 (url-http-debug "Found existing connection: %s:%d %S" host port found))
116 (url-http-debug "Reusing existing connection: %s:%d" host port)
117 (url-http-debug "Contacting host: %s:%d" host port))
118 (url-lazy-message "Contacting host: %s:%d" host port)
119 (url-http-mark-connection-as-busy
122 (let ((buf (generate-new-buffer " *url-http-temp*")))
123 ;; `url-open-stream' needs a buffer in which to do things
124 ;; like authentication. But we use another buffer afterwards.
126 (let ((proc (url-open-stream host buf host port)))
127 ;; url-open-stream might return nil.
128 (when (processp proc)
129 ;; Drop the temp buffer link before killing the buffer.
130 (set-process-buffer proc nil))
132 (kill-buffer buf)))))))
134 ;; Building an HTTP request
135 (defun url-http-user-agent-string ()
136 (if (or (eq url-privacy-level 'paranoid)
137 (and (listp url-privacy-level)
138 (memq 'agent url-privacy-level)))
140 (format "User-Agent: %sURL/%s%s\r\n"
142 (concat url-package-name "/" url-package-version " ")
146 ((and url-os-type url-system-type)
147 (concat " (" url-os-type "; " url-system-type ")"))
148 ((or url-os-type url-system-type)
149 (concat " (" (or url-system-type url-os-type) ")"))
152 (defun url-http-create-request (url &optional ref-url)
153 "Create an HTTP request for URL, referred to by REF-URL."
154 (declare (special proxy-object proxy-info
155 url-http-method url-http-data
156 url-http-extra-headers))
157 (let* ((extra-headers)
159 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
160 (proxy-obj (and (boundp 'proxy-object) proxy-object))
161 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
162 url-http-extra-headers))
165 (let ((url-basic-auth-storage
166 'url-http-proxy-basic-auth-storage))
167 (url-get-authentication url nil 'any nil))))
168 (real-fname (concat (url-filename (or proxy-obj url))
169 (url-recreate-url-attributes (or proxy-obj url))))
170 (host (url-host (or proxy-obj url)))
171 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers))
173 (url-get-authentication (or
174 (and (boundp 'proxy-info)
176 url) nil 'any nil))))
177 (if (equal "" real-fname)
178 (setq real-fname "/"))
179 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
181 (setq auth (concat "Authorization: " auth "\r\n")))
183 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
185 ;; Protection against stupid values in the referer
186 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
187 (string= ref-url "")))
190 ;; We do not want to expose the referer if the user is paranoid.
191 (if (or (memq url-privacy-level '(low high paranoid))
192 (and (listp url-privacy-level)
193 (memq 'lastloc url-privacy-level)))
196 ;; url-http-extra-headers contains an assoc-list of
197 ;; header/value pairs that we need to put into the request.
198 (setq extra-headers (mapconcat
200 (concat (car x) ": " (cdr x)))
201 url-http-extra-headers "\r\n"))
202 (if (not (equal extra-headers ""))
203 (setq extra-headers (concat extra-headers "\r\n")))
205 ;; This was done with a call to `format'. Concatting parts has
206 ;; the advantage of keeping the parts of each header together and
207 ;; allows us to elide null lines directly, at the cost of making
208 ;; the layout less clear.
210 ;; We used to concat directly, but if one of the strings happens
211 ;; to being multibyte (even if it only contains pure ASCII) then
212 ;; every string gets converted with `string-MAKE-multibyte' which
213 ;; turns the 127-255 codes into things like latin-1 accented chars
214 ;; (it would work right if it used `string-TO-multibyte' instead).
215 ;; So to avoid the problem we force every string to be unibyte.
217 ;; FIXME: Instead of `string-AS-unibyte' we'd want
218 ;; `string-to-unibyte', so as to properly signal an error if one
219 ;; of the strings contains a multibyte char.
224 (or url-http-method "GET") " "
225 (if proxy-obj (url-recreate-url proxy-obj) real-fname)
226 " HTTP/" url-http-version "\r\n"
227 ;; Version of MIME we speak
228 "MIME-Version: 1.0\r\n"
229 ;; (maybe) Try to keep the connection open
230 "Connection: " (if (or proxy-obj
231 (not url-http-attempt-keepalives))
232 "close" "keep-alive") "\r\n"
233 ;; HTTP extensions we support
234 (if url-extensions-header
236 "Extension: %s\r\n" url-extensions-header))
237 ;; Who we want to talk to
238 (if (/= (url-port (or proxy-obj url))
239 (url-scheme-get-property
240 (url-type (or proxy-obj url)) 'default-port))
242 "Host: %s:%d\r\n" host (url-port (or proxy-obj url)))
243 (format "Host: %s\r\n" host))
245 (if url-personal-mail-address
247 "From: " url-personal-mail-address "\r\n"))
248 ;; Encodings we understand
249 (if url-mime-encoding-string
251 "Accept-encoding: " url-mime-encoding-string "\r\n"))
252 (if url-mime-charset-string
254 "Accept-charset: " url-mime-charset-string "\r\n"))
255 ;; Languages we understand
256 (if url-mime-language-string
258 "Accept-language: " url-mime-language-string "\r\n"))
259 ;; Types we understand
260 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
262 (url-http-user-agent-string)
263 ;; Proxy Authorization
268 (url-cookie-generate-header-lines host real-fname
269 (equal "https" (url-type url)))
271 (if (and (not no-cache)
272 (member url-http-method '("GET" nil)))
273 (let ((tm (url-is-cached (or proxy-obj url))))
275 (concat "If-modified-since: "
276 (url-get-normalized-date tm) "\r\n"))))
279 "Referer: " ref-url "\r\n"))
284 "Content-length: " (number-to-string
285 (length url-http-data))
292 (url-http-debug "Request is: \n%s" request)
296 (defun url-http-clean-headers ()
297 "Remove trailing \r from header lines.
298 This allows us to use `mail-fetch-field', etc."
299 (declare (special url-http-end-of-headers))
300 (goto-char (point-min))
301 (while (re-search-forward "\r$" url-http-end-of-headers t)
304 (defun url-http-handle-authentication (proxy)
305 (declare (special status success url-http-method url-http-data
306 url-callback-function url-callback-arguments))
307 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
308 (let ((auths (or (nreverse
310 (if proxy "proxy-authenticate" "www-authenticate")
314 (url (url-recreate-url url-current-object))
315 (url-basic-auth-storage 'url-http-real-basic-auth-storage)
318 ;; Cheating, but who cares? :)
320 (setq url-basic-auth-storage 'url-http-proxy-basic-auth-storage))
322 ;; find strongest supported auth
323 (dolist (this-auth auths)
324 (setq this-auth (url-eat-trailing-space
325 (url-strip-leading-spaces
328 (if (string-match "[ \t]" this-auth)
329 (downcase (substring this-auth 0 (match-beginning 0)))
330 (downcase this-auth)))
331 (registered (url-auth-registered this-type))
332 (this-strength (cddr registered)))
333 (when (and registered (> this-strength strength))
336 strength this-strength))))
338 (if (not (url-auth-registered type))
341 (goto-char (point-max))
342 (insert "<hr>Sorry, but I do not know how to handle " type
343 " authentication. If you'd like to write it,"
344 " send it to " url-bug-address ".<hr>")
346 (let* ((args (url-parse-args (subst-char-in-string ?, ?\; auth)))
347 (auth (url-get-authentication url (cdr-safe (assoc "realm" args))
351 (push (cons (if proxy "Proxy-Authorization" "Authorization") auth)
352 url-http-extra-headers)
353 (let ((url-request-method url-http-method)
354 (url-request-data url-http-data)
355 (url-request-extra-headers url-http-extra-headers))
356 (url-retrieve-internal url url-callback-function
357 url-callback-arguments)))))))
359 (defun url-http-parse-response ()
360 "Parse just the response code."
361 (declare (special url-http-end-of-headers url-http-response-status))
362 (if (not url-http-end-of-headers)
363 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
364 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
365 (goto-char (point-min))
366 (skip-chars-forward " \t\n") ; Skip any blank crap
367 (skip-chars-forward "HTTP/") ; Skip HTTP Version
368 (read (current-buffer))
369 (setq url-http-response-status (read (current-buffer))))
371 (defun url-http-handle-cookies ()
372 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
373 The buffer must already be narrowed to the headers, so `mail-fetch-field' will
375 (let ((cookies (mail-fetch-field "Set-Cookie" nil nil t))
376 (cookies2 (mail-fetch-field "Set-Cookie2" nil nil t))
377 (url-current-object url-http-target-url))
378 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
379 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
381 (url-cookie-handle-set-cookie (pop cookies)))
383 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
387 (defun url-http-parse-headers ()
388 "Parse and handle HTTP specific headers.
389 Return t if and only if the current buffer is still active and
390 should be shown to the user."
391 ;; The comments after each status code handled are taken from RFC
393 (declare (special url-http-end-of-headers url-http-response-status
394 url-http-method url-http-data url-http-process
395 url-callback-function url-callback-arguments))
397 (url-http-mark-connection-as-free (url-host url-current-object)
398 (url-port url-current-object)
401 (if (or (not (boundp 'url-http-end-of-headers))
402 (not url-http-end-of-headers))
403 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
404 (goto-char (point-min))
405 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
406 (url-http-parse-response)
407 (mail-narrow-to-head)
408 ;;(narrow-to-region (point-min) url-http-end-of-headers)
409 (let ((connection (mail-fetch-field "Connection")))
411 (string= (downcase connection) "close"))
412 (delete-process url-http-process)))
415 (setq class (/ url-http-response-status 100))
416 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status)
417 (url-http-handle-cookies)
420 ;; Classes of response codes
422 ;; 5xx = Server Error
423 ;; 4xx = Client Error
426 ;; 1xx = Informational
427 (1 ; Information messages
428 ;; 100 = Continue with request
429 ;; 101 = Switching protocols
430 ;; 102 = Processing (Added by DAV)
431 (url-mark-buffer-as-dead (current-buffer))
432 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status))
437 ;; 203 Non-authoritative information
440 ;; 206 Partial content
441 ;; 207 Multi-status (Added by DAV)
442 (case url-http-response-status
444 ;; No new data, just stay at the same document
445 (url-mark-buffer-as-dead (current-buffer))
448 ;; Generic success for all others. Store in the cache, and
449 ;; mark it as successful.
451 (if (and url-automatic-caching (equal url-http-method "GET"))
452 (url-store-in-cache (current-buffer)))
455 ;; 300 Multiple choices
456 ;; 301 Moved permanently
461 ;; 307 Temporary redirect
462 (let ((redirect-uri (or (mail-fetch-field "Location")
463 (mail-fetch-field "URI"))))
464 (case url-http-response-status
466 ;; Quoth the spec (section 10.3.1)
467 ;; -------------------------------
468 ;; The requested resource corresponds to any one of a set of
469 ;; representations, each with its own specific location and
470 ;; agent-driven negotiation information is being provided so
471 ;; that the user can select a preferred representation and
472 ;; redirect its request to that location.
474 ;; If the server has a preferred choice of representation, it
475 ;; SHOULD include the specific URI for that representation in
476 ;; the Location field; user agents MAY use the Location field
477 ;; value for automatic redirection.
478 ;; -------------------------------
479 ;; We do not support agent-driven negotiation, so we just
480 ;; redirect to the preferred URI if one is provided.
483 ;; If the 301|302 status code is received in response to a
484 ;; request other than GET or HEAD, the user agent MUST NOT
485 ;; automatically redirect the request unless it can be
486 ;; confirmed by the user, since this might change the
487 ;; conditions under which the request was issued.
488 (if (member url-http-method '("HEAD" "GET"))
489 ;; Automatic redirection is ok
491 ;; It is just too big of a pain in the ass to get this
492 ;; prompt all the time. We will just silently lose our
493 ;; data and convert to a GET method.
494 (url-http-debug "Converting `%s' request to `GET' because of REDIRECT(%d)"
495 url-http-method url-http-response-status)
496 (setq url-http-method "GET"
499 ;; The response to the request can be found under a different
500 ;; URI and SHOULD be retrieved using a GET method on that
502 (setq url-http-method "GET"
505 ;; The 304 response MUST NOT contain a message-body.
506 (url-http-debug "Extracting document from cache... (%s)"
507 (url-cache-create-filename (url-view-url t)))
508 (url-cache-extract (url-cache-create-filename (url-view-url t)))
509 (setq redirect-uri nil
512 ;; The requested resource MUST be accessed through the
513 ;; proxy given by the Location field. The Location field
514 ;; gives the URI of the proxy. The recipient is expected
515 ;; to repeat this single request via the proxy. 305
516 ;; responses MUST only be generated by origin servers.
517 (error "Redirection thru a proxy server not supported: %s"
520 ;; Treat everything like '300'
523 ;; Clean off any whitespace and/or <...> cruft.
524 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
525 (setq redirect-uri (match-string 1 redirect-uri)))
526 (if (string-match "^<\\(.*\\)>$" redirect-uri)
527 (setq redirect-uri (match-string 1 redirect-uri)))
529 ;; Some stupid sites (like sourceforge) send a
530 ;; non-fully-qualified URL (ie: /), which royally confuses
532 (if (not (string-match url-nonrelative-link redirect-uri))
533 ;; Be careful to use the real target URL, otherwise we may
534 ;; compute the redirection relative to the URL of the proxy.
536 (url-expand-file-name redirect-uri url-http-target-url)))
537 (let ((url-request-method url-http-method)
538 (url-request-data url-http-data)
539 (url-request-extra-headers url-http-extra-headers))
540 ;; Remember that the request was redirected.
541 (setf (car url-callback-arguments)
542 (nconc (list :redirect redirect-uri)
543 (car url-callback-arguments)))
544 ;; Put in the current buffer a forwarding pointer to the new
545 ;; destination buffer.
546 ;; FIXME: This is a hack to fix url-retrieve-synchronously
547 ;; without changing the API. Instead url-retrieve should
548 ;; either simply not return the "destination" buffer, or it
549 ;; should take an optional `dest-buf' argument.
550 (set (make-local-variable 'url-redirect-buffer)
551 (url-retrieve-internal
552 redirect-uri url-callback-function
553 url-callback-arguments))
554 (url-mark-buffer-as-dead (current-buffer))))))
558 ;; 402 Payment required
561 ;; 405 Method not allowed
562 ;; 406 Not acceptable
563 ;; 407 Proxy authentication required
564 ;; 408 Request time-out
567 ;; 411 Length required
568 ;; 412 Precondition failed
569 ;; 413 Request entity too large
570 ;; 414 Request-URI too large
571 ;; 415 Unsupported media type
572 ;; 416 Requested range not satisfiable
573 ;; 417 Expectation failed
574 ;; 422 Unprocessable Entity (Added by DAV)
576 ;; 424 Failed Dependency
577 (case url-http-response-status
579 ;; The request requires user authentication. The response
580 ;; MUST include a WWW-Authenticate header field containing a
581 ;; challenge applicable to the requested resource. The
582 ;; client MAY repeat the request with a suitable
583 ;; Authorization header field.
584 (url-http-handle-authentication nil))
586 ;; This code is reserved for future use
587 (url-mark-buffer-as-dead (current-buffer))
588 (error "Somebody wants you to give them money"))
590 ;; The server understood the request, but is refusing to
591 ;; fulfill it. Authorization will not help and the request
592 ;; SHOULD NOT be repeated.
598 ;; The method specified in the Request-Line is not allowed
599 ;; for the resource identified by the Request-URI. The
600 ;; response MUST include an Allow header containing a list of
601 ;; valid methods for the requested resource.
604 ;; The resource identified by the request is only capable of
605 ;; generating response entities which have content
606 ;; characteristics nota cceptable according to the accept
607 ;; headers sent in the request.
610 ;; This code is similar to 401 (Unauthorized), but indicates
611 ;; that the client must first authenticate itself with the
612 ;; proxy. The proxy MUST return a Proxy-Authenticate header
613 ;; field containing a challenge applicable to the proxy for
614 ;; the requested resource.
615 (url-http-handle-authentication t))
617 ;; The client did not produce a request within the time that
618 ;; the server was prepared to wait. The client MAY repeat
619 ;; the request without modifications at any later time.
622 ;; The request could not be completed due to a conflict with
623 ;; the current state of the resource. This code is only
624 ;; allowed in situations where it is expected that the user
625 ;; mioght be able to resolve the conflict and resubmit the
626 ;; request. The response body SHOULD include enough
627 ;; information for the user to recognize the source of the
631 ;; The requested resource is no longer available at the
632 ;; server and no forwarding address is known.
635 ;; The server refuses to accept the request without a defined
636 ;; Content-Length. The client MAY repeat the request if it
637 ;; adds a valid Content-Length header field containing the
638 ;; length of the message-body in the request message.
640 ;; NOTE - this will never happen because
641 ;; `url-http-create-request' automatically calculates the
645 ;; The precondition given in one or more of the
646 ;; request-header fields evaluated to false when it was
647 ;; tested on the server.
650 ;; The server is refusing to process a request because the
651 ;; request entity|URI is larger than the server is willing or
655 ;; The server is refusing to service the request because the
656 ;; entity of the request is in a format not supported by the
657 ;; requested resource for the requested method.
660 ;; A server SHOULD return a response with this status code if
661 ;; a request included a Range request-header field, and none
662 ;; of the range-specifier values in this field overlap the
663 ;; current extent of the selected resource, and the request
664 ;; did not include an If-Range request-header field.
667 ;; The expectation given in an Expect request-header field
668 ;; could not be met by this server, or, if the server is a
669 ;; proxy, the server has unambiguous evidence that the
670 ;; request could not be met by the next-hop server.
673 ;; The request could not be understood by the server due to
674 ;; malformed syntax. The client SHOULD NOT repeat the
675 ;; request without modifications.
677 ;; Tell the callback that an error occurred, and what the
680 (setf (car url-callback-arguments)
681 (nconc (list :error (list 'error 'http url-http-response-status))
682 (car url-callback-arguments)))))
684 ;; 500 Internal server error
685 ;; 501 Not implemented
687 ;; 503 Service unavailable
688 ;; 504 Gateway time-out
689 ;; 505 HTTP version not supported
690 ;; 507 Insufficient storage
692 (case url-http-response-status
694 ;; The server does not support the functionality required to
695 ;; fulfill the request.
698 ;; The server, while acting as a gateway or proxy, received
699 ;; an invalid response from the upstream server it accessed
700 ;; in attempting to fulfill the request.
703 ;; The server is currently unable to handle the request due
704 ;; to a temporary overloading or maintenance of the server.
705 ;; The implication is that this is a temporary condition
706 ;; which will be alleviated after some delay. If known, the
707 ;; length of the delay MAY be indicated in a Retry-After
708 ;; header. If no Retry-After is given, the client SHOULD
709 ;; handle the response as it would for a 500 response.
712 ;; The server, while acting as a gateway or proxy, did not
713 ;; receive a timely response from the upstream server
714 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
715 ;; auxiliary server (e.g. DNS) it needed to access in
716 ;; attempting to complete the request.
719 ;; The server does not support, or refuses to support, the
720 ;; HTTP protocol version that was used in the request
724 ;; The method could not be performed on the resource
725 ;; because the server is unable to store the representation
726 ;; needed to successfully complete the request. This
727 ;; condition is considered to be temporary. If the request
728 ;; which received this status code was the result of a user
729 ;; action, the request MUST NOT be repeated until it is
730 ;; requested by a separate user action.
732 ;; Tell the callback that an error occurred, and what the
735 (setf (car url-callback-arguments)
736 (nconc (list :error (list 'error 'http url-http-response-status))
737 (car url-callback-arguments)))))
739 (error "Unknown class of HTTP response code: %d (%d)"
740 class url-http-response-status)))
742 (url-mark-buffer-as-dead (current-buffer)))
743 (url-http-debug "Finished parsing HTTP headers: %S" success)
748 (defun url-http-activate-callback ()
749 "Activate callback specified when this buffer was created."
750 (declare (special url-http-process
751 url-callback-function
752 url-callback-arguments))
753 (url-http-mark-connection-as-free (url-host url-current-object)
754 (url-port url-current-object)
756 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
757 (apply url-callback-function url-callback-arguments))
761 ;; These unfortunately cannot be macros... please ignore them!
762 (defun url-http-idle-sentinel (proc why)
763 "Remove this (now defunct) process PROC from the list of open connections."
764 (maphash (lambda (key val)
766 (puthash key (delq proc val) url-http-open-connections)))
767 url-http-open-connections))
769 (defun url-http-end-of-document-sentinel (proc why)
770 ;; Sentinel used for old HTTP/0.9 or connections we know are going
771 ;; to die as the 'end of document' notifier.
772 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
773 (process-buffer proc))
774 (url-http-idle-sentinel proc why)
775 (with-current-buffer (process-buffer proc)
776 (goto-char (point-min))
777 (if (not (looking-at "HTTP/"))
778 ;; HTTP/0.9 just gets passed back no matter what
779 (url-http-activate-callback)
780 (if (url-http-parse-headers)
781 (url-http-activate-callback)))))
783 (defun url-http-simple-after-change-function (st nd length)
784 ;; Function used when we do NOT know how long the document is going to be
785 ;; Just _very_ simple 'downloaded %d' type of info.
786 (declare (special url-http-end-of-headers))
787 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
789 (defun url-http-content-length-after-change-function (st nd length)
790 "Function used when we DO know how long the document is going to be.
791 More sophisticated percentage downloaded, etc.
792 Also does minimal parsing of HTTP headers and will actually cause
793 the callback to be triggered."
794 (declare (special url-current-object
795 url-http-end-of-headers
796 url-http-content-length
797 url-http-content-type
799 (if url-http-content-type
800 (url-display-percentage
801 "Reading [%s]... %s of %s (%d%%)"
802 (url-percentage (- nd url-http-end-of-headers)
803 url-http-content-length)
804 url-http-content-type
805 (url-pretty-length (- nd url-http-end-of-headers))
806 (url-pretty-length url-http-content-length)
807 (url-percentage (- nd url-http-end-of-headers)
808 url-http-content-length))
809 (url-display-percentage
810 "Reading... %s of %s (%d%%)"
811 (url-percentage (- nd url-http-end-of-headers)
812 url-http-content-length)
813 (url-pretty-length (- nd url-http-end-of-headers))
814 (url-pretty-length url-http-content-length)
815 (url-percentage (- nd url-http-end-of-headers)
816 url-http-content-length)))
818 (if (> (- nd url-http-end-of-headers) url-http-content-length)
820 ;; Found the end of the document! Wheee!
821 (url-display-percentage nil nil)
822 (message "Reading... done.")
823 (if (url-http-parse-headers)
824 (url-http-activate-callback)))))
826 (defun url-http-chunked-encoding-after-change-function (st nd length)
827 "Function used when dealing with 'chunked' encoding.
828 Cannot give a sophisticated percentage, but we need a different
829 function to look for the special 0-length chunk that signifies
830 the end of the document."
831 (declare (special url-current-object
832 url-http-end-of-headers
833 url-http-content-type
834 url-http-chunked-length
835 url-http-chunked-counter
836 url-http-process url-http-chunked-start))
839 (let ((read-next-chunk t)
842 (no-initial-crlf nil))
843 ;; We need to loop thru looking for more chunks even within
844 ;; one after-change-function call.
845 (while read-next-chunk
846 (setq no-initial-crlf (= 0 url-http-chunked-counter))
847 (if url-http-content-type
848 (url-display-percentage nil
849 "Reading [%s]... chunk #%d"
850 url-http-content-type url-http-chunked-counter)
851 (url-display-percentage nil
852 "Reading... chunk #%d"
853 url-http-chunked-counter))
854 (url-http-debug "Reading chunk %d (%d %d %d)"
855 url-http-chunked-counter st nd length)
856 (setq regexp (if no-initial-crlf
857 "\\([0-9a-z]+\\).*\r?\n"
858 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
860 (if url-http-chunked-start
861 ;; We know how long the chunk is supposed to be, skip over
862 ;; leading crap if possible.
863 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
865 (url-http-debug "Got to the end of chunk #%d!"
866 url-http-chunked-counter)
867 (goto-char (+ url-http-chunked-start
868 url-http-chunked-length)))
869 (url-http-debug "Still need %d bytes to hit end of chunk"
870 (- (+ url-http-chunked-start
871 url-http-chunked-length)
873 (setq read-next-chunk nil)))
874 (if (not read-next-chunk)
875 (url-http-debug "Still spinning for next chunk...")
876 (if no-initial-crlf (skip-chars-forward "\r\n"))
877 (if (not (looking-at regexp))
879 ;; Must not have received the entirety of the chunk header,
880 ;; need to spin some more.
881 (url-http-debug "Did not see start of chunk @ %d!" (point))
882 (setq read-next-chunk nil))
883 (add-text-properties (match-beginning 0) (match-end 0)
889 (setq url-http-chunked-length (string-to-number (buffer-substring
893 url-http-chunked-counter (1+ url-http-chunked-counter)
894 url-http-chunked-start (set-marker
895 (or url-http-chunked-start
898 ; (if (not url-http-debug)
899 (delete-region (match-beginning 0) (match-end 0));)
900 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
901 url-http-chunked-counter url-http-chunked-length
902 (marker-position url-http-chunked-start))
903 (if (= 0 url-http-chunked-length)
905 ;; Found the end of the document! Wheee!
906 (url-http-debug "Saw end of stream chunk!")
907 (setq read-next-chunk nil)
908 (url-display-percentage nil nil)
909 (goto-char (match-end 1))
910 (if (re-search-forward "^\r*$" nil t)
911 (url-http-debug "Saw end of trailers..."))
912 (if (url-http-parse-headers)
913 (url-http-activate-callback))))))))))
915 (defun url-http-wait-for-headers-change-function (st nd length)
916 ;; This will wait for the headers to arrive and then splice in the
917 ;; next appropriate after-change-function, etc.
918 (declare (special url-current-object
919 url-http-end-of-headers
920 url-http-content-type
921 url-http-content-length
922 url-http-transfer-encoding
923 url-callback-function
924 url-callback-arguments
927 url-http-after-change-function
928 url-http-response-status))
929 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
932 (let ((end-of-headers nil)
934 (content-length nil))
935 (goto-char (point-min))
936 (if (not (looking-at "^HTTP/[1-9]\\.[0-9]"))
937 ;; Not HTTP/x.y data, must be 0.9
938 ;; God, I wish this could die.
939 (setq end-of-headers t
940 url-http-end-of-headers 0
942 (if (re-search-forward "^\r*$" nil t)
943 ;; Saw the end of the headers
945 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
946 (setq url-http-end-of-headers (set-marker (make-marker)
949 (url-http-clean-headers))))
951 (if (not end-of-headers)
952 ;; Haven't seen the end of the headers yet, need to wait
953 ;; for more data to arrive.
956 (message "HTTP/0.9 How I hate thee!")
958 (url-http-parse-response)
959 (mail-narrow-to-head)
960 ;;(narrow-to-region (point-min) url-http-end-of-headers)
961 (setq url-http-transfer-encoding (mail-fetch-field
963 url-http-content-type (mail-fetch-field "content-type"))
964 (if (mail-fetch-field "content-length")
965 (setq url-http-content-length
966 (string-to-number (mail-fetch-field "content-length"))))
968 (if url-http-transfer-encoding
969 (setq url-http-transfer-encoding
970 (downcase url-http-transfer-encoding)))
973 ((or (= url-http-response-status 204)
974 (= url-http-response-status 205))
975 (url-http-debug "%d response must have headers only (%s)."
976 url-http-response-status (buffer-name))
977 (if (url-http-parse-headers)
978 (url-http-activate-callback)))
979 ((string= "HEAD" url-http-method)
980 ;; A HEAD request is _ALWAYS_ terminated by the header
981 ;; information, regardless of any entity headers,
982 ;; according to section 4.4 of the HTTP/1.1 draft.
983 (url-http-debug "HEAD request must have headers only (%s)."
985 (if (url-http-parse-headers)
986 (url-http-activate-callback)))
987 ((string= "CONNECT" url-http-method)
988 ;; A CONNECT request is finished, but we cannot stick this
989 ;; back on the free connectin list
990 (url-http-debug "CONNECT request must have headers only.")
991 (if (url-http-parse-headers)
992 (url-http-activate-callback)))
993 ((equal url-http-response-status 304)
994 ;; Only allowed to have a header section. We have to handle
995 ;; this here instead of in url-http-parse-headers because if
996 ;; you have a cached copy of something without a known
997 ;; content-length, and try to retrieve it from the cache, we'd
998 ;; fall into the 'being dumb' section and wait for the
999 ;; connection to terminate, which means we'd wait for 10
1000 ;; seconds for the keep-alives to time out on some servers.
1001 (if (url-http-parse-headers)
1002 (url-http-activate-callback)))
1004 ;; HTTP/0.9 always signaled end-of-connection by closing the
1007 "Saw HTTP/0.9 response, connection closed means end of document.")
1008 (setq url-http-after-change-function
1009 'url-http-simple-after-change-function))
1010 ((equal url-http-transfer-encoding "chunked")
1011 (url-http-debug "Saw chunked encoding.")
1012 (setq url-http-after-change-function
1013 'url-http-chunked-encoding-after-change-function)
1014 (if (> nd url-http-end-of-headers)
1017 "Calling initial chunked-encoding for extra data at end of headers")
1018 (url-http-chunked-encoding-after-change-function
1019 (marker-position url-http-end-of-headers) nd
1020 (- nd url-http-end-of-headers)))))
1021 ((integerp url-http-content-length)
1023 "Got a content-length, being smart about document end.")
1024 (setq url-http-after-change-function
1025 'url-http-content-length-after-change-function)
1027 ((= 0 url-http-content-length)
1028 ;; We got a NULL body! Activate the callback
1031 "Got 0-length content-length, activating callback immediately.")
1032 (if (url-http-parse-headers)
1033 (url-http-activate-callback)))
1034 ((> nd url-http-end-of-headers)
1035 ;; Have some leftover data
1036 (url-http-debug "Calling initial content-length for extra data at end of headers")
1037 (url-http-content-length-after-change-function
1038 (marker-position url-http-end-of-headers)
1040 (- nd url-http-end-of-headers)))
1044 (url-http-debug "No content-length, being dumb.")
1045 (setq url-http-after-change-function
1046 'url-http-simple-after-change-function)))))
1047 ;; We are still at the beginning of the buffer... must just be
1048 ;; waiting for a response.
1049 (url-http-debug "Spinning waiting for headers..."))
1050 (goto-char (point-max)))
1053 (defun url-http (url callback cbargs)
1054 "Retrieve URL via HTTP asynchronously.
1055 URL must be a parsed URL. See `url-generic-parse-url' for details.
1056 When retrieval is completed, the function CALLBACK is executed with
1057 CBARGS as the arguments."
1058 (check-type url vector "Need a pre-parsed URL.")
1059 (declare (special url-current-object
1060 url-http-end-of-headers
1061 url-http-content-type
1062 url-http-content-length
1063 url-http-transfer-encoding
1064 url-http-after-change-function
1065 url-callback-function
1066 url-callback-arguments
1068 url-http-extra-headers
1070 url-http-chunked-length
1071 url-http-chunked-start
1072 url-http-chunked-counter
1074 (let ((connection (url-http-find-free-connection (url-host url)
1076 (buffer (generate-new-buffer (format " *http %s:%d*"
1079 (if (not connection)
1080 ;; Failed to open the connection for some reason
1082 (kill-buffer buffer)
1084 (error "Could not create connection to %s:%d" (url-host url)
1086 (with-current-buffer buffer
1087 (mm-disable-multibyte)
1088 (setq url-current-object url
1089 mode-line-format "%b [%s]")
1091 (dolist (var '(url-http-end-of-headers
1092 url-http-content-type
1093 url-http-content-length
1094 url-http-transfer-encoding
1095 url-http-after-change-function
1096 url-http-response-status
1097 url-http-chunked-length
1098 url-http-chunked-counter
1099 url-http-chunked-start
1100 url-callback-function
1101 url-callback-arguments
1104 url-http-extra-headers
1106 url-http-target-url))
1107 (set (make-local-variable var) nil))
1109 (setq url-http-method (or url-request-method "GET")
1110 url-http-extra-headers url-request-extra-headers
1111 url-http-data url-request-data
1112 url-http-process connection
1113 url-http-chunked-length nil
1114 url-http-chunked-start nil
1115 url-http-chunked-counter 0
1116 url-callback-function callback
1117 url-callback-arguments cbargs
1118 url-http-after-change-function 'url-http-wait-for-headers-change-function
1119 url-http-target-url (if (boundp 'proxy-object)
1121 url-current-object))
1123 (set-process-buffer connection buffer)
1124 (set-process-filter connection 'url-http-generic-filter)
1125 (let ((status (process-status connection)))
1127 ((eq status 'connect)
1128 ;; Asynchronous connection
1129 (set-process-sentinel connection 'url-http-async-sentinel))
1130 ((eq status 'failed)
1131 ;; Asynchronous connection failed
1132 (error "Could not create connection to %s:%d" (url-host url)
1135 (set-process-sentinel connection 'url-http-end-of-document-sentinel)
1136 (process-send-string connection (url-http-create-request url)))))))
1139 (defun url-http-async-sentinel (proc why)
1140 (declare (special url-callback-arguments))
1141 ;; We are performing an asynchronous connection, and a status change
1143 (with-current-buffer (process-buffer proc)
1145 ((string= (substring why 0 4) "open")
1146 (set-process-sentinel proc 'url-http-end-of-document-sentinel)
1147 (process-send-string proc (url-http-create-request url-current-object)))
1149 (setf (car url-callback-arguments)
1150 (nconc (list :error (list 'error 'connection-failed why
1151 :host (url-host url-current-object)
1152 :service (url-port url-current-object)))
1153 (car url-callback-arguments)))
1154 (url-http-activate-callback)))))
1156 ;; Since Emacs 19/20 does not allow you to change the
1157 ;; `after-change-functions' hook in the midst of running them, we fake
1158 ;; an after change by hooking into the process filter and inserting
1159 ;; the data ourselves. This is slightly less efficient, but there
1160 ;; were tons of weird ways the after-change code was biting us in the
1162 (defun url-http-generic-filter (proc data)
1163 ;; Sometimes we get a zero-length data chunk after the process has
1164 ;; been changed to 'free', which means it has no buffer associated
1165 ;; with it. Do nothing if there is no buffer, or 0 length data.
1166 (declare (special url-http-after-change-function))
1167 (and (process-buffer proc)
1168 (/= (length data) 0)
1169 (with-current-buffer (process-buffer proc)
1170 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1171 (funcall url-http-after-change-function
1174 (goto-char (point-max))
1179 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1180 ;;; file-name-handler stuff from here on out
1181 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1182 (defalias 'url-http-symbol-value-in-buffer
1183 (if (fboundp 'symbol-value-in-buffer)
1184 'symbol-value-in-buffer
1185 (lambda (symbol buffer &optional unbound-value)
1186 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1187 (with-current-buffer buffer
1188 (if (not (boundp symbol))
1190 (symbol-value symbol))))))
1192 (defun url-http-head (url)
1193 (let ((url-request-method "HEAD")
1194 (url-request-data nil))
1195 (url-retrieve-synchronously url)))
1198 (defun url-http-file-exists-p (url)
1201 (buffer (url-http-head url)))
1204 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1206 exists (and (integerp status)
1207 (>= status 200) (< status 300)))
1208 (kill-buffer buffer))
1212 (defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1214 (defun url-http-head-file-attributes (url &optional id-format)
1215 (let ((buffer (url-http-head url)))
1219 nil ;dir / link / normal file
1220 1 ;number of links to file.
1222 nil nil nil ;atime ; mtime ; ctime
1223 (url-http-symbol-value-in-buffer 'url-http-content-length
1225 (eval-when-compile (make-string 10 ?-))
1226 nil nil nil) ;whether gid would change ; inode ; device.
1227 (kill-buffer buffer)))))
1230 (defun url-http-file-attributes (url &optional id-format)
1231 (if (url-dav-supported-p url)
1232 (url-dav-file-attributes url id-format)
1233 (url-http-head-file-attributes url id-format)))
1236 (defun url-http-options (url)
1237 "Return a property list describing options available for URL.
1238 This list is retrieved using the `OPTIONS' HTTP method.
1240 Property list members:
1243 A list of symbols specifying what HTTP methods the resource
1247 A list of numbers specifying what DAV protocol/schema versions are
1251 A list of supported DASL search types supported (string form)
1254 A list of the units available for use in partial document fetches.
1257 The `Platform For Privacy Protection' description for the resource.
1258 Currently this is just the raw header contents. This is likely to
1259 change once P3P is formally supported by the URL package or
1261 (let* ((url-request-method "OPTIONS")
1262 (url-request-data nil)
1263 (buffer (url-retrieve-synchronously url))
1266 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1267 'url-http-response-status buffer 0) 100)))
1268 ;; Only parse the options if we got a 2xx response code!
1269 (with-current-buffer buffer
1272 (mail-narrow-to-head)
1274 ;; Figure out what methods are supported.
1275 (when (setq header (mail-fetch-field "allow"))
1276 (setq options (plist-put
1278 (mapcar 'intern (split-string header "[ ,]+")))))
1281 (when (setq header (mail-fetch-field "dav"))
1282 (setq options (plist-put
1285 (mapcar 'string-to-number
1286 (split-string header "[, ]+"))))))
1289 (when (setq header (mail-fetch-field "dasl"))
1290 (setq options (plist-put
1292 (split-string header "[, ]+"))))
1294 ;; P3P - should get more detailed here. FIXME
1295 (when (setq header (mail-fetch-field "p3p"))
1296 (setq options (plist-put options 'p3p header)))
1298 ;; Check for whether they accept byte-range requests.
1299 (when (setq header (mail-fetch-field "accept-ranges"))
1300 (setq options (plist-put
1304 (split-string header "[, ]+"))))))
1306 (if buffer (kill-buffer buffer))
1309 ;; HTTPS. This used to be in url-https.el, but that file collides
1310 ;; with url-http.el on systems with 8-character file names.
1314 (defconst url-https-default-port 443 "Default HTTPS port.")
1316 (defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
1318 (defalias 'url-https-expand-file-name 'url-http-expand-file-name)
1320 (defmacro url-https-create-secure-wrapper (method args)
1321 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1322 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
1323 (let ((url-gateway-method 'tls))
1324 (,(intern (format (if method "url-http-%s" "url-http") method))
1325 ,@(remove '&rest (remove '&optional args))))))
1327 ;;;###autoload (autoload 'url-https "url-http")
1328 (url-https-create-secure-wrapper nil (url callback cbargs))
1329 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1330 (url-https-create-secure-wrapper file-exists-p (url))
1331 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1332 (url-https-create-secure-wrapper file-readable-p (url))
1333 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1334 (url-https-create-secure-wrapper file-attributes (url &optional id-format))
1338 ;; arch-tag: ba7c59ae-c0f4-4a31-9617-d85f221732ee
1339 ;;; url-http.el ends here