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