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