(Vimage_library_alist): Moved from image.el.
[emacs.git] / lisp / url / url-http.el
blob16d51a0258c55d7cc781c6bbe24d2400ecfacacc
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.
9 ;;
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)
13 ;; any later version.
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.
25 ;;; Commentary:
27 ;;; Code:
29 (eval-when-compile
30 (require 'cl)
31 (defvar url-http-extra-headers))
32 (require 'url-gw)
33 (require 'url-util)
34 (require 'url-parse)
35 (require 'url-cookie)
36 (require 'mail-parse)
37 (require 'url-auth)
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
51 :size 17)
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
67 request.
70 ;(eval-when-compile
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
77 ;; connections.
78 (defsubst url-http-debug (&rest args)
79 (if quit-flag
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)
83 (if proc
84 (progn
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)
95 proc)
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)
104 nil)
106 (defun url-http-find-free-connection (host port)
107 (let ((conns (gethash (cons host port) url-http-open-connections))
108 (found nil))
109 (while (and conns (not found))
110 (if (not (memq (process-status (car conns)) '(run open)))
111 (progn
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))
117 (pop conns))
118 (if 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
123 (or found
124 (url-open-stream host nil host
125 port)))))
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"
134 (if url-package-name
135 (concat url-package-name "/" url-package-version " ")
137 url-version
138 (cond
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) ")"))
143 (t "")))))
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)
149 (request nil)
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))
154 (not proxy-obj))
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)
160 (url-filename url)))
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)
166 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)))
171 (if auth
172 (setq auth (concat "Authorization: " auth "\r\n")))
173 (if proxy-auth
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 "")))
179 (setq ref-url nil))
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)))
185 (setq ref-url nil))
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
190 (lambda (x)
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.
200 (setq request
201 (concat
202 ;; The request
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
212 (format
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))
218 (format
219 "Host: %s:%d\r\n" host (url-port (or proxy-obj url)))
220 (format "Host: %s\r\n" host))
221 ;; Who its from
222 (if url-personal-mail-address
223 (concat
224 "From: " url-personal-mail-address "\r\n"))
225 ;; Encodings we understand
226 (if url-mime-encoding-string
227 (concat
228 "Accept-encoding: " url-mime-encoding-string "\r\n"))
229 (if url-mime-charset-string
230 (concat
231 "Accept-charset: " url-mime-charset-string "\r\n"))
232 ;; Languages we understand
233 (if url-mime-language-string
234 (concat
235 "Accept-language: " url-mime-language-string "\r\n"))
236 ;; Types we understand
237 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
238 ;; User agent
239 (url-http-user-agent-string)
240 ;; Proxy Authorization
241 proxy-auth
242 ;; Authorization
243 auth
244 ;; Cookies
245 (url-cookie-generate-header-lines host real-fname
246 (equal "https" (url-type url)))
247 ;; If-modified-since
248 (if (and (not no-cache)
249 (member url-request-method '("GET" nil)))
250 (let ((tm (url-is-cached (or proxy-obj url))))
251 (if tm
252 (concat "If-modified-since: "
253 (url-get-normalized-date tm) "\r\n"))))
254 ;; Whence we came
255 (if ref-url (concat
256 "Referer: " ref-url "\r\n"))
257 extra-headers
258 ;; Length of data
259 (if url-request-data
260 (concat
261 "Content-length: " (number-to-string
262 (length url-request-data))
263 "\r\n"))
264 ;; End request
265 "\r\n"
266 ;; Any data
267 url-request-data))
268 (url-http-debug "Request is: \n%s" request)
269 request))
271 ;; Parsing routines
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)
278 (replace-match "")))
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"))
285 "basic"))
286 (type nil)
287 (url (url-recreate-url url-current-object))
288 (url-basic-auth-storage 'url-http-real-basic-auth-storage)
291 ;; Cheating, but who cares? :)
292 (if proxy
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))
301 (progn
302 (widen)
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>")
307 (setq status t))
308 (let* ((args auth)
309 (ctr (1- (length args)))
310 auth)
311 (while (/= 0 ctr)
312 (if (char-equal ?, (aref args ctr))
313 (aset args ctr ?\;))
314 (setq ctr (1- ctr)))
315 (setq args (url-parse-args args)
316 auth (url-get-authentication url (cdr-safe (assoc "realm" args))
317 type t args))
318 (if (not auth)
319 (setq success t)
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
343 work correctly."
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)))
349 (while cookies
350 (url-cookie-handle-set-cookie (pop cookies)))
351 ;;; (while cookies2
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
361 ;; 2616 (HTTP/1.1)
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)
368 url-http-process)
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)
378 (let ((class nil)
379 (success nil))
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)
384 (case class
385 ;; Classes of response codes
387 ;; 5xx = Server Error
388 ;; 4xx = Client Error
389 ;; 3xx = Redirection
390 ;; 2xx = Successful
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))
398 (2 ; Success
399 ;; 200 Ok
400 ;; 201 Created
401 ;; 202 Accepted
402 ;; 203 Non-authoritative information
403 ;; 204 No content
404 ;; 205 Reset content
405 ;; 206 Partial content
406 ;; 207 Multi-status (Added by DAV)
407 (case url-http-response-status
408 ((204 205)
409 ;; No new data, just stay at the same document
410 (url-mark-buffer-as-dead (current-buffer))
411 (setq success t))
412 (otherwise
413 ;; Generic success for all others. Store in the cache, and
414 ;; mark it as successful.
415 (widen)
416 (if (and url-automatic-caching (equal url-http-method "GET"))
417 (url-store-in-cache (current-buffer)))
418 (setq success t))))
419 (3 ; Redirection
420 ;; 300 Multiple choices
421 ;; 301 Moved permanently
422 ;; 302 Found
423 ;; 303 See other
424 ;; 304 Not modified
425 ;; 305 Use proxy
426 ;; 307 Temporary redirect
427 (let ((redirect-uri (or (mail-fetch-field "Location")
428 (mail-fetch-field "URI"))))
429 (case url-http-response-status
430 (300
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.
438 ;; [...]
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.
446 nil)
447 ((301 302 307)
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"
462 url-http-data nil)))
463 (303
464 ;; The response to the request can be found under a different
465 ;; URI and SHOULD be retrieved using a GET method on that
466 ;; resource.
467 (setq url-http-method "GET"
468 url-http-data nil))
469 (304
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
475 success t))
476 (305
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"
483 redirect-uri))
484 (otherwise
485 ;; Treat everything like '300'
486 nil))
487 (when redirect-uri
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
496 ;; the URL library.
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))))))
505 (4 ; Client error
506 ;; 400 Bad Request
507 ;; 401 Unauthorized
508 ;; 402 Payment required
509 ;; 403 Forbidden
510 ;; 404 Not found
511 ;; 405 Method not allowed
512 ;; 406 Not acceptable
513 ;; 407 Proxy authentication required
514 ;; 408 Request time-out
515 ;; 409 Conflict
516 ;; 410 Gone
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)
525 ;; 423 Locked
526 ;; 424 Failed Dependency
527 (case url-http-response-status
528 (401
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))
535 (402
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"))
539 (403
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.
543 (setq success t))
544 (404
545 ;; Not found
546 (setq success t))
547 (405
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.
552 (setq success t))
553 (406
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.
558 (setq success t))
559 (407
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))
566 (408
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.
570 (setq success t))
571 (409
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
578 ;; conflict.
579 (setq success t))
580 (410
581 ;; The requested resource is no longer available at the
582 ;; server and no forwarding address is known.
583 (setq success t))
584 (411
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
592 ;; content-length.
593 (setq success t))
594 (412
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.
598 (setq success t))
599 ((413 414)
600 ;; The server is refusing to process a request because the
601 ;; request entity|URI is larger than the server is willing or
602 ;; able to process.
603 (setq success t))
604 (415
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.
608 (setq success t))
609 (416
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.
615 (setq success t))
616 (417
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.
621 (setq success t))
622 (otherwise
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.
626 (setq success t))))
628 ;; 500 Internal server error
629 ;; 501 Not implemented
630 ;; 502 Bad gateway
631 ;; 503 Service unavailable
632 ;; 504 Gateway time-out
633 ;; 505 HTTP version not supported
634 ;; 507 Insufficient storage
635 (setq success t)
636 (case url-http-response-status
637 (501
638 ;; The server does not support the functionality required to
639 ;; fulfill the request.
640 nil)
641 (502
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.
645 nil)
646 (503
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.
654 nil)
655 (504
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.
661 nil)
662 (505
663 ;; The server does not support, or refuses to support, the
664 ;; HTTP protocol version that was used in the request
665 ;; message.
666 nil)
667 (507 ; DAV
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.
675 nil)))
676 (otherwise
677 (error "Unknown class of HTTP response code: %d (%d)"
678 class url-http-response-status)))
679 (if (not success)
680 (url-mark-buffer-as-dead (current-buffer)))
681 (url-http-debug "Finished parsing HTTP headers: %S" success)
682 (widen)
683 success))
685 ;; Miscellaneous
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)
693 url-http-process)
694 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
695 (apply url-callback-function url-callback-arguments))
697 ;; )
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)
703 (if (memq proc 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)
713 (save-excursion
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
737 url-http-process))
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)
758 (progn
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))
776 (save-excursion
777 (goto-char st)
778 (let ((read-next-chunk t)
779 (case-fold-search t)
780 (regexp nil)
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))
803 (progn
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)
811 nd))
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))
817 (progn
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)
823 (list 'start-open t
824 'end-open t
825 'chunked-encoding t
826 'face (if (featurep 'xemacs)
827 'text-cursor
828 'cursor)
829 'invisible t))
830 (setq url-http-chunked-length (string-to-number (buffer-substring
831 (match-beginning 1)
832 (match-end 1))
834 url-http-chunked-counter (1+ url-http-chunked-counter)
835 url-http-chunked-start (set-marker
836 (or url-http-chunked-start
837 (make-marker))
838 (match-end 0)))
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)
845 (progn
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
866 url-http-process
867 url-http-method
868 url-http-after-change-function
869 url-http-response-status))
870 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
871 (buffer-name))
872 (if (not (bobp))
873 (let ((end-of-headers nil)
874 (old-http 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
882 old-http t)
883 (if (re-search-forward "^\r*$" nil t)
884 ;; Saw the end of the headers
885 (progn
886 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
887 (setq url-http-end-of-headers (set-marker (make-marker)
888 (point))
889 end-of-headers t)
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.
896 (if old-http
897 (message "HTTP/0.9 How I hate thee!")
898 (progn
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
903 "transfer-encoding")
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"))))
908 (widen)))
909 (if url-http-transfer-encoding
910 (setq url-http-transfer-encoding
911 (downcase url-http-transfer-encoding)))
913 (cond
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)."
925 (buffer-name))
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)))
944 (old-http
945 ;; HTTP/0.9 always signaled end-of-connection by closing the
946 ;; connection.
947 (url-http-debug
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)
956 (progn
957 (url-http-debug
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)
963 (url-http-debug
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)
967 (cond
968 ((= 0 url-http-content-length)
969 ;; We got a NULL body! Activate the callback
970 ;; immediately!
971 (url-http-debug
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)))
983 nil)))
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)))
993 ;;;###autoload
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
1008 url-http-method
1009 url-http-extra-headers
1010 url-http-data
1011 url-http-chunked-length
1012 url-http-chunked-start
1013 url-http-chunked-counter
1014 url-http-process))
1015 (let ((connection (url-http-find-free-connection (url-host url)
1016 (url-port url)))
1017 (buffer (generate-new-buffer (format " *http %s:%d*"
1018 (url-host url)
1019 (url-port url)))))
1020 (if (not connection)
1021 ;; Failed to open the connection for some reason
1022 (progn
1023 (kill-buffer buffer)
1024 (setq buffer nil)
1025 (error "Could not create connection to %s:%d" (url-host url)
1026 (url-port url)))
1027 (save-excursion
1028 (set-buffer buffer)
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
1044 url-http-process
1045 url-http-method
1046 url-http-extra-headers
1047 url-http-data
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)
1062 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))))
1069 buffer))
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
1076 ;; shorts.
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)
1084 (save-excursion
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
1088 (point-max)
1089 (progn
1090 (goto-char (point-max))
1091 (insert data)
1092 (point-max))
1093 (length data)))))
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."
1102 (save-excursion
1103 (set-buffer buffer)
1104 (if (not (boundp symbol))
1105 unbound-value
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)))
1114 ;;;###autoload
1115 (defun url-http-file-exists-p (url)
1116 (let ((status nil)
1117 (exists nil)
1118 (buffer (url-http-head url)))
1119 (if (not buffer)
1120 (setq exists nil)
1121 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1122 buffer 500)
1123 exists (and (>= status 200) (< status 300)))
1124 (kill-buffer buffer))
1125 exists))
1127 ;;;###autoload
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))
1132 (attributes nil))
1133 (when buffer
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
1140 buffer -1))
1141 (setf (nth 8 attributes) (eval-when-compile (make-string 10 ?-)))
1142 (kill-buffer buffer))
1143 attributes))
1145 ;;;###autoload
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)))
1151 ;;;###autoload
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:
1158 methods
1159 A list of symbols specifying what HTTP methods the resource
1160 supports.
1163 A list of numbers specifying what DAV protocol/schema versions are
1164 supported.
1166 dasl
1167 A list of supported DASL search types supported (string form)
1169 ranges
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
1176 Emacs/W3.
1178 (let* ((url-request-method "OPTIONS")
1179 (url-request-data nil)
1180 (buffer (url-retrieve-synchronously url))
1181 (header nil)
1182 (options nil))
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!
1186 (save-excursion
1187 (save-restriction
1188 (save-match-data
1189 (set-buffer buffer)
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
1195 options 'methods
1196 (mapcar 'intern (split-string header "[ ,]+")))))
1198 ;; Check for DAV
1199 (when (setq header (mail-fetch-field "dav"))
1200 (setq options (plist-put
1201 options 'dav
1202 (delq 0
1203 (mapcar 'string-to-number
1204 (split-string header "[, ]+"))))))
1206 ;; Now for DASL
1207 (when (setq header (mail-fetch-field "dasl"))
1208 (setq options (plist-put
1209 options 'dasl
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
1219 options 'ranges
1220 (delq 'none
1221 (mapcar 'intern
1222 (split-string header "[, ]+"))))))
1223 ))))
1224 (if buffer (kill-buffer buffer))
1225 options))
1227 (provide 'url-http)
1229 ;; arch-tag: ba7c59ae-c0f4-4a31-9617-d85f221732ee
1230 ;;; url-http.el ends here