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