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
))
267 (url-http-debug "Request is: \n%s" request
)
271 (defun url-http-clean-headers ()
272 "Remove trailing \r from header lines.
273 This allows us to use `mail-fetch-field', etc."
274 (declare (special url-http-end-of-headers
))
275 (goto-char (point-min))
276 (while (re-search-forward "\r$" url-http-end-of-headers t
)
279 (defun url-http-handle-authentication (proxy)
280 (declare (special status success url-http-method url-http-data
281 url-callback-function url-callback-arguments
))
282 (url-http-debug "Handling %s authentication" (if proxy
"proxy" "normal"))
283 (let ((auth (or (mail-fetch-field (if proxy
"proxy-authenticate" "www-authenticate"))
286 (url (url-recreate-url url-current-object
))
287 (url-basic-auth-storage 'url-http-real-basic-auth-storage
)
290 ;; Cheating, but who cares? :)
292 (setq url-basic-auth-storage
'url-http-proxy-basic-auth-storage
))
294 (setq auth
(url-eat-trailing-space (url-strip-leading-spaces auth
)))
295 (if (string-match "[ \t]" auth
)
296 (setq type
(downcase (substring auth
0 (match-beginning 0))))
297 (setq type
(downcase auth
)))
299 (if (not (url-auth-registered type
))
302 (goto-char (point-max))
303 (insert "<hr>Sorry, but I do not know how to handle " type
304 " authentication. If you'd like to write it,"
305 " send it to " url-bug-address
".<hr>")
308 (ctr (1- (length args
)))
311 (if (char-equal ?
, (aref args ctr
))
314 (setq args
(url-parse-args args
)
315 auth
(url-get-authentication url
(cdr-safe (assoc "realm" args
))
319 (push (cons (if proxy
"Proxy-Authorization" "Authorization") auth
)
320 url-http-extra-headers
)
321 (let ((url-request-method url-http-method
)
322 (url-request-data url-http-data
)
323 (url-request-extra-headers url-http-extra-headers
))
324 (url-retrieve url url-callback-function url-callback-arguments
))))
325 (kill-buffer (current-buffer)))))
327 (defun url-http-parse-response ()
328 "Parse just the response code."
329 (declare (special url-http-end-of-headers url-http-response-status
))
330 (if (not url-http-end-of-headers
)
331 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
332 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
333 (goto-char (point-min))
334 (skip-chars-forward " \t\n") ; Skip any blank crap
335 (skip-chars-forward "HTTP/") ; Skip HTTP Version
336 (read (current-buffer))
337 (setq url-http-response-status
(read (current-buffer))))
339 (defun url-http-handle-cookies ()
340 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
341 The buffer must already be narrowed to the headers, so mail-fetch-field will
343 (let ((cookies (mail-fetch-field "Set-Cookie" nil nil t
))
344 (cookies2 (mail-fetch-field "Set-Cookie2" nil nil t
)))
345 (and cookies
(url-http-debug "Found %d Set-Cookie headers" (length cookies
)))
346 (and cookies2
(url-http-debug "Found %d Set-Cookie2 headers" (length cookies2
)))
348 (url-cookie-handle-set-cookie (pop cookies
)))
350 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
354 (defun url-http-parse-headers ()
355 "Parse and handle HTTP specific headers.
356 Return t if and only if the current buffer is still active and
357 should be shown to the user."
358 ;; The comments after each status code handled are taken from RFC
360 (declare (special url-http-end-of-headers url-http-response-status
361 url-http-method url-http-data url-http-process
362 url-callback-function url-callback-arguments
))
364 (url-http-mark-connection-as-free (url-host url-current-object
)
365 (url-port url-current-object
)
368 (if (or (not (boundp 'url-http-end-of-headers
))
369 (not url-http-end-of-headers
))
370 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
371 (goto-char (point-min))
372 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
373 (url-http-parse-response)
374 (mail-narrow-to-head)
375 ;;(narrow-to-region (point-min) url-http-end-of-headers)
378 (setq class
(/ url-http-response-status
100))
379 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status
)
380 (url-http-handle-cookies)
383 ;; Classes of response codes
385 ;; 5xx = Server Error
386 ;; 4xx = Client Error
389 ;; 1xx = Informational
390 (1 ; Information messages
391 ;; 100 = Continue with request
392 ;; 101 = Switching protocols
393 ;; 102 = Processing (Added by DAV)
394 (url-mark-buffer-as-dead (current-buffer))
395 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status
))
400 ;; 203 Non-authoritative information
403 ;; 206 Partial content
404 ;; 207 Multi-status (Added by DAV)
405 (case url-http-response-status
407 ;; No new data, just stay at the same document
408 (url-mark-buffer-as-dead (current-buffer))
411 ;; Generic success for all others. Store in the cache, and
412 ;; mark it as successful.
414 (if (equal url-http-method
"GET")
415 (url-store-in-cache (current-buffer)))
418 ;; 300 Multiple choices
419 ;; 301 Moved permanently
424 ;; 307 Temporary redirect
425 (let ((redirect-uri (or (mail-fetch-field "Location")
426 (mail-fetch-field "URI"))))
427 (case url-http-response-status
429 ;; Quoth the spec (section 10.3.1)
430 ;; -------------------------------
431 ;; The requested resource corresponds to any one of a set of
432 ;; representations, each with its own specific location and
433 ;; agent-driven negotiation information is being provided so
434 ;; that the user can select a preferred representation and
435 ;; redirect its request to that location.
437 ;; If the server has a preferred choice of representation, it
438 ;; SHOULD include the specific URI for that representation in
439 ;; the Location field; user agents MAY use the Location field
440 ;; value for automatic redirection.
441 ;; -------------------------------
442 ;; We do not support agent-driven negotiation, so we just
443 ;; redirect to the preferred URI if one is provided.
446 ;; If the 301|302 status code is received in response to a
447 ;; request other than GET or HEAD, the user agent MUST NOT
448 ;; automatically redirect the request unless it can be
449 ;; confirmed by the user, since this might change the
450 ;; conditions under which the request was issued.
451 (if (member url-http-method
'("HEAD" "GET"))
452 ;; Automatic redirection is ok
454 ;; It is just too big of a pain in the ass to get this
455 ;; prompt all the time. We will just silently lose our
456 ;; data and convert to a GET method.
457 (url-http-debug "Converting `%s' request to `GET' because of REDIRECT(%d)"
458 url-http-method url-http-response-status
)
459 (setq url-http-method
"GET"
460 url-request-data nil
)))
462 ;; The response to the request can be found under a different
463 ;; URI and SHOULD be retrieved using a GET method on that
465 (setq url-http-method
"GET"
468 ;; The 304 response MUST NOT contain a message-body.
469 (url-http-debug "Extracting document from cache... (%s)"
470 (url-cache-create-filename (url-view-url t
)))
471 (url-cache-extract (url-cache-create-filename (url-view-url t
)))
472 (setq redirect-uri nil
475 ;; The requested resource MUST be accessed through the
476 ;; proxy given by the Location field. The Location field
477 ;; gives the URI of the proxy. The recipient is expected
478 ;; to repeat this single request via the proxy. 305
479 ;; responses MUST only be generated by origin servers.
480 (error "Redirection thru a proxy server not supported: %s"
483 ;; Treat everything like '300'
486 ;; Clean off any whitespace and/or <...> cruft.
487 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri
)
488 (setq redirect-uri
(match-string 1 redirect-uri
)))
489 (if (string-match "^<\\(.*\\)>$" redirect-uri
)
490 (setq redirect-uri
(match-string 1 redirect-uri
)))
492 ;; Some stupid sites (like sourceforge) send a
493 ;; non-fully-qualified URL (ie: /), which royally confuses
495 (if (not (string-match url-nonrelative-link redirect-uri
))
496 (setq redirect-uri
(url-expand-file-name redirect-uri
)))
497 (let ((url-request-method url-http-method
)
498 (url-request-data url-http-data
)
499 (url-request-extra-headers url-http-extra-headers
))
500 (url-retrieve redirect-uri url-callback-function
501 url-callback-arguments
)
502 (url-mark-buffer-as-dead (current-buffer))))))
506 ;; 402 Payment required
509 ;; 405 Method not allowed
510 ;; 406 Not acceptable
511 ;; 407 Proxy authentication required
512 ;; 408 Request time-out
515 ;; 411 Length required
516 ;; 412 Precondition failed
517 ;; 413 Request entity too large
518 ;; 414 Request-URI too large
519 ;; 415 Unsupported media type
520 ;; 416 Requested range not satisfiable
521 ;; 417 Expectation failed
522 ;; 422 Unprocessable Entity (Added by DAV)
524 ;; 424 Failed Dependency
525 (case url-http-response-status
527 ;; The request requires user authentication. The response
528 ;; MUST include a WWW-Authenticate header field containing a
529 ;; challenge applicable to the requested resource. The
530 ;; client MAY repeat the request with a suitable
531 ;; Authorization header field.
532 (url-http-handle-authentication nil
))
534 ;; This code is reserved for future use
535 (url-mark-buffer-as-dead (current-buffer))
536 (error "Somebody wants you to give them money"))
538 ;; The server understood the request, but is refusing to
539 ;; fulfill it. Authorization will not help and the request
540 ;; SHOULD NOT be repeated.
546 ;; The method specified in the Request-Line is not allowed
547 ;; for the resource identified by the Request-URI. The
548 ;; response MUST include an Allow header containing a list of
549 ;; valid methods for the requested resource.
552 ;; The resource identified by the request is only capable of
553 ;; generating response entities which have content
554 ;; characteristics nota cceptable according to the accept
555 ;; headers sent in the request.
558 ;; This code is similar to 401 (Unauthorized), but indicates
559 ;; that the client must first authenticate itself with the
560 ;; proxy. The proxy MUST return a Proxy-Authenticate header
561 ;; field containing a challenge applicable to the proxy for
562 ;; the requested resource.
563 (url-http-handle-authentication t
))
565 ;; The client did not produce a request within the time that
566 ;; the server was prepared to wait. The client MAY repeat
567 ;; the request without modifications at any later time.
570 ;; The request could not be completed due to a conflict with
571 ;; the current state of the resource. This code is only
572 ;; allowed in situations where it is expected that the user
573 ;; mioght be able to resolve the conflict and resubmit the
574 ;; request. The response body SHOULD include enough
575 ;; information for the user to recognize the source of the
579 ;; The requested resource is no longer available at the
580 ;; server and no forwarding address is known.
583 ;; The server refuses to accept the request without a defined
584 ;; Content-Length. The client MAY repeat the request if it
585 ;; adds a valid Content-Length header field containing the
586 ;; length of the message-body in the request message.
588 ;; NOTE - this will never happen because
589 ;; `url-http-create-request' automatically calculates the
593 ;; The precondition given in one or more of the
594 ;; request-header fields evaluated to false when it was
595 ;; tested on the server.
598 ;; The server is refusing to process a request because the
599 ;; request entity|URI is larger than the server is willing or
603 ;; The server is refusing to service the request because the
604 ;; entity of the request is in a format not supported by the
605 ;; requested resource for the requested method.
608 ;; A server SHOULD return a response with this status code if
609 ;; a request included a Range request-header field, and none
610 ;; of the range-specifier values in this field overlap the
611 ;; current extent of the selected resource, and the request
612 ;; did not include an If-Range request-header field.
615 ;; The expectation given in an Expect request-header field
616 ;; could not be met by this server, or, if the server is a
617 ;; proxy, the server has unambiguous evidence that the
618 ;; request could not be met by the next-hop server.
621 ;; The request could not be understood by the server due to
622 ;; malformed syntax. The client SHOULD NOT repeat the
623 ;; request without modifications.
626 ;; 500 Internal server error
627 ;; 501 Not implemented
629 ;; 503 Service unavailable
630 ;; 504 Gateway time-out
631 ;; 505 HTTP version not supported
632 ;; 507 Insufficient storage
634 (case url-http-response-status
636 ;; The server does not support the functionality required to
637 ;; fulfill the request.
640 ;; The server, while acting as a gateway or proxy, received
641 ;; an invalid response from the upstream server it accessed
642 ;; in attempting to fulfill the request.
645 ;; The server is currently unable to handle the request due
646 ;; to a temporary overloading or maintenance of the server.
647 ;; The implication is that this is a temporary condition
648 ;; which will be alleviated after some delay. If known, the
649 ;; length of the delay MAY be indicated in a Retry-After
650 ;; header. If no Retry-After is given, the client SHOULD
651 ;; handle the response as it would for a 500 response.
654 ;; The server, while acting as a gateway or proxy, did not
655 ;; receive a timely response from the upstream server
656 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
657 ;; auxiliary server (e.g. DNS) it needed to access in
658 ;; attempting to complete the request.
661 ;; The server does not support, or refuses to support, the
662 ;; HTTP protocol version that was used in the request
666 ;; The method could not be performed on the resource
667 ;; because the server is unable to store the representation
668 ;; needed to successfully complete the request. This
669 ;; condition is considered to be temporary. If the request
670 ;; which received this status code was the result of a user
671 ;; action, the request MUST NOT be repeated until it is
672 ;; requested by a separate user action.
675 (error "Unknown class of HTTP response code: %d (%d)"
676 class url-http-response-status
)))
678 (url-mark-buffer-as-dead (current-buffer)))
679 (url-http-debug "Finished parsing HTTP headers: %S" success
)
684 (defun url-http-activate-callback ()
685 "Activate callback specified when this buffer was created."
686 (declare (special url-http-process
687 url-callback-function
688 url-callback-arguments
))
689 (url-http-mark-connection-as-free (url-host url-current-object
)
690 (url-port url-current-object
)
692 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
693 (apply url-callback-function url-callback-arguments
))
697 ;; These unfortunately cannot be macros... please ignore them!
698 (defun url-http-idle-sentinel (proc why
)
699 "Remove this (now defunct) process PROC from the list of open connections."
700 (maphash (lambda (key val
)
702 (puthash key
(delq proc val
) url-http-open-connections
)))
703 url-http-open-connections
))
705 (defun url-http-end-of-document-sentinel (proc why
)
706 ;; Sentinel used for old HTTP/0.9 or connections we know are going
707 ;; to die as the 'end of document' notifier.
708 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
709 (process-buffer proc
))
710 (url-http-idle-sentinel proc why
)
712 (set-buffer (process-buffer proc
))
713 (goto-char (point-min))
714 (if (not (looking-at "HTTP/"))
715 ;; HTTP/0.9 just gets passed back no matter what
716 (url-http-activate-callback)
717 (if (url-http-parse-headers)
718 (url-http-activate-callback)))))
720 (defun url-http-simple-after-change-function (st nd length
)
721 ;; Function used when we do NOT know how long the document is going to be
722 ;; Just _very_ simple 'downloaded %d' type of info.
723 (declare (special url-http-end-of-headers
))
724 (url-lazy-message "Reading %s..." (url-pretty-length nd
)))
726 (defun url-http-content-length-after-change-function (st nd length
)
727 "Function used when we DO know how long the document is going to be.
728 More sophisticated percentage downloaded, etc.
729 Also does minimal parsing of HTTP headers and will actually cause
730 the callback to be triggered."
731 (declare (special url-current-object
732 url-http-end-of-headers
733 url-http-content-length
734 url-http-content-type
736 (if url-http-content-type
737 (url-display-percentage
738 "Reading [%s]... %s of %s (%d%%)"
739 (url-percentage (- nd url-http-end-of-headers
)
740 url-http-content-length
)
741 url-http-content-type
742 (url-pretty-length (- nd url-http-end-of-headers
))
743 (url-pretty-length url-http-content-length
)
744 (url-percentage (- nd url-http-end-of-headers
)
745 url-http-content-length
))
746 (url-display-percentage
747 "Reading... %s of %s (%d%%)"
748 (url-percentage (- nd url-http-end-of-headers
)
749 url-http-content-length
)
750 (url-pretty-length (- nd url-http-end-of-headers
))
751 (url-pretty-length url-http-content-length
)
752 (url-percentage (- nd url-http-end-of-headers
)
753 url-http-content-length
)))
755 (if (> (- nd url-http-end-of-headers
) url-http-content-length
)
757 ;; Found the end of the document! Wheee!
758 (url-display-percentage nil nil
)
759 (message "Reading... done.")
760 (if (url-http-parse-headers)
761 (url-http-activate-callback)))))
763 (defun url-http-chunked-encoding-after-change-function (st nd length
)
764 "Function used when dealing with 'chunked' encoding.
765 Cannot give a sophisticated percentage, but we need a different
766 function to look for the special 0-length chunk that signifies
767 the end of the document."
768 (declare (special url-current-object
769 url-http-end-of-headers
770 url-http-content-type
771 url-http-chunked-length
772 url-http-chunked-counter
773 url-http-process url-http-chunked-start
))
776 (let ((read-next-chunk t
)
779 (no-initial-crlf nil
))
780 ;; We need to loop thru looking for more chunks even within
781 ;; one after-change-function call.
782 (while read-next-chunk
783 (setq no-initial-crlf
(= 0 url-http-chunked-counter
))
784 (if url-http-content-type
785 (url-display-percentage nil
786 "Reading [%s]... chunk #%d"
787 url-http-content-type url-http-chunked-counter
)
788 (url-display-percentage nil
789 "Reading... chunk #%d"
790 url-http-chunked-counter
))
791 (url-http-debug "Reading chunk %d (%d %d %d)"
792 url-http-chunked-counter st nd length
)
793 (setq regexp
(if no-initial-crlf
794 "\\([0-9a-z]+\\).*\r?\n"
795 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
797 (if url-http-chunked-start
798 ;; We know how long the chunk is supposed to be, skip over
799 ;; leading crap if possible.
800 (if (> nd
(+ url-http-chunked-start url-http-chunked-length
))
802 (url-http-debug "Got to the end of chunk #%d!"
803 url-http-chunked-counter
)
804 (goto-char (+ url-http-chunked-start
805 url-http-chunked-length
)))
806 (url-http-debug "Still need %d bytes to hit end of chunk"
807 (- (+ url-http-chunked-start
808 url-http-chunked-length
)
810 (setq read-next-chunk nil
)))
811 (if (not read-next-chunk
)
812 (url-http-debug "Still spinning for next chunk...")
813 (if no-initial-crlf
(skip-chars-forward "\r\n"))
814 (if (not (looking-at regexp
))
816 ;; Must not have received the entirety of the chunk header,
817 ;; need to spin some more.
818 (url-http-debug "Did not see start of chunk @ %d!" (point))
819 (setq read-next-chunk nil
))
820 (add-text-properties (match-beginning 0) (match-end 0)
824 'face
(if (featurep 'xemacs
)
828 (setq url-http-chunked-length
(string-to-int (buffer-substring
832 url-http-chunked-counter
(1+ url-http-chunked-counter
)
833 url-http-chunked-start
(set-marker
834 (or url-http-chunked-start
837 ; (if (not url-http-debug)
838 (delete-region (match-beginning 0) (match-end 0));)
839 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
840 url-http-chunked-counter url-http-chunked-length
841 (marker-position url-http-chunked-start
))
842 (if (= 0 url-http-chunked-length
)
844 ;; Found the end of the document! Wheee!
845 (url-http-debug "Saw end of stream chunk!")
846 (setq read-next-chunk nil
)
847 (url-display-percentage nil nil
)
848 (goto-char (match-end 1))
849 (if (re-search-forward "^\r*$" nil t
)
850 (message "Saw end of trailers..."))
851 (if (url-http-parse-headers)
852 (url-http-activate-callback))))))))))
854 (defun url-http-wait-for-headers-change-function (st nd length
)
855 ;; This will wait for the headers to arrive and then splice in the
856 ;; next appropriate after-change-function, etc.
857 (declare (special url-current-object
858 url-http-end-of-headers
859 url-http-content-type
860 url-http-content-length
861 url-http-transfer-encoding
862 url-callback-function
863 url-callback-arguments
866 url-http-after-change-function
867 url-http-response-status
))
868 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
871 (let ((end-of-headers nil
)
873 (content-length nil
))
874 (goto-char (point-min))
875 (if (not (looking-at "^HTTP/[1-9]\\.[0-9]"))
876 ;; Not HTTP/x.y data, must be 0.9
877 ;; God, I wish this could die.
878 (setq end-of-headers t
879 url-http-end-of-headers
0
881 (if (re-search-forward "^\r*$" nil t
)
882 ;; Saw the end of the headers
884 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
885 (setq url-http-end-of-headers
(set-marker (make-marker)
888 (url-http-clean-headers))))
890 (if (not end-of-headers
)
891 ;; Haven't seen the end of the headers yet, need to wait
892 ;; for more data to arrive.
895 (message "HTTP/0.9 How I hate thee!")
897 (url-http-parse-response)
898 (mail-narrow-to-head)
899 ;;(narrow-to-region (point-min) url-http-end-of-headers)
900 (setq url-http-transfer-encoding
(mail-fetch-field
902 url-http-content-type
(mail-fetch-field "content-type"))
903 (if (mail-fetch-field "content-length")
904 (setq url-http-content-length
905 (string-to-int (mail-fetch-field "content-length"))))
907 (if url-http-transfer-encoding
908 (setq url-http-transfer-encoding
909 (downcase url-http-transfer-encoding
)))
912 ((or (= url-http-response-status
204)
913 (= url-http-response-status
205))
914 (url-http-debug "%d response must have headers only (%s)."
915 url-http-response-status
(buffer-name))
916 (if (url-http-parse-headers)
917 (url-http-activate-callback)))
918 ((string= "HEAD" url-http-method
)
919 ;; A HEAD request is _ALWAYS_ terminated by the header
920 ;; information, regardless of any entity headers,
921 ;; according to section 4.4 of the HTTP/1.1 draft.
922 (url-http-debug "HEAD request must have headers only (%s)."
924 (if (url-http-parse-headers)
925 (url-http-activate-callback)))
926 ((string= "CONNECT" url-http-method
)
927 ;; A CONNECT request is finished, but we cannot stick this
928 ;; back on the free connectin list
929 (url-http-debug "CONNECT request must have headers only.")
930 (if (url-http-parse-headers)
931 (url-http-activate-callback)))
932 ((equal url-http-response-status
304)
933 ;; Only allowed to have a header section. We have to handle
934 ;; this here instead of in url-http-parse-headers because if
935 ;; you have a cached copy of something without a known
936 ;; content-length, and try to retrieve it from the cache, we'd
937 ;; fall into the 'being dumb' section and wait for the
938 ;; connection to terminate, which means we'd wait for 10
939 ;; seconds for the keep-alives to time out on some servers.
940 (if (url-http-parse-headers)
941 (url-http-activate-callback)))
943 ;; HTTP/0.9 always signaled end-of-connection by closing the
946 "Saw HTTP/0.9 response, connection closed means end of document.")
947 (setq url-http-after-change-function
948 'url-http-simple-after-change-function
))
949 ((equal url-http-transfer-encoding
"chunked")
950 (url-http-debug "Saw chunked encoding.")
951 (setq url-http-after-change-function
952 'url-http-chunked-encoding-after-change-function
)
953 (if (> nd url-http-end-of-headers
)
956 "Calling initial chunked-encoding for extra data at end of headers")
957 (url-http-chunked-encoding-after-change-function
958 (marker-position url-http-end-of-headers
) nd
959 (- nd url-http-end-of-headers
)))))
960 ((integerp url-http-content-length
)
962 "Got a content-length, being smart about document end.")
963 (setq url-http-after-change-function
964 'url-http-content-length-after-change-function
)
966 ((= 0 url-http-content-length
)
967 ;; We got a NULL body! Activate the callback
970 "Got 0-length content-length, activating callback immediately.")
971 (if (url-http-parse-headers)
972 (url-http-activate-callback)))
973 ((> nd url-http-end-of-headers
)
974 ;; Have some leftover data
975 (url-http-debug "Calling initial content-length for extra data at end of headers")
976 (url-http-content-length-after-change-function
977 (marker-position url-http-end-of-headers
)
979 (- nd url-http-end-of-headers
)))
983 (url-http-debug "No content-length, being dumb.")
984 (setq url-http-after-change-function
985 'url-http-simple-after-change-function
)))))
986 ;; We are still at the beginning of the buffer... must just be
987 ;; waiting for a response.
988 (url-http-debug "Spinning waiting for headers..."))
989 (goto-char (point-max)))
992 (defun url-http (url callback cbargs
)
993 "Retrieve URL via HTTP asynchronously.
994 URL must be a parsed URL. See `url-generic-parse-url' for details.
995 When retrieval is completed, the function CALLBACK is executed with
996 CBARGS as the arguments."
997 (check-type url vector
"Need a pre-parsed URL.")
998 (declare (special url-current-object
999 url-http-end-of-headers
1000 url-http-content-type
1001 url-http-content-length
1002 url-http-transfer-encoding
1003 url-http-after-change-function
1004 url-callback-function
1005 url-callback-arguments
1007 url-http-extra-headers
1009 url-http-chunked-length
1010 url-http-chunked-start
1011 url-http-chunked-counter
1013 (let ((connection (url-http-find-free-connection (url-host url
)
1015 (buffer (generate-new-buffer (format " *http %s:%d*"
1018 (if (not connection
)
1019 ;; Failed to open the connection for some reason
1021 (kill-buffer buffer
)
1023 (error "Could not create connection to %s:%d" (url-host url
)
1027 (mm-disable-multibyte)
1028 (setq url-current-object url
1029 mode-line-format
"%b [%s]")
1031 (dolist (var '(url-http-end-of-headers
1032 url-http-content-type
1033 url-http-content-length
1034 url-http-transfer-encoding
1035 url-http-after-change-function
1036 url-http-response-status
1037 url-http-chunked-length
1038 url-http-chunked-counter
1039 url-http-chunked-start
1040 url-callback-function
1041 url-callback-arguments
1044 url-http-extra-headers
1046 (set (make-local-variable var
) nil
))
1048 (setq url-http-method
(or url-request-method
"GET")
1049 url-http-extra-headers url-request-extra-headers
1050 url-http-data url-request-data
1051 url-http-process connection
1052 url-http-chunked-length nil
1053 url-http-chunked-start nil
1054 url-http-chunked-counter
0
1055 url-callback-function callback
1056 url-callback-arguments cbargs
1057 url-http-after-change-function
'url-http-wait-for-headers-change-function
)
1059 (set-process-buffer connection buffer
)
1060 (set-process-sentinel connection
'url-http-end-of-document-sentinel
)
1061 (set-process-filter connection
'url-http-generic-filter
)
1062 (process-send-string connection
(url-http-create-request url
))))
1065 ;; Since Emacs 19/20 does not allow you to change the
1066 ;; `after-change-functions' hook in the midst of running them, we fake
1067 ;; an after change by hooking into the process filter and inserting
1068 ;; the data ourselves. This is slightly less efficient, but there
1069 ;; were tons of weird ways the after-change code was biting us in the
1071 (defun url-http-generic-filter (proc data
)
1072 ;; Sometimes we get a zero-length data chunk after the process has
1073 ;; been changed to 'free', which means it has no buffer associated
1074 ;; with it. Do nothing if there is no buffer, or 0 length data.
1075 (declare (special url-http-after-change-function
))
1076 (and (process-buffer proc
)
1077 (/= (length data
) 0)
1079 (set-buffer (process-buffer proc
))
1080 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc
)
1081 (funcall url-http-after-change-function
1084 (goto-char (point-max))
1089 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1090 ;;; file-name-handler stuff from here on out
1091 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1092 (if (not (fboundp 'symbol-value-in-buffer
))
1093 (defun url-http-symbol-value-in-buffer (symbol buffer
1094 &optional unbound-value
)
1095 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1098 (if (not (boundp symbol
))
1100 (symbol-value symbol
))))
1101 (defalias 'url-http-symbol-value-in-buffer
'symbol-value-in-buffer
))
1103 (defun url-http-head (url)
1104 (let ((url-request-method "HEAD")
1105 (url-request-data nil
))
1106 (url-retrieve-synchronously url
)))
1109 (defun url-http-file-exists-p (url)
1112 (buffer (url-http-head url
)))
1115 (setq status
(url-http-symbol-value-in-buffer 'url-http-response-status
1117 exists
(and (>= status
200) (< status
300)))
1118 (kill-buffer buffer
))
1122 (defalias 'url-http-file-readable-p
'url-http-file-exists-p
)
1124 (defun url-http-head-file-attributes (url &optional id-format
)
1125 (let ((buffer (url-http-head url
))
1128 (setq attributes
(make-list 11 nil
))
1129 (setf (nth 1 attributes
) 1) ; Number of links to file
1130 (setf (nth 2 attributes
) 0) ; file uid
1131 (setf (nth 3 attributes
) 0) ; file gid
1132 (setf (nth 7 attributes
) ; file size
1133 (url-http-symbol-value-in-buffer 'url-http-content-length
1135 (setf (nth 8 attributes
) (eval-when-compile (make-string 10 ?-
)))
1136 (kill-buffer buffer
))
1140 (defun url-http-file-attributes (url &optional id-format
)
1141 (if (url-dav-supported-p url
)
1142 (url-dav-file-attributes url id-format
)
1143 (url-http-head-file-attributes url id-format
)))
1146 (defun url-http-options (url)
1147 "Returns a property list describing options available for URL.
1148 This list is retrieved using the `OPTIONS' HTTP method.
1150 Property list members:
1153 A list of symbols specifying what HTTP methods the resource
1157 A list of numbers specifying what DAV protocol/schema versions are
1161 A list of supported DASL search types supported (string form)
1164 A list of the units available for use in partial document fetches.
1167 The `Platform For Privacy Protection' description for the resource.
1168 Currently this is just the raw header contents. This is likely to
1169 change once P3P is formally supported by the URL package or
1172 (let* ((url-request-method "OPTIONS")
1173 (url-request-data nil
)
1174 (buffer (url-retrieve-synchronously url
))
1177 (when (and buffer
(= 2 (/ (url-http-symbol-value-in-buffer
1178 'url-http-response-status buffer
0) 100)))
1179 ;; Only parse the options if we got a 2xx response code!
1184 (mail-narrow-to-head)
1186 ;; Figure out what methods are supported.
1187 (when (setq header
(mail-fetch-field "allow"))
1188 (setq options
(plist-put
1190 (mapcar 'intern
(split-string header
"[ ,]+")))))
1193 (when (setq header
(mail-fetch-field "dav"))
1194 (setq options
(plist-put
1197 (mapcar 'string-to-number
1198 (split-string header
"[, ]+"))))))
1201 (when (setq header
(mail-fetch-field "dasl"))
1202 (setq options
(plist-put
1204 (split-string header
"[, ]+"))))
1206 ;; P3P - should get more detailed here. FIXME
1207 (when (setq header
(mail-fetch-field "p3p"))
1208 (setq options
(plist-put options
'p3p header
)))
1210 ;; Check for whether they accept byte-range requests.
1211 (when (setq header
(mail-fetch-field "accept-ranges"))
1212 (setq options
(plist-put
1216 (split-string header
"[, ]+"))))))
1218 (if buffer
(kill-buffer buffer
))
1223 ;; arch-tag: ba7c59ae-c0f4-4a31-9617-d85f221732ee
1224 ;;; url-http.el ends here