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