* lisp/textmodes/text-mode.el (paragraph-indent-minor-mode): Make it
[emacs.git] / lisp / url / url-http.el
blob18d28e89f783a2afbb89f972148d7ae1fc28f7b8
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-proxy 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 (setq class (/ url-http-response-status 100))
513 (url-http-debug "Parsed HTTP headers: class=%d status=%d"
514 class url-http-response-status)
515 (when (url-use-cookies url-http-target-url)
516 (url-http-handle-cookies))
518 (pcase class
519 ;; Classes of response codes
521 ;; 5xx = Server Error
522 ;; 4xx = Client Error
523 ;; 3xx = Redirection
524 ;; 2xx = Successful
525 ;; 1xx = Informational
526 (1 ; Information messages
527 ;; 100 = Continue with request
528 ;; 101 = Switching protocols
529 ;; 102 = Processing (Added by DAV)
530 (url-mark-buffer-as-dead buffer)
531 (error "HTTP responses in class 1xx not supported (%d)"
532 url-http-response-status))
533 (2 ; Success
534 ;; 200 Ok
535 ;; 201 Created
536 ;; 202 Accepted
537 ;; 203 Non-authoritative information
538 ;; 204 No content
539 ;; 205 Reset content
540 ;; 206 Partial content
541 ;; 207 Multi-status (Added by DAV)
542 (pcase status-symbol
543 ((or `no-content `reset-content)
544 ;; No new data, just stay at the same document
545 (url-mark-buffer-as-dead buffer)
546 (setq success t))
548 ;; Generic success for all others. Store in the cache, and
549 ;; mark it as successful.
550 (widen)
551 (if (and url-automatic-caching (equal url-http-method "GET"))
552 (url-store-in-cache buffer))
553 (setq success t))))
554 (3 ; Redirection
555 ;; 300 Multiple choices
556 ;; 301 Moved permanently
557 ;; 302 Found
558 ;; 303 See other
559 ;; 304 Not modified
560 ;; 305 Use proxy
561 ;; 307 Temporary redirect
562 (let ((redirect-uri (or (mail-fetch-field "Location")
563 (mail-fetch-field "URI"))))
564 (pcase status-symbol
565 (`multiple-choices ; 300
566 ;; Quoth the spec (section 10.3.1)
567 ;; -------------------------------
568 ;; The requested resource corresponds to any one of a set of
569 ;; representations, each with its own specific location and
570 ;; agent-driven negotiation information is being provided so
571 ;; that the user can select a preferred representation and
572 ;; redirect its request to that location.
573 ;; [...]
574 ;; If the server has a preferred choice of representation, it
575 ;; SHOULD include the specific URI for that representation in
576 ;; the Location field; user agents MAY use the Location field
577 ;; value for automatic redirection.
578 ;; -------------------------------
579 ;; We do not support agent-driven negotiation, so we just
580 ;; redirect to the preferred URI if one is provided.
581 nil)
582 ((or `moved-permanently `found `temporary-redirect) ; 301 302 307
583 ;; If the 301|302 status code is received in response to a
584 ;; request other than GET or HEAD, the user agent MUST NOT
585 ;; automatically redirect the request unless it can be
586 ;; confirmed by the user, since this might change the
587 ;; conditions under which the request was issued.
588 (unless (member url-http-method '("HEAD" "GET"))
589 (setq redirect-uri nil)))
590 (`see-other ; 303
591 ;; The response to the request can be found under a different
592 ;; URI and SHOULD be retrieved using a GET method on that
593 ;; resource.
594 (setq url-http-method "GET"
595 url-http-data nil))
596 (`not-modified ; 304
597 ;; The 304 response MUST NOT contain a message-body.
598 (url-http-debug "Extracting document from cache... (%s)"
599 (url-cache-create-filename (url-view-url t)))
600 (url-cache-extract (url-cache-create-filename (url-view-url t)))
601 (setq redirect-uri nil
602 success t))
603 (`use-proxy ; 305
604 ;; The requested resource MUST be accessed through the
605 ;; proxy given by the Location field. The Location field
606 ;; gives the URI of the proxy. The recipient is expected
607 ;; to repeat this single request via the proxy. 305
608 ;; responses MUST only be generated by origin servers.
609 (error "Redirection thru a proxy server not supported: %s"
610 redirect-uri))
612 ;; Treat everything like '300'
613 nil))
614 (when redirect-uri
615 ;; Clean off any whitespace and/or <...> cruft.
616 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
617 (setq redirect-uri (match-string 1 redirect-uri)))
618 (if (string-match "^<\\(.*\\)>$" redirect-uri)
619 (setq redirect-uri (match-string 1 redirect-uri)))
621 ;; Some stupid sites (like sourceforge) send a
622 ;; non-fully-qualified URL (ie: /), which royally confuses
623 ;; the URL library.
624 (if (not (string-match url-nonrelative-link redirect-uri))
625 ;; Be careful to use the real target URL, otherwise we may
626 ;; compute the redirection relative to the URL of the proxy.
627 (setq redirect-uri
628 (url-expand-file-name redirect-uri url-http-target-url)))
629 (let ((url-request-method url-http-method)
630 (url-request-data url-http-data)
631 (url-request-extra-headers url-http-extra-headers))
632 ;; Check existing number of redirects
633 (if (or (< url-max-redirections 0)
634 (and (> url-max-redirections 0)
635 (let ((events (car url-callback-arguments))
636 (old-redirects 0))
637 (while events
638 (if (eq (car events) :redirect)
639 (setq old-redirects (1+ old-redirects)))
640 (and (setq events (cdr events))
641 (setq events (cdr events))))
642 (< old-redirects url-max-redirections))))
643 ;; url-max-redirections hasn't been reached, so go
644 ;; ahead and redirect.
645 (progn
646 ;; Remember that the request was redirected.
647 (setf (car url-callback-arguments)
648 (nconc (list :redirect redirect-uri)
649 (car url-callback-arguments)))
650 ;; Put in the current buffer a forwarding pointer to the new
651 ;; destination buffer.
652 ;; FIXME: This is a hack to fix url-retrieve-synchronously
653 ;; without changing the API. Instead url-retrieve should
654 ;; either simply not return the "destination" buffer, or it
655 ;; should take an optional `dest-buf' argument.
656 (set (make-local-variable 'url-redirect-buffer)
657 (url-retrieve-internal
658 redirect-uri url-callback-function
659 url-callback-arguments
660 (url-silent url-current-object)
661 (not (url-use-cookies url-current-object))))
662 (url-mark-buffer-as-dead buffer))
663 ;; We hit url-max-redirections, so issue an error and
664 ;; stop redirecting.
665 (url-http-debug "Maximum redirections reached")
666 (setf (car url-callback-arguments)
667 (nconc (list :error (list 'error 'http-redirect-limit
668 redirect-uri))
669 (car url-callback-arguments)))
670 (setq success t))))))
671 (4 ; Client error
672 ;; 400 Bad Request
673 ;; 401 Unauthorized
674 ;; 402 Payment required
675 ;; 403 Forbidden
676 ;; 404 Not found
677 ;; 405 Method not allowed
678 ;; 406 Not acceptable
679 ;; 407 Proxy authentication required
680 ;; 408 Request time-out
681 ;; 409 Conflict
682 ;; 410 Gone
683 ;; 411 Length required
684 ;; 412 Precondition failed
685 ;; 413 Request entity too large
686 ;; 414 Request-URI too large
687 ;; 415 Unsupported media type
688 ;; 416 Requested range not satisfiable
689 ;; 417 Expectation failed
690 ;; 422 Unprocessable Entity (Added by DAV)
691 ;; 423 Locked
692 ;; 424 Failed Dependency
693 (pcase status-symbol
694 (`unauthorized ; 401
695 ;; The request requires user authentication. The response
696 ;; MUST include a WWW-Authenticate header field containing a
697 ;; challenge applicable to the requested resource. The
698 ;; client MAY repeat the request with a suitable
699 ;; Authorization header field.
700 (url-http-handle-authentication nil))
701 (`payment-required ; 402
702 ;; This code is reserved for future use
703 (url-mark-buffer-as-dead buffer)
704 (error "Somebody wants you to give them money"))
705 (`forbidden ; 403
706 ;; The server understood the request, but is refusing to
707 ;; fulfill it. Authorization will not help and the request
708 ;; SHOULD NOT be repeated.
709 (setq success t))
710 (`not-found ; 404
711 ;; Not found
712 (setq success t))
713 (`method-not-allowed ; 405
714 ;; The method specified in the Request-Line is not allowed
715 ;; for the resource identified by the Request-URI. The
716 ;; response MUST include an Allow header containing a list of
717 ;; valid methods for the requested resource.
718 (setq success t))
719 (`not-acceptable ; 406
720 ;; The resource identified by the request is only capable of
721 ;; generating response entities which have content
722 ;; characteristics not acceptable according to the accept
723 ;; headers sent in the request.
724 (setq success t))
725 (`proxy-authentication-required ; 407
726 ;; This code is similar to 401 (Unauthorized), but indicates
727 ;; that the client must first authenticate itself with the
728 ;; proxy. The proxy MUST return a Proxy-Authenticate header
729 ;; field containing a challenge applicable to the proxy for
730 ;; the requested resource.
731 (url-http-handle-authentication t))
732 (`request-timeout ; 408
733 ;; The client did not produce a request within the time that
734 ;; the server was prepared to wait. The client MAY repeat
735 ;; the request without modifications at any later time.
736 (setq success t))
737 (`conflict ; 409
738 ;; The request could not be completed due to a conflict with
739 ;; the current state of the resource. This code is only
740 ;; allowed in situations where it is expected that the user
741 ;; might be able to resolve the conflict and resubmit the
742 ;; request. The response body SHOULD include enough
743 ;; information for the user to recognize the source of the
744 ;; conflict.
745 (setq success t))
746 (`gone ; 410
747 ;; The requested resource is no longer available at the
748 ;; server and no forwarding address is known.
749 (setq success t))
750 (`length-required ; 411
751 ;; The server refuses to accept the request without a defined
752 ;; Content-Length. The client MAY repeat the request if it
753 ;; adds a valid Content-Length header field containing the
754 ;; length of the message-body in the request message.
756 ;; NOTE - this will never happen because
757 ;; `url-http-create-request' automatically calculates the
758 ;; content-length.
759 (setq success t))
760 (`precondition-failed ; 412
761 ;; The precondition given in one or more of the
762 ;; request-header fields evaluated to false when it was
763 ;; tested on the server.
764 (setq success t))
765 ((or `request-entity-too-large `request-uri-too-large) ; 413 414
766 ;; The server is refusing to process a request because the
767 ;; request entity|URI is larger than the server is willing or
768 ;; able to process.
769 (setq success t))
770 (`unsupported-media-type ; 415
771 ;; The server is refusing to service the request because the
772 ;; entity of the request is in a format not supported by the
773 ;; requested resource for the requested method.
774 (setq success t))
775 (`requested-range-not-satisfiable ; 416
776 ;; A server SHOULD return a response with this status code if
777 ;; a request included a Range request-header field, and none
778 ;; of the range-specifier values in this field overlap the
779 ;; current extent of the selected resource, and the request
780 ;; did not include an If-Range request-header field.
781 (setq success t))
782 (`expectation-failed ; 417
783 ;; The expectation given in an Expect request-header field
784 ;; could not be met by this server, or, if the server is a
785 ;; proxy, the server has unambiguous evidence that the
786 ;; request could not be met by the next-hop server.
787 (setq success t))
789 ;; The request could not be understood by the server due to
790 ;; malformed syntax. The client SHOULD NOT repeat the
791 ;; request without modifications.
792 (setq success t)))
793 ;; Tell the callback that an error occurred, and what the
794 ;; status code was.
795 (when success
796 (setf (car url-callback-arguments)
797 (nconc (list :error (list 'error 'http url-http-response-status))
798 (car url-callback-arguments)))))
800 ;; 500 Internal server error
801 ;; 501 Not implemented
802 ;; 502 Bad gateway
803 ;; 503 Service unavailable
804 ;; 504 Gateway time-out
805 ;; 505 HTTP version not supported
806 ;; 507 Insufficient storage
807 (setq success t)
808 (pcase url-http-response-status
809 (`not-implemented ; 501
810 ;; The server does not support the functionality required to
811 ;; fulfill the request.
812 nil)
813 (`bad-gateway ; 502
814 ;; The server, while acting as a gateway or proxy, received
815 ;; an invalid response from the upstream server it accessed
816 ;; in attempting to fulfill the request.
817 nil)
818 (`service-unavailable ; 503
819 ;; The server is currently unable to handle the request due
820 ;; to a temporary overloading or maintenance of the server.
821 ;; The implication is that this is a temporary condition
822 ;; which will be alleviated after some delay. If known, the
823 ;; length of the delay MAY be indicated in a Retry-After
824 ;; header. If no Retry-After is given, the client SHOULD
825 ;; handle the response as it would for a 500 response.
826 nil)
827 (`gateway-timeout ; 504
828 ;; The server, while acting as a gateway or proxy, did not
829 ;; receive a timely response from the upstream server
830 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
831 ;; auxiliary server (e.g. DNS) it needed to access in
832 ;; attempting to complete the request.
833 nil)
834 (`http-version-not-supported ; 505
835 ;; The server does not support, or refuses to support, the
836 ;; HTTP protocol version that was used in the request
837 ;; message.
838 nil)
839 (`insufficient-storage ; 507 (DAV)
840 ;; The method could not be performed on the resource
841 ;; because the server is unable to store the representation
842 ;; needed to successfully complete the request. This
843 ;; condition is considered to be temporary. If the request
844 ;; which received this status code was the result of a user
845 ;; action, the request MUST NOT be repeated until it is
846 ;; requested by a separate user action.
847 nil))
848 ;; Tell the callback that an error occurred, and what the
849 ;; status code was.
850 (when success
851 (setf (car url-callback-arguments)
852 (nconc (list :error (list 'error 'http url-http-response-status))
853 (car url-callback-arguments)))))
855 (error "Unknown class of HTTP response code: %d (%d)"
856 class url-http-response-status)))
857 (if (not success)
858 (url-mark-buffer-as-dead buffer))
859 (url-http-debug "Finished parsing HTTP headers: %S" success)
860 (widen)
861 success))
863 ;; Miscellaneous
864 (defun url-http-activate-callback ()
865 "Activate callback specified when this buffer was created."
866 (url-http-mark-connection-as-free (url-host url-current-object)
867 (url-port url-current-object)
868 url-http-process)
869 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
870 (apply url-callback-function url-callback-arguments))
872 ;; )
874 ;; These unfortunately cannot be macros... please ignore them!
875 (defun url-http-idle-sentinel (proc why)
876 "Remove (now defunct) process PROC from the list of open connections."
877 (maphash (lambda (key val)
878 (if (memq proc val)
879 (puthash key (delq proc val) url-http-open-connections)))
880 url-http-open-connections))
882 (defun url-http-end-of-document-sentinel (proc why)
883 ;; Sentinel used to handle (i) terminated old HTTP/0.9 connections,
884 ;; and (ii) closed connection due to reusing a HTTP connection which
885 ;; we believed was still alive, but which the server closed on us.
886 ;; We handle case (ii) by calling `url-http' again.
887 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
888 (process-buffer proc))
889 (url-http-idle-sentinel proc why)
890 (when (buffer-name (process-buffer proc))
891 (with-current-buffer (process-buffer proc)
892 (goto-char (point-min))
893 (cond ((not (looking-at "HTTP/"))
894 (if url-http-no-retry
895 ;; HTTP/0.9 just gets passed back no matter what
896 (url-http-activate-callback)
897 ;; Call `url-http' again if our connection expired.
898 (erase-buffer)
899 (url-http url-current-object url-callback-function
900 url-callback-arguments (current-buffer))))
901 ((url-http-parse-headers)
902 (url-http-activate-callback))))))
904 (defun url-http-simple-after-change-function (st nd length)
905 ;; Function used when we do NOT know how long the document is going to be
906 ;; Just _very_ simple 'downloaded %d' type of info.
907 (url-lazy-message "Reading %s..." (url-pretty-length nd)))
909 (defun url-http-content-length-after-change-function (st nd length)
910 "Function used when we DO know how long the document is going to be.
911 More sophisticated percentage downloaded, etc.
912 Also does minimal parsing of HTTP headers and will actually cause
913 the callback to be triggered."
914 (if url-http-content-type
915 (url-display-percentage
916 "Reading [%s]... %s of %s (%d%%)"
917 (url-percentage (- nd url-http-end-of-headers)
918 url-http-content-length)
919 url-http-content-type
920 (url-pretty-length (- nd url-http-end-of-headers))
921 (url-pretty-length url-http-content-length)
922 (url-percentage (- nd url-http-end-of-headers)
923 url-http-content-length))
924 (url-display-percentage
925 "Reading... %s of %s (%d%%)"
926 (url-percentage (- nd url-http-end-of-headers)
927 url-http-content-length)
928 (url-pretty-length (- nd url-http-end-of-headers))
929 (url-pretty-length url-http-content-length)
930 (url-percentage (- nd url-http-end-of-headers)
931 url-http-content-length)))
933 (if (> (- nd url-http-end-of-headers) url-http-content-length)
934 (progn
935 ;; Found the end of the document! Wheee!
936 (url-display-percentage nil nil)
937 (url-lazy-message "Reading... done.")
938 (if (url-http-parse-headers)
939 (url-http-activate-callback)))))
941 (defun url-http-chunked-encoding-after-change-function (st nd length)
942 "Function used when dealing with 'chunked' encoding.
943 Cannot give a sophisticated percentage, but we need a different
944 function to look for the special 0-length chunk that signifies
945 the end of the document."
946 (save-excursion
947 (goto-char st)
948 (let ((read-next-chunk t)
949 (case-fold-search t)
950 (regexp nil)
951 (no-initial-crlf nil))
952 ;; We need to loop thru looking for more chunks even within
953 ;; one after-change-function call.
954 (while read-next-chunk
955 (setq no-initial-crlf (= 0 url-http-chunked-counter))
956 (if url-http-content-type
957 (url-display-percentage nil
958 "Reading [%s]... chunk #%d"
959 url-http-content-type url-http-chunked-counter)
960 (url-display-percentage nil
961 "Reading... chunk #%d"
962 url-http-chunked-counter))
963 (url-http-debug "Reading chunk %d (%d %d %d)"
964 url-http-chunked-counter st nd length)
965 (setq regexp (if no-initial-crlf
966 "\\([0-9a-z]+\\).*\r?\n"
967 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
969 (if url-http-chunked-start
970 ;; We know how long the chunk is supposed to be, skip over
971 ;; leading crap if possible.
972 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
973 (progn
974 (url-http-debug "Got to the end of chunk #%d!"
975 url-http-chunked-counter)
976 (goto-char (+ url-http-chunked-start
977 url-http-chunked-length)))
978 (url-http-debug "Still need %d bytes to hit end of chunk"
979 (- (+ url-http-chunked-start
980 url-http-chunked-length)
981 nd))
982 (setq read-next-chunk nil)))
983 (if (not read-next-chunk)
984 (url-http-debug "Still spinning for next chunk...")
985 (if no-initial-crlf (skip-chars-forward "\r\n"))
986 (if (not (looking-at regexp))
987 (progn
988 ;; Must not have received the entirety of the chunk header,
989 ;; need to spin some more.
990 (url-http-debug "Did not see start of chunk @ %d!" (point))
991 (setq read-next-chunk nil))
992 (add-text-properties (match-beginning 0) (match-end 0)
993 (list 'start-open t
994 'end-open t
995 'chunked-encoding t
996 'face 'cursor
997 'invisible t))
998 (setq url-http-chunked-length (string-to-number (buffer-substring
999 (match-beginning 1)
1000 (match-end 1))
1002 url-http-chunked-counter (1+ url-http-chunked-counter)
1003 url-http-chunked-start (set-marker
1004 (or url-http-chunked-start
1005 (make-marker))
1006 (match-end 0)))
1007 ; (if (not url-http-debug)
1008 (delete-region (match-beginning 0) (match-end 0));)
1009 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1010 url-http-chunked-counter url-http-chunked-length
1011 (marker-position url-http-chunked-start))
1012 (if (= 0 url-http-chunked-length)
1013 (progn
1014 ;; Found the end of the document! Wheee!
1015 (url-http-debug "Saw end of stream chunk!")
1016 (setq read-next-chunk nil)
1017 (url-display-percentage nil nil)
1018 ;; Every chunk, even the last 0-length one, is
1019 ;; terminated by CRLF. Skip it.
1020 (when (looking-at "\r?\n")
1021 (url-http-debug "Removing terminator of last chunk")
1022 (delete-region (match-beginning 0) (match-end 0)))
1023 (if (re-search-forward "^\r*$" nil t)
1024 (url-http-debug "Saw end of trailers..."))
1025 (if (url-http-parse-headers)
1026 (url-http-activate-callback))))))))))
1028 (defun url-http-wait-for-headers-change-function (st nd length)
1029 ;; This will wait for the headers to arrive and then splice in the
1030 ;; next appropriate after-change-function, etc.
1031 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1032 (buffer-name))
1033 (let ((end-of-headers nil)
1034 (old-http nil)
1035 (process-buffer (current-buffer))
1036 (content-length nil))
1037 (when (not (bobp))
1038 (goto-char (point-min))
1039 (if (and (looking-at ".*\n") ; have one line at least
1040 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1041 ;; Not HTTP/x.y data, must be 0.9
1042 ;; God, I wish this could die.
1043 (setq end-of-headers t
1044 url-http-end-of-headers 0
1045 old-http t)
1046 (when (re-search-forward "^\r*$" nil t)
1047 ;; Saw the end of the headers
1048 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1049 (setq url-http-end-of-headers (set-marker (make-marker)
1050 (point))
1051 end-of-headers t)
1052 (setq nd (- nd (url-http-clean-headers)))))
1054 (if (not end-of-headers)
1055 ;; Haven't seen the end of the headers yet, need to wait
1056 ;; for more data to arrive.
1058 (unless old-http
1059 (url-http-parse-response)
1060 (mail-narrow-to-head)
1061 (setq url-http-transfer-encoding (mail-fetch-field
1062 "transfer-encoding")
1063 url-http-content-type (mail-fetch-field "content-type"))
1064 (if (mail-fetch-field "content-length")
1065 (setq url-http-content-length
1066 (string-to-number (mail-fetch-field "content-length"))))
1067 (widen))
1068 (when url-http-transfer-encoding
1069 (setq url-http-transfer-encoding
1070 (downcase url-http-transfer-encoding)))
1072 (cond
1073 ((null url-http-response-status)
1074 ;; We got back a headerless malformed response from the
1075 ;; server.
1076 (url-http-activate-callback))
1077 ((or (= url-http-response-status 204)
1078 (= url-http-response-status 205))
1079 (url-http-debug "%d response must have headers only (%s)."
1080 url-http-response-status (buffer-name))
1081 (when (url-http-parse-headers)
1082 (url-http-activate-callback)))
1083 ((string= "HEAD" url-http-method)
1084 ;; A HEAD request is _ALWAYS_ terminated by the header
1085 ;; information, regardless of any entity headers,
1086 ;; according to section 4.4 of the HTTP/1.1 draft.
1087 (url-http-debug "HEAD request must have headers only (%s)."
1088 (buffer-name))
1089 (when (url-http-parse-headers)
1090 (url-http-activate-callback)))
1091 ((string= "CONNECT" url-http-method)
1092 ;; A CONNECT request is finished, but we cannot stick this
1093 ;; back on the free connection list
1094 (url-http-debug "CONNECT request must have headers only.")
1095 (when (url-http-parse-headers)
1096 (url-http-activate-callback)))
1097 ((equal url-http-response-status 304)
1098 ;; Only allowed to have a header section. We have to handle
1099 ;; this here instead of in url-http-parse-headers because if
1100 ;; you have a cached copy of something without a known
1101 ;; content-length, and try to retrieve it from the cache, we'd
1102 ;; fall into the 'being dumb' section and wait for the
1103 ;; connection to terminate, which means we'd wait for 10
1104 ;; seconds for the keep-alives to time out on some servers.
1105 (when (url-http-parse-headers)
1106 (url-http-activate-callback)))
1107 (old-http
1108 ;; HTTP/0.9 always signaled end-of-connection by closing the
1109 ;; connection.
1110 (url-http-debug
1111 "Saw HTTP/0.9 response, connection closed means end of document.")
1112 (setq url-http-after-change-function
1113 'url-http-simple-after-change-function))
1114 ((equal url-http-transfer-encoding "chunked")
1115 (url-http-debug "Saw chunked encoding.")
1116 (setq url-http-after-change-function
1117 'url-http-chunked-encoding-after-change-function)
1118 (when (> nd url-http-end-of-headers)
1119 (url-http-debug
1120 "Calling initial chunked-encoding for extra data at end of headers")
1121 (url-http-chunked-encoding-after-change-function
1122 (marker-position url-http-end-of-headers) nd
1123 (- nd url-http-end-of-headers))))
1124 ((integerp url-http-content-length)
1125 (url-http-debug
1126 "Got a content-length, being smart about document end.")
1127 (setq url-http-after-change-function
1128 'url-http-content-length-after-change-function)
1129 (cond
1130 ((= 0 url-http-content-length)
1131 ;; We got a NULL body! Activate the callback
1132 ;; immediately!
1133 (url-http-debug
1134 "Got 0-length content-length, activating callback immediately.")
1135 (when (url-http-parse-headers)
1136 (url-http-activate-callback)))
1137 ((> nd url-http-end-of-headers)
1138 ;; Have some leftover data
1139 (url-http-debug "Calling initial content-length for extra data at end of headers")
1140 (url-http-content-length-after-change-function
1141 (marker-position url-http-end-of-headers)
1143 (- nd url-http-end-of-headers)))
1145 nil)))
1147 (url-http-debug "No content-length, being dumb.")
1148 (setq url-http-after-change-function
1149 'url-http-simple-after-change-function)))))
1150 ;; We are still at the beginning of the buffer... must just be
1151 ;; waiting for a response.
1152 (url-http-debug "Spinning waiting for headers...")
1153 (when (eq process-buffer (current-buffer))
1154 (goto-char (point-max)))))
1156 ;;;###autoload
1157 (defun url-http (url callback cbargs &optional retry-buffer)
1158 "Retrieve URL via HTTP asynchronously.
1159 URL must be a parsed URL. See `url-generic-parse-url' for details.
1160 When retrieval is completed, the function CALLBACK is executed with
1161 CBARGS as the arguments.
1163 Optional arg RETRY-BUFFER, if non-nil, specifies the buffer of a
1164 previous `url-http' call, which is being re-attempted."
1165 (cl-check-type url vector "Need a pre-parsed URL.")
1166 (let* ((host (url-host (or url-using-proxy url)))
1167 (port (url-port (or url-using-proxy url)))
1168 (connection (url-http-find-free-connection host port))
1169 (buffer (or retry-buffer
1170 (generate-new-buffer
1171 (format " *http %s:%d*" host port)))))
1172 (if (not connection)
1173 ;; Failed to open the connection for some reason
1174 (progn
1175 (kill-buffer buffer)
1176 (setq buffer nil)
1177 (error "Could not create connection to %s:%d" host port))
1178 (with-current-buffer buffer
1179 (mm-disable-multibyte)
1180 (setq url-current-object url
1181 mode-line-format "%b [%s]")
1183 (dolist (var '(url-http-end-of-headers
1184 url-http-content-type
1185 url-http-content-length
1186 url-http-transfer-encoding
1187 url-http-after-change-function
1188 url-http-response-version
1189 url-http-response-status
1190 url-http-chunked-length
1191 url-http-chunked-counter
1192 url-http-chunked-start
1193 url-callback-function
1194 url-callback-arguments
1195 url-show-status
1196 url-http-process
1197 url-http-method
1198 url-http-extra-headers
1199 url-http-data
1200 url-http-target-url
1201 url-http-no-retry
1202 url-http-connection-opened
1203 url-http-proxy))
1204 (set (make-local-variable var) nil))
1206 (setq url-http-method (or url-request-method "GET")
1207 url-http-extra-headers url-request-extra-headers
1208 url-http-data url-request-data
1209 url-http-process connection
1210 url-http-chunked-length nil
1211 url-http-chunked-start nil
1212 url-http-chunked-counter 0
1213 url-callback-function callback
1214 url-callback-arguments cbargs
1215 url-http-after-change-function 'url-http-wait-for-headers-change-function
1216 url-http-target-url url-current-object
1217 url-http-no-retry retry-buffer
1218 url-http-connection-opened nil
1219 url-http-proxy url-using-proxy)
1221 (set-process-buffer connection buffer)
1222 (set-process-filter connection 'url-http-generic-filter)
1223 (let ((status (process-status connection)))
1224 (cond
1225 ((eq status 'connect)
1226 ;; Asynchronous connection
1227 (set-process-sentinel connection 'url-http-async-sentinel))
1228 ((eq status 'failed)
1229 ;; Asynchronous connection failed
1230 (error "Could not create connection to %s:%d" host port))
1232 (set-process-sentinel connection
1233 'url-http-end-of-document-sentinel)
1234 (process-send-string connection (url-http-create-request)))))))
1235 buffer))
1237 (defun url-http-async-sentinel (proc why)
1238 ;; We are performing an asynchronous connection, and a status change
1239 ;; has occurred.
1240 (when (buffer-name (process-buffer proc))
1241 (with-current-buffer (process-buffer proc)
1242 (cond
1243 (url-http-connection-opened
1244 (setq url-http-no-retry t)
1245 (url-http-end-of-document-sentinel proc why))
1246 ((string= (substring why 0 4) "open")
1247 (setq url-http-connection-opened t)
1248 (condition-case error
1249 (process-send-string proc (url-http-create-request))
1250 (file-error
1251 (setq url-http-connection-opened nil)
1252 (message "HTTP error: %s" error))))
1254 (setf (car url-callback-arguments)
1255 (nconc (list :error (list 'error 'connection-failed why
1256 :host (url-host (or url-http-proxy url-current-object))
1257 :service (url-port (or url-http-proxy url-current-object))))
1258 (car url-callback-arguments)))
1259 (url-http-activate-callback))))))
1261 ;; Since Emacs 19/20 does not allow you to change the
1262 ;; `after-change-functions' hook in the midst of running them, we fake
1263 ;; an after change by hooking into the process filter and inserting
1264 ;; the data ourselves. This is slightly less efficient, but there
1265 ;; were tons of weird ways the after-change code was biting us in the
1266 ;; shorts.
1267 ;; FIXME this can probably be simplified since the above is no longer true.
1268 (defun url-http-generic-filter (proc data)
1269 ;; Sometimes we get a zero-length data chunk after the process has
1270 ;; been changed to 'free', which means it has no buffer associated
1271 ;; with it. Do nothing if there is no buffer, or 0 length data.
1272 (and (process-buffer proc)
1273 (/= (length data) 0)
1274 (with-current-buffer (process-buffer proc)
1275 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1276 (funcall url-http-after-change-function
1277 (point-max)
1278 (progn
1279 (goto-char (point-max))
1280 (insert data)
1281 (point-max))
1282 (length data)))))
1284 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1285 ;;; file-name-handler stuff from here on out
1286 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1287 (defalias 'url-http-symbol-value-in-buffer
1288 (if (fboundp 'symbol-value-in-buffer)
1289 'symbol-value-in-buffer
1290 (lambda (symbol buffer &optional unbound-value)
1291 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1292 (with-current-buffer buffer
1293 (if (not (boundp symbol))
1294 unbound-value
1295 (symbol-value symbol))))))
1297 (defun url-http-head (url)
1298 (let ((url-request-method "HEAD")
1299 (url-request-data nil))
1300 (url-retrieve-synchronously url)))
1302 ;;;###autoload
1303 (defun url-http-file-exists-p (url)
1304 (let ((status nil)
1305 (exists nil)
1306 (buffer (url-http-head url)))
1307 (if (not buffer)
1308 (setq exists nil)
1309 (setq status (url-http-symbol-value-in-buffer 'url-http-response-status
1310 buffer 500)
1311 exists (and (integerp status)
1312 (>= status 200) (< status 300)))
1313 (kill-buffer buffer))
1314 exists))
1316 ;;;###autoload
1317 (defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1319 (defun url-http-head-file-attributes (url &optional id-format)
1320 (let ((buffer (url-http-head url)))
1321 (when buffer
1322 (prog1
1323 (list
1324 nil ;dir / link / normal file
1325 1 ;number of links to file.
1326 0 0 ;uid ; gid
1327 nil nil nil ;atime ; mtime ; ctime
1328 (url-http-symbol-value-in-buffer 'url-http-content-length
1329 buffer -1)
1330 (eval-when-compile (make-string 10 ?-))
1331 nil nil nil) ;whether gid would change ; inode ; device.
1332 (kill-buffer buffer)))))
1334 (declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
1336 ;;;###autoload
1337 (defun url-http-file-attributes (url &optional id-format)
1338 (if (url-dav-supported-p url)
1339 (url-dav-file-attributes url id-format)
1340 (url-http-head-file-attributes url id-format)))
1342 ;;;###autoload
1343 (defun url-http-options (url)
1344 "Return a property list describing options available for URL.
1345 This list is retrieved using the `OPTIONS' HTTP method.
1347 Property list members:
1349 methods
1350 A list of symbols specifying what HTTP methods the resource
1351 supports.
1354 A list of numbers specifying what DAV protocol/schema versions are
1355 supported.
1357 dasl
1358 A list of supported DASL search types supported (string form)
1360 ranges
1361 A list of the units available for use in partial document fetches.
1364 The `Platform For Privacy Protection' description for the resource.
1365 Currently this is just the raw header contents. This is likely to
1366 change once P3P is formally supported by the URL package or
1367 Emacs/W3."
1368 (let* ((url-request-method "OPTIONS")
1369 (url-request-data nil)
1370 (buffer (url-retrieve-synchronously url))
1371 (header nil)
1372 (options nil))
1373 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1374 'url-http-response-status buffer 0) 100)))
1375 ;; Only parse the options if we got a 2xx response code!
1376 (with-current-buffer buffer
1377 (save-restriction
1378 (save-match-data
1379 (mail-narrow-to-head)
1381 ;; Figure out what methods are supported.
1382 (when (setq header (mail-fetch-field "allow"))
1383 (setq options (plist-put
1384 options 'methods
1385 (mapcar 'intern (split-string header "[ ,]+")))))
1387 ;; Check for DAV
1388 (when (setq header (mail-fetch-field "dav"))
1389 (setq options (plist-put
1390 options 'dav
1391 (delq 0
1392 (mapcar 'string-to-number
1393 (split-string header "[, ]+"))))))
1395 ;; Now for DASL
1396 (when (setq header (mail-fetch-field "dasl"))
1397 (setq options (plist-put
1398 options 'dasl
1399 (split-string header "[, ]+"))))
1401 ;; P3P - should get more detailed here. FIXME
1402 (when (setq header (mail-fetch-field "p3p"))
1403 (setq options (plist-put options 'p3p header)))
1405 ;; Check for whether they accept byte-range requests.
1406 (when (setq header (mail-fetch-field "accept-ranges"))
1407 (setq options (plist-put
1408 options 'ranges
1409 (delq 'none
1410 (mapcar 'intern
1411 (split-string header "[, ]+"))))))
1412 ))))
1413 (if buffer (kill-buffer buffer))
1414 options))
1416 ;; HTTPS. This used to be in url-https.el, but that file collides
1417 ;; with url-http.el on systems with 8-character file names.
1418 (require 'tls)
1420 ;;;###autoload
1421 (defconst url-https-default-port 443 "Default HTTPS port.")
1422 ;;;###autoload
1423 (defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
1425 ;; FIXME what is the point of this alias being an autoload?
1426 ;; Trying to use it will not cause url-http to be loaded,
1427 ;; since the full alias just gets dumped into loaddefs.el.
1429 ;;;###autoload (autoload 'url-default-expander "url-expand")
1430 ;;;###autoload
1431 (defalias 'url-https-expand-file-name 'url-default-expander)
1433 (defmacro url-https-create-secure-wrapper (method args)
1434 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1435 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
1436 (let ((url-gateway-method 'tls))
1437 (,(intern (format (if method "url-http-%s" "url-http") method))
1438 ,@(remove '&rest (remove '&optional args))))))
1440 ;;;###autoload (autoload 'url-https "url-http")
1441 (url-https-create-secure-wrapper nil (url callback cbargs))
1442 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1443 (url-https-create-secure-wrapper file-exists-p (url))
1444 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1445 (url-https-create-secure-wrapper file-readable-p (url))
1446 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1447 (url-https-create-secure-wrapper file-attributes (url &optional id-format))
1449 (provide 'url-http)
1451 ;;; url-http.el ends here