]> code.delx.au - gnu-emacs/blob - lisp/url/url-http.el
Merge from emacs-24; up to 2014-07-27T01:00:26Z!fgallina@gnu.org
[gnu-emacs] / lisp / url / url-http.el
1 ;;; url-http.el --- HTTP retrieval routines
2
3 ;; Copyright (C) 1999, 2001, 2004-2014 Free Software Foundation, Inc.
4
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: comm, data, processes
8
9 ;; This file is part of GNU Emacs.
10 ;;
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl-lib))
29
30 (defvar url-callback-arguments)
31 (defvar url-callback-function)
32 (defvar url-current-object)
33 (defvar url-http-after-change-function)
34 (defvar url-http-chunked-counter)
35 (defvar url-http-chunked-length)
36 (defvar url-http-chunked-start)
37 (defvar url-http-connection-opened)
38 (defvar url-http-content-length)
39 (defvar url-http-content-type)
40 (defvar url-http-data)
41 (defvar url-http-end-of-headers)
42 (defvar url-http-extra-headers)
43 (defvar url-http-method)
44 (defvar url-http-no-retry)
45 (defvar url-http-process)
46 (defvar url-http-proxy)
47 (defvar url-http-response-status)
48 (defvar url-http-response-version)
49 (defvar url-http-target-url)
50 (defvar url-http-transfer-encoding)
51 (defvar url-show-status)
52
53 (require 'url-gw)
54 (require 'url-parse)
55 (require 'url-cookie)
56 (require 'mail-parse)
57 (require 'url-auth)
58 (require 'url)
59 (autoload 'url-cache-create-filename "url-cache")
60
61 (defconst url-http-default-port 80 "Default HTTP port.")
62 (defconst url-http-asynchronous-p t "HTTP retrievals are asynchronous.")
63 (defalias 'url-http-expand-file-name 'url-default-expander)
64
65 (defvar url-http-real-basic-auth-storage nil)
66 (defvar url-http-proxy-basic-auth-storage nil)
67
68 (defvar url-http-open-connections (make-hash-table :test 'equal
69 :size 17)
70 "A hash table of all open network connections.")
71
72 (defvar url-http-version "1.1"
73 "What version of HTTP we advertise, as a string.
74 Valid values are 1.1 and 1.0.
75 This is only useful when debugging the HTTP subsystem.
76
77 Setting this to 1.0 will tell servers not to send chunked encoding,
78 and other HTTP/1.1 specific features.")
79
80 (defvar url-http-attempt-keepalives t
81 "Whether to use a single TCP connection multiple times in HTTP.
82 This is only useful when debugging the HTTP subsystem. Setting to
83 nil will explicitly close the connection to the server after every
84 request.")
85
86 (defconst url-http-codes
87 '((100 continue "Continue with request")
88 (101 switching-protocols "Switching protocols")
89 (102 processing "Processing (Added by DAV)")
90 (200 OK "OK")
91 (201 created "Created")
92 (202 accepted "Accepted")
93 (203 non-authoritative "Non-authoritative information")
94 (204 no-content "No content")
95 (205 reset-content "Reset content")
96 (206 partial-content "Partial content")
97 (207 multi-status "Multi-status (Added by DAV)")
98 (300 multiple-choices "Multiple choices")
99 (301 moved-permanently "Moved permanently")
100 (302 found "Found")
101 (303 see-other "See other")
102 (304 not-modified "Not modified")
103 (305 use-proxy "Use proxy")
104 (307 temporary-redirect "Temporary redirect")
105 (400 bad-request "Bad Request")
106 (401 unauthorized "Unauthorized")
107 (402 payment-required "Payment required")
108 (403 forbidden "Forbidden")
109 (404 not-found "Not found")
110 (405 method-not-allowed "Method not allowed")
111 (406 not-acceptable "Not acceptable")
112 (407 proxy-authentication-required "Proxy authentication required")
113 (408 request-timeout "Request time-out")
114 (409 conflict "Conflict")
115 (410 gone "Gone")
116 (411 length-required "Length required")
117 (412 precondition-failed "Precondition failed")
118 (413 request-entity-too-large "Request entity too large")
119 (414 request-uri-too-large "Request-URI too large")
120 (415 unsupported-media-type "Unsupported media type")
121 (416 requested-range-not-satisfiable "Requested range not satisfiable")
122 (417 expectation-failed "Expectation failed")
123 (422 unprocessable-entity "Unprocessable Entity (Added by DAV)")
124 (423 locked "Locked")
125 (424 failed-Dependency "Failed Dependency")
126 (500 internal-server-error "Internal server error")
127 (501 not-implemented "Not implemented")
128 (502 bad-gateway "Bad gateway")
129 (503 service-unavailable "Service unavailable")
130 (504 gateway-timeout "Gateway time-out")
131 (505 http-version-not-supported "HTTP version not supported")
132 (507 insufficient-storage "Insufficient storage"))
133 "The HTTP return codes and their text.")
134
135 ;(eval-when-compile
136 ;; These are all macros so that they are hidden from external sight
137 ;; when the file is byte-compiled.
138 ;;
139 ;; This allows us to expose just the entry points we want.
140
141 ;; These routines will allow us to implement persistent HTTP
142 ;; connections.
143 (defsubst url-http-debug (&rest args)
144 (if quit-flag
145 (let ((proc (get-buffer-process (current-buffer))))
146 ;; The user hit C-g, honor it! Some things can get in an
147 ;; incredibly tight loop (chunked encoding)
148 (if proc
149 (progn
150 (set-process-sentinel proc nil)
151 (set-process-filter proc nil)))
152 (error "Transfer interrupted!")))
153 (apply 'url-debug 'http args))
154
155 (defun url-http-mark-connection-as-busy (host port proc)
156 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc)
157 (set-process-query-on-exit-flag proc t)
158 (puthash (cons host port)
159 (delq proc (gethash (cons host port) url-http-open-connections))
160 url-http-open-connections)
161 proc)
162
163 (defun url-http-mark-connection-as-free (host port proc)
164 (url-http-debug "Marking connection as free: %s:%d %S" host port proc)
165 (when (memq (process-status proc) '(open run connect))
166 (set-process-buffer proc nil)
167 (set-process-sentinel proc 'url-http-idle-sentinel)
168 (set-process-query-on-exit-flag proc nil)
169 (puthash (cons host port)
170 (cons proc (gethash (cons host port) url-http-open-connections))
171 url-http-open-connections))
172 nil)
173
174 (defun url-http-find-free-connection (host port &optional gateway-method)
175 (let ((conns (gethash (cons host port) url-http-open-connections))
176 (connection nil))
177 (while (and conns (not connection))
178 (if (not (memq (process-status (car conns)) '(run open connect)))
179 (progn
180 (url-http-debug "Cleaning up dead process: %s:%d %S"
181 host port (car conns))
182 (url-http-idle-sentinel (car conns) nil))
183 (setq connection (car conns))
184 (url-http-debug "Found existing connection: %s:%d %S" host port connection))
185 (pop conns))
186 (if connection
187 (url-http-debug "Reusing existing connection: %s:%d" host port)
188 (url-http-debug "Contacting host: %s:%d" host port))
189 (url-lazy-message "Contacting host: %s:%d" host port)
190
191 (unless connection
192 (let ((buf (generate-new-buffer " *url-http-temp*")))
193 ;; `url-open-stream' needs a buffer in which to do things
194 ;; like authentication. But we use another buffer afterwards.
195 (unwind-protect
196 (let ((proc (url-open-stream host buf host port gateway-method)))
197 ;; url-open-stream might return nil.
198 (when (processp proc)
199 ;; Drop the temp buffer link before killing the buffer.
200 (set-process-buffer proc nil)
201 (setq connection proc)))
202 ;; If there was an error on connect, make sure we don't
203 ;; get queried.
204 (when (get-buffer-process buf)
205 (set-process-query-on-exit-flag (get-buffer-process buf) nil))
206 (kill-buffer buf))))
207
208 (if connection
209 (url-http-mark-connection-as-busy host port connection))))
210
211 ;; Building an HTTP request
212 (defun url-http-user-agent-string ()
213 (if (or (eq url-privacy-level 'paranoid)
214 (and (listp url-privacy-level)
215 (memq 'agent url-privacy-level)))
216 ""
217 (format "User-Agent: %sURL/%s\r\n"
218 (if url-package-name
219 (concat url-package-name "/" url-package-version " ")
220 "")
221 url-version)))
222
223 (defun url-http-create-request (&optional ref-url)
224 "Create an HTTP request for `url-http-target-url', referred to by REF-URL."
225 (let* ((extra-headers)
226 (request nil)
227 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers)))
228 (using-proxy url-http-proxy)
229 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
230 url-http-extra-headers))
231 (not using-proxy))
232 nil
233 (let ((url-basic-auth-storage
234 'url-http-proxy-basic-auth-storage))
235 (url-get-authentication url-http-proxy nil 'any nil))))
236 (real-fname (url-filename url-http-target-url))
237 (host (url-host url-http-target-url))
238 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers))
239 nil
240 (url-get-authentication (or
241 (and (boundp 'proxy-info)
242 proxy-info)
243 url-http-target-url) nil 'any nil))))
244 (if (equal "" real-fname)
245 (setq real-fname "/"))
246 (setq no-cache (and no-cache (string-match "no-cache" no-cache)))
247 (if auth
248 (setq auth (concat "Authorization: " auth "\r\n")))
249 (if proxy-auth
250 (setq proxy-auth (concat "Proxy-Authorization: " proxy-auth "\r\n")))
251
252 ;; Protection against stupid values in the referrer
253 (if (and ref-url (stringp ref-url) (or (string= ref-url "file:nil")
254 (string= ref-url "")))
255 (setq ref-url nil))
256
257 ;; We do not want to expose the referrer if the user is paranoid.
258 (if (or (memq url-privacy-level '(low high paranoid))
259 (and (listp url-privacy-level)
260 (memq 'lastloc url-privacy-level)))
261 (setq ref-url nil))
262
263 ;; url-http-extra-headers contains an assoc-list of
264 ;; header/value pairs that we need to put into the request.
265 (setq extra-headers (mapconcat
266 (lambda (x)
267 (concat (car x) ": " (cdr x)))
268 url-http-extra-headers "\r\n"))
269 (if (not (equal extra-headers ""))
270 (setq extra-headers (concat extra-headers "\r\n")))
271
272 ;; This was done with a call to `format'. Concatenating parts has
273 ;; the advantage of keeping the parts of each header together and
274 ;; allows us to elide null lines directly, at the cost of making
275 ;; the layout less clear.
276 (setq request
277 ;; We used to concat directly, but if one of the strings happens
278 ;; to being multibyte (even if it only contains pure ASCII) then
279 ;; every string gets converted with `string-MAKE-multibyte' which
280 ;; turns the 127-255 codes into things like latin-1 accented chars
281 ;; (it would work right if it used `string-TO-multibyte' instead).
282 ;; So to avoid the problem we force every string to be unibyte.
283 (mapconcat
284 ;; FIXME: Instead of `string-AS-unibyte' we'd want
285 ;; `string-to-unibyte', so as to properly signal an error if one
286 ;; of the strings contains a multibyte char.
287 'string-as-unibyte
288 (delq nil
289 (list
290 ;; The request
291 (or url-http-method "GET") " "
292 (if using-proxy (url-recreate-url url-http-target-url) real-fname)
293 " HTTP/" url-http-version "\r\n"
294 ;; Version of MIME we speak
295 "MIME-Version: 1.0\r\n"
296 ;; (maybe) Try to keep the connection open
297 "Connection: " (if (or using-proxy
298 (not url-http-attempt-keepalives))
299 "close" "keep-alive") "\r\n"
300 ;; HTTP extensions we support
301 (if url-extensions-header
302 (format
303 "Extension: %s\r\n" url-extensions-header))
304 ;; Who we want to talk to
305 (if (/= (url-port url-http-target-url)
306 (url-scheme-get-property
307 (url-type url-http-target-url) 'default-port))
308 (format
309 "Host: %s:%d\r\n" host (url-port url-http-target-url))
310 (format "Host: %s\r\n" host))
311 ;; Who its from
312 (if url-personal-mail-address
313 (concat
314 "From: " url-personal-mail-address "\r\n"))
315 ;; Encodings we understand
316 (if (or url-mime-encoding-string
317 ;; MS-Windows loads zlib dynamically, so recheck
318 ;; in case they made it available since
319 ;; initialization in url-vars.el.
320 (and (eq 'system-type 'windows-nt)
321 (fboundp 'zlib-available-p)
322 (zlib-available-p)
323 (setq url-mime-encoding-string "gzip")))
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 ""))
368 (url-http-debug "Request is: \n%s" request)
369 request))
370
371 ;; Parsing routines
372 (defun url-http-clean-headers ()
373 "Remove trailing \r from header lines.
374 This allows us to use `mail-fetch-field', etc.
375 Return the number of characters removed."
376 (let ((end (marker-position url-http-end-of-headers)))
377 (goto-char (point-min))
378 (while (re-search-forward "\r$" url-http-end-of-headers t)
379 (replace-match ""))
380 (- end url-http-end-of-headers)))
381
382 (defun url-http-handle-authentication (proxy)
383 (url-http-debug "Handling %s authentication" (if proxy "proxy" "normal"))
384 (let ((auths (or (nreverse
385 (mail-fetch-field
386 (if proxy "proxy-authenticate" "www-authenticate")
387 nil nil t))
388 '("basic")))
389 (type nil)
390 (url (url-recreate-url url-current-object))
391 (auth-url (url-recreate-url
392 (if (and proxy (boundp 'url-http-proxy))
393 url-http-proxy
394 url-current-object)))
395 (url-basic-auth-storage (if proxy
396 ;; Cheating, but who cares? :)
397 'url-http-proxy-basic-auth-storage
398 'url-http-real-basic-auth-storage))
399 auth
400 (strength 0))
401
402 ;; find strongest supported auth
403 (dolist (this-auth auths)
404 (setq this-auth (url-eat-trailing-space
405 (url-strip-leading-spaces
406 this-auth)))
407 (let* ((this-type
408 (downcase (if (string-match "[ \t]" this-auth)
409 (substring this-auth 0 (match-beginning 0))
410 this-auth)))
411 (registered (url-auth-registered this-type))
412 (this-strength (cddr registered)))
413 (when (and registered (> this-strength strength))
414 (setq auth this-auth
415 type this-type
416 strength this-strength))))
417
418 (if (not (url-auth-registered type))
419 (progn
420 (widen)
421 (goto-char (point-max))
422 (insert "<hr>Sorry, but I do not know how to handle " type
423 " authentication. If you'd like to write it,"
424 " please use M-x report-emacs-bug RET.<hr>")
425 ;; We used to set a `status' var (declared "special") but I can't
426 ;; find the corresponding let-binding, so it's probably an error.
427 ;; FIXME: Maybe it was supposed to set `success', i.e. to return t?
428 ;; (setq status t)
429 nil) ;; Not success yet.
430
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 t ;Success.
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))
444 nil))))) ;; Not success yet.
445
446 (defun url-http-parse-response ()
447 "Parse just the response code."
448 (if (not url-http-end-of-headers)
449 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
450 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
451 (goto-char (point-min))
452 (skip-chars-forward " \t\n") ; Skip any blank crap
453 (skip-chars-forward "HTTP/") ; Skip HTTP Version
454 (setq url-http-response-version
455 (buffer-substring (point)
456 (progn
457 (skip-chars-forward "[0-9].")
458 (point))))
459 (setq url-http-response-status (read (current-buffer))))
460
461 (defun url-http-handle-cookies ()
462 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
463 The buffer must already be narrowed to the headers, so `mail-fetch-field' will
464 work correctly."
465 (let ((cookies (nreverse (mail-fetch-field "Set-Cookie" nil nil t)))
466 (cookies2 (nreverse (mail-fetch-field "Set-Cookie2" nil nil t))))
467 (and cookies (url-http-debug "Found %d Set-Cookie headers" (length cookies)))
468 (and cookies2 (url-http-debug "Found %d Set-Cookie2 headers" (length cookies2)))
469 (while cookies
470 (url-cookie-handle-set-cookie (pop cookies)))
471 ;;; (while cookies2
472 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
473 )
474 )
475
476 (defun url-http-parse-headers ()
477 "Parse and handle HTTP specific headers.
478 Return t if and only if the current buffer is still active and
479 should be shown to the user."
480 ;; The comments after each status code handled are taken from RFC
481 ;; 2616 (HTTP/1.1)
482 (url-http-mark-connection-as-free (url-host url-current-object)
483 (url-port url-current-object)
484 url-http-process)
485
486 (if (or (not (boundp 'url-http-end-of-headers))
487 (not url-http-end-of-headers))
488 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
489 (goto-char (point-min))
490 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
491 (url-http-parse-response)
492 (mail-narrow-to-head)
493 ;;(narrow-to-region (point-min) url-http-end-of-headers)
494 (let ((connection (mail-fetch-field "Connection")))
495 ;; In HTTP 1.0, keep the connection only if there is a
496 ;; "Connection: keep-alive" header.
497 ;; In HTTP 1.1 (and greater), keep the connection unless there is a
498 ;; "Connection: close" header
499 (cond
500 ((string= url-http-response-version "1.0")
501 (unless (and connection
502 (string= (downcase connection) "keep-alive"))
503 (delete-process url-http-process)))
504 (t
505 (when (and connection
506 (string= (downcase connection) "close"))
507 (delete-process url-http-process)))))
508 (let* ((buffer (current-buffer))
509 (class (/ url-http-response-status 100))
510 (success nil)
511 ;; other status symbols: jewelry and luxury cars
512 (status-symbol (cadr (assq url-http-response-status url-http-codes))))
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))
517
518 (pcase class
519 ;; Classes of response codes
520 ;;
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 (_
547 ;; Generic success for all others. Store in the cache, and
548 ;; mark it as successful.
549 (widen)
550 (if (and url-automatic-caching (equal url-http-method "GET"))
551 (url-store-in-cache buffer))))
552 (setq success t))
553 (3 ; Redirection
554 ;; 300 Multiple choices
555 ;; 301 Moved permanently
556 ;; 302 Found
557 ;; 303 See other
558 ;; 304 Not modified
559 ;; 305 Use proxy
560 ;; 307 Temporary redirect
561 (let ((redirect-uri (or (mail-fetch-field "Location")
562 (mail-fetch-field "URI"))))
563 (pcase status-symbol
564 (`multiple-choices ; 300
565 ;; Quoth the spec (section 10.3.1)
566 ;; -------------------------------
567 ;; The requested resource corresponds to any one of a set of
568 ;; representations, each with its own specific location and
569 ;; agent-driven negotiation information is being provided so
570 ;; that the user can select a preferred representation and
571 ;; redirect its request to that location.
572 ;; [...]
573 ;; If the server has a preferred choice of representation, it
574 ;; SHOULD include the specific URI for that representation in
575 ;; the Location field; user agents MAY use the Location field
576 ;; value for automatic redirection.
577 ;; -------------------------------
578 ;; We do not support agent-driven negotiation, so we just
579 ;; redirect to the preferred URI if one is provided.
580 nil)
581 ((or `moved-permanently `found `temporary-redirect) ; 301 302 307
582 ;; If the 301|302 status code is received in response to a
583 ;; request other than GET or HEAD, the user agent MUST NOT
584 ;; automatically redirect the request unless it can be
585 ;; confirmed by the user, since this might change the
586 ;; conditions under which the request was issued.
587 (unless (member url-http-method '("HEAD" "GET"))
588 (setq redirect-uri nil)))
589 (`see-other ; 303
590 ;; The response to the request can be found under a different
591 ;; URI and SHOULD be retrieved using a GET method on that
592 ;; resource.
593 (setq url-http-method "GET"
594 url-http-data nil))
595 (`not-modified ; 304
596 ;; The 304 response MUST NOT contain a message-body.
597 (url-http-debug "Extracting document from cache... (%s)"
598 (url-cache-create-filename (url-view-url t)))
599 (url-cache-extract (url-cache-create-filename (url-view-url t)))
600 (setq redirect-uri nil
601 success t))
602 (`use-proxy ; 305
603 ;; The requested resource MUST be accessed through the
604 ;; proxy given by the Location field. The Location field
605 ;; gives the URI of the proxy. The recipient is expected
606 ;; to repeat this single request via the proxy. 305
607 ;; responses MUST only be generated by origin servers.
608 (error "Redirection thru a proxy server not supported: %s"
609 redirect-uri))
610 (_
611 ;; Treat everything like '300'
612 nil))
613 (when redirect-uri
614 ;; Clean off any whitespace and/or <...> cruft.
615 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri)
616 (setq redirect-uri (match-string 1 redirect-uri)))
617 (if (string-match "^<\\(.*\\)>$" redirect-uri)
618 (setq redirect-uri (match-string 1 redirect-uri)))
619
620 ;; Some stupid sites (like sourceforge) send a
621 ;; non-fully-qualified URL (ie: /), which royally confuses
622 ;; the URL library.
623 (if (not (string-match url-nonrelative-link redirect-uri))
624 ;; Be careful to use the real target URL, otherwise we may
625 ;; compute the redirection relative to the URL of the proxy.
626 (setq redirect-uri
627 (url-expand-file-name redirect-uri url-http-target-url)))
628 (let ((url-request-method url-http-method)
629 (url-request-data url-http-data)
630 (url-request-extra-headers url-http-extra-headers))
631 ;; Check existing number of redirects
632 (if (or (< url-max-redirections 0)
633 (and (> url-max-redirections 0)
634 (let ((events (car url-callback-arguments))
635 (old-redirects 0))
636 (while events
637 (if (eq (car events) :redirect)
638 (setq old-redirects (1+ old-redirects)))
639 (and (setq events (cdr events))
640 (setq events (cdr events))))
641 (< old-redirects url-max-redirections))))
642 ;; url-max-redirections hasn't been reached, so go
643 ;; ahead and redirect.
644 (progn
645 ;; Remember that the request was redirected.
646 (setf (car url-callback-arguments)
647 (nconc (list :redirect redirect-uri)
648 (car url-callback-arguments)))
649 ;; Put in the current buffer a forwarding pointer to the new
650 ;; destination buffer.
651 ;; FIXME: This is a hack to fix url-retrieve-synchronously
652 ;; without changing the API. Instead url-retrieve should
653 ;; either simply not return the "destination" buffer, or it
654 ;; should take an optional `dest-buf' argument.
655 (set (make-local-variable 'url-redirect-buffer)
656 (url-retrieve-internal
657 redirect-uri url-callback-function
658 url-callback-arguments
659 (url-silent url-current-object)
660 (not (url-use-cookies url-current-object))))
661 (url-mark-buffer-as-dead buffer))
662 ;; We hit url-max-redirections, so issue an error and
663 ;; stop redirecting.
664 (url-http-debug "Maximum redirections reached")
665 (setf (car url-callback-arguments)
666 (nconc (list :error (list 'error 'http-redirect-limit
667 redirect-uri))
668 (car url-callback-arguments)))
669 (setq success t))))))
670 (4 ; Client error
671 ;; 400 Bad Request
672 ;; 401 Unauthorized
673 ;; 402 Payment required
674 ;; 403 Forbidden
675 ;; 404 Not found
676 ;; 405 Method not allowed
677 ;; 406 Not acceptable
678 ;; 407 Proxy authentication required
679 ;; 408 Request time-out
680 ;; 409 Conflict
681 ;; 410 Gone
682 ;; 411 Length required
683 ;; 412 Precondition failed
684 ;; 413 Request entity too large
685 ;; 414 Request-URI too large
686 ;; 415 Unsupported media type
687 ;; 416 Requested range not satisfiable
688 ;; 417 Expectation failed
689 ;; 422 Unprocessable Entity (Added by DAV)
690 ;; 423 Locked
691 ;; 424 Failed Dependency
692 (setq success
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 t)
710 (`not-found ; 404
711 ;; Not found
712 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 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 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 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 t)
746 (`gone ; 410
747 ;; The requested resource is no longer available at the
748 ;; server and no forwarding address is known.
749 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.
755 ;;
756 ;; NOTE - this will never happen because
757 ;; `url-http-create-request' automatically calculates the
758 ;; content-length.
759 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 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 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 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 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 t)
788 (_
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 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)))))
799 (5
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)))))
854 (_
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-handle-content-transfer-encoding))
860 (url-http-debug "Finished parsing HTTP headers: %S" success)
861 (widen)
862 (goto-char (point-min))
863 success))
864
865 (declare-function zlib-decompress-region "decompress.c" (start end))
866
867 (defun url-handle-content-transfer-encoding ()
868 (let ((encoding (mail-fetch-field "content-encoding")))
869 (when (and encoding
870 (fboundp 'zlib-available-p)
871 (zlib-available-p)
872 (equal (downcase encoding) "gzip"))
873 (save-restriction
874 (widen)
875 (goto-char (point-min))
876 (when (search-forward "\n\n")
877 (zlib-decompress-region (point) (point-max)))))))
878
879 ;; Miscellaneous
880 (defun url-http-activate-callback ()
881 "Activate callback specified when this buffer was created."
882 (url-http-mark-connection-as-free (url-host url-current-object)
883 (url-port url-current-object)
884 url-http-process)
885 (url-http-debug "Activating callback in buffer (%s)" (buffer-name))
886 (apply url-callback-function url-callback-arguments))
887
888 ;; )
889
890 ;; These unfortunately cannot be macros... please ignore them!
891 (defun url-http-idle-sentinel (proc why)
892 "Remove (now defunct) process PROC from the list of open connections."
893 (maphash (lambda (key val)
894 (if (memq proc val)
895 (puthash key (delq proc val) url-http-open-connections)))
896 url-http-open-connections))
897
898 (defun url-http-end-of-document-sentinel (proc why)
899 ;; Sentinel used to handle (i) terminated old HTTP/0.9 connections,
900 ;; and (ii) closed connection due to reusing a HTTP connection which
901 ;; we believed was still alive, but which the server closed on us.
902 ;; We handle case (ii) by calling `url-http' again.
903 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
904 (process-buffer proc))
905 (url-http-idle-sentinel proc why)
906 (when (buffer-name (process-buffer proc))
907 (with-current-buffer (process-buffer proc)
908 (goto-char (point-min))
909 (cond ((not (looking-at "HTTP/"))
910 (if url-http-no-retry
911 ;; HTTP/0.9 just gets passed back no matter what
912 (url-http-activate-callback)
913 ;; Call `url-http' again if our connection expired.
914 (erase-buffer)
915 (let ((url-request-method url-http-method)
916 (url-request-extra-headers url-http-extra-headers)
917 (url-request-data url-http-data))
918 (url-http url-current-object url-callback-function
919 url-callback-arguments (current-buffer)))))
920 ((url-http-parse-headers)
921 (url-http-activate-callback))))))
922
923 (defun url-http-simple-after-change-function (st nd length)
924 ;; Function used when we do NOT know how long the document is going to be
925 ;; Just _very_ simple 'downloaded %d' type of info.
926 (url-lazy-message "Reading %s..." (file-size-human-readable nd)))
927
928 (defun url-http-content-length-after-change-function (st nd length)
929 "Function used when we DO know how long the document is going to be.
930 More sophisticated percentage downloaded, etc.
931 Also does minimal parsing of HTTP headers and will actually cause
932 the callback to be triggered."
933 (if url-http-content-type
934 (url-display-percentage
935 "Reading [%s]... %s of %s (%d%%)"
936 (url-percentage (- nd url-http-end-of-headers)
937 url-http-content-length)
938 url-http-content-type
939 (file-size-human-readable (- nd url-http-end-of-headers))
940 (file-size-human-readable url-http-content-length)
941 (url-percentage (- nd url-http-end-of-headers)
942 url-http-content-length))
943 (url-display-percentage
944 "Reading... %s of %s (%d%%)"
945 (url-percentage (- nd url-http-end-of-headers)
946 url-http-content-length)
947 (file-size-human-readable (- nd url-http-end-of-headers))
948 (file-size-human-readable url-http-content-length)
949 (url-percentage (- nd url-http-end-of-headers)
950 url-http-content-length)))
951
952 (if (> (- nd url-http-end-of-headers) url-http-content-length)
953 (progn
954 ;; Found the end of the document! Wheee!
955 (url-display-percentage nil nil)
956 (url-lazy-message "Reading... done.")
957 (if (url-http-parse-headers)
958 (url-http-activate-callback)))))
959
960 (defun url-http-chunked-encoding-after-change-function (st nd length)
961 "Function used when dealing with 'chunked' encoding.
962 Cannot give a sophisticated percentage, but we need a different
963 function to look for the special 0-length chunk that signifies
964 the end of the document."
965 (save-excursion
966 (goto-char st)
967 (let ((read-next-chunk t)
968 (case-fold-search t)
969 (regexp nil)
970 (no-initial-crlf nil))
971 ;; We need to loop thru looking for more chunks even within
972 ;; one after-change-function call.
973 (while read-next-chunk
974 (setq no-initial-crlf (= 0 url-http-chunked-counter))
975 (if url-http-content-type
976 (url-display-percentage nil
977 "Reading [%s]... chunk #%d"
978 url-http-content-type url-http-chunked-counter)
979 (url-display-percentage nil
980 "Reading... chunk #%d"
981 url-http-chunked-counter))
982 (url-http-debug "Reading chunk %d (%d %d %d)"
983 url-http-chunked-counter st nd length)
984 (setq regexp (if no-initial-crlf
985 "\\([0-9a-z]+\\).*\r?\n"
986 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
987
988 (if url-http-chunked-start
989 ;; We know how long the chunk is supposed to be, skip over
990 ;; leading crap if possible.
991 (if (> nd (+ url-http-chunked-start url-http-chunked-length))
992 (progn
993 (url-http-debug "Got to the end of chunk #%d!"
994 url-http-chunked-counter)
995 (goto-char (+ url-http-chunked-start
996 url-http-chunked-length)))
997 (url-http-debug "Still need %d bytes to hit end of chunk"
998 (- (+ url-http-chunked-start
999 url-http-chunked-length)
1000 nd))
1001 (setq read-next-chunk nil)))
1002 (if (not read-next-chunk)
1003 (url-http-debug "Still spinning for next chunk...")
1004 (if no-initial-crlf (skip-chars-forward "\r\n"))
1005 (if (not (looking-at regexp))
1006 (progn
1007 ;; Must not have received the entirety of the chunk header,
1008 ;; need to spin some more.
1009 (url-http-debug "Did not see start of chunk @ %d!" (point))
1010 (setq read-next-chunk nil))
1011 (add-text-properties (match-beginning 0) (match-end 0)
1012 (list 'start-open t
1013 'end-open t
1014 'chunked-encoding t
1015 'face 'cursor
1016 'invisible t))
1017 (setq url-http-chunked-length (string-to-number (buffer-substring
1018 (match-beginning 1)
1019 (match-end 1))
1020 16)
1021 url-http-chunked-counter (1+ url-http-chunked-counter)
1022 url-http-chunked-start (set-marker
1023 (or url-http-chunked-start
1024 (make-marker))
1025 (match-end 0)))
1026 ; (if (not url-http-debug)
1027 (delete-region (match-beginning 0) (match-end 0));)
1028 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1029 url-http-chunked-counter url-http-chunked-length
1030 (marker-position url-http-chunked-start))
1031 (if (= 0 url-http-chunked-length)
1032 (progn
1033 ;; Found the end of the document! Wheee!
1034 (url-http-debug "Saw end of stream chunk!")
1035 (setq read-next-chunk nil)
1036 (url-display-percentage nil nil)
1037 ;; Every chunk, even the last 0-length one, is
1038 ;; terminated by CRLF. Skip it.
1039 (when (looking-at "\r?\n")
1040 (url-http-debug "Removing terminator of last chunk")
1041 (delete-region (match-beginning 0) (match-end 0)))
1042 (if (re-search-forward "^\r*$" nil t)
1043 (url-http-debug "Saw end of trailers..."))
1044 (if (url-http-parse-headers)
1045 (url-http-activate-callback))))))))))
1046
1047 (defun url-http-wait-for-headers-change-function (st nd length)
1048 ;; This will wait for the headers to arrive and then splice in the
1049 ;; next appropriate after-change-function, etc.
1050 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1051 (buffer-name))
1052 (let ((end-of-headers nil)
1053 (old-http nil)
1054 (process-buffer (current-buffer))
1055 (content-length nil))
1056 (when (not (bobp))
1057 (goto-char (point-min))
1058 (if (and (looking-at ".*\n") ; have one line at least
1059 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1060 ;; Not HTTP/x.y data, must be 0.9
1061 ;; God, I wish this could die.
1062 (setq end-of-headers t
1063 url-http-end-of-headers 0
1064 old-http t)
1065 ;; Blank line at end of headers.
1066 (when (re-search-forward "^\r?\n" nil t)
1067 (backward-char 1)
1068 ;; Saw the end of the headers
1069 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1070 (setq url-http-end-of-headers (set-marker (make-marker)
1071 (point))
1072 end-of-headers t)
1073 (setq nd (- nd (url-http-clean-headers)))))
1074
1075 (if (not end-of-headers)
1076 ;; Haven't seen the end of the headers yet, need to wait
1077 ;; for more data to arrive.
1078 nil
1079 (unless old-http
1080 (url-http-parse-response)
1081 (mail-narrow-to-head)
1082 (setq url-http-transfer-encoding (mail-fetch-field
1083 "transfer-encoding")
1084 url-http-content-type (mail-fetch-field "content-type"))
1085 (if (mail-fetch-field "content-length")
1086 (setq url-http-content-length
1087 (string-to-number (mail-fetch-field "content-length"))))
1088 (widen))
1089 (when url-http-transfer-encoding
1090 (setq url-http-transfer-encoding
1091 (downcase url-http-transfer-encoding)))
1092
1093 (cond
1094 ((null url-http-response-status)
1095 ;; We got back a headerless malformed response from the
1096 ;; server.
1097 (url-http-activate-callback))
1098 ((or (= url-http-response-status 204)
1099 (= url-http-response-status 205))
1100 (url-http-debug "%d response must have headers only (%s)."
1101 url-http-response-status (buffer-name))
1102 (when (url-http-parse-headers)
1103 (url-http-activate-callback)))
1104 ((string= "HEAD" url-http-method)
1105 ;; A HEAD request is _ALWAYS_ terminated by the header
1106 ;; information, regardless of any entity headers,
1107 ;; according to section 4.4 of the HTTP/1.1 draft.
1108 (url-http-debug "HEAD request must have headers only (%s)."
1109 (buffer-name))
1110 (when (url-http-parse-headers)
1111 (url-http-activate-callback)))
1112 ((string= "CONNECT" url-http-method)
1113 ;; A CONNECT request is finished, but we cannot stick this
1114 ;; back on the free connection list
1115 (url-http-debug "CONNECT request must have headers only.")
1116 (when (url-http-parse-headers)
1117 (url-http-activate-callback)))
1118 ((equal url-http-response-status 304)
1119 ;; Only allowed to have a header section. We have to handle
1120 ;; this here instead of in url-http-parse-headers because if
1121 ;; you have a cached copy of something without a known
1122 ;; content-length, and try to retrieve it from the cache, we'd
1123 ;; fall into the 'being dumb' section and wait for the
1124 ;; connection to terminate, which means we'd wait for 10
1125 ;; seconds for the keep-alives to time out on some servers.
1126 (when (url-http-parse-headers)
1127 (url-http-activate-callback)))
1128 (old-http
1129 ;; HTTP/0.9 always signaled end-of-connection by closing the
1130 ;; connection.
1131 (url-http-debug
1132 "Saw HTTP/0.9 response, connection closed means end of document.")
1133 (setq url-http-after-change-function
1134 'url-http-simple-after-change-function))
1135 ((equal url-http-transfer-encoding "chunked")
1136 (url-http-debug "Saw chunked encoding.")
1137 (setq url-http-after-change-function
1138 'url-http-chunked-encoding-after-change-function)
1139 (when (> nd url-http-end-of-headers)
1140 (url-http-debug
1141 "Calling initial chunked-encoding for extra data at end of headers")
1142 (url-http-chunked-encoding-after-change-function
1143 (marker-position url-http-end-of-headers) nd
1144 (- nd url-http-end-of-headers))))
1145 ((integerp url-http-content-length)
1146 (url-http-debug
1147 "Got a content-length, being smart about document end.")
1148 (setq url-http-after-change-function
1149 'url-http-content-length-after-change-function)
1150 (cond
1151 ((= 0 url-http-content-length)
1152 ;; We got a NULL body! Activate the callback
1153 ;; immediately!
1154 (url-http-debug
1155 "Got 0-length content-length, activating callback immediately.")
1156 (when (url-http-parse-headers)
1157 (url-http-activate-callback)))
1158 ((> nd url-http-end-of-headers)
1159 ;; Have some leftover data
1160 (url-http-debug "Calling initial content-length for extra data at end of headers")
1161 (url-http-content-length-after-change-function
1162 (marker-position url-http-end-of-headers)
1163 nd
1164 (- nd url-http-end-of-headers)))
1165 (t
1166 nil)))
1167 (t
1168 (url-http-debug "No content-length, being dumb.")
1169 (setq url-http-after-change-function
1170 'url-http-simple-after-change-function)))))
1171 ;; We are still at the beginning of the buffer... must just be
1172 ;; waiting for a response.
1173 (url-http-debug "Spinning waiting for headers...")
1174 (when (eq process-buffer (current-buffer))
1175 (goto-char (point-max)))))
1176
1177 (defun url-http (url callback cbargs &optional retry-buffer gateway-method)
1178 "Retrieve URL via HTTP asynchronously.
1179 URL must be a parsed URL. See `url-generic-parse-url' for details.
1180
1181 When retrieval is completed, execute the function CALLBACK, passing it
1182 an updated value of CBARGS as arguments. The first element in CBARGS
1183 should be a plist describing what has happened so far during the
1184 request, as described in the docstring of `url-retrieve' (if in
1185 doubt, specify nil).
1186
1187 Optional arg RETRY-BUFFER, if non-nil, specifies the buffer of a
1188 previous `url-http' call, which is being re-attempted.
1189
1190 Optional arg GATEWAY-METHOD specifies the gateway to be used,
1191 overriding the value of `url-gateway-method'."
1192 (cl-check-type url vector "Need a pre-parsed URL.")
1193 (let* ((host (url-host (or url-using-proxy url)))
1194 (port (url-port (or url-using-proxy url)))
1195 (connection (url-http-find-free-connection host port gateway-method))
1196 (buffer (or retry-buffer
1197 (generate-new-buffer
1198 (format " *http %s:%d*" host port)))))
1199 (if (not connection)
1200 ;; Failed to open the connection for some reason
1201 (progn
1202 (kill-buffer buffer)
1203 (setq buffer nil)
1204 (error "Could not create connection to %s:%d" host port))
1205 (with-current-buffer buffer
1206 (mm-disable-multibyte)
1207 (setq url-current-object url
1208 mode-line-format "%b [%s]")
1209
1210 (dolist (var '(url-http-end-of-headers
1211 url-http-content-type
1212 url-http-content-length
1213 url-http-transfer-encoding
1214 url-http-after-change-function
1215 url-http-response-version
1216 url-http-response-status
1217 url-http-chunked-length
1218 url-http-chunked-counter
1219 url-http-chunked-start
1220 url-callback-function
1221 url-callback-arguments
1222 url-show-status
1223 url-http-process
1224 url-http-method
1225 url-http-extra-headers
1226 url-http-data
1227 url-http-target-url
1228 url-http-no-retry
1229 url-http-connection-opened
1230 url-http-proxy))
1231 (set (make-local-variable var) nil))
1232
1233 (setq url-http-method (or url-request-method "GET")
1234 url-http-extra-headers url-request-extra-headers
1235 url-http-data url-request-data
1236 url-http-process connection
1237 url-http-chunked-length nil
1238 url-http-chunked-start nil
1239 url-http-chunked-counter 0
1240 url-callback-function callback
1241 url-callback-arguments cbargs
1242 url-http-after-change-function 'url-http-wait-for-headers-change-function
1243 url-http-target-url url-current-object
1244 url-http-no-retry retry-buffer
1245 url-http-connection-opened nil
1246 url-http-proxy url-using-proxy)
1247
1248 (set-process-buffer connection buffer)
1249 (set-process-filter connection 'url-http-generic-filter)
1250 (pcase (process-status connection)
1251 (`connect
1252 ;; Asynchronous connection
1253 (set-process-sentinel connection 'url-http-async-sentinel))
1254 (`failed
1255 ;; Asynchronous connection failed
1256 (error "Could not create connection to %s:%d" host port))
1257 (_
1258 (set-process-sentinel connection
1259 'url-http-end-of-document-sentinel)
1260 (process-send-string connection (url-http-create-request))))))
1261 buffer))
1262
1263 (defun url-http-async-sentinel (proc why)
1264 ;; We are performing an asynchronous connection, and a status change
1265 ;; has occurred.
1266 (when (buffer-name (process-buffer proc))
1267 (with-current-buffer (process-buffer proc)
1268 (cond
1269 (url-http-connection-opened
1270 (setq url-http-no-retry t)
1271 (url-http-end-of-document-sentinel proc why))
1272 ((string= (substring why 0 4) "open")
1273 (setq url-http-connection-opened t)
1274 (condition-case error
1275 (process-send-string proc (url-http-create-request))
1276 (file-error
1277 (setq url-http-connection-opened nil)
1278 (message "HTTP error: %s" error))))
1279 (t
1280 (setf (car url-callback-arguments)
1281 (nconc (list :error (list 'error 'connection-failed why
1282 :host (url-host (or url-http-proxy url-current-object))
1283 :service (url-port (or url-http-proxy url-current-object))))
1284 (car url-callback-arguments)))
1285 (url-http-activate-callback))))))
1286
1287 ;; Since Emacs 19/20 does not allow you to change the
1288 ;; `after-change-functions' hook in the midst of running them, we fake
1289 ;; an after change by hooking into the process filter and inserting
1290 ;; the data ourselves. This is slightly less efficient, but there
1291 ;; were tons of weird ways the after-change code was biting us in the
1292 ;; shorts.
1293 ;; FIXME this can probably be simplified since the above is no longer true.
1294 (defun url-http-generic-filter (proc data)
1295 ;; Sometimes we get a zero-length data chunk after the process has
1296 ;; been changed to 'free', which means it has no buffer associated
1297 ;; with it. Do nothing if there is no buffer, or 0 length data.
1298 (and (process-buffer proc)
1299 (/= (length data) 0)
1300 (with-current-buffer (process-buffer proc)
1301 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc)
1302 (funcall url-http-after-change-function
1303 (point-max)
1304 (progn
1305 (goto-char (point-max))
1306 (insert data)
1307 (point-max))
1308 (length data)))))
1309
1310 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1311 ;;; file-name-handler stuff from here on out
1312 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1313 (defalias 'url-http-symbol-value-in-buffer
1314 (if (fboundp 'symbol-value-in-buffer)
1315 'symbol-value-in-buffer
1316 (lambda (symbol buffer &optional unbound-value)
1317 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1318 (with-current-buffer buffer
1319 (if (not (boundp symbol))
1320 unbound-value
1321 (symbol-value symbol))))))
1322
1323 (defun url-http-head (url)
1324 (let ((url-request-method "HEAD")
1325 (url-request-data nil))
1326 (url-retrieve-synchronously url)))
1327
1328 (defun url-http-file-exists-p (url)
1329 (let ((buffer (url-http-head url)))
1330 (when buffer
1331 (let ((status (url-http-symbol-value-in-buffer 'url-http-response-status
1332 buffer 500)))
1333 (prog1
1334 (and (integerp status)
1335 (>= status 200) (< status 300))
1336 (kill-buffer buffer))))))
1337
1338 (defalias 'url-http-file-readable-p 'url-http-file-exists-p)
1339
1340 (defun url-http-head-file-attributes (url &optional id-format)
1341 (let ((buffer (url-http-head url)))
1342 (when buffer
1343 (prog1
1344 (list
1345 nil ;dir / link / normal file
1346 1 ;number of links to file.
1347 0 0 ;uid ; gid
1348 nil nil nil ;atime ; mtime ; ctime
1349 (url-http-symbol-value-in-buffer 'url-http-content-length
1350 buffer -1)
1351 (eval-when-compile (make-string 10 ?-))
1352 nil nil nil) ;whether gid would change ; inode ; device.
1353 (kill-buffer buffer)))))
1354
1355 (declare-function url-dav-file-attributes "url-dav" (url &optional id-format))
1356
1357 (defun url-http-file-attributes (url &optional id-format)
1358 (if (url-dav-supported-p url)
1359 (url-dav-file-attributes url id-format)
1360 (url-http-head-file-attributes url id-format)))
1361
1362 (defun url-http-options (url)
1363 "Return a property list describing options available for URL.
1364 This list is retrieved using the `OPTIONS' HTTP method.
1365
1366 Property list members:
1367
1368 methods
1369 A list of symbols specifying what HTTP methods the resource
1370 supports.
1371
1372 dav
1373 A list of numbers specifying what DAV protocol/schema versions are
1374 supported.
1375
1376 dasl
1377 A list of supported DASL search types supported (string form)
1378
1379 ranges
1380 A list of the units available for use in partial document fetches.
1381
1382 p3p
1383 The `Platform For Privacy Protection' description for the resource.
1384 Currently this is just the raw header contents. This is likely to
1385 change once P3P is formally supported by the URL package or
1386 Emacs/W3."
1387 (let* ((url-request-method "OPTIONS")
1388 (url-request-data nil)
1389 (buffer (url-retrieve-synchronously url))
1390 (header nil)
1391 (options nil))
1392 (when (and buffer (= 2 (/ (url-http-symbol-value-in-buffer
1393 'url-http-response-status buffer 0) 100)))
1394 ;; Only parse the options if we got a 2xx response code!
1395 (with-current-buffer buffer
1396 (save-restriction
1397 (save-match-data
1398 (mail-narrow-to-head)
1399
1400 ;; Figure out what methods are supported.
1401 (when (setq header (mail-fetch-field "allow"))
1402 (setq options (plist-put
1403 options 'methods
1404 (mapcar 'intern (split-string header "[ ,]+")))))
1405
1406 ;; Check for DAV
1407 (when (setq header (mail-fetch-field "dav"))
1408 (setq options (plist-put
1409 options 'dav
1410 (delq 0
1411 (mapcar 'string-to-number
1412 (split-string header "[, ]+"))))))
1413
1414 ;; Now for DASL
1415 (when (setq header (mail-fetch-field "dasl"))
1416 (setq options (plist-put
1417 options 'dasl
1418 (split-string header "[, ]+"))))
1419
1420 ;; P3P - should get more detailed here. FIXME
1421 (when (setq header (mail-fetch-field "p3p"))
1422 (setq options (plist-put options 'p3p header)))
1423
1424 ;; Check for whether they accept byte-range requests.
1425 (when (setq header (mail-fetch-field "accept-ranges"))
1426 (setq options (plist-put
1427 options 'ranges
1428 (delq 'none
1429 (mapcar 'intern
1430 (split-string header "[, ]+"))))))
1431 ))))
1432 (if buffer (kill-buffer buffer))
1433 options))
1434
1435 ;; HTTPS. This used to be in url-https.el, but that file collides
1436 ;; with url-http.el on systems with 8-character file names.
1437 (require 'tls)
1438
1439 (defconst url-https-default-port 443 "Default HTTPS port.")
1440 (defconst url-https-asynchronous-p t "HTTPS retrievals are asynchronous.")
1441
1442 ;; FIXME what is the point of this alias being an autoload?
1443 ;; Trying to use it will not cause url-http to be loaded,
1444 ;; since the full alias just gets dumped into loaddefs.el.
1445
1446 ;;;###autoload (autoload 'url-default-expander "url-expand")
1447 ;;;###autoload
1448 (defalias 'url-https-expand-file-name 'url-default-expander)
1449
1450 (defmacro url-https-create-secure-wrapper (method args)
1451 `(defun ,(intern (format (if method "url-https-%s" "url-https") method)) ,args
1452 ,(format "HTTPS wrapper around `%s' call." (or method "url-http"))
1453 (,(intern (format (if method "url-http-%s" "url-http") method))
1454 ,@(remove '&rest (remove '&optional (append args (if method nil '(nil 'tls))))))))
1455
1456 ;;;###autoload (autoload 'url-https "url-http")
1457 (url-https-create-secure-wrapper nil (url callback cbargs))
1458 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1459 (url-https-create-secure-wrapper file-exists-p (url))
1460 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1461 (url-https-create-secure-wrapper file-readable-p (url))
1462 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1463 (url-https-create-secure-wrapper file-attributes (url &optional id-format))
1464
1465 (provide 'url-http)
1466
1467 ;;; url-http.el ends here