1 ;;; url-http.el --- HTTP retrieval routines -*- lexical-binding:t -*-
3 ;; Copyright (C) 1999, 2001, 2004-2018 Free Software Foundation, Inc.
5 ;; Author: Bill Perry <wmperry@gnu.org>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: comm, data, processes
9 ;; This file is part of GNU Emacs.
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.
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.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
34 (defvar url-callback-arguments
)
35 (defvar url-callback-function
)
36 (defvar url-current-object
)
37 (defvar url-http-after-change-function
)
38 (defvar url-http-chunked-counter
)
39 (defvar url-http-chunked-length
)
40 (defvar url-http-chunked-start
)
41 (defvar url-http-connection-opened
)
42 (defvar url-http-content-length
)
43 (defvar url-http-content-type
)
44 (defvar url-http-data
)
45 (defvar url-http-end-of-headers
)
46 (defvar url-http-extra-headers
)
47 (defvar url-http-noninteractive
)
48 (defvar url-http-method
)
49 (defvar url-http-no-retry
)
50 (defvar url-http-process
)
51 (defvar url-http-proxy
)
52 (defvar url-http-response-status
)
53 (defvar url-http-response-version
)
54 (defvar url-http-target-url
)
55 (defvar url-http-transfer-encoding
)
56 (defvar url-show-status
)
57 (defvar url-http-referer
)
65 (autoload 'url-cache-create-filename
"url-cache")
67 (defconst url-http-default-port
80 "Default HTTP port.")
68 (defconst url-http-asynchronous-p t
"HTTP retrievals are asynchronous.")
69 (defalias 'url-http-expand-file-name
'url-default-expander
)
71 (defvar url-http-real-basic-auth-storage nil
)
72 (defvar url-http-proxy-basic-auth-storage nil
)
74 (defvar url-http-open-connections
(make-hash-table :test
'equal
76 "A hash table of all open network connections.")
78 (defvar url-http-version
"1.1"
79 "What version of HTTP we advertise, as a string.
80 Valid values are 1.1 and 1.0.
81 This is only useful when debugging the HTTP subsystem.
83 Setting this to 1.0 will tell servers not to send chunked encoding,
84 and other HTTP/1.1 specific features.")
86 (defvar url-http-attempt-keepalives t
87 "Whether to use a single TCP connection multiple times in HTTP.
88 This is only useful when debugging the HTTP subsystem. Setting to
89 nil will explicitly close the connection to the server after every
92 (defconst url-http-codes
93 '((100 continue
"Continue with request")
94 (101 switching-protocols
"Switching protocols")
95 (102 processing
"Processing (Added by DAV)")
97 (201 created
"Created")
98 (202 accepted
"Accepted")
99 (203 non-authoritative
"Non-authoritative information")
100 (204 no-content
"No content")
101 (205 reset-content
"Reset content")
102 (206 partial-content
"Partial content")
103 (207 multi-status
"Multi-status (Added by DAV)")
104 (300 multiple-choices
"Multiple choices")
105 (301 moved-permanently
"Moved permanently")
107 (303 see-other
"See other")
108 (304 not-modified
"Not modified")
109 (305 use-proxy
"Use proxy")
110 (307 temporary-redirect
"Temporary redirect")
111 (400 bad-request
"Bad Request")
112 (401 unauthorized
"Unauthorized")
113 (402 payment-required
"Payment required")
114 (403 forbidden
"Forbidden")
115 (404 not-found
"Not found")
116 (405 method-not-allowed
"Method not allowed")
117 (406 not-acceptable
"Not acceptable")
118 (407 proxy-authentication-required
"Proxy authentication required")
119 (408 request-timeout
"Request time-out")
120 (409 conflict
"Conflict")
122 (411 length-required
"Length required")
123 (412 precondition-failed
"Precondition failed")
124 (413 request-entity-too-large
"Request entity too large")
125 (414 request-uri-too-large
"Request-URI too large")
126 (415 unsupported-media-type
"Unsupported media type")
127 (416 requested-range-not-satisfiable
"Requested range not satisfiable")
128 (417 expectation-failed
"Expectation failed")
129 (422 unprocessable-entity
"Unprocessable Entity (Added by DAV)")
130 (423 locked
"Locked")
131 (424 failed-Dependency
"Failed Dependency")
132 (451 unavailable-for-legal-reasons
"Unavailable for legal reasons") ;RFC 7725
133 (500 internal-server-error
"Internal server error")
134 (501 not-implemented
"Not implemented")
135 (502 bad-gateway
"Bad gateway")
136 (503 service-unavailable
"Service unavailable")
137 (504 gateway-timeout
"Gateway time-out")
138 (505 http-version-not-supported
"HTTP version not supported")
139 (507 insufficient-storage
"Insufficient storage"))
140 "The HTTP return codes and their text.")
142 (defconst url-https-default-port
443 "Default HTTPS port.")
145 ;; These are all macros so that they are hidden from external sight
146 ;; when the file is byte-compiled.
148 ;; This allows us to expose just the entry points we want.
150 ;; These routines will allow us to implement persistent HTTP
152 (defsubst url-http-debug
(&rest args
)
154 (let ((proc (get-buffer-process (current-buffer))))
155 ;; The user hit C-g, honor it! Some things can get in an
156 ;; incredibly tight loop (chunked encoding)
159 (set-process-sentinel proc nil
)
160 (set-process-filter proc nil
)))
161 (error "Transfer interrupted!")))
162 (apply 'url-debug
'http args
))
164 (defun url-http-mark-connection-as-busy (host port proc
)
165 (url-http-debug "Marking connection as busy: %s:%d %S" host port proc
)
166 (set-process-query-on-exit-flag proc t
)
167 (puthash (cons host port
)
168 (delq proc
(gethash (cons host port
) url-http-open-connections
))
169 url-http-open-connections
)
172 (defun url-http-mark-connection-as-free (host port proc
)
173 (url-http-debug "Marking connection as free: %s:%d %S" host port proc
)
174 (when (memq (process-status proc
) '(open run connect
))
175 (set-process-buffer proc nil
)
176 (set-process-sentinel proc
'url-http-idle-sentinel
)
177 (set-process-query-on-exit-flag proc nil
)
178 (puthash (cons host port
)
179 (cons proc
(gethash (cons host port
) url-http-open-connections
))
180 url-http-open-connections
))
183 (defun url-http-find-free-connection (host port
&optional gateway-method
)
184 (let ((conns (gethash (cons host port
) url-http-open-connections
))
186 (while (and conns
(not connection
))
187 (if (not (memq (process-status (car conns
)) '(run open connect
)))
189 (url-http-debug "Cleaning up dead process: %s:%d %S"
190 host port
(car conns
))
191 (url-http-idle-sentinel (car conns
) nil
))
192 (setq connection
(car conns
))
193 (url-http-debug "Found existing connection: %s:%d %S" host port connection
))
196 (url-http-debug "Reusing existing connection: %s:%d" host port
)
197 (url-http-debug "Contacting host: %s:%d" host port
))
198 (url-lazy-message "Contacting host: %s:%d" host port
)
201 (let ((buf (generate-new-buffer " *url-http-temp*")))
202 ;; `url-open-stream' needs a buffer in which to do things
203 ;; like authentication. But we use another buffer afterwards.
205 (let ((proc (url-open-stream host buf
207 (url-host url-using-proxy
)
210 (url-port url-using-proxy
)
213 ;; url-open-stream might return nil.
214 (when (processp proc
)
215 ;; Drop the temp buffer link before killing the buffer.
216 (set-process-buffer proc nil
)
217 (setq connection proc
)))
218 ;; If there was an error on connect, make sure we don't
220 (when (get-buffer-process buf
)
221 (set-process-query-on-exit-flag (get-buffer-process buf
) nil
))
225 (url-http-mark-connection-as-busy host port connection
))))
227 (defun url-http--user-agent-default-string ()
228 "Compute a default User-Agent string based on `url-privacy-level'."
229 (let ((package-info (when url-package-name
230 (format "%s/%s" url-package-name url-package-version
)))
231 (emacs-info (unless (and (listp url-privacy-level
)
232 (memq 'emacs url-privacy-level
))
233 (format "Emacs/%s" emacs-version
)))
234 (os-info (unless (and (listp url-privacy-level
)
235 (memq 'os url-privacy-level
))
236 (format "(%s; %s)" url-system-type url-os-type
)))
237 (url-info (format "URL/%s" url-version
)))
238 (string-join (delq nil
(list package-info url-info
242 (defun url-http--get-referer (url)
243 (url-http-debug "getting referer from buffer: buffer:%S target-url:%S lastloc:%S" (current-buffer) url url-current-lastloc
)
244 (when url-current-lastloc
245 (if (not (url-p url-current-lastloc
))
246 (setq url-current-lastloc
(url-generic-parse-url url-current-lastloc
)))
247 (let ((referer (copy-sequence url-current-lastloc
)))
248 (setf (url-host referer
) (puny-encode-domain (url-host referer
)))
249 (let ((referer-string (url-recreate-url referer
)))
250 (when (and (not (memq url-privacy-level
'(low high paranoid
)))
251 (not (and (listp url-privacy-level
)
252 (memq 'lastloc url-privacy-level
))))
253 ;; url-privacy-level allows referer. But url-lastloc-privacy-level
254 ;; may restrict who we send it to.
255 (cl-case url-lastloc-privacy-level
257 (let ((referer-host (url-host referer
))
258 (url-host (url-host url
)))
259 (when (string= referer-host url-host
)
262 (let ((referer-domain (url-domain referer
))
263 (url-domain (url-domain url
)))
264 (when (and referer-domain
266 (string= referer-domain url-domain
))
269 referer-string
)))))))
271 ;; Building an HTTP request
272 (defun url-http-user-agent-string ()
273 "Compute a User-Agent string.
274 The string is based on `url-privacy-level' and `url-user-agent'."
276 (or (eq url-privacy-level
'paranoid
)
277 (and (listp url-privacy-level
)
278 (memq 'agent url-privacy-level
))))
282 ((functionp url-user-agent
) (funcall url-user-agent
))
283 ((stringp url-user-agent
) url-user-agent
)
284 ((eq url-user-agent
'default
) (url-http--user-agent-default-string))))))
285 (if ua-string
(format "User-Agent: %s\r\n" (string-trim ua-string
)) "")))
287 (defun url-http-create-request ()
288 "Create an HTTP request for `url-http-target-url', using `url-http-referer'
289 as the Referer-header (subject to `url-privacy-level'."
290 (let* ((extra-headers)
292 (no-cache (cdr-safe (assoc "Pragma" url-http-extra-headers
)))
293 (using-proxy url-http-proxy
)
294 (proxy-auth (if (or (cdr-safe (assoc "Proxy-Authorization"
295 url-http-extra-headers
))
298 (let ((url-basic-auth-storage
299 'url-http-proxy-basic-auth-storage
))
300 (url-get-authentication url-http-proxy nil
'any nil
))))
301 (real-fname (url-filename url-http-target-url
))
302 (host (url-host url-http-target-url
))
303 (auth (if (cdr-safe (assoc "Authorization" url-http-extra-headers
))
305 (url-get-authentication (or
306 (and (boundp 'proxy-info
)
308 url-http-target-url
) nil
'any nil
)))
309 (ref-url url-http-referer
))
310 (if (equal "" real-fname
)
311 (setq real-fname
"/"))
312 (setq no-cache
(and no-cache
(string-match "no-cache" no-cache
)))
314 (setq auth
(concat "Authorization: " auth
"\r\n")))
316 (setq proxy-auth
(concat "Proxy-Authorization: " proxy-auth
"\r\n")))
318 ;; Protection against stupid values in the referrer
319 (if (and ref-url
(stringp ref-url
) (or (string= ref-url
"file:nil")
320 (string= ref-url
"")))
323 ;; url-http-extra-headers contains an assoc-list of
324 ;; header/value pairs that we need to put into the request.
325 (setq extra-headers
(mapconcat
327 (concat (car x
) ": " (cdr x
)))
328 url-http-extra-headers
"\r\n"))
329 (if (not (equal extra-headers
""))
330 (setq extra-headers
(concat extra-headers
"\r\n")))
332 ;; This was done with a call to `format'. Concatenating parts has
333 ;; the advantage of keeping the parts of each header together and
334 ;; allows us to elide null lines directly, at the cost of making
335 ;; the layout less clear.
339 (or url-http-method
"GET") " "
340 (url-http--encode-string
341 (if using-proxy
(url-recreate-url url-http-target-url
) real-fname
))
342 " HTTP/" url-http-version
"\r\n"
343 ;; Version of MIME we speak
344 "MIME-Version: 1.0\r\n"
345 ;; (maybe) Try to keep the connection open
346 "Connection: " (if (or using-proxy
347 (not url-http-attempt-keepalives
))
348 "close" "keep-alive") "\r\n"
349 ;; HTTP extensions we support
350 (if url-extensions-header
352 "Extension: %s\r\n" url-extensions-header
))
353 ;; Who we want to talk to
354 (if (/= (url-port url-http-target-url
)
355 (url-scheme-get-property
356 (url-type url-http-target-url
) 'default-port
))
358 "Host: %s:%d\r\n" (puny-encode-domain host
)
359 (url-port url-http-target-url
))
360 (format "Host: %s\r\n" (puny-encode-domain host
)))
362 (if url-personal-mail-address
364 "From: " url-personal-mail-address
"\r\n"))
365 ;; Encodings we understand
366 (if (or url-mime-encoding-string
367 ;; MS-Windows loads zlib dynamically, so recheck
368 ;; in case they made it available since
369 ;; initialization in url-vars.el.
370 (and (eq 'system-type
'windows-nt
)
371 (fboundp 'zlib-available-p
)
373 (setq url-mime-encoding-string
"gzip")))
375 "Accept-encoding: " url-mime-encoding-string
"\r\n"))
376 (if url-mime-charset-string
379 (url-http--encode-string url-mime-charset-string
)
381 ;; Languages we understand
382 (if url-mime-language-string
384 "Accept-language: " url-mime-language-string
"\r\n"))
385 ;; Types we understand
386 "Accept: " (or url-mime-accept-string
"*/*") "\r\n"
388 (url-http-user-agent-string)
389 ;; Proxy Authorization
394 (when (url-use-cookies url-http-target-url
)
395 (url-http--encode-string
396 (url-cookie-generate-header-lines
398 (equal "https" (url-type url-http-target-url
)))))
400 (if (and (not no-cache
)
401 (member url-http-method
'("GET" nil
)))
402 (let ((tm (url-is-cached url-http-target-url
)))
404 (concat "If-modified-since: "
405 (url-get-normalized-date tm
) "\r\n"))))
408 "Referer: " ref-url
"\r\n"))
413 "Content-length: " (number-to-string
414 (length url-http-data
))
421 (unless (= (string-bytes request
)
423 (error "Multibyte text in HTTP request: %s" request
))
424 (url-http-debug "Request is: \n%s" request
)
427 (defun url-http--encode-string (s)
428 (if (multibyte-string-p s
)
429 (encode-coding-string s
'us-ascii
)
433 (defun url-http-clean-headers ()
434 "Remove trailing \r from header lines.
435 This allows us to use `mail-fetch-field', etc.
436 Return the number of characters removed."
437 (let ((end (marker-position url-http-end-of-headers
)))
438 (goto-char (point-min))
439 (while (re-search-forward "\r$" url-http-end-of-headers t
)
441 (- end url-http-end-of-headers
)))
443 (defun url-http-handle-authentication (proxy)
444 (url-http-debug "Handling %s authentication" (if proxy
"proxy" "normal"))
445 (let ((auths (or (nreverse
447 (if proxy
"proxy-authenticate" "www-authenticate")
451 (url (url-recreate-url url-current-object
))
452 (auth-url (url-recreate-url
453 (if (and proxy
(boundp 'url-http-proxy
))
455 url-current-object
)))
456 (url-basic-auth-storage (if proxy
457 ;; Cheating, but who cares? :)
458 'url-http-proxy-basic-auth-storage
459 'url-http-real-basic-auth-storage
))
463 ;; find strongest supported auth
464 (dolist (this-auth auths
)
465 (setq this-auth
(url-eat-trailing-space
466 (url-strip-leading-spaces
469 (downcase (if (string-match "[ \t]" this-auth
)
470 (substring this-auth
0 (match-beginning 0))
472 (registered (url-auth-registered this-type
))
473 (this-strength (cddr registered
)))
474 (when (and registered
(> this-strength strength
))
477 strength this-strength
))))
479 (if (not (url-auth-registered type
))
482 (goto-char (point-max))
483 (insert "<hr>Sorry, but I do not know how to handle " (or type auth url
"")
484 " authentication. If you'd like to write it,"
485 " please use M-x report-emacs-bug RET.<hr>")
486 ;; We used to set a `status' var (declared "special") but I can't
487 ;; find the corresponding let-binding, so it's probably an error.
488 ;; FIXME: Maybe it was supposed to set `success', i.e. to return t?
490 nil
) ;; Not success yet.
492 (let* ((args (url-parse-args (subst-char-in-string ?
, ?\
; auth)))
493 (auth (url-get-authentication auth-url
494 (cdr-safe (assoc "realm" args
))
498 (push (cons (if proxy
"Proxy-Authorization" "Authorization") auth
)
499 url-http-extra-headers
)
500 (let ((url-request-method url-http-method
)
501 (url-request-data url-http-data
)
502 (url-request-extra-headers url-http-extra-headers
))
503 (url-retrieve-internal url url-callback-function
504 url-callback-arguments
))
505 nil
))))) ;; Not success yet.
507 (defun url-http-parse-response ()
508 "Parse just the response code."
509 (if (not url-http-end-of-headers
)
510 (error "Trying to parse HTTP response code in odd buffer: %s" (buffer-name)))
511 (url-http-debug "url-http-parse-response called in (%s)" (buffer-name))
512 (goto-char (point-min))
513 (skip-chars-forward " \t\n") ; Skip any blank crap
514 (skip-chars-forward "HTTP/") ; Skip HTTP Version
515 (setq url-http-response-version
516 (buffer-substring (point)
518 (skip-chars-forward "[0-9].")
520 (setq url-http-response-status
(read (current-buffer))))
522 (defun url-http-handle-cookies ()
523 "Handle all set-cookie / set-cookie2 headers in an HTTP response.
524 The buffer must already be narrowed to the headers, so `mail-fetch-field' will
526 (let ((cookies (nreverse (mail-fetch-field "Set-Cookie" nil nil t
)))
527 (cookies2 (nreverse (mail-fetch-field "Set-Cookie2" nil nil t
))))
528 (and cookies
(url-http-debug "Found %d Set-Cookie headers" (length cookies
)))
529 (and cookies2
(url-http-debug "Found %d Set-Cookie2 headers" (length cookies2
)))
531 (url-cookie-handle-set-cookie (pop cookies
)))
533 ;;; (url-cookie-handle-set-cookie2 (pop cookies)))
537 (declare-function gnutls-peer-status
"gnutls.c" (proc))
538 (declare-function gnutls-negotiate
"gnutls.el" t t
)
540 (defun url-http-parse-headers ()
541 "Parse and handle HTTP specific headers.
542 Return t if and only if the current buffer is still active and
543 should be shown to the user."
544 ;; The comments after each status code handled are taken from RFC
546 (url-http-mark-connection-as-free (url-host url-current-object
)
547 (url-port url-current-object
)
549 ;; Pass the https certificate on to the caller.
550 (when (gnutls-available-p)
551 (let ((status (gnutls-peer-status url-http-process
)))
553 (plist-get (car url-callback-arguments
) :peer
))
554 (setcar url-callback-arguments
555 (plist-put (car url-callback-arguments
)
557 (if (or (not (boundp 'url-http-end-of-headers
))
558 (not url-http-end-of-headers
))
559 (error "Trying to parse headers in odd buffer: %s" (buffer-name)))
560 (goto-char (point-min))
561 (url-http-debug "url-http-parse-headers called in (%s)" (buffer-name))
562 (url-http-parse-response)
563 (mail-narrow-to-head)
564 ;;(narrow-to-region (point-min) url-http-end-of-headers)
565 (let ((connection (mail-fetch-field "Connection")))
566 ;; In HTTP 1.0, keep the connection only if there is a
567 ;; "Connection: keep-alive" header.
568 ;; In HTTP 1.1 (and greater), keep the connection unless there is a
569 ;; "Connection: close" header
571 ((string= url-http-response-version
"1.0")
572 (unless (and connection
573 (string= (downcase connection
) "keep-alive"))
574 (delete-process url-http-process
)))
576 (when (and connection
577 (string= (downcase connection
) "close"))
578 (delete-process url-http-process
)))))
579 (let* ((buffer (current-buffer))
580 (class (/ url-http-response-status
100))
582 ;; other status symbols: jewelry and luxury cars
583 (status-symbol (cadr (assq url-http-response-status url-http-codes
))))
584 (url-http-debug "Parsed HTTP headers: class=%d status=%d"
585 class url-http-response-status
)
586 (when (url-use-cookies url-http-target-url
)
587 (url-http-handle-cookies))
590 ;; Classes of response codes
592 ;; 5xx = Server Error
593 ;; 4xx = Client Error
596 ;; 1xx = Informational
597 (1 ; Information messages
598 ;; 100 = Continue with request
599 ;; 101 = Switching protocols
600 ;; 102 = Processing (Added by DAV)
601 (url-mark-buffer-as-dead buffer
)
602 (error "HTTP responses in class 1xx not supported (%d)"
603 url-http-response-status
))
608 ;; 203 Non-authoritative information
611 ;; 206 Partial content
612 ;; 207 Multi-status (Added by DAV)
614 ((or `no-content
`reset-content
)
615 ;; No new data, just stay at the same document
616 (url-mark-buffer-as-dead buffer
))
618 ;; Generic success for all others. Store in the cache, and
619 ;; mark it as successful.
621 (if (and url-automatic-caching
(equal url-http-method
"GET"))
622 (url-store-in-cache buffer
))))
625 ;; 300 Multiple choices
626 ;; 301 Moved permanently
631 ;; 307 Temporary redirect
632 (let ((redirect-uri (or (mail-fetch-field "Location")
633 (mail-fetch-field "URI"))))
635 (`multiple-choices
; 300
636 ;; Quoth the spec (section 10.3.1)
637 ;; -------------------------------
638 ;; The requested resource corresponds to any one of a set of
639 ;; representations, each with its own specific location and
640 ;; agent-driven negotiation information is being provided so
641 ;; that the user can select a preferred representation and
642 ;; redirect its request to that location.
644 ;; If the server has a preferred choice of representation, it
645 ;; SHOULD include the specific URI for that representation in
646 ;; the Location field; user agents MAY use the Location field
647 ;; value for automatic redirection.
648 ;; -------------------------------
649 ;; We do not support agent-driven negotiation, so we just
650 ;; redirect to the preferred URI if one is provided.
653 ;; 302 Found was ambiguously defined in the standards, but
654 ;; it's now recommended that it's treated like 303 instead
655 ;; of 307, since that's what most servers expect.
656 (setq url-http-method
"GET"
659 ;; The response to the request can be found under a different
660 ;; URI and SHOULD be retrieved using a GET method on that
662 (setq url-http-method
"GET"
665 ;; The 304 response MUST NOT contain a message-body.
666 (url-http-debug "Extracting document from cache... (%s)"
667 (url-cache-create-filename (url-view-url t
)))
668 (url-cache-extract (url-cache-create-filename (url-view-url t
)))
669 (setq redirect-uri nil
672 ;; The requested resource MUST be accessed through the
673 ;; proxy given by the Location field. The Location field
674 ;; gives the URI of the proxy. The recipient is expected
675 ;; to repeat this single request via the proxy. 305
676 ;; responses MUST only be generated by origin servers.
677 (error "Redirection thru a proxy server not supported: %s"
680 ;; Treat everything like '300'
683 ;; Clean off any whitespace and/or <...> cruft.
684 (if (string-match "\\([^ \t]+\\)[ \t]" redirect-uri
)
685 (setq redirect-uri
(match-string 1 redirect-uri
)))
686 (if (string-match "^<\\(.*\\)>$" redirect-uri
)
687 (setq redirect-uri
(match-string 1 redirect-uri
)))
689 ;; Some stupid sites (like sourceforge) send a
690 ;; non-fully-qualified URL (ie: /), which royally confuses
692 (if (not (string-match url-nonrelative-link redirect-uri
))
693 ;; Be careful to use the real target URL, otherwise we may
694 ;; compute the redirection relative to the URL of the proxy.
696 (url-expand-file-name redirect-uri url-http-target-url
)))
697 ;; Do not automatically include an authorization header in the
698 ;; redirect. If needed it will be regenerated by the relevant
699 ;; auth scheme when the new request happens.
700 (setq url-http-extra-headers
701 (cl-remove "Authorization"
702 url-http-extra-headers
:key
'car
:test
'equal
))
703 (let ((url-request-method url-http-method
)
704 (url-request-data url-http-data
)
705 (url-request-extra-headers url-http-extra-headers
))
706 ;; Check existing number of redirects
707 (if (or (< url-max-redirections
0)
708 (and (> url-max-redirections
0)
709 (let ((events (car url-callback-arguments
))
712 (if (eq (car events
) :redirect
)
713 (setq old-redirects
(1+ old-redirects
)))
714 (and (setq events
(cdr events
))
715 (setq events
(cdr events
))))
716 (< old-redirects url-max-redirections
))))
717 ;; url-max-redirections hasn't been reached, so go
718 ;; ahead and redirect.
720 ;; Remember that the request was redirected.
721 (setf (car url-callback-arguments
)
722 (nconc (list :redirect redirect-uri
)
723 (car url-callback-arguments
)))
724 ;; Put in the current buffer a forwarding pointer to the new
725 ;; destination buffer.
726 ;; FIXME: This is a hack to fix url-retrieve-synchronously
727 ;; without changing the API. Instead url-retrieve should
728 ;; either simply not return the "destination" buffer, or it
729 ;; should take an optional `dest-buf' argument.
730 (set (make-local-variable 'url-redirect-buffer
)
731 (url-retrieve-internal
732 redirect-uri url-callback-function
733 url-callback-arguments
734 (url-silent url-current-object
)
735 (not (url-use-cookies url-current-object
))))
736 (url-mark-buffer-as-dead buffer
))
737 ;; We hit url-max-redirections, so issue an error and
739 (url-http-debug "Maximum redirections reached")
740 (setf (car url-callback-arguments
)
741 (nconc (list :error
(list 'error
'http-redirect-limit
743 (car url-callback-arguments
)))
744 (setq success t
))))))
748 ;; 402 Payment required
751 ;; 405 Method not allowed
752 ;; 406 Not acceptable
753 ;; 407 Proxy authentication required
754 ;; 408 Request time-out
757 ;; 411 Length required
758 ;; 412 Precondition failed
759 ;; 413 Request entity too large
760 ;; 414 Request-URI too large
761 ;; 415 Unsupported media type
762 ;; 416 Requested range not satisfiable
763 ;; 417 Expectation failed
764 ;; 422 Unprocessable Entity (Added by DAV)
766 ;; 424 Failed Dependency
770 ;; The request requires user authentication. The response
771 ;; MUST include a WWW-Authenticate header field containing a
772 ;; challenge applicable to the requested resource. The
773 ;; client MAY repeat the request with a suitable
774 ;; Authorization header field.
775 (url-http-handle-authentication nil
))
776 (`payment-required
; 402
777 ;; This code is reserved for future use
778 (url-mark-buffer-as-dead buffer
)
779 (error "Somebody wants you to give them money"))
781 ;; The server understood the request, but is refusing to
782 ;; fulfill it. Authorization will not help and the request
783 ;; SHOULD NOT be repeated.
788 (`method-not-allowed
; 405
789 ;; The method specified in the Request-Line is not allowed
790 ;; for the resource identified by the Request-URI. The
791 ;; response MUST include an Allow header containing a list of
792 ;; valid methods for the requested resource.
794 (`not-acceptable
; 406
795 ;; The resource identified by the request is only capable of
796 ;; generating response entities which have content
797 ;; characteristics not acceptable according to the accept
798 ;; headers sent in the request.
800 (`proxy-authentication-required
; 407
801 ;; This code is similar to 401 (Unauthorized), but indicates
802 ;; that the client must first authenticate itself with the
803 ;; proxy. The proxy MUST return a Proxy-Authenticate header
804 ;; field containing a challenge applicable to the proxy for
805 ;; the requested resource.
806 (url-http-handle-authentication t
))
807 (`request-timeout
; 408
808 ;; The client did not produce a request within the time that
809 ;; the server was prepared to wait. The client MAY repeat
810 ;; the request without modifications at any later time.
813 ;; The request could not be completed due to a conflict with
814 ;; the current state of the resource. This code is only
815 ;; allowed in situations where it is expected that the user
816 ;; might be able to resolve the conflict and resubmit the
817 ;; request. The response body SHOULD include enough
818 ;; information for the user to recognize the source of the
822 ;; The requested resource is no longer available at the
823 ;; server and no forwarding address is known.
825 (`length-required
; 411
826 ;; The server refuses to accept the request without a defined
827 ;; Content-Length. The client MAY repeat the request if it
828 ;; adds a valid Content-Length header field containing the
829 ;; length of the message-body in the request message.
831 ;; NOTE - this will never happen because
832 ;; `url-http-create-request' automatically calculates the
835 (`precondition-failed
; 412
836 ;; The precondition given in one or more of the
837 ;; request-header fields evaluated to false when it was
838 ;; tested on the server.
840 ((or `request-entity-too-large
`request-uri-too-large
) ; 413 414
841 ;; The server is refusing to process a request because the
842 ;; request entity|URI is larger than the server is willing or
845 (`unsupported-media-type
; 415
846 ;; The server is refusing to service the request because the
847 ;; entity of the request is in a format not supported by the
848 ;; requested resource for the requested method.
850 (`requested-range-not-satisfiable
; 416
851 ;; A server SHOULD return a response with this status code if
852 ;; a request included a Range request-header field, and none
853 ;; of the range-specifier values in this field overlap the
854 ;; current extent of the selected resource, and the request
855 ;; did not include an If-Range request-header field.
857 (`expectation-failed
; 417
858 ;; The expectation given in an Expect request-header field
859 ;; could not be met by this server, or, if the server is a
860 ;; proxy, the server has unambiguous evidence that the
861 ;; request could not be met by the next-hop server.
864 ;; The request could not be understood by the server due to
865 ;; malformed syntax. The client SHOULD NOT repeat the
866 ;; request without modifications.
868 ;; Tell the callback that an error occurred, and what the
871 (setf (car url-callback-arguments
)
872 (nconc (list :error
(list 'error
'http url-http-response-status
))
873 (car url-callback-arguments
)))))
875 ;; 500 Internal server error
876 ;; 501 Not implemented
878 ;; 503 Service unavailable
879 ;; 504 Gateway time-out
880 ;; 505 HTTP version not supported
881 ;; 507 Insufficient storage
883 (pcase url-http-response-status
884 (`not-implemented
; 501
885 ;; The server does not support the functionality required to
886 ;; fulfill the request.
889 ;; The server, while acting as a gateway or proxy, received
890 ;; an invalid response from the upstream server it accessed
891 ;; in attempting to fulfill the request.
893 (`service-unavailable
; 503
894 ;; The server is currently unable to handle the request due
895 ;; to a temporary overloading or maintenance of the server.
896 ;; The implication is that this is a temporary condition
897 ;; which will be alleviated after some delay. If known, the
898 ;; length of the delay MAY be indicated in a Retry-After
899 ;; header. If no Retry-After is given, the client SHOULD
900 ;; handle the response as it would for a 500 response.
902 (`gateway-timeout
; 504
903 ;; The server, while acting as a gateway or proxy, did not
904 ;; receive a timely response from the upstream server
905 ;; specified by the URI (e.g. HTTP, FTP, LDAP) or some other
906 ;; auxiliary server (e.g. DNS) it needed to access in
907 ;; attempting to complete the request.
909 (`http-version-not-supported
; 505
910 ;; The server does not support, or refuses to support, the
911 ;; HTTP protocol version that was used in the request
914 (`insufficient-storage
; 507 (DAV)
915 ;; The method could not be performed on the resource
916 ;; because the server is unable to store the representation
917 ;; needed to successfully complete the request. This
918 ;; condition is considered to be temporary. If the request
919 ;; which received this status code was the result of a user
920 ;; action, the request MUST NOT be repeated until it is
921 ;; requested by a separate user action.
923 ;; Tell the callback that an error occurred, and what the
926 (setf (car url-callback-arguments
)
927 (nconc (list :error
(list 'error
'http url-http-response-status
))
928 (car url-callback-arguments
)))))
930 (error "Unknown class of HTTP response code: %d (%d)"
931 class url-http-response-status
)))
933 (url-mark-buffer-as-dead buffer
)
934 (url-handle-content-transfer-encoding))
935 (url-http-debug "Finished parsing HTTP headers: %S" success
)
937 (goto-char (point-min))
940 (declare-function zlib-decompress-region
"decompress.c" (start end
))
942 (defun url-handle-content-transfer-encoding ()
943 (let ((encoding (mail-fetch-field "content-encoding")))
945 (fboundp 'zlib-available-p
)
947 (equal (downcase encoding
) "gzip"))
950 (goto-char (point-min))
951 (when (search-forward "\n\n")
952 (zlib-decompress-region (point) (point-max)))))))
955 (defun url-http-activate-callback ()
956 "Activate callback specified when this buffer was created."
957 (url-http-mark-connection-as-free (url-host url-current-object
)
958 (url-port url-current-object
)
960 (url-http-debug "Activating callback in buffer (%s): %S %S"
961 (buffer-name) url-callback-function url-callback-arguments
)
962 (apply url-callback-function url-callback-arguments
))
966 ;; These unfortunately cannot be macros... please ignore them!
967 (defun url-http-idle-sentinel (proc _why
)
968 "Remove (now defunct) process PROC from the list of open connections."
969 (maphash (lambda (key val
)
971 (puthash key
(delq proc val
) url-http-open-connections
)))
972 url-http-open-connections
))
974 (defun url-http-end-of-document-sentinel (proc why
)
975 ;; Sentinel used to handle (i) terminated old HTTP/0.9 connections,
976 ;; and (ii) closed connection due to reusing a HTTP connection which
977 ;; we believed was still alive, but which the server closed on us.
978 ;; We handle case (ii) by calling `url-http' again.
979 (url-http-debug "url-http-end-of-document-sentinel in buffer (%s)"
980 (process-buffer proc
))
981 (url-http-idle-sentinel proc why
)
982 (when (buffer-name (process-buffer proc
))
983 (with-current-buffer (process-buffer proc
)
984 (goto-char (point-min))
985 (cond ((not (looking-at "HTTP/"))
986 (if url-http-no-retry
987 ;; HTTP/0.9 just gets passed back no matter what
988 (url-http-activate-callback)
989 ;; Call `url-http' again if our connection expired.
991 (let ((url-request-method url-http-method
)
992 (url-request-extra-headers url-http-extra-headers
)
993 (url-request-data url-http-data
)
994 (url-using-proxy (url-find-proxy-for-url
996 (url-host url-current-object
))))
997 (when url-using-proxy
998 (setq url-using-proxy
999 (url-generic-parse-url url-using-proxy
)))
1000 (url-http url-current-object url-callback-function
1001 url-callback-arguments
(current-buffer)))))
1002 ((url-http-parse-headers)
1003 (url-http-activate-callback))))))
1005 (defun url-http-simple-after-change-function (_st _nd _length
)
1006 ;; Function used when we do NOT know how long the document is going to be
1007 ;; Just _very_ simple 'downloaded %d' type of info.
1008 (url-lazy-message "Reading %s..." (file-size-human-readable (buffer-size))))
1010 (defun url-http-content-length-after-change-function (_st nd _length
)
1011 "Function used when we DO know how long the document is going to be.
1012 More sophisticated percentage downloaded, etc.
1013 Also does minimal parsing of HTTP headers and will actually cause
1014 the callback to be triggered."
1015 (if url-http-content-type
1016 (url-display-percentage
1017 "Reading [%s]... %s of %s (%d%%)"
1018 (url-percentage (- nd url-http-end-of-headers
)
1019 url-http-content-length
)
1020 url-http-content-type
1021 (file-size-human-readable (- nd url-http-end-of-headers
))
1022 (file-size-human-readable url-http-content-length
)
1023 (url-percentage (- nd url-http-end-of-headers
)
1024 url-http-content-length
))
1025 (url-display-percentage
1026 "Reading... %s of %s (%d%%)"
1027 (url-percentage (- nd url-http-end-of-headers
)
1028 url-http-content-length
)
1029 (file-size-human-readable (- nd url-http-end-of-headers
))
1030 (file-size-human-readable url-http-content-length
)
1031 (url-percentage (- nd url-http-end-of-headers
)
1032 url-http-content-length
)))
1034 (if (> (- nd url-http-end-of-headers
) url-http-content-length
)
1036 ;; Found the end of the document! Wheee!
1037 (url-display-percentage nil nil
)
1038 (url-lazy-message "Reading... done.")
1039 (if (url-http-parse-headers)
1040 (url-http-activate-callback)))))
1042 (defun url-http-chunked-encoding-after-change-function (st nd length
)
1043 "Function used when dealing with chunked encoding.
1044 Cannot give a sophisticated percentage, but we need a different
1045 function to look for the special 0-length chunk that signifies
1046 the end of the document."
1049 (let ((read-next-chunk t
)
1050 (case-fold-search t
)
1052 (no-initial-crlf nil
))
1053 ;; We need to loop thru looking for more chunks even within
1054 ;; one after-change-function call.
1055 (while read-next-chunk
1056 (setq no-initial-crlf
(= 0 url-http-chunked-counter
))
1057 (if url-http-content-type
1058 (url-display-percentage nil
1059 "Reading [%s]... chunk #%d"
1060 url-http-content-type url-http-chunked-counter
)
1061 (url-display-percentage nil
1062 "Reading... chunk #%d"
1063 url-http-chunked-counter
))
1064 (url-http-debug "Reading chunk %d (%d %d %d)"
1065 url-http-chunked-counter st nd length
)
1066 (setq regexp
(if no-initial-crlf
1067 "\\([0-9a-z]+\\).*\r?\n"
1068 "\r?\n\\([0-9a-z]+\\).*\r?\n"))
1070 (if url-http-chunked-start
1071 ;; We know how long the chunk is supposed to be, skip over
1072 ;; leading crap if possible.
1073 (if (> nd
(+ url-http-chunked-start url-http-chunked-length
))
1075 (url-http-debug "Got to the end of chunk #%d!"
1076 url-http-chunked-counter
)
1077 (goto-char (+ url-http-chunked-start
1078 url-http-chunked-length
)))
1079 (url-http-debug "Still need %d bytes to hit end of chunk"
1080 (- (+ url-http-chunked-start
1081 url-http-chunked-length
)
1083 (setq read-next-chunk nil
)))
1084 (if (not read-next-chunk
)
1085 (url-http-debug "Still spinning for next chunk...")
1086 (if no-initial-crlf
(skip-chars-forward "\r\n"))
1087 (if (not (looking-at regexp
))
1089 ;; Must not have received the entirety of the chunk header,
1090 ;; need to spin some more.
1091 (url-http-debug "Did not see start of chunk @ %d!" (point))
1092 (setq read-next-chunk nil
))
1093 (add-text-properties (match-beginning 0) (match-end 0)
1099 (setq url-http-chunked-length
(string-to-number (buffer-substring
1103 url-http-chunked-counter
(1+ url-http-chunked-counter
)
1104 url-http-chunked-start
(set-marker
1105 (or url-http-chunked-start
1108 ; (if (not url-http-debug)
1109 (delete-region (match-beginning 0) (match-end 0));)
1110 (url-http-debug "Saw start of chunk %d (length=%d, start=%d"
1111 url-http-chunked-counter url-http-chunked-length
1112 (marker-position url-http-chunked-start
))
1113 (if (= 0 url-http-chunked-length
)
1115 ;; Found the end of the document! Wheee!
1116 (url-http-debug "Saw end of stream chunk!")
1117 (setq read-next-chunk nil
)
1118 (url-display-percentage nil nil
)
1119 ;; Every chunk, even the last 0-length one, is
1120 ;; terminated by CRLF. Skip it.
1121 (when (looking-at "\r?\n")
1122 (url-http-debug "Removing terminator of last chunk")
1123 (delete-region (match-beginning 0) (match-end 0)))
1124 (if (re-search-forward "^\r?\n" nil t
)
1125 (url-http-debug "Saw end of trailers..."))
1126 (if (url-http-parse-headers)
1127 (url-http-activate-callback))))))))))
1129 (defun url-http-wait-for-headers-change-function (_st nd _length
)
1130 ;; This will wait for the headers to arrive and then splice in the
1131 ;; next appropriate after-change-function, etc.
1132 (url-http-debug "url-http-wait-for-headers-change-function (%s)"
1134 (let ((end-of-headers nil
)
1136 (process-buffer (current-buffer))
1137 ;; (content-length nil)
1140 (goto-char (point-min))
1141 (if (and (looking-at ".*\n") ; have one line at least
1142 (not (looking-at "^HTTP/[1-9]\\.[0-9]")))
1143 ;; Not HTTP/x.y data, must be 0.9
1144 ;; God, I wish this could die.
1145 (setq end-of-headers t
1146 url-http-end-of-headers
0
1148 ;; Blank line at end of headers.
1149 (when (re-search-forward "^\r?\n" nil t
)
1151 ;; Saw the end of the headers
1152 (url-http-debug "Saw end of headers... (%s)" (buffer-name))
1153 (setq url-http-end-of-headers
(set-marker (make-marker)
1156 (setq nd
(- nd
(url-http-clean-headers)))))
1158 (if (not end-of-headers
)
1159 ;; Haven't seen the end of the headers yet, need to wait
1160 ;; for more data to arrive.
1163 (url-http-parse-response)
1164 (mail-narrow-to-head)
1165 (setq url-http-transfer-encoding
(mail-fetch-field
1166 "transfer-encoding")
1167 url-http-content-type
(mail-fetch-field "content-type"))
1168 (if (mail-fetch-field "content-length")
1169 (setq url-http-content-length
1170 (string-to-number (mail-fetch-field "content-length"))))
1172 (when url-http-transfer-encoding
1173 (setq url-http-transfer-encoding
1174 (downcase url-http-transfer-encoding
)))
1177 ((null url-http-response-status
)
1178 ;; We got back a headerless malformed response from the
1180 (url-http-activate-callback))
1181 ((or (= url-http-response-status
204)
1182 (= url-http-response-status
205))
1183 (url-http-debug "%d response must have headers only (%s)."
1184 url-http-response-status
(buffer-name))
1185 (when (url-http-parse-headers)
1186 (url-http-activate-callback)))
1187 ((string= "HEAD" url-http-method
)
1188 ;; A HEAD request is _ALWAYS_ terminated by the header
1189 ;; information, regardless of any entity headers,
1190 ;; according to section 4.4 of the HTTP/1.1 draft.
1191 (url-http-debug "HEAD request must have headers only (%s)."
1193 (when (url-http-parse-headers)
1194 (url-http-activate-callback)))
1195 ((string= "CONNECT" url-http-method
)
1196 ;; A CONNECT request is finished, but we cannot stick this
1197 ;; back on the free connection list
1198 (url-http-debug "CONNECT request must have headers only.")
1199 (when (url-http-parse-headers)
1200 (url-http-activate-callback)))
1201 ((equal url-http-response-status
304)
1202 ;; Only allowed to have a header section. We have to handle
1203 ;; this here instead of in url-http-parse-headers because if
1204 ;; you have a cached copy of something without a known
1205 ;; content-length, and try to retrieve it from the cache, we'd
1206 ;; fall into the 'being dumb' section and wait for the
1207 ;; connection to terminate, which means we'd wait for 10
1208 ;; seconds for the keep-alives to time out on some servers.
1209 (when (url-http-parse-headers)
1210 (url-http-activate-callback)))
1212 ;; HTTP/0.9 always signaled end-of-connection by closing the
1215 "Saw HTTP/0.9 response, connection closed means end of document.")
1216 (setq url-http-after-change-function
1217 'url-http-simple-after-change-function
))
1218 ((equal url-http-transfer-encoding
"chunked")
1219 (url-http-debug "Saw chunked encoding.")
1220 (setq url-http-after-change-function
1221 'url-http-chunked-encoding-after-change-function
)
1222 (when (> nd url-http-end-of-headers
)
1224 "Calling initial chunked-encoding for extra data at end of headers")
1225 (url-http-chunked-encoding-after-change-function
1226 (marker-position url-http-end-of-headers
) nd
1227 (- nd url-http-end-of-headers
))))
1228 ((integerp url-http-content-length
)
1230 "Got a content-length, being smart about document end.")
1231 (setq url-http-after-change-function
1232 'url-http-content-length-after-change-function
)
1234 ((= 0 url-http-content-length
)
1235 ;; We got a NULL body! Activate the callback
1238 "Got 0-length content-length, activating callback immediately.")
1239 (when (url-http-parse-headers)
1240 (url-http-activate-callback)))
1241 ((> nd url-http-end-of-headers
)
1242 ;; Have some leftover data
1243 (url-http-debug "Calling initial content-length for extra data at end of headers")
1244 (url-http-content-length-after-change-function
1245 (marker-position url-http-end-of-headers
)
1247 (- nd url-http-end-of-headers
)))
1251 (url-http-debug "No content-length, being dumb.")
1252 (setq url-http-after-change-function
1253 'url-http-simple-after-change-function
)))))
1254 ;; We are still at the beginning of the buffer... must just be
1255 ;; waiting for a response.
1256 (url-http-debug "Spinning waiting for headers...")
1257 (when (eq process-buffer
(current-buffer))
1258 (goto-char (point-max)))))
1260 (defun url-http (url callback cbargs
&optional retry-buffer gateway-method
)
1261 "Retrieve URL via HTTP asynchronously.
1262 URL must be a parsed URL. See `url-generic-parse-url' for details.
1264 When retrieval is completed, execute the function CALLBACK,
1265 passing it an updated value of CBARGS as arguments. The first
1266 element in CBARGS should be a plist describing what has happened
1267 so far during the request, as described in the docstring of
1268 `url-retrieve' (if in doubt, specify nil). The current buffer
1269 then CALLBACK is executed is the retrieval buffer.
1271 Optional arg RETRY-BUFFER, if non-nil, specifies the buffer of a
1272 previous `url-http' call, which is being re-attempted.
1274 Optional arg GATEWAY-METHOD specifies the gateway to be used,
1275 overriding the value of `url-gateway-method'.
1277 The return value of this function is the retrieval buffer."
1278 (cl-check-type url url
"Need a pre-parsed URL.")
1279 (let* (;; (host (url-host (or url-using-proxy url)))
1280 ;; (port (url-port (or url-using-proxy url)))
1281 (nsm-noninteractive (or url-request-noninteractive
1282 (and (boundp 'url-http-noninteractive
)
1283 url-http-noninteractive
)))
1284 ;; The following binding is needed in url-open-stream, which
1285 ;; is called from url-http-find-free-connection.
1286 (url-current-object url
)
1287 (connection (url-http-find-free-connection (url-host url
)
1290 (mime-accept-string url-mime-accept-string
)
1291 (buffer (or retry-buffer
1292 (generate-new-buffer
1293 (format " *http %s:%d*" (url-host url
) (url-port url
)))))
1294 (referer (url-http--get-referer url
)))
1295 (if (not connection
)
1296 ;; Failed to open the connection for some reason
1298 (kill-buffer buffer
)
1300 (error "Could not create connection to %s:%d" (url-host url
)
1302 (with-current-buffer buffer
1303 (mm-disable-multibyte)
1304 (setq url-current-object url
1305 mode-line-format
"%b [%s]")
1307 (dolist (var '(url-http-end-of-headers
1308 url-http-content-type
1309 url-http-content-length
1310 url-http-transfer-encoding
1311 url-http-after-change-function
1312 url-http-response-version
1313 url-http-response-status
1314 url-http-chunked-length
1315 url-http-chunked-counter
1316 url-http-chunked-start
1317 url-callback-function
1318 url-callback-arguments
1322 url-http-extra-headers
1323 url-http-noninteractive
1327 url-http-connection-opened
1328 url-mime-accept-string
1331 (set (make-local-variable var
) nil
))
1333 (setq url-http-method
(or url-request-method
"GET")
1334 url-http-extra-headers url-request-extra-headers
1335 url-http-noninteractive url-request-noninteractive
1336 url-http-data url-request-data
1337 url-http-process connection
1338 url-http-chunked-length nil
1339 url-http-chunked-start nil
1340 url-http-chunked-counter
0
1341 url-callback-function callback
1342 url-callback-arguments cbargs
1343 url-http-after-change-function
'url-http-wait-for-headers-change-function
1344 url-http-target-url url-current-object
1345 url-http-no-retry retry-buffer
1346 url-http-connection-opened nil
1347 url-mime-accept-string mime-accept-string
1348 url-http-proxy url-using-proxy
1349 url-http-referer referer
)
1351 (set-process-buffer connection buffer
)
1352 (set-process-filter connection
'url-http-generic-filter
)
1353 (pcase (process-status connection
)
1355 ;; Asynchronous connection
1356 (set-process-sentinel connection
'url-http-async-sentinel
))
1358 ;; Asynchronous connection failed
1359 (error "Could not create connection to %s:%d" (url-host url
)
1362 (if (and url-http-proxy
(string= "https"
1363 (url-type url-current-object
)))
1364 (url-https-proxy-connect connection
)
1365 (set-process-sentinel connection
1366 'url-http-end-of-document-sentinel
)
1367 (process-send-string connection
(url-http-create-request)))))))
1370 (defun url-https-proxy-connect (connection)
1371 (setq url-http-after-change-function
'url-https-proxy-after-change-function
)
1372 (process-send-string connection
(format (concat "CONNECT %s:%d HTTP/1.1\r\n"
1375 (url-host url-current-object
)
1376 (or (url-port url-current-object
)
1377 url-https-default-port
)
1378 (url-host url-current-object
))))
1380 (defun url-https-proxy-after-change-function (_st _nd _length
)
1381 (let* ((process-buffer (current-buffer))
1382 (proc (get-buffer-process process-buffer
)))
1383 (goto-char (point-min))
1384 (when (re-search-forward "^\r?\n" nil t
)
1386 ;; Saw the end of the headers
1387 (setq url-http-end-of-headers
(set-marker (make-marker) (point)))
1388 (url-http-parse-response)
1390 ((null url-http-response-status
)
1391 ;; We got back a headerless malformed response from the
1393 (url-http-activate-callback)
1394 (error "Malformed response from proxy, fail!"))
1395 ((= url-http-response-status
200)
1396 (if (gnutls-available-p)
1398 (let ((tls-connection (gnutls-negotiate
1400 :hostname
(url-host url-current-object
)
1401 :verify-error nil
)))
1402 ;; check certificate validity
1403 (setq tls-connection
1404 (nsm-verify-connection tls-connection
1405 (url-host url-current-object
)
1406 (url-port url-current-object
)))
1407 (with-current-buffer process-buffer
(erase-buffer))
1408 (set-process-buffer tls-connection process-buffer
)
1409 (setq url-http-after-change-function
1410 'url-http-wait-for-headers-change-function
)
1411 (set-process-filter tls-connection
'url-http-generic-filter
)
1412 (process-send-string tls-connection
1413 (url-http-create-request)))
1415 (url-http-activate-callback)
1416 (error "gnutls-error: %s" e
))
1418 (url-http-activate-callback)
1419 (error "error: %s" e
)))
1420 (error "error: gnutls support needed!")))
1422 (url-http-debug "error response: %d" url-http-response-status
)
1423 (url-http-activate-callback))))))
1425 (defun url-http-async-sentinel (proc why
)
1426 ;; We are performing an asynchronous connection, and a status change
1428 (when (buffer-name (process-buffer proc
))
1429 (with-current-buffer (process-buffer proc
)
1431 (url-http-connection-opened
1432 (setq url-http-no-retry t
)
1433 (url-http-end-of-document-sentinel proc why
))
1434 ((string= (substring why
0 4) "open")
1435 (setq url-http-connection-opened t
)
1436 (if (and url-http-proxy
(string= "https" (url-type url-current-object
)))
1437 (url-https-proxy-connect proc
)
1438 (condition-case error
1439 (process-send-string proc
(url-http-create-request))
1441 (setq url-http-connection-opened nil
)
1442 (message "HTTP error: %s" error
)))))
1444 (setf (car url-callback-arguments
)
1445 (nconc (list :error
(list 'error
'connection-failed why
1446 :host
(url-host (or url-http-proxy url-current-object
))
1447 :service
(url-port (or url-http-proxy url-current-object
))))
1448 (car url-callback-arguments
)))
1449 (url-http-activate-callback))))))
1451 ;; Since Emacs 19/20 does not allow you to change the
1452 ;; `after-change-functions' hook in the midst of running them, we fake
1453 ;; an after change by hooking into the process filter and inserting
1454 ;; the data ourselves. This is slightly less efficient, but there
1455 ;; were tons of weird ways the after-change code was biting us in the
1457 ;; FIXME this can probably be simplified since the above is no longer true.
1458 (defun url-http-generic-filter (proc data
)
1459 ;; Sometimes we get a zero-length data chunk after the process has
1460 ;; been changed to 'free', which means it has no buffer associated
1461 ;; with it. Do nothing if there is no buffer, or 0 length data.
1462 (and (process-buffer proc
)
1463 (/= (length data
) 0)
1464 (with-current-buffer (process-buffer proc
)
1465 (url-http-debug "Calling after change function `%s' for `%S'" url-http-after-change-function proc
)
1466 (funcall url-http-after-change-function
1469 (goto-char (point-max))
1474 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1475 ;;; file-name-handler stuff from here on out
1476 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1477 (defalias 'url-http-symbol-value-in-buffer
1478 (if (fboundp 'symbol-value-in-buffer
)
1479 'symbol-value-in-buffer
1480 (lambda (symbol buffer
&optional unbound-value
)
1481 "Return the value of SYMBOL in BUFFER, or UNBOUND-VALUE if it is unbound."
1482 (with-current-buffer buffer
1483 (if (not (boundp symbol
))
1485 (symbol-value symbol
))))))
1487 (defun url-http-head (url)
1488 (let ((url-request-method "HEAD")
1489 (url-request-data nil
))
1490 (url-retrieve-synchronously url
)))
1492 (defun url-http-file-exists-p (url)
1493 (let ((buffer (url-http-head url
)))
1495 (let ((status (url-http-symbol-value-in-buffer 'url-http-response-status
1498 (and (integerp status
)
1499 (>= status
200) (< status
300))
1500 (kill-buffer buffer
))))))
1502 (defalias 'url-http-file-readable-p
'url-http-file-exists-p
)
1504 (defun url-http-head-file-attributes (url &optional _id-format
)
1505 (let ((buffer (url-http-head url
)))
1509 nil
;dir / link / normal file
1510 1 ;number of links to file.
1512 nil nil nil
;atime ; mtime ; ctime
1513 (url-http-symbol-value-in-buffer 'url-http-content-length
1515 (eval-when-compile (make-string 10 ?-
))
1516 nil nil nil
) ;whether gid would change ; inode ; device.
1517 (kill-buffer buffer
)))))
1519 (declare-function url-dav-file-attributes
"url-dav" (url &optional _id-format
))
1521 (defun url-http-file-attributes (url &optional id-format
)
1522 (if (url-dav-supported-p url
)
1523 (url-dav-file-attributes url id-format
)
1524 (url-http-head-file-attributes url id-format
)))
1526 (defun url-http-options (url)
1527 "Return a property list describing options available for URL.
1528 This list is retrieved using the `OPTIONS' HTTP method.
1530 Property list members:
1533 A list of symbols specifying what HTTP methods the resource
1537 A list of numbers specifying what DAV protocol/schema versions are
1541 A list of supported DASL search types supported (string form)
1544 A list of the units available for use in partial document fetches.
1547 The `Platform For Privacy Protection' description for the resource.
1548 Currently this is just the raw header contents. This is likely to
1549 change once P3P is formally supported by the URL package or
1551 (let* ((url-request-method "OPTIONS")
1552 (url-request-data nil
)
1553 (buffer (url-retrieve-synchronously url
))
1556 (when (and buffer
(= 2 (/ (url-http-symbol-value-in-buffer
1557 'url-http-response-status buffer
0) 100)))
1558 ;; Only parse the options if we got a 2xx response code!
1559 (with-current-buffer buffer
1562 (mail-narrow-to-head)
1564 ;; Figure out what methods are supported.
1565 (when (setq header
(mail-fetch-field "allow"))
1566 (setq options
(plist-put
1568 (mapcar 'intern
(split-string header
"[ ,]+")))))
1571 (when (setq header
(mail-fetch-field "dav"))
1572 (setq options
(plist-put
1575 (mapcar 'string-to-number
1576 (split-string header
"[, ]+"))))))
1579 (when (setq header
(mail-fetch-field "dasl"))
1580 (setq options
(plist-put
1582 (split-string header
"[, ]+"))))
1584 ;; P3P - should get more detailed here. FIXME
1585 (when (setq header
(mail-fetch-field "p3p"))
1586 (setq options
(plist-put options
'p3p header
)))
1588 ;; Check for whether they accept byte-range requests.
1589 (when (setq header
(mail-fetch-field "accept-ranges"))
1590 (setq options
(plist-put
1594 (split-string header
"[, ]+"))))))
1596 (if buffer
(kill-buffer buffer
))
1599 ;; HTTPS. This used to be in url-https.el, but that file collides
1600 ;; with url-http.el on systems with 8-character file names.
1603 (defconst url-https-asynchronous-p t
"HTTPS retrievals are asynchronous.")
1605 ;; FIXME what is the point of this alias being an autoload?
1606 ;; Trying to use it will not cause url-http to be loaded,
1607 ;; since the full alias just gets dumped into loaddefs.el.
1609 ;;;###autoload (autoload 'url-default-expander "url-expand")
1611 (defalias 'url-https-expand-file-name
'url-default-expander
)
1613 (defmacro url-https-create-secure-wrapper
(method args
)
1614 `(defun ,(intern (format (if method
"url-https-%s" "url-https") method
)) ,args
1615 ,(format "HTTPS wrapper around `%s' call." (or method
"url-http"))
1616 (,(intern (format (if method
"url-http-%s" "url-http") method
))
1617 ,@(remove '&rest
(remove '&optional
(append args
(if method nil
'(nil 'tls
))))))))
1619 ;;;###autoload (autoload 'url-https "url-http")
1620 (url-https-create-secure-wrapper nil
(url callback cbargs
))
1621 ;;;###autoload (autoload 'url-https-file-exists-p "url-http")
1622 (url-https-create-secure-wrapper file-exists-p
(url))
1623 ;;;###autoload (autoload 'url-https-file-readable-p "url-http")
1624 (url-https-create-secure-wrapper file-readable-p
(url))
1625 ;;;###autoload (autoload 'url-https-file-attributes "url-http")
1626 (url-https-create-secure-wrapper file-attributes
(url &optional id-format
))
1630 ;;; url-http.el ends here