response.scm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. ;;; HTTP response objects
  2. ;; Copyright (C) 2010, 2011, 2012, 2013, 2014 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. ;;; Code:
  18. (define-module (web response)
  19. #:use-module (rnrs bytevectors)
  20. #:use-module (ice-9 binary-ports)
  21. #:use-module (ice-9 rdelim)
  22. #:use-module (ice-9 match)
  23. #:use-module (srfi srfi-9)
  24. #:use-module (web http)
  25. #:export (response?
  26. response-version
  27. response-code
  28. response-reason-phrase
  29. response-headers
  30. response-port
  31. read-response
  32. build-response
  33. adapt-response-version
  34. write-response
  35. response-must-not-include-body?
  36. response-body-port
  37. read-response-body
  38. write-response-body
  39. ;; General headers
  40. ;;
  41. response-cache-control
  42. response-connection
  43. response-date
  44. response-pragma
  45. response-trailer
  46. response-transfer-encoding
  47. response-upgrade
  48. response-via
  49. response-warning
  50. ;; Entity headers
  51. ;;
  52. response-allow
  53. response-content-encoding
  54. response-content-language
  55. response-content-length
  56. response-content-location
  57. response-content-md5
  58. response-content-range
  59. response-content-type
  60. text-content-type?
  61. response-expires
  62. response-last-modified
  63. ;; Response headers
  64. ;;
  65. response-accept-ranges
  66. response-age
  67. response-etag
  68. response-location
  69. response-proxy-authenticate
  70. response-retry-after
  71. response-server
  72. response-vary
  73. response-www-authenticate))
  74. (define-record-type <response>
  75. (make-response version code reason-phrase headers port)
  76. response?
  77. (version response-version)
  78. (code response-code)
  79. (reason-phrase %response-reason-phrase)
  80. (headers response-headers)
  81. (port response-port))
  82. (define (bad-response message . args)
  83. (throw 'bad-response message args))
  84. (define (non-negative-integer? n)
  85. (and (number? n) (>= n 0) (exact? n) (integer? n)))
  86. (define (validate-headers headers)
  87. (if (pair? headers)
  88. (let ((h (car headers)))
  89. (if (pair? h)
  90. (let ((k (car h)) (v (cdr h)))
  91. (if (valid-header? k v)
  92. (validate-headers (cdr headers))
  93. (bad-response "Bad value for header ~a: ~s" k v)))
  94. (bad-response "Header not a pair: ~a" h)))
  95. (if (not (null? headers))
  96. (bad-response "Headers not a list: ~a" headers))))
  97. (define* (build-response #:key (version '(1 . 1)) (code 200) reason-phrase
  98. (headers '()) port (validate-headers? #t))
  99. "Construct an HTTP response object. If VALIDATE-HEADERS? is true,
  100. the headers are each run through their respective validators."
  101. (cond
  102. ((not (and (pair? version)
  103. (non-negative-integer? (car version))
  104. (non-negative-integer? (cdr version))))
  105. (bad-response "Bad version: ~a" version))
  106. ((not (and (non-negative-integer? code) (< code 600)))
  107. (bad-response "Bad code: ~a" code))
  108. ((and reason-phrase (not (string? reason-phrase)))
  109. (bad-response "Bad reason phrase" reason-phrase))
  110. (else
  111. (if validate-headers?
  112. (validate-headers headers))))
  113. (make-response version code reason-phrase headers port))
  114. (define *reason-phrases*
  115. '((100 . "Continue")
  116. (101 . "Switching Protocols")
  117. (200 . "OK")
  118. (201 . "Created")
  119. (202 . "Accepted")
  120. (203 . "Non-Authoritative Information")
  121. (204 . "No Content")
  122. (205 . "Reset Content")
  123. (206 . "Partial Content")
  124. (300 . "Multiple Choices")
  125. (301 . "Moved Permanently")
  126. (302 . "Found")
  127. (303 . "See Other")
  128. (304 . "Not Modified")
  129. (305 . "Use Proxy")
  130. (307 . "Temporary Redirect")
  131. (400 . "Bad Request")
  132. (401 . "Unauthorized")
  133. (402 . "Payment Required")
  134. (403 . "Forbidden")
  135. (404 . "Not Found")
  136. (405 . "Method Not Allowed")
  137. (406 . "Not Acceptable")
  138. (407 . "Proxy Authentication Required")
  139. (408 . "Request Timeout")
  140. (409 . "Conflict")
  141. (410 . "Gone")
  142. (411 . "Length Required")
  143. (412 . "Precondition Failed")
  144. (413 . "Request Entity Too Large")
  145. (414 . "Request-URI Too Long")
  146. (415 . "Unsupported Media Type")
  147. (416 . "Requested Range Not Satisfiable")
  148. (417 . "Expectation Failed")
  149. (500 . "Internal Server Error")
  150. (501 . "Not Implemented")
  151. (502 . "Bad Gateway")
  152. (503 . "Service Unavailable")
  153. (504 . "Gateway Timeout")
  154. (505 . "HTTP Version Not Supported")))
  155. (define (code->reason-phrase code)
  156. (or (assv-ref *reason-phrases* code)
  157. "(Unknown)"))
  158. (define (response-reason-phrase response)
  159. "Return the reason phrase given in RESPONSE, or the standard
  160. reason phrase for the response's code."
  161. (or (%response-reason-phrase response)
  162. (code->reason-phrase (response-code response))))
  163. (define (text-content-type? type)
  164. "Return #t if TYPE, a symbol as returned by `response-content-type',
  165. represents a textual type such as `text/plain'."
  166. (let ((type (symbol->string type)))
  167. (or (string-prefix? "text/" type)
  168. (string-suffix? "/xml" type)
  169. (string-suffix? "+xml" type))))
  170. (define (read-response port)
  171. "Read an HTTP response from PORT.
  172. As a side effect, sets the encoding on PORT to
  173. ISO-8859-1 (latin-1), so that reading one character reads one byte. See
  174. the discussion of character sets in \"HTTP Responses\" in the manual,
  175. for more information."
  176. (set-port-encoding! port "ISO-8859-1")
  177. (call-with-values (lambda () (read-response-line port))
  178. (lambda (version code reason-phrase)
  179. (make-response version code reason-phrase (read-headers port) port))))
  180. (define (adapt-response-version response version)
  181. "Adapt the given response to a different HTTP version. Returns a new
  182. HTTP response.
  183. The idea is that many applications might just build a response for the
  184. default HTTP version, and this method could handle a number of
  185. programmatic transformations to respond to older HTTP versions (0.9 and
  186. 1.0). But currently this function is a bit heavy-handed, just updating
  187. the version field."
  188. (build-response #:code (response-code response)
  189. #:version version
  190. #:headers (response-headers response)
  191. #:port (response-port response)))
  192. (define (write-response r port)
  193. "Write the given HTTP response to PORT.
  194. Returns a new response, whose ‘response-port’ will continue writing
  195. on PORT, perhaps using some transfer encoding."
  196. (write-response-line (response-version r) (response-code r)
  197. (response-reason-phrase r) port)
  198. (write-headers (response-headers r) port)
  199. (display "\r\n" port)
  200. (if (eq? port (response-port r))
  201. r
  202. (make-response (response-version r) (response-code r)
  203. (response-reason-phrase r) (response-headers r) port)))
  204. (define (response-must-not-include-body? r)
  205. "Returns ‘#t’ if the response R is not permitted to have a body.
  206. This is true for some response types, like those with code 304."
  207. ;; RFC 2616, section 4.3.
  208. (or (<= 100 (response-code r) 199)
  209. (= (response-code r) 204)
  210. (= (response-code r) 304)))
  211. (define (make-delimited-input-port port len keep-alive?)
  212. "Return an input port that reads from PORT, and makes sure that
  213. exactly LEN bytes are available from PORT. Closing the returned port
  214. closes PORT, unless KEEP-ALIVE? is true."
  215. (define bytes-read 0)
  216. (define (fail)
  217. (bad-response "EOF while reading response body: ~a bytes of ~a"
  218. bytes-read len))
  219. (define (read! bv start count)
  220. ;; Read at most LEN bytes in total. HTTP/1.1 doesn't say what to do
  221. ;; when a server provides more than the Content-Length, but it seems
  222. ;; wise to just stop reading at LEN.
  223. (let ((count (min count (- len bytes-read))))
  224. (let loop ((ret (get-bytevector-n! port bv start count)))
  225. (cond ((eof-object? ret)
  226. (if (= bytes-read len)
  227. 0 ; EOF
  228. (fail)))
  229. ((and (zero? ret) (> count 0))
  230. ;; Do not return zero since zero means EOF, so try again.
  231. (loop (get-bytevector-n! port bv start count)))
  232. (else
  233. (set! bytes-read (+ bytes-read ret))
  234. ret)))))
  235. (define close
  236. (and (not keep-alive?)
  237. (lambda ()
  238. (close port))))
  239. (make-custom-binary-input-port "delimited input port" read! #f #f close))
  240. (define* (response-body-port r #:key (decode? #t) (keep-alive? #t))
  241. "Return an input port from which the body of R can be read. The
  242. encoding of the returned port is set according to R's ‘content-type’
  243. header, when it's textual, except if DECODE? is ‘#f’. Return #f when
  244. no body is available.
  245. When KEEP-ALIVE? is ‘#f’, closing the returned port also closes R's
  246. response port."
  247. (define port
  248. (cond
  249. ((member '(chunked) (response-transfer-encoding r))
  250. (make-chunked-input-port (response-port r)
  251. #:keep-alive? keep-alive?))
  252. ((response-content-length r)
  253. => (lambda (len)
  254. (make-delimited-input-port (response-port r)
  255. len keep-alive?)))
  256. ((response-must-not-include-body? r)
  257. #f)
  258. ((or (memq 'close (response-connection r))
  259. (and (equal? (response-version r) '(1 . 0))
  260. (not (memq 'keep-alive (response-connection r)))))
  261. (response-port r))
  262. (else
  263. ;; Here we have a message with no transfer encoding, no
  264. ;; content-length, and a response that won't necessarily be closed
  265. ;; by the server. Not much we can do; assume that the client
  266. ;; knows how to handle it.
  267. (response-port r))))
  268. (when (and decode? port)
  269. (match (response-content-type r)
  270. (((? text-content-type?) . props)
  271. (set-port-encoding! port
  272. (or (assq-ref props 'charset)
  273. "ISO-8859-1")))
  274. (_ #f)))
  275. port)
  276. (define (read-response-body r)
  277. "Reads the response body from R, as a bytevector. Returns
  278. ‘#f’ if there was no response body."
  279. (let ((body (and=> (response-body-port r #:decode? #f)
  280. get-bytevector-all)))
  281. ;; Reading a body of length 0 will result in get-bytevector-all
  282. ;; returning the EOF object.
  283. (if (eof-object? body)
  284. #vu8()
  285. body)))
  286. (define (write-response-body r bv)
  287. "Write BV, a bytevector, to the port corresponding to the HTTP
  288. response R."
  289. (put-bytevector (response-port r) bv))
  290. (define-syntax define-response-accessor
  291. (lambda (x)
  292. (syntax-case x ()
  293. ((_ field)
  294. #'(define-response-accessor field #f))
  295. ((_ field def) (identifier? #'field)
  296. #`(define* (#,(datum->syntax
  297. #'field
  298. (symbol-append 'response- (syntax->datum #'field)))
  299. response
  300. #:optional (default def))
  301. (cond
  302. ((assq 'field (response-headers response)) => cdr)
  303. (else default)))))))
  304. ;; General headers
  305. ;;
  306. (define-response-accessor cache-control '())
  307. (define-response-accessor connection '())
  308. (define-response-accessor date #f)
  309. (define-response-accessor pragma '())
  310. (define-response-accessor trailer '())
  311. (define-response-accessor transfer-encoding '())
  312. (define-response-accessor upgrade '())
  313. (define-response-accessor via '())
  314. (define-response-accessor warning '())
  315. ;; Entity headers
  316. ;;
  317. (define-response-accessor allow '())
  318. (define-response-accessor content-encoding '())
  319. (define-response-accessor content-language '())
  320. (define-response-accessor content-length #f)
  321. (define-response-accessor content-location #f)
  322. (define-response-accessor content-md5 #f)
  323. (define-response-accessor content-range #f)
  324. (define-response-accessor content-type #f)
  325. (define-response-accessor expires #f)
  326. (define-response-accessor last-modified #f)
  327. ;; Response headers
  328. ;;
  329. (define-response-accessor accept-ranges #f)
  330. (define-response-accessor age #f)
  331. (define-response-accessor etag #f)
  332. (define-response-accessor location #f)
  333. (define-response-accessor proxy-authenticate #f)
  334. (define-response-accessor retry-after #f)
  335. (define-response-accessor server #f)
  336. (define-response-accessor vary '())
  337. (define-response-accessor www-authenticate #f)