client.scm 14 KB

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