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