1 ;;; url-http.el --- HTTP retrieval routines
3 ;; Copyright (c) 1999, 2001, 2004 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., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
31 (defvar url-http-extra-headers
))
38 (autoload 'url-retrieve-synchronously
"url")
39 (autoload 'url-retrieve
"url")
40 (autoload 'url-cache-create-filename
"url-cache")
41 (autoload 'url-mark-buffer-as-dead
"url")
43 (defconst url-http-default-port
80 "Default HTTP port.")
44 (defconst url-http-asynchronous-p t
"HTTP retrievals are asynchronous.")
45 (defalias 'url-http-expand-file-name
'url-default-expander
)
47 (defvar url-http-real-basic-auth-storage nil
)
48 (defvar url-http-proxy-basic-auth-storage nil
)
50 (defvar url-http-open-connections
(make-hash-table :test
'equal
52 "A hash table of all open network connections.")
54 (defvar url-http-version
"1.1"
55 "What version of HTTP we advertise, as a string.
56 Valid values are 1.1 and 1.0.
57 This is only useful when debugging the HTTP subsystem.
59 Setting this to 1.0 will tell servers not to send chunked encoding,
60 and other HTTP/1.1 specific features.
63 (defvar url-http-attempt-keepalives t
64 "Whether to use a single TCP connection multiple times in HTTP.
65 This is only useful when debugging the HTTP subsystem. Setting to
66 `nil' will explicitly close the connection to the server after every
71 ;; These are all macros so that they are hidden from external sight
72 ;; when the file is byte-compiled.
74 ;; This allows us to expose just the entry points we want.
76 ;; These routines will allow us to implement persistent HTTP
78 (defsubst url-http-debug
(&rest args
)
80 (let ((proc (get-buffer-process (current-buffer))))
81 ;; The user hit C-g, honor it! Some things can get in an
82 ;; incredibly tight loop (chunked encoding)
85 (set-process-sentinel proc nil
)
86 (set-process-filter proc nil
)))
87 (error "Transfer interrupted!")))
88 (apply 'url-debug
'http args
))
90 (defun url-http-mark-connection-as-busy (host port proc
)
91 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc
)
92 (puthash (cons host port
)
93 (delq proc
(gethash (cons host port
) url-http-open-connections
))
94 url-http-open-connections
)
97 (defun url-http-mark-connection-as-free (host port proc
)
98 (url-http-debug "Marking connection as free: %s:%d %S" host port proc
)
99 (set-process-buffer proc nil
)
100 (set-process-sentinel proc
'url-http-idle-sentinel
)
101 (puthash (cons host port
)
102 (cons proc
(gethash (cons host port
) url-http-open-connections
))
103 url-http-open-connections
)
106 (defun url-http-find-free-connection (host port
)
107 (let ((conns (gethash (cons host port
) url-http-open-connections
))
109 (while (and conns
(not found
))
110 (if (not (memq (process-status (car conns
)) '(run open
)))
112 (url-http-debug "Cleaning up dead process: %s:%d %S"
113 host port
(car conns
))
114 (url-http-idle-sentinel (car conns
) nil
))
115 (setq found
(car conns
))
116 (url-http-debug "Found existing connection: %s:%d %S" host port found
))
119 (url-http-debug "Reusing existing connection: %s:%d" host port
)
120 (url-http-debug "Contacting host: %s:%d" host port
))
121 (url-lazy-message "Contacting host: %s:%d" host port
)
122 (url-http-mark-connection-as-busy host port
124 (url-open-stream host nil host
127 ;; Building an HTTP request
128 (defun url-http-user-agent-string ()
129 (if (or (eq url-privacy-level
'paranoid
)
130 (and (listp url-privacy-level
)
131 (memq 'agent url-privacy-level
)))
133 (format "User-Agent: %sURL/%s%s\r\n"
135 (concat url-package-name
"/" url-package-version
" ")
139 ((and url-os-type url-system-type
)
140 (concat " (" url-os-type
"; " url-system-type
")"))
141 ((or url-os-type url-system-type
)
142 (concat " (" (or url-system-type url-os-type
) ")"))
145 (defun url-http-create-request (url &optional ref-url
)
146 "Create an HTTP request for URL, referred to by REF-URL."
147 (declare (special proxy-object proxy-info
))
148 (let* ((extra-headers)
150 (no-cache (cdr-safe (assoc "Pragma" url-request-extra-headers
)))
151 (proxy-obj (and (boundp 'proxy-object
) proxy-object
))
152 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
153 url-request-extra-headers
))
156 (let ((url-basic-auth-storage
157 'url-http-proxy-basic-auth-storage
))
158 (url-get-authentication url nil
'any nil
))))
159 (real-fname (if proxy-obj
(url-recreate-url proxy-obj
)
161 (host (url-host (or proxy-obj url
)))
162 (auth (if (cdr-safe (assoc "Authorization" url-request-extra-headers
))
164 (url-get-authentication (or
165 (and (boundp 'proxy-info
)
167 url
) nil
'any nil
))))
168 (if (equal "" real-fname
)
169 (setq real-fname
"/"))
170 (setq no-cache
(and no-cache
(string-match "no-cache" no-cache
)))
172 (setq auth
(concat "Authorization: " auth
"\r\n")))
174 (setq proxy-auth
(concat "Proxy-Authorization: " proxy-auth
"\r\n")))
176 ;; Protection against stupid values in the referer
177 (if (and ref-url
(stringp ref-url
) (or (string= ref-url
"file:nil")
178 (string= ref-url
"")))
181 ;; We do not want to expose the referer if the user is paranoid.
182 (if (or (memq url-privacy-level
'(low high paranoid
))
183 (and (listp url-privacy-level
)
184 (memq 'lastloc url-privacy-level
)))
187 ;; url-request-extra-headers contains an assoc-list of
188 ;; header/value pairs that we need to put into the request.
189 (setq extra-headers
(mapconcat
191 (concat (car x
) ": " (cdr x
)))
192 url-request-extra-headers
"\r\n"))
193 (if (not (equal extra-headers
""))
194 (setq extra-headers
(concat extra-headers
"\r\n")))
196 ;; This was done with a call to `format'. Concatting parts has
197 ;; the advantage of keeping the parts of each header togther and
198 ;; allows us to elide null lines directly, at the cost of making
199 ;; the layout less clear.
203 (or url-request-method
"GET") " " real-fname
" HTTP/" url-http-version
"\r\n"
204 ;; Version of MIME we speak
205 "MIME-Version: 1.0\r\n"
206 ;; (maybe) Try to keep the connection open
207 "Connection: " (if (or proxy-obj
208 (not url-http-attempt-keepalives
))
209 "close" "keep-alive") "\r\n"
210 ;; HTTP extensions we support
211 (if url-extensions-header
213 "Extension: %s\r\n" url-extensions-header
))
214 ;; Who we want to talk to
215 (if (/= (url-port (or proxy-obj url
))
216 (url-scheme-get-property
217 (url-type (or proxy-obj url
)) 'default-port
))
219 "Host: %s:%d\r\n" host
(url-port (or proxy-obj url
)))
220 (format "Host: %s\r\n" host
))
222 (if url-personal-mail-address
224 "From: " url-personal-mail-address
"\r\n"))
225 ;; Encodings we understand
226 (if url-mime-encoding-string
228 "Accept-encoding: " url-mime-encoding-string
"\r\n"))
229 (if url-mime-charset-string
231 "Accept-charset: " url-mime-charset-string
"\r\n"))
232 ;; Languages we understand
233 (if url-mime-language-string
235 "Accept-language: " url-mime-language-string
"\r\n"))
236 ;; Types we understand
237 "Accept: " (or url-mime-accept-string
"*/*") "\r\n"
239 (url-http-user-agent-string)
240 ;; Proxy Authorization
245 (url-cookie-generate-header-lines host real-fname
246 (equal "https" (url-type url
)))
248 (if (and (not no-cache
)
249 (member url-request-method
'("GET" nil
)))
250 (let ((tm (url-is-cached (or proxy-obj url
))))
252 (concat "If-modified-since: "
253 (url-get-normalized-date tm
) "\r\n"))))
256 "Referer: " ref-url
"\r\n"))
261 "Content-length: " (number-to-string
262 (length url-request-data
))
268 (url-http-debug "Request is: \n%s" request
)
272 (defun url-http-clean-headers ()
273 "Remove trailing \r from header lines.
274 This allows us to use `mail-fetch-field', etc."
275 (declare (special url-http-end-of-headers
))
276 (goto-char (point-min))
277 (while (re-search-forward "\r$" url-http-end-of-headers t
)
280 (defun url-http-handle-authentication (proxy)
281 (declare (special status success url-http-method url-http-data
282 url-callback-function url-callback-arguments
))
283 (url-http-debug "Handling %s authentication" (if proxy
"proxy" "normal"))
284 (let ((auth (or (mail-fetch-field (if proxy
"proxy-authenticate" "www-authenticate"))
287 (url (url-recreate-url url-current-object
))
288 (url-basic-auth-storage 'url-http-real-basic-auth-storage
)
291 ;; Cheating, but who cares? :)
293 (setq url-basic-auth-storage
'url-http-proxy-basic-auth-storage
))
295 (setq auth
(url-eat-trailing-space (url-strip-leading-spaces auth
)))
296 (if (string-match "[ \t]" auth
)
297 (setq type
(downcase (substring auth
0 (match-beginning 0))))
298 (setq type
(downcase auth
)))
300 (if (not (url-auth-registered type
))
303 (goto-char (point-max))
304 (insert "<hr>Sorry, but I do not know how to handle " type
305 " authentication. If you'd like to write it,"
306 " send it to " url-bug-address
".<hr>")
309 (ctr (1- (length args
)))
312 (if (char-equal ?
, (aref args ctr
))
315 (setq args
(url-parse-args args
)
316 auth
(url-get-authentication url
(cdr-safe (assoc "realm" args
))
320 (push (cons (if proxy
"Proxy-Authorization" "Authorization") auth
)
321 url-http-extra-headers
)
322 (let ((url-request-method url-http-method
)
323 (url-request-data url-http-data
)
324 (url-request-extra-headers url-http-extra-headers
))
325 (url-retrieve url url-callback-function
326 url-callback-arguments
)))))))
328 (defun url-http-parse-response ()
329 "Parse just the response code."
330 (declare (special url-http-end-of-headers url-http-response-status
))
331 (if (not url-http-end-of-headers
)
332 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
333 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
334 (goto-char (point-min))
335 (skip-chars-forward " \t\n") ; Skip any blank crap
336 (skip-chars-forward "HTTP/") ; Skip HTTP Version
337 (read (current-buffer))
338 (setq url-http-response-status
(read (current-buffer))))
340 (defun url-http-handle-cookies ()
341 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
342 The buffer must already be narrowed to the headers, so mail-fetch-field will
344 (let ((cookies (mail-fetch-field "Set-Cookie" nil nil t
))
345 (cookies2 (mail-fetch-field "Set-Cookie2" nil nil t
))
346 (url-current-object url-http-cookies-sources
))
347 (and cookies
(url-http-debug "Found %d Set-Cookie headers" (length cookies
)))
348 (and cookies2
(url-http-debug "Found %d Set-Cookie2 headers" (length cookies2
)))
350 (url-cookie-handle-set-cookie (pop cookies
)))
352 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
356 (defun url-http-parse-headers ()
357 "Parse and handle HTTP specific headers.
358 Return t if and only if the current buffer is still active and
359 should be shown to the user."
360 ;; The comments after each status code handled are taken from RFC
362 (declare (special url-http-end-of-headers url-http-response-status
363 url-http-method url-http-data url-http-process
364 url-callback-function url-callback-arguments
))
366 (url-http-mark-connection-as-free (url-host url-current-object
)
367 (url-port url-current-object
)
370 (if (or (not (boundp 'url-http-end-of-headers
))
371 (not url-http-end-of-headers
))
372 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
373 (goto-char (point-min))
374 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
375 (url-http-parse-response)
376 (mail-narrow-to-head)
377 ;;(narrow-to-region (point-min) url-http-end-of-headers)
380 (setq class
(/ url-http-response-status
100))
381 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status
)
382 (url-http-handle-cookies)
385 ;; Classes of response codes
387 ;; 5xx = Server Error
388 ;; 4xx = Client Error
391 ;; 1xx = Informational
392 (1 ; Information messages
393 ;; 100 = Continue with request
394 ;; 101 = Switching protocols
395 ;; 102 = Processing (Added by DAV)
396 (url-mark-buffer-as-dead (current-buffer))
397 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status
))
402 ;; 203 Non-authoritative information
405 ;; 206 Partial content
406 ;; 207 Multi-status (Added by DAV)
407 (case url-http-response-status
409 ;; No new data, just stay at the same document
410 (url-mark-buffer-as-dead (current-buffer))
413 ;; Generic success for all others. Store in the cache, and
414 ;; mark it as successful.
416 (if (and url-automatic-caching
(equal url-http-method
"GET"))
417 (url-store-in-cache (current-buffer)))
420 ;; 300 Multiple choices
421 ;; 301 Moved permanently
426 ;; 307 Temporary redirect
427 (let ((redirect-uri (or (mail-fetch-field "Location")
428 (mail-fetch-field "URI"))))
429 (case url-http-response-status
431 ;; Quoth the spec (section 10.3.1)
432 ;; -------------------------------
433 ;; The requested resource corresponds to any one of a set of
434 ;; representations, each with its own specific location and
435 ;; agent-driven negotiation information is being provided so
436 ;; that the user can select a preferred representation and
437 ;; redirect its request to that location.
439 ;; If the server has a preferred choice of representation, it
440 ;; SHOULD include the specific URI for that representation in
441 ;; the Location field; user agents MAY use the Location field
442 ;; value for automatic redirection.
443 ;; -------------------------------
444 ;; We do not support agent-driven negotiation, so we just
445 ;; redirect to the preferred URI if one is provided.
448 ;; If the 301|302 status code is received in response to a
449 ;; request other than GET or HEAD, the user agent MUST NOT
450 ;; automatically redirect the request unless it can be
451 ;; confirmed by the user, since this might change the
452 ;; conditions under which the request was issued.
453 (if (member url-http-method
'("HEAD" "GET"))
454 ;; Automatic redirection is ok
456 ;; It is just too big of a pain in the ass to get this
457 ;; prompt all the time. We will just silently lose our
458 ;; data and convert to a GET method.
459 (url-http-debug "Converting `%s' request to `GET' because of REDIRECT(%d)"
460 url-http-method url-http-response-status
)
461 (setq url-http-method
"GET"
464 ;; The response to the request can be found under a different
465 ;; URI and SHOULD be retrieved using a GET method on that
467 (setq url-http-method
"GET"
470 ;; The 304 response MUST NOT contain a message-body.
471 (url-http-debug "Extracting document from cache... (%s)"
472 (url-cache-create-filename (url-view-url t
)))
473 (url-cache-extract (url-cache-create-filename (url-view-url t
)))
474 (setq redirect-uri nil
477 ;; The requested resource MUST be accessed through the
478 ;; proxy given by the Location field. The Location field
479 ;; gives the URI of the proxy. The recipient is expected
480 ;; to repeat this single request via the proxy. 305
481 ;; responses MUST only be generated by origin servers.
482 (error "Redirection thru a proxy server not supported: %s"
485 ;; Treat everything like '300'
488 ;; Clean off any whitespace and/or <...> cruft.
489 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri
)
490 (setq redirect-uri
(match-string 1 redirect-uri
)))
491 (if (string-match "^<\\(.*\\)>$" redirect-uri
)
492 (setq redirect-uri
(match-string 1 redirect-uri
)))
494 ;; Some stupid sites (like sourceforge) send a
495 ;; non-fully-qualified URL (ie: /), which royally confuses
497 (if (not (string-match url-nonrelative-link redirect-uri
))
498 (setq redirect-uri
(url-expand-file-name redirect-uri
)))
499 (let ((url-request-method url-http-method
)
500 (url-request-data url-http-data
)
501 (url-request-extra-headers url-http-extra-headers
))
502 (url-retrieve redirect-uri url-callback-function
503 url-callback-arguments
)
504 (url-mark-buffer-as-dead (current-buffer))))))
508 ;; 402 Payment required
511 ;; 405 Method not allowed
512 ;; 406 Not acceptable
513 ;; 407 Proxy authentication required
514 ;; 408 Request time-out
517 ;; 411 Length required
518 ;; 412 Precondition failed
519 ;; 413 Request entity too large
520 ;; 414 Request-URI too large
521 ;; 415 Unsupported media type
522 ;; 416 Requested range not satisfiable
523 ;; 417 Expectation failed
524 ;; 422 Unprocessable Entity (Added by DAV)
526 ;; 424 Failed Dependency
527 (case url-http-response-status
529 ;; The request requires user authentication. The response
530 ;; MUST include a WWW-Authenticate header field containing a
531 ;; challenge applicable to the requested resource. The
532 ;; client MAY repeat the request with a suitable
533 ;; Authorization header field.
534 (url-http-handle-authentication nil
))
536 ;; This code is reserved for future use
537 (url-mark-buffer-as-dead (current-buffer))
538 (error "Somebody wants you to give them money"))
540 ;; The server understood the request, but is refusing to
541 ;; fulfill it. Authorization will not help and the request
542 ;; SHOULD NOT be repeated.
548 ;; The method specified in the Request-Line is not allowed
549 ;; for the resource identified by the Request-URI. The
550 ;; response MUST include an Allow header containing a list of
551 ;; valid methods for the requested resource.
554 ;; The resource identified by the request is only capable of
555 ;; generating response entities which have content
556 ;; characteristics nota cceptable according to the accept
557 ;; headers sent in the request.
560 ;; This code is similar to 401 (Unauthorized), but indicates
561 ;; that the client must first authenticate itself with the
562 ;; proxy. The proxy MUST return a Proxy-Authenticate header
563 ;; field containing a challenge applicable to the proxy for
564 ;; the requested resource.
565 (url-http-handle-authentication t
))
567 ;; The client did not produce a request within the time that
568 ;; the server was prepared to wait. The client MAY repeat
569 ;; the request without modifications at any later time.
572 ;; The request could not be completed due to a conflict with
573 ;; the current state of the resource. This code is only
574 ;; allowed in situations where it is expected that the user
575 ;; mioght be able to resolve the conflict and resubmit the
576 ;; request. The response body SHOULD include enough
577 ;; information for the user to recognize the source of the
581 ;; The requested resource is no longer available at the
582 ;; server and no forwarding address is known.
585 ;; The server refuses to accept the request without a defined
586 ;; Content-Length. The client MAY repeat the request if it
587 ;; adds a valid Content-Length header field containing the
588 ;; length of the message-body in the request message.
590 ;; NOTE - this will never happen because
591 ;; `url-http-create-request' automatically calculates the
595 ;; The precondition given in one or more of the
596 ;; request-header fields evaluated to false when it was
597 ;; tested on the server.
600 ;; The server is refusing to process a request because the
601 ;; request entity|URI is larger than the server is willing or
605 ;; The server is refusing to service the request because the
606 ;; entity of the request is in a format not supported by the
607 ;; requested resource for the requested method.
610 ;; A server SHOULD return a response with this status code if
611 ;; a request included a Range request-header field, and none
612 ;; of the range-specifier values in this field overlap the
613 ;; current extent of the selected resource, and the request
614 ;; did not include an If-Range request-header field.
617 ;; The expectation given in an Expect request-header field
618 ;; could not be met by this server, or, if the server is a
619 ;; proxy, the server has unambiguous evidence that the
620 ;; request could not be met by the next-hop server.
623 ;; The request could not be understood by the server due to
624 ;; malformed syntax. The client SHOULD NOT repeat the
625 ;; request without modifications.
628 ;; 500 Internal server error
629 ;; 501 Not implemented
631 ;; 503 Service unavailable
632 ;; 504 Gateway time-out
633 ;; 505 HTTP version not supported
634 ;; 507 Insufficient storage
636 (case url-http-response-status
638 ;; The server does not support the functionality required to
639 ;; fulfill the request.
642 ;; The server, while acting as a gateway or proxy, received
643 ;; an invalid response from the upstream server it accessed
644 ;; in attempting to fulfill the request.
647 ;; The server is currently unable to handle the request due
648 ;; to a temporary overloading or maintenance of the server.
649 ;; The implication is that this is a temporary condition
650 ;; which will be alleviated after some delay. If known, the
651 ;; length of the delay MAY be indicated in a Retry-After
652 ;; header. If no Retry-After is given, the client SHOULD
653 ;; handle the response as it would for a 500 response.
656 ;; The server, while acting as a gateway or proxy, did not
657 ;; receive a timely response from the upstream server
658 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
659 ;; auxiliary server (e.g. DNS) it needed to access in
660 ;; attempting to complete the request.
663 ;; The server does not support, or refuses to support, the
664 ;; HTTP protocol version that was used in the request
668 ;; The method could not be performed on the resource
669 ;; because the server is unable to store the representation
670 ;; needed to successfully complete the request. This
671 ;; condition is considered to be temporary. If the request
672 ;; which received this status code was the result of a user
673 ;; action, the request MUST NOT be repeated until it is
674 ;; requested by a separate user action.
677 (error "Unknown class of HTTP response code: %d (%d)"
678 class url-http-response-status
)))
680 (url-mark-buffer-as-dead (current-buffer)))
681 (url-http-debug "Finished parsing HTTP headers: %S" success
)
686 (defun url-http-activate-callback ()
687 "Activate callback specified when this buffer was created."
688 (declare (special url-http-process
689 url-callback-function
690 url-callback-arguments
))
691 (url-http-mark-connection-as-free (url-host url-current-object
)
692 (url-port url-current-object
)
694 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
695 (apply url-callback-function url-callback-arguments
))
699 ;; These unfortunately cannot be macros... please ignore them!
700 (defun url-http-idle-sentinel (proc why
)
701 "Remove this (now defunct) process PROC from the list of open connections."
702 (maphash (lambda (key val
)
704 (puthash key
(delq proc val
) url-http-open-connections
)))
705 url-http-open-connections
))
707 (defun url-http-end-of-document-sentinel (proc why
)
708 ;; Sentinel used for old HTTP/0.9 or connections we know are going
709 ;; to die as the 'end of document' notifier.
710 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
711 (process-buffer proc
))
712 (url-http-idle-sentinel proc why
)
714 (set-buffer (process-buffer proc
))
715 (goto-char (point-min))
716 (if (not (looking-at "HTTP/"))
717 ;; HTTP/0.9 just gets passed back no matter what
718 (url-http-activate-callback)
719 (if (url-http-parse-headers)
720 (url-http-activate-callback)))))
722 (defun url-http-simple-after-change-function (st nd length
)
723 ;; Function used when we do NOT know how long the document is going to be
724 ;; Just _very_ simple 'downloaded %d' type of info.
725 (declare (special url-http-end-of-headers
))
726 (url-lazy-message "Reading %s..." (url-pretty-length nd
)))
728 (defun url-http-content-length-after-change-function (st nd length
)
729 "Function used when we DO know how long the document is going to be.
730 More sophisticated percentage downloaded, etc.
731 Also does minimal parsing of HTTP headers and will actually cause
732 the callback to be triggered."
733 (declare (special url-current-object
734 url-http-end-of-headers
735 url-http-content-length
736 url-http-content-type
738 (if url-http-content-type
739 (url-display-percentage
740 "Reading [%s]... %s of %s (%d%%)"
741 (url-percentage (- nd url-http-end-of-headers
)
742 url-http-content-length
)
743 url-http-content-type
744 (url-pretty-length (- nd url-http-end-of-headers
))
745 (url-pretty-length url-http-content-length
)
746 (url-percentage (- nd url-http-end-of-headers
)
747 url-http-content-length
))
748 (url-display-percentage
749 "Reading... %s of %s (%d%%)"
750 (url-percentage (- nd url-http-end-of-headers
)
751 url-http-content-length
)
752 (url-pretty-length (- nd url-http-end-of-headers
))
753 (url-pretty-length url-http-content-length
)
754 (url-percentage (- nd url-http-end-of-headers
)
755 url-http-content-length
)))
757 (if (> (- nd url-http-end-of-headers
) url-http-content-length
)
759 ;; Found the end of the document! Wheee!
760 (url-display-percentage nil nil
)
761 (message "Reading... done.")
762 (if (url-http-parse-headers)
763 (url-http-activate-callback)))))
765 (defun url-http-chunked-encoding-after-change-function (st nd length
)
766 "Function used when dealing with 'chunked' encoding.
767 Cannot give a sophisticated percentage, but we need a different
768 function to look for the special 0-length chunk that signifies
769 the end of the document."
770 (declare (special url-current-object
771 url-http-end-of-headers
772 url-http-content-type
773 url-http-chunked-length
774 url-http-chunked-counter
775 url-http-process url-http-chunked-start
))
778 (let ((read-next-chunk t
)
781 (no-initial-crlf nil
))
782 ;; We need to loop thru looking for more chunks even within
783 ;; one after-change-function call.
784 (while read-next-chunk
785 (setq no-initial-crlf
(= 0 url-http-chunked-counter
))
786 (if url-http-content-type
787 (url-display-percentage nil
788 "Reading [%s]... chunk #%d"
789 url-http-content-type url-http-chunked-counter
)
790 (url-display-percentage nil
791 "Reading... chunk #%d"
792 url-http-chunked-counter
))
793 (url-http-debug "Reading chunk %d (%d %d %d)"
794 url-http-chunked-counter st nd length
)
795 (setq regexp
(if no-initial-crlf
796 "\\([0-9a-z]+\\).*\r?\n"
797 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
799 (if url-http-chunked-start
800 ;; We know how long the chunk is supposed to be, skip over
801 ;; leading crap if possible.
802 (if (> nd
(+ url-http-chunked-start url-http-chunked-length
))
804 (url-http-debug "Got to the end of chunk #%d!"
805 url-http-chunked-counter
)
806 (goto-char (+ url-http-chunked-start
807 url-http-chunked-length
)))
808 (url-http-debug "Still need %d bytes to hit end of chunk"
809 (- (+ url-http-chunked-start
810 url-http-chunked-length
)
812 (setq read-next-chunk nil
)))
813 (if (not read-next-chunk
)
814 (url-http-debug "Still spinning for next chunk...")
815 (if no-initial-crlf
(skip-chars-forward "\r\n"))
816 (if (not (looking-at regexp
))
818 ;; Must not have received the entirety of the chunk header,
819 ;; need to spin some more.
820 (url-http-debug "Did not see start of chunk @ %d!" (point))
821 (setq read-next-chunk nil
))
822 (add-text-properties (match-beginning 0) (match-end 0)
826 'face
(if (featurep 'xemacs
)
830 (setq url-http-chunked-length
(string-to-number (buffer-substring
834 url-http-chunked-counter
(1+ url-http-chunked-counter
)
835 url-http-chunked-start
(set-marker
836 (or url-http-chunked-start
839 ; (if (not url-http-debug)
840 (delete-region (match-beginning 0) (match-end 0));)
841 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
842 url-http-chunked-counter url-http-chunked-length
843 (marker-position url-http-chunked-start
))
844 (if (= 0 url-http-chunked-length
)
846 ;; Found the end of the document! Wheee!
847 (url-http-debug "Saw end of stream chunk!")
848 (setq read-next-chunk nil
)
849 (url-display-percentage nil nil
)
850 (goto-char (match-end 1))
851 (if (re-search-forward "^\r*$" nil t
)
852 (message "Saw end of trailers..."))
853 (if (url-http-parse-headers)
854 (url-http-activate-callback))))))))))
856 (defun url-http-wait-for-headers-change-function (st nd length
)
857 ;; This will wait for the headers to arrive and then splice in the
858 ;; next appropriate after-change-function, etc.
859 (declare (special url-current-object
860 url-http-end-of-headers
861 url-http-content-type
862 url-http-content-length
863 url-http-transfer-encoding
864 url-callback-function
865 url-callback-arguments
868 url-http-after-change-function
869 url-http-response-status
))
870 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
873 (let ((end-of-headers nil
)
875 (content-length nil
))
876 (goto-char (point-min))
877 (if (not (looking-at "^HTTP/[1-9]\\.[0-9]"))
878 ;; Not HTTP/x.y data, must be 0.9
879 ;; God, I wish this could die.
880 (setq end-of-headers t
881 url-http-end-of-headers
0
883 (if (re-search-forward "^\r*$" nil t
)
884 ;; Saw the end of the headers
886 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
887 (setq url-http-end-of-headers
(set-marker (make-marker)
890 (url-http-clean-headers))))
892 (if (not end-of-headers
)
893 ;; Haven't seen the end of the headers yet, need to wait
894 ;; for more data to arrive.
897 (message "HTTP/0.9 How I hate thee!")
899 (url-http-parse-response)
900 (mail-narrow-to-head)
901 ;;(narrow-to-region (point-min) url-http-end-of-headers)
902 (setq url-http-transfer-encoding
(mail-fetch-field
904 url-http-content-type
(mail-fetch-field "content-type"))
905 (if (mail-fetch-field "content-length")
906 (setq url-http-content-length
907 (string-to-number (mail-fetch-field "content-length"))))
909 (if url-http-transfer-encoding
910 (setq url-http-transfer-encoding
911 (downcase url-http-transfer-encoding
)))
914 ((or (= url-http-response-status
204)
915 (= url-http-response-status
205))
916 (url-http-debug "%d response must have headers only (%s)."
917 url-http-response-status
(buffer-name))
918 (if (url-http-parse-headers)
919 (url-http-activate-callback)))
920 ((string= "HEAD" url-http-method
)
921 ;; A HEAD request is _ALWAYS_ terminated by the header
922 ;; information, regardless of any entity headers,
923 ;; according to section 4.4 of the HTTP/1.1 draft.
924 (url-http-debug "HEAD request must have headers only (%s)."
926 (if (url-http-parse-headers)
927 (url-http-activate-callback)))
928 ((string= "CONNECT" url-http-method
)
929 ;; A CONNECT request is finished, but we cannot stick this
930 ;; back on the free connectin list
931 (url-http-debug "CONNECT request must have headers only.")
932 (if (url-http-parse-headers)
933 (url-http-activate-callback)))
934 ((equal url-http-response-status
304)
935 ;; Only allowed to have a header section. We have to handle
936 ;; this here instead of in url-http-parse-headers because if
937 ;; you have a cached copy of something without a known
938 ;; content-length, and try to retrieve it from the cache, we'd
939 ;; fall into the 'being dumb' section and wait for the
940 ;; connection to terminate, which means we'd wait for 10
941 ;; seconds for the keep-alives to time out on some servers.
942 (if (url-http-parse-headers)
943 (url-http-activate-callback)))
945 ;; HTTP/0.9 always signaled end-of-connection by closing the
948 "Saw HTTP/0.9 response, connection closed means end of document.")
949 (setq url-http-after-change-function
950 'url-http-simple-after-change-function
))
951 ((equal url-http-transfer-encoding
"chunked")
952 (url-http-debug "Saw chunked encoding.")
953 (setq url-http-after-change-function
954 'url-http-chunked-encoding-after-change-function
)
955 (if (> nd url-http-end-of-headers
)
958 "Calling initial chunked-encoding for extra data at end of headers")
959 (url-http-chunked-encoding-after-change-function
960 (marker-position url-http-end-of-headers
) nd
961 (- nd url-http-end-of-headers
)))))
962 ((integerp url-http-content-length
)
964 "Got a content-length, being smart about document end.")
965 (setq url-http-after-change-function
966 'url-http-content-length-after-change-function
)
968 ((= 0 url-http-content-length
)
969 ;; We got a NULL body! Activate the callback
972 "Got 0-length content-length, activating callback immediately.")
973 (if (url-http-parse-headers)
974 (url-http-activate-callback)))
975 ((> nd url-http-end-of-headers
)
976 ;; Have some leftover data
977 (url-http-debug "Calling initial content-length for extra data at end of headers")
978 (url-http-content-length-after-change-function
979 (marker-position url-http-end-of-headers
)
981 (- nd url-http-end-of-headers
)))
985 (url-http-debug "No content-length, being dumb.")
986 (setq url-http-after-change-function
987 'url-http-simple-after-change-function
)))))
988 ;; We are still at the beginning of the buffer... must just be
989 ;; waiting for a response.
990 (url-http-debug "Spinning waiting for headers..."))
991 (goto-char (point-max)))
994 (defun url-http (url callback cbargs
)
995 "Retrieve URL via HTTP asynchronously.
996 URL must be a parsed URL. See `url-generic-parse-url' for details.
997 When retrieval is completed, the function CALLBACK is executed with
998 CBARGS as the arguments."
999 (check-type url vector
"Need a pre-parsed URL.")
1000 (declare (special url-current-object
1001 url-http-end-of-headers
1002 url-http-content-type
1003 url-http-content-length
1004 url-http-transfer-encoding
1005 url-http-after-change-function
1006 url-callback-function
1007 url-callback-arguments
1009 url-http-extra-headers
1011 url-http-chunked-length
1012 url-http-chunked-start
1013 url-http-chunked-counter
1015 (let ((connection (url-http-find-free-connection (url-host url
)
1017 (buffer (generate-new-buffer (format " *http %s:%d*"
1020 (if (not connection
)
1021 ;; Failed to open the connection for some reason
1023 (kill-buffer buffer
)
1025 (error "Could not create connection to %s:%d" (url-host url
)
1029 (mm-disable-multibyte)
1030 (setq url-current-object url
1031 mode-line-format
"%b [%s]")
1033 (dolist (var '(url-http-end-of-headers
1034 url-http-content-type
1035 url-http-content-length
1036 url-http-transfer-encoding
1037 url-http-after-change-function
1038 url-http-response-status
1039 url-http-chunked-length
1040 url-http-chunked-counter
1041 url-http-chunked-start
1042 url-callback-function
1043 url-callback-arguments
1046 url-http-extra-headers
1048 url-http-cookies-sources
))
1049 (set (make-local-variable var
) nil
))
1051 (setq url-http-method
(or url-request-method
"GET")
1052 url-http-extra-headers url-request-extra-headers
1053 url-http-data url-request-data
1054 url-http-process connection
1055 url-http-chunked-length nil
1056 url-http-chunked-start nil
1057 url-http-chunked-counter
0
1058 url-callback-function callback
1059 url-callback-arguments cbargs
1060 url-http-after-change-function
'url-http-wait-for-headers-change-function
1061 url-http-cookies-sources
(if (boundp 'proxy-object
)
1063 url-current-object
))
1065 (set-process-buffer connection buffer
)
1066 (set-process-sentinel connection
'url-http-end-of-document-sentinel
)
1067 (set-process-filter connection
'url-http-generic-filter
)
1068 (process-send-string connection
(url-http-create-request url
))))
1071 ;; Since Emacs 19/20 does not allow you to change the
1072 ;; `after-change-functions' hook in the midst of running them, we fake
1073 ;; an after change by hooking into the process filter and inserting
1074 ;; the data ourselves. This is slightly less efficient, but there
1075 ;; were tons of weird ways the after-change code was biting us in the
1077 (defun url-http-generic-filter (proc data
)
1078 ;; Sometimes we get a zero-length data chunk after the process has
1079 ;; been changed to 'free', which means it has no buffer associated
1080 ;; with it. Do nothing if there is no buffer, or 0 length data.
1081 (declare (special url-http-after-change-function
))
1082 (and (process-buffer proc
)
1083 (/= (length data
) 0)
1085 (set-buffer (process-buffer proc
))
1086 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc
)
1087 (funcall url-http-after-change-function
1090 (goto-char (point-max))
1095 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1096 ;;; file-name-handler stuff from here on out
1097 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1098 (if (not (fboundp 'symbol-value-in-buffer
))
1099 (defun url-http-symbol-value-in-buffer (symbol buffer
1100 &optional unbound-value
)
1101 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1104 (if (not (boundp symbol
))
1106 (symbol-value symbol
))))
1107 (defalias 'url-http-symbol-value-in-buffer
'symbol-value-in-buffer
))
1109 (defun url-http-head (url)
1110 (let ((url-request-method "HEAD")
1111 (url-request-data nil
))
1112 (url-retrieve-synchronously url
)))
1115 (defun url-http-file-exists-p (url)
1118 (buffer (url-http-head url
)))
1121 (setq status
(url-http-symbol-value-in-buffer 'url-http-response-status
1123 exists
(and (>= status
200) (< status
300)))
1124 (kill-buffer buffer
))
1128 (defalias 'url-http-file-readable-p
'url-http-file-exists-p
)
1130 (defun url-http-head-file-attributes (url &optional id-format
)
1131 (let ((buffer (url-http-head url
))
1134 (setq attributes
(make-list 11 nil
))
1135 (setf (nth 1 attributes
) 1) ; Number of links to file
1136 (setf (nth 2 attributes
) 0) ; file uid
1137 (setf (nth 3 attributes
) 0) ; file gid
1138 (setf (nth 7 attributes
) ; file size
1139 (url-http-symbol-value-in-buffer 'url-http-content-length
1141 (setf (nth 8 attributes
) (eval-when-compile (make-string 10 ?-
)))
1142 (kill-buffer buffer
))
1146 (defun url-http-file-attributes (url &optional id-format
)
1147 (if (url-dav-supported-p url
)
1148 (url-dav-file-attributes url id-format
)
1149 (url-http-head-file-attributes url id-format
)))
1152 (defun url-http-options (url)
1153 "Returns a property list describing options available for URL.
1154 This list is retrieved using the `OPTIONS' HTTP method.
1156 Property list members:
1159 A list of symbols specifying what HTTP methods the resource
1163 A list of numbers specifying what DAV protocol/schema versions are
1167 A list of supported DASL search types supported (string form)
1170 A list of the units available for use in partial document fetches.
1173 The `Platform For Privacy Protection' description for the resource.
1174 Currently this is just the raw header contents. This is likely to
1175 change once P3P is formally supported by the URL package or
1178 (let* ((url-request-method "OPTIONS")
1179 (url-request-data nil
)
1180 (buffer (url-retrieve-synchronously url
))
1183 (when (and buffer
(= 2 (/ (url-http-symbol-value-in-buffer
1184 'url-http-response-status buffer
0) 100)))
1185 ;; Only parse the options if we got a 2xx response code!
1190 (mail-narrow-to-head)
1192 ;; Figure out what methods are supported.
1193 (when (setq header
(mail-fetch-field "allow"))
1194 (setq options
(plist-put
1196 (mapcar 'intern
(split-string header
"[ ,]+")))))
1199 (when (setq header
(mail-fetch-field "dav"))
1200 (setq options
(plist-put
1203 (mapcar 'string-to-number
1204 (split-string header
"[, ]+"))))))
1207 (when (setq header
(mail-fetch-field "dasl"))
1208 (setq options
(plist-put
1210 (split-string header
"[, ]+"))))
1212 ;; P3P - should get more detailed here. FIXME
1213 (when (setq header
(mail-fetch-field "p3p"))
1214 (setq options
(plist-put options
'p3p header
)))
1216 ;; Check for whether they accept byte-range requests.
1217 (when (setq header
(mail-fetch-field "accept-ranges"))
1218 (setq options
(plist-put
1222 (split-string header
"[, ]+"))))))
1224 (if buffer
(kill-buffer buffer
))
1229 ;; arch-tag: ba7c59ae-c0f4-4a31-9617-d85f221732ee
1230 ;;; url-http.el ends here