response.scm 13 KB

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