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