Spaces:
Sleeping
Sleeping
File size: 15,184 Bytes
f65fe85 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
;;; Web client
;; Copyright (C) 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary:
;;;
;;; (web client) is a simple HTTP URL fetcher for Guile.
;;;
;;; In its current incarnation, (web client) is synchronous. If you
;;; want to fetch a number of URLs at once, probably the best thing to
;;; do is to write an event-driven URL fetcher, similar in structure to
;;; the web server.
;;;
;;; Another option, good but not as performant, would be to use threads,
;;; possibly via a thread pool.
;;;
;;; Code:
(define-module (web client)
#:use-module (rnrs bytevectors)
#:use-module (ice-9 binary-ports)
#:use-module (ice-9 iconv)
#:use-module (ice-9 rdelim)
#:use-module (web request)
#:use-module (web response)
#:use-module (web uri)
#:use-module (web http)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-9 gnu)
#:export (current-http-proxy
open-socket-for-uri
http-get
http-get*
http-head
http-post
http-put
http-delete
http-trace
http-options))
(define current-http-proxy
(make-parameter (let ((proxy (getenv "http_proxy")))
(and (not (equal? proxy ""))
proxy))))
(define (ensure-uri uri-or-string)
(cond
((string? uri-or-string) (string->uri uri-or-string))
((uri? uri-or-string) uri-or-string)
(else (error "Invalid URI" uri-or-string))))
(define (open-socket-for-uri uri-or-string)
"Return an open input/output port for a connection to URI."
(define http-proxy (current-http-proxy))
(define uri (ensure-uri (or http-proxy uri-or-string)))
(define addresses
(let ((port (uri-port uri)))
(delete-duplicates
(getaddrinfo (uri-host uri)
(cond (port => number->string)
(else (symbol->string (uri-scheme uri))))
(if port
AI_NUMERICSERV
0))
(lambda (ai1 ai2)
(equal? (addrinfo:addr ai1) (addrinfo:addr ai2))))))
(let loop ((addresses addresses))
(let* ((ai (car addresses))
(s (with-fluids ((%default-port-encoding #f))
;; Restrict ourselves to TCP.
(socket (addrinfo:fam ai) SOCK_STREAM IPPROTO_IP))))
(catch 'system-error
(lambda ()
(connect s (addrinfo:addr ai))
;; Buffer input and output on this port.
(setvbuf s _IOFBF)
;; If we're using a proxy, make a note of that.
(when http-proxy (set-http-proxy-port?! s #t))
s)
(lambda args
;; Connection failed, so try one of the other addresses.
(close s)
(if (null? (cdr addresses))
(apply throw args)
(loop (cdr addresses))))))))
(define (extend-request r k v . additional)
(let ((r (set-field r (request-headers)
(assoc-set! (copy-tree (request-headers r))
k v))))
(if (null? additional)
r
(apply extend-request r additional))))
;; -> request body
(define (sanitize-request request body)
"\"Sanitize\" the given request and body, ensuring that they are
complete and coherent. This method is most useful for methods that send
data to the server, like POST, but can be used for any method. Return
two values: a request and a bytevector, possibly the same ones that were
passed as arguments.
If BODY is a string, encodes the string to a bytevector, in an encoding
appropriate for REQUEST. Adds a ‘content-length’ and ‘content-type’
header, as necessary.
If BODY is a procedure, it is called with a port as an argument, and the
output collected as a bytevector. In the future we might try to instead
use a compressing, chunk-encoded port, and call this procedure later.
Authors are advised not to rely on the procedure being called at any
particular time.
Note that we rely on the request itself already having been validated,
as is the case by default with a request returned by `build-request'."
(cond
((not body)
(let ((length (request-content-length request)))
(if length
;; FIXME make this stricter: content-length header should be
;; prohibited if there's no body, even if the content-length
;; is 0.
(unless (zero? length)
(error "content-length, but no body"))
(when (assq 'transfer-encoding (request-headers request))
(error "transfer-encoding not allowed with no body")))
(values request #vu8())))
((string? body)
(let* ((type (request-content-type request '(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-request
(if declared-charset
request
(extend-request request 'content-type
`(,@type (charset . ,charset))))
(string->bytevector body charset))))
((procedure? body)
(let* ((type (request-content-type request
'(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-request
(if declared-charset
request
(extend-request request 'content-type
`(,@type (charset . ,charset))))
(call-with-encoded-output-string charset body))))
((not (bytevector? body))
(error "unexpected body type"))
(else
(values (let ((rlen (request-content-length request))
(blen (bytevector-length body)))
(cond
(rlen (if (= rlen blen)
request
(error "bad content-length" rlen blen)))
(else (extend-request request 'content-length blen))))
body))))
(define (decode-response-body response body)
;; `body' is either #f or a bytevector.
(cond
((not body) body)
((bytevector? body)
(let ((rlen (response-content-length response))
(blen (bytevector-length body)))
(cond
((and rlen (not (= rlen blen)))
(error "bad content-length" rlen blen))
((response-content-type response)
=> (lambda (type)
(cond
((text-content-type? (car type))
;; RFC 2616 3.7.1: "When no explicit charset parameter is
;; provided by the sender, media subtypes of the "text"
;; type are defined to have a default charset value of
;; "ISO-8859-1" when received via HTTP."
(bytevector->string body (or (assq-ref (cdr type) 'charset)
"iso-8859-1")))
(else body))))
(else body))))
(else
(error "unexpected body type" body))))
;; We could expose this to user code if there is demand.
(define* (request uri #:key
(body #f)
(port (open-socket-for-uri uri))
(method 'GET)
(version '(1 . 1))
(keep-alive? #f)
(headers '())
(decode-body? #t)
(streaming? #f)
(request
(build-request
(ensure-uri uri)
#:method method
#:version version
#:headers (if keep-alive?
headers
(cons '(connection close) headers))
#:port port)))
(call-with-values (lambda () (sanitize-request request body))
(lambda (request body)
(let ((request (write-request request port)))
(when body
(write-request-body request body))
(force-output (request-port request))
(let ((response (read-response port)))
(cond
((eq? (request-method request) 'HEAD)
(unless keep-alive?
(close-port port))
(values response #f))
(streaming?
(values response
(response-body-port response
#:keep-alive? keep-alive?
#:decode? decode-body?)))
(else
(let ((body (read-response-body response)))
(unless keep-alive?
(close-port port))
(values response
(if decode-body?
(decode-response-body response body)
body))))))))))
(define* (http-get uri #:key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1)) (keep-alive? #f)
;; #:headers is the new name of #:extra-headers.
(extra-headers #f) (headers (or extra-headers '()))
(decode-body? #t) (streaming? #f))
"Connect to the server corresponding to URI and ask for the
resource, using the ‘GET’ method. If you already have a port open,
pass it as PORT. The port will be closed at the end of the
request unless KEEP-ALIVE? is true. Any extra headers in the
alist HEADERS will be added to the request.
If BODY is not ‘#f’, a message body will also be sent with the HTTP
request. If BODY is a string, it is encoded according to the
content-type in HEADERS, defaulting to UTF-8. Otherwise BODY should be
a bytevector, or ‘#f’ for no body. Although it's allowed to send a
message body along with any request, usually only POST and PUT requests
have bodies. See ‘http-put’ and ‘http-post’ documentation, for more.
If DECODE-BODY? is true, as is the default, the body of the
response will be decoded to string, if it is a textual content-type.
Otherwise it will be returned as a bytevector.
However, if STREAMING? is true, instead of eagerly reading the response
body from the server, this function only reads off the headers. The
response body will be returned as a port on which the data may be read.
Unless KEEP-ALIVE? is true, the port will be closed after the full
response body has been read.
Returns two values: the response read from the server, and the response
body as a string, bytevector, #f value, or as a port (if STREAMING? is
true)."
(when extra-headers
(issue-deprecation-warning
"The #:extra-headers argument to http-get has been renamed to #:headers. "
"Please update your code."))
(request uri #:method 'GET #:body body
#:port port #:version version #:keep-alive? keep-alive?
#:headers headers #:decode-body? decode-body?
#:streaming? streaming?))
(define* (http-get* uri #:key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1)) (keep-alive? #f)
;; #:headers is the new name of #:extra-headers.
(extra-headers #f) (headers (or extra-headers '()))
(decode-body? #t))
"Deprecated in favor of (http-get #:streaming? #t)."
(issue-deprecation-warning
"`http-get*' has been deprecated. "
"Instead, use `http-get' with the #:streaming? #t keyword argument.")
(http-get uri #:body body
#:port port #:version version #:keep-alive? keep-alive?
#:headers headers #:decode-body? #t #:streaming? #t))
(define-syntax-rule (define-http-verb http-verb method doc)
(define* (http-verb uri #:key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1))
(keep-alive? #f)
(headers '())
(decode-body? #t)
(streaming? #f))
doc
(request uri
#:body body #:method method
#:port port #:version version #:keep-alive? keep-alive?
#:headers headers #:decode-body? decode-body?
#:streaming? streaming?)))
(define-http-verb http-head
'HEAD
"Fetch message headers for the given URI using the HTTP \"HEAD\"
method.
This function is similar to ‘http-get’, except it uses the \"HEAD\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and ‘#f’. Responses to HEAD
requests do not have a body. The second value is only returned so that
other procedures can treat all of the http-foo verbs identically.")
(define-http-verb http-post
'POST
"Post data to the given URI using the HTTP \"POST\" method.
This function is similar to ‘http-get’, except it uses the \"POST\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and the response body.")
(define-http-verb http-put
'PUT
"Put data at the given URI using the HTTP \"PUT\" method.
This function is similar to ‘http-get’, except it uses the \"PUT\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and the response body.")
(define-http-verb http-delete
'DELETE
"Delete data at the given URI using the HTTP \"DELETE\" method.
This function is similar to ‘http-get’, except it uses the \"DELETE\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and the response body.")
(define-http-verb http-trace
'TRACE
"Send an HTTP \"TRACE\" request.
This function is similar to ‘http-get’, except it uses the \"TRACE\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and the response body.")
(define-http-verb http-options
'OPTIONS
"Query characteristics of an HTTP resource using the HTTP \"OPTIONS\"
method.
This function is similar to ‘http-get’, except it uses the \"OPTIONS\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values: the resulting response, and the response body.")
|