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