* fileio.c: Fix bugs with large file offsets.
[emacs.git] / lisp / url / url-http.el
bloba21aed21436ffd3aaf9a5b3d4b190d820897bf55
1 ;;; url-http.el --- HTTP retrieval routines
3 ;; Copyright (C) 1999, 2001, 2004-2011 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 3 of the License, or
13 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;;; Code:
27 (eval-when-compile (require 'cl))
28 (defvar url-http-extra-headers)
29 (defvar url-http-target-url)
30 (defvar url-http-proxy)
31 (defvar url-http-connection-opened)
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 (require 'url)
39 (autoload 'url-cache-create-filename "url-cache")
41 (defconst url-http-default-port 80 "Default HTTP port.")
42 (defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
43 (defalias 'url-http-expand-file-name 'url-default-expander)
45 (defvar url-http-real-basic-auth-storage nil)
46 (defvar url-http-proxy-basic-auth-storage nil)
48 (defvar url-http-open-connections (make-hash-table :test 'equal
49 :size 17)
50 "A hash table of all open network connections.")
52 (defvar url-http-version "1.1"
53 "What version of HTTP we advertise, as a string.
54 Valid values are 1.1 and 1.0.
55 This is only useful when debugging the HTTP subsystem.
57 Setting this to 1.0 will tell servers not to send chunked encoding,
58 and other HTTP/1.1 specific features.")
60 (defvar url-http-attempt-keepalives t
61 "Whether to use a single TCP connection multiple times in HTTP.
62 This is only useful when debugging the HTTP subsystem. Setting to
63 nil will explicitly close the connection to the server after every
64 request.")
66 (defconst url-http-codes
67 '((100 continue "Continue with request")
68 (101 switching-protocols "Switching protocols")
69 (102 processing "Processing (Added by DAV)")
70 (200 OK "OK")
71 (201 created "Created")
72 (202 accepted "Accepted")
73 (203 non-authoritative "Non-authoritative information")
74 (204 no-content "No content")
75 (205 reset-content "Reset content")
76 (206 partial-content "Partial content")
77 (207 multi-status "Multi-status (Added by DAV)")
78 (300 multiple-choices "Multiple choices")
79 (301 moved-permanently "Moved permanently")
80 (302 found "Found")
81 (303 see-other "See other")
82 (304 not-modified "Not modified")
83 (305 use-proxy "Use proxy")
84 (307 temporary-redirect "Temporary redirect")
85 (400 bad-request "Bad Request")
86 (401 unauthorized "Unauthorized")
87 (402 payment-required "Payment required")
88 (403 forbidden "Forbidden")
89 (404 not-found "Not found")
90 (405 method-not-allowed "Method not allowed")
91 (406 not-acceptable "Not acceptable")
92 (407 proxy-authentication-required "Proxy authentication required")
93 (408 request-timeout "Request time-out")
94 (409 conflict "Conflict")
95 (410 gone "Gone")
96 (411 length-required "Length required")
97 (412 precondition-failed "Precondition failed")
98 (413 request-entity-too-large "Request entity too large")
99 (414 request-uri-too-large "Request-URI too large")
100 (415 unsupported-media-type "Unsupported media type")
101 (416 requested-range-not-satisfiable "Requested range not satisfiable")
102 (417 expectation-failed "Expectation failed")
103 (422 unprocessable-entity "Unprocessable Entity (Added by DAV)")
104 (423 locked "Locked")
105 (424 failed-Dependency "Failed Dependency")
106 (500 internal-server-error "Internal server error")
107 (501 not-implemented "Not implemented")
108 (502 bad-gateway "Bad gateway")
109 (503 service-unavailable "Service unavailable")
110 (504 gateway-timeout "Gateway time-out")
111 (505 http-version-not-supported "HTTP version not supported")
112 (507 insufficient-storage "Insufficient storage")
113 "The HTTP return codes and their text."))
115 ;(eval-when-compile
116 ;; These are all macros so that they are hidden from external sight
117 ;; when the file is byte-compiled.
119 ;; This allows us to expose just the entry points we want.
121 ;; These routines will allow us to implement persistent HTTP
122 ;; connections.
123 (defsubst url-http-debug (&rest args)
124 (if quit-flag
125 (let ((proc (get-buffer-process (current-buffer))))
126 ;; The user hit C-g, honor it! Some things can get in an
127 ;; incredibly tight loop (chunked encoding)
128 (if proc
129 (progn
130 (set-process-sentinel proc nil)
131 (set-process-filter proc nil)))
132 (error "Transfer interrupted!")))
133 (apply 'url-debug 'http args))
135 (defun url-http-mark-connection-as-busy (host port proc)
136 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
137 (set-process-query-on-exit-flag proc t)
138 (puthash (cons host port)
139 (delq proc (gethash (cons host port) url-http-open-connections))
140 url-http-open-connections)
141 proc)
143 (defun url-http-mark-connection-as-free (host port proc)
144 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
145 (when (memq (process-status proc) '(open run connect))
146 (set-process-buffer proc nil)
147 (set-process-sentinel proc 'url-http-idle-sentinel)
148 (set-process-query-on-exit-flag proc nil)
149 (puthash (cons host port)
150 (cons proc (gethash (cons host port) url-http-open-connections))
151 url-http-open-connections))
152 nil)
154 (defun url-http-find-free-connection (host port)
155 (let ((conns (gethash (cons host port) url-http-open-connections))
156 (found nil))
157 (while (and conns (not found))
158 (if (not (memq (process-status (car conns)) '(run open connect)))
159 (progn
160 (url-http-debug "Cleaning up dead process: %s:%d %S"
161 host port (car conns))
162 (url-http-idle-sentinel (car conns) nil))
163 (setq found (car conns))
164 (url-http-debug "Found existing connection: %s:%d %S" host port found))
165 (pop conns))
166 (if found
167 (url-http-debug "Reusing existing connection: %s:%d" host port)
168 (url-http-debug "Contacting host: %s:%d" host port))
169 (url-lazy-message "Contacting host: %s:%d" host port)
170 (url-http-mark-connection-as-busy
171 host port
172 (or found
173 (let ((buf (generate-new-buffer " *url-http-temp*")))
174 ;; `url-open-stream' needs a buffer in which to do things
175 ;; like authentication. But we use another buffer afterwards.
176 (unwind-protect
177 (let ((proc (url-open-stream host buf host port)))
178 ;; url-open-stream might return nil.
179 (when (processp proc)
180 ;; Drop the temp buffer link before killing the buffer.
181 (set-process-buffer proc nil))
182 proc)
183 (kill-buffer buf)))))))
185 ;; Building an HTTP request
186 (defun url-http-user-agent-string ()
187 (if (or (eq url-privacy-level 'paranoid)
188 (and (listp url-privacy-level)
189 (memq 'agent url-privacy-level)))
191 (format "User-Agent: %sURL/%s%s\r\n"
192 (if url-package-name
193 (concat url-package-name "/" url-package-version " ")
195 url-version
196 (cond
197 ((and url-os-type url-system-type)
198 (concat " (" url-os-type "; " url-system-type ")"))
199 ((or url-os-type url-system-type)
200 (concat " (" (or url-system-type url-os-type) ")"))
201 (t "")))))
203 (defun url-http-create-request (&optional ref-url)
204 "Create an HTTP request for `url-http-target-url', referred to by REF-URL."
205 (declare (special proxy-info
206 url-http-method url-http-data
207 url-http-extra-headers))
208 (let* ((extra-headers)
209 (request nil)
210 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
211 (using-proxy url-http-proxy)
212 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
213 url-http-extra-headers))
214 (not using-proxy))
216 (let ((url-basic-auth-storage
217 'url-http-proxy-basic-auth-storage))
218 (url-get-authentication url-http-target-url nil 'any nil))))
219 (real-fname (concat (url-filename url-http-target-url)
220 (url-recreate-url-attributes url-http-target-url)))
221 (host (url-host url-http-target-url))
222 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers))
224 (url-get-authentication (or
225 (and (boundp 'proxy-info)
226 proxy-info)
227 url-http-target-url) nil 'any nil))))
228 (if (equal "" real-fname)
229 (setq real-fname "/"))
230 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
231 (if auth
232 (setq auth (concat "Authorization: " auth "\r\n")))
233 (if proxy-auth
234 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
236 ;; Protection against stupid values in the referer
237 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
238 (string= ref-url "")))
239 (setq ref-url nil))
241 ;; We do not want to expose the referer if the user is paranoid.
242 (if (or (memq url-privacy-level '(low high paranoid))
243 (and (listp url-privacy-level)
244 (memq 'lastloc url-privacy-level)))
245 (setq ref-url nil))
247 ;; url-http-extra-headers contains an assoc-list of
248 ;; header/value pairs that we need to put into the request.
249 (setq extra-headers (mapconcat
250 (lambda (x)
251 (concat (car x) ": " (cdr x)))
252 url-http-extra-headers "\r\n"))
253 (if (not (equal extra-headers ""))
254 (setq extra-headers (concat extra-headers "\r\n")))
256 ;; This was done with a call to `format'. Concatting parts has
257 ;; the advantage of keeping the parts of each header together and
258 ;; allows us to elide null lines directly, at the cost of making
259 ;; the layout less clear.
260 (setq request
261 ;; We used to concat directly, but if one of the strings happens
262 ;; to being multibyte (even if it only contains pure ASCII) then
263 ;; every string gets converted with `string-MAKE-multibyte' which
264 ;; turns the 127-255 codes into things like latin-1 accented chars
265 ;; (it would work right if it used `string-TO-multibyte' instead).
266 ;; So to avoid the problem we force every string to be unibyte.
267 (mapconcat
268 ;; FIXME: Instead of `string-AS-unibyte' we'd want
269 ;; `string-to-unibyte', so as to properly signal an error if one
270 ;; of the strings contains a multibyte char.
271 'string-as-unibyte
272 (delq nil
273 (list
274 ;; The request
275 (or url-http-method "GET") " "
276 (if using-proxy (url-recreate-url url-http-target-url) real-fname)
277 " HTTP/" url-http-version "\r\n"
278 ;; Version of MIME we speak
279 "MIME-Version: 1.0\r\n"
280 ;; (maybe) Try to keep the connection open
281 "Connection: " (if (or using-proxy
282 (not url-http-attempt-keepalives))
283 "close" "keep-alive") "\r\n"
284 ;; HTTP extensions we support
285 (if url-extensions-header
286 (format
287 "Extension: %s\r\n" url-extensions-header))
288 ;; Who we want to talk to
289 (if (/= (url-port url-http-target-url)
290 (url-scheme-get-property
291 (url-type url-http-target-url) 'default-port))
292 (format
293 "Host: %s:%d\r\n" host (url-port url-http-target-url))
294 (format "Host: %s\r\n" host))
295 ;; Who its from
296 (if url-personal-mail-address
297 (concat
298 "From: " url-personal-mail-address "\r\n"))
299 ;; Encodings we understand
300 (if url-mime-encoding-string
301 (concat
302 "Accept-encoding: " url-mime-encoding-string "\r\n"))
303 (if url-mime-charset-string
304 (concat
305 "Accept-charset: " url-mime-charset-string "\r\n"))
306 ;; Languages we understand
307 (if url-mime-language-string
308 (concat
309 "Accept-language: " url-mime-language-string "\r\n"))
310 ;; Types we understand
311 "Accept: " (or url-mime-accept-string "*/*") "\r\n"
312 ;; User agent
313 (url-http-user-agent-string)
314 ;; Proxy Authorization
315 proxy-auth
316 ;; Authorization
317 auth
318 ;; Cookies
319 (url-cookie-generate-header-lines host real-fname
320 (equal "https" (url-type url-http-target-url)))
321 ;; If-modified-since
322 (if (and (not no-cache)
323 (member url-http-method '("GET" nil)))
324 (let ((tm (url-is-cached url-http-target-url)))
325 (if tm
326 (concat "If-modified-since: "
327 (url-get-normalized-date tm) "\r\n"))))
328 ;; Whence we came
329 (if ref-url (concat
330 "Referer: " ref-url "\r\n"))
331 extra-headers
332 ;; Length of data
333 (if url-http-data
334 (concat
335 "Content-length: " (number-to-string
336 (length url-http-data))
337 "\r\n"))
338 ;; End request
339 "\r\n"
340 ;; Any data
341 url-http-data))
342 ""))
343 (url-http-debug "Request is: \n%s" request)
344 request))
346 ;; Parsing routines
347 (defun url-http-clean-headers ()
348 "Remove trailing \r from header lines.
349 This allows us to use `mail-fetch-field', etc."
350 (declare (special url-http-end-of-headers))
351 (goto-char (point-min))
352 (while (re-search-forward "\r$" url-http-end-of-headers t)
353 (replace-match "")))
355 (defun url-http-handle-authentication (proxy)
356 (declare (special status success url-http-method url-http-data
357 url-callback-function url-callback-arguments))
358 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
359 (let ((auths (or (nreverse
360 (mail-fetch-field
361 (if proxy "proxy-authenticate" "www-authenticate")
362 nil nil t))
363 '("basic")))
364 (type nil)
365 (url (url-recreate-url url-current-object))
366 (auth-url (url-recreate-url
367 (if (and proxy (boundp 'url-http-proxy))
368 url-http-proxy
369 url-current-object)))
370 (url-basic-auth-storage (if proxy
371 ;; Cheating, but who cares? :)
372 'url-http-proxy-basic-auth-storage
373 'url-http-real-basic-auth-storage))
374 auth
375 (strength 0))
377 ;; find strongest supported auth
378 (dolist (this-auth auths)
379 (setq this-auth (url-eat-trailing-space
380 (url-strip-leading-spaces
381 this-auth)))
382 (let* ((this-type
383 (if (string-match "[ \t]" this-auth)
384 (downcase (substring this-auth 0 (match-beginning 0)))
385 (downcase this-auth)))
386 (registered (url-auth-registered this-type))
387 (this-strength (cddr registered)))
388 (when (and registered (> this-strength strength))
389 (setq auth this-auth
390 type this-type
391 strength this-strength))))
393 (if (not (url-auth-registered type))
394 (progn
395 (widen)
396 (goto-char (point-max))
397 (insert "<hr>Sorry, but I do not know how to handle " type
398 " authentication. If you'd like to write it,"
399 " send it to " url-bug-address ".<hr>")
400 (setq status t))
401 (let* ((args (url-parse-args (subst-char-in-string ?, ?\; auth)))
402 (auth (url-get-authentication auth-url
403 (cdr-safe (assoc "realm" args))
404 type t args)))
405 (if (not auth)
406 (setq success t)
407 (push (cons (if proxy "Proxy-Authorization" "Authorization") auth)
408 url-http-extra-headers)
409 (let ((url-request-method url-http-method)
410 (url-request-data url-http-data)
411 (url-request-extra-headers url-http-extra-headers))
412 (url-retrieve-internal url url-callback-function
413 url-callback-arguments)))))))
415 (defun url-http-parse-response ()
416 "Parse just the response code."
417 (declare (special url-http-end-of-headers url-http-response-status
418 url-http-response-version))
419 (if (not url-http-end-of-headers)
420 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
421 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
422 (goto-char (point-min))
423 (skip-chars-forward " \t\n") ; Skip any blank crap
424 (skip-chars-forward "HTTP/") ; Skip HTTP Version
425 (setq url-http-response-version
426 (buffer-substring (point)
427 (progn
428 (skip-chars-forward "[0-9].")
429 (point))))
430 (setq url-http-response-status (read (current-buffer))))
432 (defun url-http-handle-cookies ()
433 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
434 The buffer must already be narrowed to the headers, so `mail-fetch-field' will
435 work correctly."
436 (let ((cookies (nreverse (mail-fetch-field "Set-Cookie" nil nil t)))
437 (cookies2 (nreverse (mail-fetch-field "Set-Cookie2" nil nil t))))
438 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
439 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
440 (while cookies
441 (url-cookie-handle-set-cookie (pop cookies)))
442 ;;; (while cookies2
443 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
447 (defun url-http-parse-headers ()
448 "Parse and handle HTTP specific headers.
449 Return t if and only if the current buffer is still active and
450 should be shown to the user."
451 ;; The comments after each status code handled are taken from RFC
452 ;; 2616 (HTTP/1.1)
453 (declare (special url-http-end-of-headers url-http-response-status
454 url-http-response-version
455 url-http-method url-http-data url-http-process
456 url-callback-function url-callback-arguments))
458 (url-http-mark-connection-as-free (url-host url-current-object)
459 (url-port url-current-object)
460 url-http-process)
462 (if (or (not (boundp 'url-http-end-of-headers))
463 (not url-http-end-of-headers))
464 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
465 (goto-char (point-min))
466 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
467 (url-http-parse-response)
468 (mail-narrow-to-head)
469 ;;(narrow-to-region (point-min) url-http-end-of-headers)
470 (let ((connection (mail-fetch-field "Connection")))
471 ;; In HTTP 1.0, keep the connection only if there is a
472 ;; "Connection: keep-alive" header.
473 ;; In HTTP 1.1 (and greater), keep the connection unless there is a
474 ;; "Connection: close" header
475 (cond
476 ((string= url-http-response-version "1.0")
477 (unless (and connection
478 (string= (downcase connection) "keep-alive"))
479 (delete-process url-http-process)))
481 (when (and connection
482 (string= (downcase connection) "close"))
483 (delete-process url-http-process)))))
484 (let ((buffer (current-buffer))
485 (class nil)
486 (success nil)
487 ;; other status symbols: jewelry and luxury cars
488 (status-symbol (cadr (assq url-http-response-status url-http-codes)))
489 ;; The filename part of a URL could be in remote file syntax,
490 ;; see Bug#6717 for an example. We disable file name
491 ;; handlers, therefore.
492 (file-name-handler-alist nil))
493 (setq class (/ url-http-response-status 100))
494 (url-http-debug "Parsed HTTP headers: class=%d status=%d" class url-http-response-status)
495 (url-http-handle-cookies)
497 (case class
498 ;; Classes of response codes
500 ;; 5xx = Server Error
501 ;; 4xx = Client Error
502 ;; 3xx = Redirection
503 ;; 2xx = Successful
504 ;; 1xx = Informational
505 (1 ; Information messages
506 ;; 100 = Continue with request
507 ;; 101 = Switching protocols
508 ;; 102 = Processing (Added by DAV)
509 (url-mark-buffer-as-dead buffer)
510 (error "HTTP responses in class 1xx not supported (%d)" url-http-response-status))
511 (2 ; Success
512 ;; 200 Ok
513 ;; 201 Created
514 ;; 202 Accepted
515 ;; 203 Non-authoritative information
516 ;; 204 No content
517 ;; 205 Reset content
518 ;; 206 Partial content
519 ;; 207 Multi-status (Added by DAV)
520 (case status-symbol
521 ((no-content reset-content)
522 ;; No new data, just stay at the same document
523 (url-mark-buffer-as-dead buffer)
524 (setq success t))
525 (otherwise
526 ;; Generic success for all others. Store in the cache, and
527 ;; mark it as successful.
528 (widen)
529 (if (and url-automatic-caching (equal url-http-method "GET"))
530 (url-store-in-cache buffer))
531 (setq success t))))
532 (3 ; Redirection
533 ;; 300 Multiple choices
534 ;; 301 Moved permanently
535 ;; 302 Found
536 ;; 303 See other
537 ;; 304 Not modified
538 ;; 305 Use proxy
539 ;; 307 Temporary redirect
540 (let ((redirect-uri (or (mail-fetch-field "Location")
541 (mail-fetch-field "URI"))))
542 (case status-symbol
543 (multiple-choices ; 300
544 ;; Quoth the spec (section 10.3.1)
545 ;; -------------------------------
546 ;; The requested resource corresponds to any one of a set of
547 ;; representations, each with its own specific location and
548 ;; agent-driven negotiation information is being provided so
549 ;; that the user can select a preferred representation and
550 ;; redirect its request to that location.
551 ;; [...]
552 ;; If the server has a preferred choice of representation, it
553 ;; SHOULD include the specific URI for that representation in
554 ;; the Location field; user agents MAY use the Location field
555 ;; value for automatic redirection.
556 ;; -------------------------------
557 ;; We do not support agent-driven negotiation, so we just
558 ;; redirect to the preferred URI if one is provided.
559 nil)
560 ((moved-permanently found temporary-redirect) ; 301 302 307
561 ;; If the 301|302 status code is received in response to a
562 ;; request other than GET or HEAD, the user agent MUST NOT
563 ;; automatically redirect the request unless it can be
564 ;; confirmed by the user, since this might change the
565 ;; conditions under which the request was issued.
566 (unless (member url-http-method '("HEAD" "GET"))
567 (setq redirect-uri nil)))
568 (see-other ; 303
569 ;; The response to the request can be found under a different
570 ;; URI and SHOULD be retrieved using a GET method on that
571 ;; resource.
572 (setq url-http-method "GET"
573 url-http-data nil))
574 (not-modified ; 304
575 ;; The 304 response MUST NOT contain a message-body.
576 (url-http-debug "Extracting document from cache... (%s)"
577 (url-cache-create-filename (url-view-url t)))
578 (url-cache-extract (url-cache-create-filename (url-view-url t)))
579 (setq redirect-uri nil
580 success t))
581 (use-proxy ; 305
582 ;; The requested resource MUST be accessed through the
583 ;; proxy given by the Location field. The Location field
584 ;; gives the URI of the proxy. The recipient is expected
585 ;; to repeat this single request via the proxy. 305
586 ;; responses MUST only be generated by origin servers.
587 (error "Redirection thru a proxy server not supported: %s"
588 redirect-uri))
589 (otherwise
590 ;; Treat everything like '300'
591 nil))
592 (when redirect-uri
593 ;; Clean off any whitespace and/or <...> cruft.
594 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
595 (setq redirect-uri (match-string 1 redirect-uri)))
596 (if (string-match "^<\\(.*\\)>$" redirect-uri)
597 (setq redirect-uri (match-string 1 redirect-uri)))
599 ;; Some stupid sites (like sourceforge) send a
600 ;; non-fully-qualified URL (ie: /), which royally confuses
601 ;; the URL library.
602 (if (not (string-match url-nonrelative-link redirect-uri))
603 ;; Be careful to use the real target URL, otherwise we may
604 ;; compute the redirection relative to the URL of the proxy.
605 (setq redirect-uri
606 (url-expand-file-name redirect-uri url-http-target-url)))
607 (let ((url-request-method url-http-method)
608 (url-request-data url-http-data)
609 (url-request-extra-headers url-http-extra-headers))
610 ;; Check existing number of redirects
611 (if (or (< url-max-redirections 0)
612 (and (> url-max-redirections 0)
613 (let ((events (car url-callback-arguments))
614 (old-redirects 0))
615 (while events
616 (if (eq (car events) :redirect)
617 (setq old-redirects (1+ old-redirects)))
618 (and (setq events (cdr events))
619 (setq events (cdr events))))
620 (< old-redirects url-max-redirections))))
621 ;; url-max-redirections hasn't been reached, so go
622 ;; ahead and redirect.
623 (progn
624 ;; Remember that the request was redirected.
625 (setf (car url-callback-arguments)
626 (nconc (list :redirect redirect-uri)
627 (car url-callback-arguments)))
628 ;; Put in the current buffer a forwarding pointer to the new
629 ;; destination buffer.
630 ;; FIXME: This is a hack to fix url-retrieve-synchronously
631 ;; without changing the API. Instead url-retrieve should
632 ;; either simply not return the "destination" buffer, or it
633 ;; should take an optional `dest-buf' argument.
634 (set (make-local-variable 'url-redirect-buffer)
635 (url-retrieve-internal
636 redirect-uri url-callback-function
637 url-callback-arguments
638 (url-silent url-current-object)))
639 (url-mark-buffer-as-dead buffer))
640 ;; We hit url-max-redirections, so issue an error and
641 ;; stop redirecting.
642 (url-http-debug "Maximum redirections reached")
643 (setf (car url-callback-arguments)
644 (nconc (list :error (list 'error 'http-redirect-limit
645 redirect-uri))
646 (car url-callback-arguments)))
647 (setq success t))))))
648 (4 ; Client error
649 ;; 400 Bad Request
650 ;; 401 Unauthorized
651 ;; 402 Payment required
652 ;; 403 Forbidden
653 ;; 404 Not found
654 ;; 405 Method not allowed
655 ;; 406 Not acceptable
656 ;; 407 Proxy authentication required
657 ;; 408 Request time-out
658 ;; 409 Conflict
659 ;; 410 Gone
660 ;; 411 Length required
661 ;; 412 Precondition failed
662 ;; 413 Request entity too large
663 ;; 414 Request-URI too large
664 ;; 415 Unsupported media type
665 ;; 416 Requested range not satisfiable
666 ;; 417 Expectation failed
667 ;; 422 Unprocessable Entity (Added by DAV)
668 ;; 423 Locked
669 ;; 424 Failed Dependency
670 (case status-symbol
671 (unauthorized ; 401
672 ;; The request requires user authentication. The response
673 ;; MUST include a WWW-Authenticate header field containing a
674 ;; challenge applicable to the requested resource. The
675 ;; client MAY repeat the request with a suitable
676 ;; Authorization header field.
677 (url-http-handle-authentication nil))
678 (payment-required ; 402
679 ;; This code is reserved for future use
680 (url-mark-buffer-as-dead buffer)
681 (error "Somebody wants you to give them money"))
682 (forbidden ; 403
683 ;; The server understood the request, but is refusing to
684 ;; fulfill it. Authorization will not help and the request
685 ;; SHOULD NOT be repeated.
686 (setq success t))
687 (not-found ; 404
688 ;; Not found
689 (setq success t))
690 (method-not-allowed ; 405
691 ;; The method specified in the Request-Line is not allowed
692 ;; for the resource identified by the Request-URI. The
693 ;; response MUST include an Allow header containing a list of
694 ;; valid methods for the requested resource.
695 (setq success t))
696 (not-acceptable ; 406
697 ;; The resource identified by the request is only capable of
698 ;; generating response entities which have content
699 ;; characteristics nota cceptable according to the accept
700 ;; headers sent in the request.
701 (setq success t))
702 (proxy-authentication-required ; 407
703 ;; This code is similar to 401 (Unauthorized), but indicates
704 ;; that the client must first authenticate itself with the
705 ;; proxy. The proxy MUST return a Proxy-Authenticate header
706 ;; field containing a challenge applicable to the proxy for
707 ;; the requested resource.
708 (url-http-handle-authentication t))
709 (request-timeout ; 408
710 ;; The client did not produce a request within the time that
711 ;; the server was prepared to wait. The client MAY repeat
712 ;; the request without modifications at any later time.
713 (setq success t))
714 (conflict ; 409
715 ;; The request could not be completed due to a conflict with
716 ;; the current state of the resource. This code is only
717 ;; allowed in situations where it is expected that the user
718 ;; mioght be able to resolve the conflict and resubmit the
719 ;; request. The response body SHOULD include enough
720 ;; information for the user to recognize the source of the
721 ;; conflict.
722 (setq success t))
723 (gone ; 410
724 ;; The requested resource is no longer available at the
725 ;; server and no forwarding address is known.
726 (setq success t))
727 (length-required ; 411
728 ;; The server refuses to accept the request without a defined
729 ;; Content-Length. The client MAY repeat the request if it
730 ;; adds a valid Content-Length header field containing the
731 ;; length of the message-body in the request message.
733 ;; NOTE - this will never happen because
734 ;; `url-http-create-request' automatically calculates the
735 ;; content-length.
736 (setq success t))
737 (precondition-failed ; 412
738 ;; The precondition given in one or more of the
739 ;; request-header fields evaluated to false when it was
740 ;; tested on the server.
741 (setq success t))
742 ((request-entity-too-large request-uri-too-large) ; 413 414
743 ;; The server is refusing to process a request because the
744 ;; request entity|URI is larger than the server is willing or
745 ;; able to process.
746 (setq success t))
747 (unsupported-media-type ; 415
748 ;; The server is refusing to service the request because the
749 ;; entity of the request is in a format not supported by the
750 ;; requested resource for the requested method.
751 (setq success t))
752 (requested-range-not-satisfiable ; 416
753 ;; A server SHOULD return a response with this status code if
754 ;; a request included a Range request-header field, and none
755 ;; of the range-specifier values in this field overlap the
756 ;; current extent of the selected resource, and the request
757 ;; did not include an If-Range request-header field.
758 (setq success t))
759 (expectation-failed ; 417
760 ;; The expectation given in an Expect request-header field
761 ;; could not be met by this server, or, if the server is a
762 ;; proxy, the server has unambiguous evidence that the
763 ;; request could not be met by the next-hop server.
764 (setq success t))
765 (otherwise
766 ;; The request could not be understood by the server due to
767 ;; malformed syntax. The client SHOULD NOT repeat the
768 ;; request without modifications.
769 (setq success t)))
770 ;; Tell the callback that an error occurred, and what the
771 ;; status code was.
772 (when success
773 (setf (car url-callback-arguments)
774 (nconc (list :error (list 'error 'http url-http-response-status))
775 (car url-callback-arguments)))))
777 ;; 500 Internal server error
778 ;; 501 Not implemented
779 ;; 502 Bad gateway
780 ;; 503 Service unavailable
781 ;; 504 Gateway time-out
782 ;; 505 HTTP version not supported
783 ;; 507 Insufficient storage
784 (setq success t)
785 (case url-http-response-status
786 (not-implemented ; 501
787 ;; The server does not support the functionality required to
788 ;; fulfill the request.
789 nil)
790 (bad-gateway ; 502
791 ;; The server, while acting as a gateway or proxy, received
792 ;; an invalid response from the upstream server it accessed
793 ;; in attempting to fulfill the request.
794 nil)
795 (service-unavailable ; 503
796 ;; The server is currently unable to handle the request due
797 ;; to a temporary overloading or maintenance of the server.
798 ;; The implication is that this is a temporary condition
799 ;; which will be alleviated after some delay. If known, the
800 ;; length of the delay MAY be indicated in a Retry-After
801 ;; header. If no Retry-After is given, the client SHOULD
802 ;; handle the response as it would for a 500 response.
803 nil)
804 (gateway-timeout ; 504
805 ;; The server, while acting as a gateway or proxy, did not
806 ;; receive a timely response from the upstream server
807 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
808 ;; auxiliary server (e.g. DNS) it needed to access in
809 ;; attempting to complete the request.
810 nil)
811 (http-version-not-supported ; 505
812 ;; The server does not support, or refuses to support, the
813 ;; HTTP protocol version that was used in the request
814 ;; message.
815 nil)
816 (insufficient-storage ; 507 (DAV)
817 ;; The method could not be performed on the resource
818 ;; because the server is unable to store the representation
819 ;; needed to successfully complete the request. This
820 ;; condition is considered to be temporary. If the request
821 ;; which received this status code was the result of a user
822 ;; action, the request MUST NOT be repeated until it is
823 ;; requested by a separate user action.
824 nil))
825 ;; Tell the callback that an error occurred, and what the
826 ;; status code was.
827 (when success
828 (setf (car url-callback-arguments)
829 (nconc (list :error (list 'error 'http url-http-response-status))
830 (car url-callback-arguments)))))
831 (otherwise
832 (error "Unknown class of HTTP response code: %d (%d)"
833 class url-http-response-status)))
834 (if (not success)
835 (url-mark-buffer-as-dead buffer))
836 (url-http-debug "Finished parsing HTTP headers: %S" success)
837 (widen)
838 success))
840 ;; Miscellaneous
841 (defun url-http-activate-callback ()
842 "Activate callback specified when this buffer was created."
843 (declare (special url-http-process
844 url-callback-function
845 url-callback-arguments))
846 (url-http-mark-connection-as-free (url-host url-current-object)
847 (url-port url-current-object)
848 url-http-process)
849 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
850 (apply url-callback-function url-callback-arguments))
852 ;; )
854 ;; These unfortunately cannot be macros... please ignore them!
855 (defun url-http-idle-sentinel (proc why)
856 "Remove (now defunct) process PROC from the list of open connections."
857 (maphash (lambda (key val)
858 (if (memq proc val)
859 (puthash key (delq proc val) url-http-open-connections)))
860 url-http-open-connections))
862 (defun url-http-end-of-document-sentinel (proc why)
863 ;; Sentinel used for old HTTP/0.9 or connections we know are going
864 ;; to die as the 'end of document' notifier.
865 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
866 (process-buffer proc))
867 (url-http-idle-sentinel proc why)
868 (when (buffer-name (process-buffer proc))
869 (with-current-buffer (process-buffer proc)
870 (goto-char (point-min))
871 (if (not (looking-at "HTTP/"))
872 ;; HTTP/0.9 just gets passed back no matter what
873 (url-http-activate-callback)
874 (if (url-http-parse-headers)
875 (url-http-activate-callback))))))
877 (defun url-http-simple-after-change-function (st nd length)
878 ;; Function used when we do NOT know how long the document is going to be
879 ;; Just _very_ simple 'downloaded %d' type of info.
880 (declare (special url-http-end-of-headers))
881 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
883 (defun url-http-content-length-after-change-function (st nd length)
884 "Function used when we DO know how long the document is going to be.
885 More sophisticated percentage downloaded, etc.
886 Also does minimal parsing of HTTP headers and will actually cause
887 the callback to be triggered."
888 (declare (special url-current-object
889 url-http-end-of-headers
890 url-http-content-length
891 url-http-content-type
892 url-http-process))
893 (if url-http-content-type
894 (url-display-percentage
895 "Reading [%s]... %s of %s (%d%%)"
896 (url-percentage (- nd url-http-end-of-headers)
897 url-http-content-length)
898 url-http-content-type
899 (url-pretty-length (- nd url-http-end-of-headers))
900 (url-pretty-length url-http-content-length)
901 (url-percentage (- nd url-http-end-of-headers)
902 url-http-content-length))
903 (url-display-percentage
904 "Reading... %s of %s (%d%%)"
905 (url-percentage (- nd url-http-end-of-headers)
906 url-http-content-length)
907 (url-pretty-length (- nd url-http-end-of-headers))
908 (url-pretty-length url-http-content-length)
909 (url-percentage (- nd url-http-end-of-headers)
910 url-http-content-length)))
912 (if (> (- nd url-http-end-of-headers) url-http-content-length)
913 (progn
914 ;; Found the end of the document! Wheee!
915 (url-display-percentage nil nil)
916 (url-lazy-message "Reading... done.")
917 (if (url-http-parse-headers)
918 (url-http-activate-callback)))))
920 (defun url-http-chunked-encoding-after-change-function (st nd length)
921 "Function used when dealing with 'chunked' encoding.
922 Cannot give a sophisticated percentage, but we need a different
923 function to look for the special 0-length chunk that signifies
924 the end of the document."
925 (declare (special url-current-object
926 url-http-end-of-headers
927 url-http-content-type
928 url-http-chunked-length
929 url-http-chunked-counter
930 url-http-process url-http-chunked-start))
931 (save-excursion
932 (goto-char st)
933 (let ((read-next-chunk t)
934 (case-fold-search t)
935 (regexp nil)
936 (no-initial-crlf nil))
937 ;; We need to loop thru looking for more chunks even within
938 ;; one after-change-function call.
939 (while read-next-chunk
940 (setq no-initial-crlf (= 0 url-http-chunked-counter))
941 (if url-http-content-type
942 (url-display-percentage nil
943 "Reading [%s]... chunk #%d"
944 url-http-content-type url-http-chunked-counter)
945 (url-display-percentage nil
946 "Reading... chunk #%d"
947 url-http-chunked-counter))
948 (url-http-debug "Reading chunk %d (%d %d %d)"
949 url-http-chunked-counter st nd length)
950 (setq regexp (if no-initial-crlf
951 "\\([0-9a-z]+\\).*\r?\n"
952 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
954 (if url-http-chunked-start
955 ;; We know how long the chunk is supposed to be, skip over
956 ;; leading crap if possible.
957 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
958 (progn
959 (url-http-debug "Got to the end of chunk #%d!"
960 url-http-chunked-counter)
961 (goto-char (+ url-http-chunked-start
962 url-http-chunked-length)))
963 (url-http-debug "Still need %d bytes to hit end of chunk"
964 (- (+ url-http-chunked-start
965 url-http-chunked-length)
966 nd))
967 (setq read-next-chunk nil)))
968 (if (not read-next-chunk)
969 (url-http-debug "Still spinning for next chunk...")
970 (if no-initial-crlf (skip-chars-forward "\r\n"))
971 (if (not (looking-at regexp))
972 (progn
973 ;; Must not have received the entirety of the chunk header,
974 ;; need to spin some more.
975 (url-http-debug "Did not see start of chunk @ %d!" (point))
976 (setq read-next-chunk nil))
977 (add-text-properties (match-beginning 0) (match-end 0)
978 (list 'start-open t
979 'end-open t
980 'chunked-encoding t
981 'face 'cursor
982 'invisible t))
983 (setq url-http-chunked-length (string-to-number (buffer-substring
984 (match-beginning 1)
985 (match-end 1))
987 url-http-chunked-counter (1+ url-http-chunked-counter)
988 url-http-chunked-start (set-marker
989 (or url-http-chunked-start
990 (make-marker))
991 (match-end 0)))
992 ; (if (not url-http-debug)
993 (delete-region (match-beginning 0) (match-end 0));)
994 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
995 url-http-chunked-counter url-http-chunked-length
996 (marker-position url-http-chunked-start))
997 (if (= 0 url-http-chunked-length)
998 (progn
999 ;; Found the end of the document! Wheee!
1000 (url-http-debug "Saw end of stream chunk!")
1001 (setq read-next-chunk nil)
1002 (url-display-percentage nil nil)
1003 ;; Every chunk, even the last 0-length one, is
1004 ;; terminated by CRLF. Skip it.
1005 (when (looking-at "\r?\n")
1006 (url-http-debug "Removing terminator of last chunk")
1007 (delete-region (match-beginning 0) (match-end 0)))
1008 (if (re-search-forward "^\r*$" nil t)
1009 (url-http-debug "Saw end of trailers..."))
1010 (if (url-http-parse-headers)
1011 (url-http-activate-callback))))))))))
1013 (defun url-http-wait-for-headers-change-function (st nd length)
1014 ;; This will wait for the headers to arrive and then splice in the
1015 ;; next appropriate after-change-function, etc.
1016 (declare (special url-current-object
1017 url-http-end-of-headers
1018 url-http-content-type
1019 url-http-content-length
1020 url-http-transfer-encoding
1021 url-callback-function
1022 url-callback-arguments
1023 url-http-process
1024 url-http-method
1025 url-http-after-change-function
1026 url-http-response-status))
1027 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1028 (buffer-name))
1029 (let ((end-of-headers nil)
1030 (old-http nil)
1031 (process-buffer (current-buffer))
1032 (content-length nil))
1033 (when (not (bobp))
1034 (goto-char (point-min))
1035 (if (and (looking-at ".*\n") ; have one line at least
1036 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1037 ;; Not HTTP/x.y data, must be 0.9
1038 ;; God, I wish this could die.
1039 (setq end-of-headers t
1040 url-http-end-of-headers 0
1041 old-http t)
1042 (when (re-search-forward "^\r*$" nil t)
1043 ;; Saw the end of the headers
1044 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1045 (setq url-http-end-of-headers (set-marker (make-marker)
1046 (point))
1047 end-of-headers t)
1048 (url-http-clean-headers)))
1050 (if (not end-of-headers)
1051 ;; Haven't seen the end of the headers yet, need to wait
1052 ;; for more data to arrive.
1054 (unless old-http
1055 (url-http-parse-response)
1056 (mail-narrow-to-head)
1057 (setq url-http-transfer-encoding (mail-fetch-field
1058 "transfer-encoding")
1059 url-http-content-type (mail-fetch-field "content-type"))
1060 (if (mail-fetch-field "content-length")
1061 (setq url-http-content-length
1062 (string-to-number (mail-fetch-field "content-length"))))
1063 (widen))
1064 (when url-http-transfer-encoding
1065 (setq url-http-transfer-encoding
1066 (downcase url-http-transfer-encoding)))
1068 (cond
1069 ((null url-http-response-status)
1070 ;; We got back a headerless malformed response from the
1071 ;; server.
1072 (url-http-activate-callback))
1073 ((or (= url-http-response-status 204)
1074 (= url-http-response-status 205))
1075 (url-http-debug "%d response must have headers only (%s)."
1076 url-http-response-status (buffer-name))
1077 (when (url-http-parse-headers)
1078 (url-http-activate-callback)))
1079 ((string= "HEAD" url-http-method)
1080 ;; A HEAD request is _ALWAYS_ terminated by the header
1081 ;; information, regardless of any entity headers,
1082 ;; according to section 4.4 of the HTTP/1.1 draft.
1083 (url-http-debug "HEAD request must have headers only (%s)."
1084 (buffer-name))
1085 (when (url-http-parse-headers)
1086 (url-http-activate-callback)))
1087 ((string= "CONNECT" url-http-method)
1088 ;; A CONNECT request is finished, but we cannot stick this
1089 ;; back on the free connectin list
1090 (url-http-debug "CONNECT request must have headers only.")
1091 (when (url-http-parse-headers)
1092 (url-http-activate-callback)))
1093 ((equal url-http-response-status 304)
1094 ;; Only allowed to have a header section. We have to handle
1095 ;; this here instead of in url-http-parse-headers because if
1096 ;; you have a cached copy of something without a known
1097 ;; content-length, and try to retrieve it from the cache, we'd
1098 ;; fall into the 'being dumb' section and wait for the
1099 ;; connection to terminate, which means we'd wait for 10
1100 ;; seconds for the keep-alives to time out on some servers.
1101 (when (url-http-parse-headers)
1102 (url-http-activate-callback)))
1103 (old-http
1104 ;; HTTP/0.9 always signaled end-of-connection by closing the
1105 ;; connection.
1106 (url-http-debug
1107 "Saw HTTP/0.9 response, connection closed means end of document.")
1108 (setq url-http-after-change-function
1109 'url-http-simple-after-change-function))
1110 ((equal url-http-transfer-encoding "chunked")
1111 (url-http-debug "Saw chunked encoding.")
1112 (setq url-http-after-change-function
1113 'url-http-chunked-encoding-after-change-function)
1114 (when (> nd url-http-end-of-headers)
1115 (url-http-debug
1116 "Calling initial chunked-encoding for extra data at end of headers")
1117 (url-http-chunked-encoding-after-change-function
1118 (marker-position url-http-end-of-headers) nd
1119 (- nd url-http-end-of-headers))))
1120 ((integerp url-http-content-length)
1121 (url-http-debug
1122 "Got a content-length, being smart about document end.")
1123 (setq url-http-after-change-function
1124 'url-http-content-length-after-change-function)
1125 (cond
1126 ((= 0 url-http-content-length)
1127 ;; We got a NULL body! Activate the callback
1128 ;; immediately!
1129 (url-http-debug
1130 "Got 0-length content-length, activating callback immediately.")
1131 (when (url-http-parse-headers)
1132 (url-http-activate-callback)))
1133 ((> nd url-http-end-of-headers)
1134 ;; Have some leftover data
1135 (url-http-debug "Calling initial content-length for extra data at end of headers")
1136 (url-http-content-length-after-change-function
1137 (marker-position url-http-end-of-headers)
1139 (- nd url-http-end-of-headers)))
1141 nil)))
1143 (url-http-debug "No content-length, being dumb.")
1144 (setq url-http-after-change-function
1145 'url-http-simple-after-change-function)))))
1146 ;; We are still at the beginning of the buffer... must just be
1147 ;; waiting for a response.
1148 (url-http-debug "Spinning waiting for headers...")
1149 (when (eq process-buffer (current-buffer))
1150 (goto-char (point-max)))))
1152 ;;;###autoload
1153 (defun url-http (url callback cbargs)
1154 "Retrieve URL via HTTP asynchronously.
1155 URL must be a parsed URL. See `url-generic-parse-url' for details.
1156 When retrieval is completed, the function CALLBACK is executed with
1157 CBARGS as the arguments."
1158 (check-type url vector "Need a pre-parsed URL.")
1159 (declare (special url-current-object
1160 url-http-end-of-headers
1161 url-http-content-type
1162 url-http-content-length
1163 url-http-transfer-encoding
1164 url-http-after-change-function
1165 url-callback-function
1166 url-callback-arguments
1167 url-show-status
1168 url-http-method
1169 url-http-extra-headers
1170 url-http-data
1171 url-http-chunked-length
1172 url-http-chunked-start
1173 url-http-chunked-counter
1174 url-http-process))
1175 (let* ((host (url-host (or url-using-proxy url)))
1176 (port (url-port (or url-using-proxy url)))
1177 (connection (url-http-find-free-connection host port))
1178 (buffer (generate-new-buffer (format " *http %s:%d*" host port))))
1179 (if (not connection)
1180 ;; Failed to open the connection for some reason
1181 (progn
1182 (kill-buffer buffer)
1183 (setq buffer nil)
1184 (error "Could not create connection to %s:%d" host port))
1185 (with-current-buffer buffer
1186 (mm-disable-multibyte)
1187 (setq url-current-object url
1188 mode-line-format "%b [%s]")
1190 (dolist (var '(url-http-end-of-headers
1191 url-http-content-type
1192 url-http-content-length
1193 url-http-transfer-encoding
1194 url-http-after-change-function
1195 url-http-response-version
1196 url-http-response-status
1197 url-http-chunked-length
1198 url-http-chunked-counter
1199 url-http-chunked-start
1200 url-callback-function
1201 url-callback-arguments
1202 url-show-status
1203 url-http-process
1204 url-http-method
1205 url-http-extra-headers
1206 url-http-data
1207 url-http-target-url
1208 url-http-connection-opened
1209 url-http-proxy))
1210 (set (make-local-variable var) nil))
1212 (setq url-http-method (or url-request-method "GET")
1213 url-http-extra-headers url-request-extra-headers
1214 url-http-data url-request-data
1215 url-http-process connection
1216 url-http-chunked-length nil
1217 url-http-chunked-start nil
1218 url-http-chunked-counter 0
1219 url-callback-function callback
1220 url-callback-arguments cbargs
1221 url-http-after-change-function 'url-http-wait-for-headers-change-function
1222 url-http-target-url url-current-object
1223 url-http-connection-opened nil
1224 url-http-proxy url-using-proxy)
1226 (set-process-buffer connection buffer)
1227 (set-process-filter connection 'url-http-generic-filter)
1228 (let ((status (process-status connection)))
1229 (cond
1230 ((eq status 'connect)
1231 ;; Asynchronous connection
1232 (set-process-sentinel connection 'url-http-async-sentinel))
1233 ((eq status 'failed)
1234 ;; Asynchronous connection failed
1235 (error "Could not create connection to %s:%d" host port))
1237 (set-process-sentinel connection 'url-http-end-of-document-sentinel)
1238 (process-send-string connection (url-http-create-request)))))))
1239 buffer))
1241 (defun url-http-async-sentinel (proc why)
1242 (declare (special url-callback-arguments))
1243 ;; We are performing an asynchronous connection, and a status change
1244 ;; has occurred.
1245 (when (buffer-name (process-buffer proc))
1246 (with-current-buffer (process-buffer proc)
1247 (cond
1248 (url-http-connection-opened
1249 (url-http-end-of-document-sentinel proc why))
1250 ((string= (substring why 0 4) "open")
1251 (setq url-http-connection-opened t)
1252 (process-send-string proc (url-http-create-request)))
1254 (setf (car url-callback-arguments)
1255 (nconc (list :error (list 'error 'connection-failed why
1256 :host (url-host (or url-http-proxy url-current-object))
1257 :service (url-port (or url-http-proxy url-current-object))))
1258 (car url-callback-arguments)))
1259 (url-http-activate-callback))))))
1261 ;; Since Emacs 19/20 does not allow you to change the
1262 ;; `after-change-functions' hook in the midst of running them, we fake
1263 ;; an after change by hooking into the process filter and inserting
1264 ;; the data ourselves. This is slightly less efficient, but there
1265 ;; were tons of weird ways the after-change code was biting us in the
1266 ;; shorts.
1267 ;; FIXME this can probably be simplified since the above is no longer true.
1268 (defun url-http-generic-filter (proc data)
1269 ;; Sometimes we get a zero-length data chunk after the process has
1270 ;; been changed to 'free', which means it has no buffer associated
1271 ;; with it. Do nothing if there is no buffer, or 0 length data.
1272 (declare (special url-http-after-change-function))
1273 (and (process-buffer proc)
1274 (/= (length data) 0)
1275 (with-current-buffer (process-buffer proc)
1276 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1277 (funcall url-http-after-change-function
1278 (point-max)
1279 (progn
1280 (goto-char (point-max))
1281 (insert data)
1282 (point-max))
1283 (length data)))))
1285 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1286 ;;; file-name-handler stuff from here on out
1287 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1288 (defalias 'url-http-symbol-value-in-buffer
1289 (if (fboundp 'symbol-value-in-buffer)
1290 'symbol-value-in-buffer
1291 (lambda (symbol buffer &optional unbound-value)
1292 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1293 (with-current-buffer buffer
1294 (if (not (boundp symbol))
1295 unbound-value
1296 (symbol-value symbol))))))
1298 (defun url-http-head (url)
1299 (let ((url-request-method "HEAD")
1300 (url-request-data nil))
1301 (url-retrieve-synchronously url)))
1303 ;;;###autoload
1304 (defun url-http-file-exists-p (url)
1305 (let ((status nil)
1306 (exists nil)
1307 (buffer (url-http-head url)))
1308 (if (not buffer)
1309 (setq exists nil)
1310 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1311 buffer 500)
1312 exists (and (integerp status)
1313 (>= status 200) (< status 300)))
1314 (kill-buffer buffer))
1315 exists))
1317 ;;;###autoload
1318 (defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1320 (defun url-http-head-file-attributes (url &optional id-format)
1321 (let ((buffer (url-http-head url)))
1322 (when buffer
1323 (prog1
1324 (list
1325 nil ;dir / link / normal file
1326 1 ;number of links to file.
1327 0 0 ;uid ; gid
1328 nil nil nil ;atime ; mtime ; ctime
1329 (url-http-symbol-value-in-buffer 'url-http-content-length
1330 buffer -1)
1331 (eval-when-compile (make-string 10 ?-))
1332 nil nil nil) ;whether gid would change ; inode ; device.
1333 (kill-buffer buffer)))))
1335 (declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
1337 ;;;###autoload
1338 (defun url-http-file-attributes (url &optional id-format)
1339 (if (url-dav-supported-p url)
1340 (url-dav-file-attributes url id-format)
1341 (url-http-head-file-attributes url id-format)))
1343 ;;;###autoload
1344 (defun url-http-options (url)
1345 "Return a property list describing options available for URL.
1346 This list is retrieved using the `OPTIONS' HTTP method.
1348 Property list members:
1350 methods
1351 A list of symbols specifying what HTTP methods the resource
1352 supports.
1355 A list of numbers specifying what DAV protocol/schema versions are
1356 supported.
1358 dasl
1359 A list of supported DASL search types supported (string form)
1361 ranges
1362 A list of the units available for use in partial document fetches.
1365 The `Platform For Privacy Protection' description for the resource.
1366 Currently this is just the raw header contents. This is likely to
1367 change once P3P is formally supported by the URL package or
1368 Emacs/W3."
1369 (let* ((url-request-method "OPTIONS")
1370 (url-request-data nil)
1371 (buffer (url-retrieve-synchronously url))
1372 (header nil)
1373 (options nil))
1374 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1375 'url-http-response-status buffer 0) 100)))
1376 ;; Only parse the options if we got a 2xx response code!
1377 (with-current-buffer buffer
1378 (save-restriction
1379 (save-match-data
1380 (mail-narrow-to-head)
1382 ;; Figure out what methods are supported.
1383 (when (setq header (mail-fetch-field "allow"))
1384 (setq options (plist-put
1385 options 'methods
1386 (mapcar 'intern (split-string header "[ ,]+")))))
1388 ;; Check for DAV
1389 (when (setq header (mail-fetch-field "dav"))
1390 (setq options (plist-put
1391 options 'dav
1392 (delq 0
1393 (mapcar 'string-to-number
1394 (split-string header "[, ]+"))))))
1396 ;; Now for DASL
1397 (when (setq header (mail-fetch-field "dasl"))
1398 (setq options (plist-put
1399 options 'dasl
1400 (split-string header "[, ]+"))))
1402 ;; P3P - should get more detailed here. FIXME
1403 (when (setq header (mail-fetch-field "p3p"))
1404 (setq options (plist-put options 'p3p header)))
1406 ;; Check for whether they accept byte-range requests.
1407 (when (setq header (mail-fetch-field "accept-ranges"))
1408 (setq options (plist-put
1409 options 'ranges
1410 (delq 'none
1411 (mapcar 'intern
1412 (split-string header "[, ]+"))))))
1413 ))))
1414 (if buffer (kill-buffer buffer))
1415 options))
1417 ;; HTTPS. This used to be in url-https.el, but that file collides
1418 ;; with url-http.el on systems with 8-character file names.
1419 (require 'tls)
1421 ;;;###autoload
1422 (defconst url-https-default-port 443 "Default HTTPS port.")
1423 ;;;###autoload
1424 (defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
1426 ;; FIXME what is the point of this alias being an autoload?
1427 ;; Trying to use it will not cause url-http to be loaded,
1428 ;; since the full alias just gets dumped into loaddefs.el.
1430 ;;;###autoload (autoload 'url-default-expander "url-expand")
1431 ;;;###autoload
1432 (defalias 'url-https-expand-file-name 'url-default-expander)
1434 (defmacro url-https-create-secure-wrapper (method args)
1435 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1436 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
1437 (let ((url-gateway-method 'tls))
1438 (,(intern (format (if method "url-http-%s" "url-http") method))
1439 ,@(remove '&rest (remove '&optional args))))))
1441 ;;;###autoload (autoload 'url-https "url-http")
1442 (url-https-create-secure-wrapper nil (url callback cbargs))
1443 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1444 (url-https-create-secure-wrapper file-exists-p (url))
1445 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1446 (url-https-create-secure-wrapper file-readable-p (url))
1447 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1448 (url-https-create-secure-wrapper file-attributes (url &optional id-format))
1450 (provide 'url-http)
1452 ;;; url-http.el ends here