server.scm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. ;;; Web server
  2. ;; Copyright (C) 2010, 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 server) is a generic web server interface, along with a main
  20. ;;; loop implementation for web servers controlled by Guile.
  21. ;;;
  22. ;;; The lowest layer is the <server-impl> object, which defines a set of
  23. ;;; hooks to open a server, read a request from a client, write a
  24. ;;; response to a client, and close a server. These hooks -- open,
  25. ;;; read, write, and close, respectively -- are bound together in a
  26. ;;; <server-impl> object. Procedures in this module take a
  27. ;;; <server-impl> object, if needed.
  28. ;;;
  29. ;;; A <server-impl> may also be looked up by name. If you pass the
  30. ;;; `http' symbol to `run-server', Guile looks for a variable named
  31. ;;; `http' in the `(web server http)' module, which should be bound to a
  32. ;;; <server-impl> object. Such a binding is made by instantiation of
  33. ;;; the `define-server-impl' syntax. In this way the run-server loop can
  34. ;;; automatically load other backends if available.
  35. ;;;
  36. ;;; The life cycle of a server goes as follows:
  37. ;;;
  38. ;;; * The `open' hook is called, to open the server. `open' takes 0 or
  39. ;;; more arguments, depending on the backend, and returns an opaque
  40. ;;; server socket object, or signals an error.
  41. ;;;
  42. ;;; * The `read' hook is called, to read a request from a new client.
  43. ;;; The `read' hook takes one arguments, the server socket. It
  44. ;;; should return three values: an opaque client socket, the
  45. ;;; request, and the request body. The request should be a
  46. ;;; `<request>' object, from `(web request)'. The body should be a
  47. ;;; string or a bytevector, or `#f' if there is no body.
  48. ;;;
  49. ;;; If the read failed, the `read' hook may return #f for the client
  50. ;;; socket, request, and body.
  51. ;;;
  52. ;;; * A user-provided handler procedure is called, with the request
  53. ;;; and body as its arguments. The handler should return two
  54. ;;; values: the response, as a `<response>' record from `(web
  55. ;;; response)', and the response body as a string, bytevector, or
  56. ;;; `#f' if not present. We also allow the reponse to be simply an
  57. ;;; alist of headers, in which case a default response object is
  58. ;;; constructed with those headers.
  59. ;;;
  60. ;;; * The `write' hook is called with three arguments: the client
  61. ;;; socket, the response, and the body. The `write' hook returns no
  62. ;;; values.
  63. ;;;
  64. ;;; * At this point the request handling is complete. For a loop, we
  65. ;;; loop back and try to read a new request.
  66. ;;;
  67. ;;; * If the user interrupts the loop, the `close' hook is called on
  68. ;;; the server socket.
  69. ;;;
  70. ;;; Code:
  71. (define-module (web server)
  72. #:use-module (srfi srfi-9)
  73. #:use-module (srfi srfi-9 gnu)
  74. #:use-module (rnrs bytevectors)
  75. #:use-module (ice-9 binary-ports)
  76. #:use-module (web request)
  77. #:use-module (web response)
  78. #:use-module (system repl error-handling)
  79. #:use-module (ice-9 control)
  80. #:use-module (ice-9 iconv)
  81. #:export (define-server-impl
  82. lookup-server-impl
  83. open-server
  84. read-client
  85. handle-request
  86. sanitize-response
  87. write-client
  88. close-server
  89. serve-one-client
  90. run-server))
  91. (define *timer* (gettimeofday))
  92. (define (print-elapsed who)
  93. (let ((t (gettimeofday)))
  94. (pk who (+ (* (- (car t) (car *timer*)) 1000000)
  95. (- (cdr t) (cdr *timer*))))
  96. (set! *timer* t)))
  97. (eval-when (expand)
  98. (define *time-debug?* #f))
  99. (define-syntax debug-elapsed
  100. (lambda (x)
  101. (syntax-case x ()
  102. ((_ who)
  103. (if *time-debug?*
  104. #'(print-elapsed who)
  105. #'*unspecified*)))))
  106. (define-record-type server-impl
  107. (make-server-impl name open read write close)
  108. server-impl?
  109. (name server-impl-name)
  110. (open server-impl-open)
  111. (read server-impl-read)
  112. (write server-impl-write)
  113. (close server-impl-close))
  114. (define-syntax-rule (define-server-impl name open read write close)
  115. (define name
  116. (make-server-impl 'name open read write close)))
  117. (define (lookup-server-impl impl)
  118. "Look up a server implementation. If IMPL is a server
  119. implementation already, it is returned directly. If it is a symbol, the
  120. binding named IMPL in the ‘(web server IMPL)’ module is
  121. looked up. Otherwise an error is signaled.
  122. Currently a server implementation is a somewhat opaque type, useful only
  123. for passing to other procedures in this module, like
  124. ‘read-client’."
  125. (cond
  126. ((server-impl? impl) impl)
  127. ((symbol? impl)
  128. (let ((impl (module-ref (resolve-module `(web server ,impl)) impl)))
  129. (if (server-impl? impl)
  130. impl
  131. (error "expected a server impl in module" `(web server ,impl)))))
  132. (else
  133. (error "expected a server-impl or a symbol" impl))))
  134. ;; -> server
  135. (define (open-server impl open-params)
  136. "Open a server for the given implementation. Return one value, the
  137. new server object. The implementation's ‘open’ procedure is
  138. applied to OPEN-PARAMS, which should be a list."
  139. (apply (server-impl-open impl) open-params))
  140. ;; -> (client request body | #f #f #f)
  141. (define (read-client impl server)
  142. "Read a new client from SERVER, by applying the implementation's
  143. ‘read’ procedure to the server. If successful, return three
  144. values: an object corresponding to the client, a request object, and the
  145. request body. If any exception occurs, return ‘#f’ for all three
  146. values."
  147. (call-with-error-handling
  148. (lambda ()
  149. ((server-impl-read impl) server))
  150. #:pass-keys '(quit interrupt)
  151. #:on-error (if (batch-mode?) 'backtrace 'debug)
  152. #:post-error (lambda _ (values #f #f #f))))
  153. (define (extend-response r k v . additional)
  154. (define (extend-alist alist k v)
  155. (let ((pair (assq k alist)))
  156. (acons k v (if pair (delq pair alist) alist))))
  157. (let ((r (set-field r (response-headers)
  158. (extend-alist (response-headers r) k v))))
  159. (if (null? additional)
  160. r
  161. (apply extend-response r additional))))
  162. ;; -> response body
  163. (define (sanitize-response request response body)
  164. "\"Sanitize\" the given response and body, making them appropriate for
  165. the given request.
  166. As a convenience to web handler authors, RESPONSE may be given as
  167. an alist of headers, in which case it is used to construct a default
  168. response. Ensures that the response version corresponds to the request
  169. version. If BODY is a string, encodes the string to a bytevector,
  170. in an encoding appropriate for RESPONSE. Adds a
  171. ‘content-length’ and ‘content-type’ header, as necessary.
  172. If BODY is a procedure, it is called with a port as an argument,
  173. and the output collected as a bytevector. In the future we might try to
  174. instead use a compressing, chunk-encoded port, and call this procedure
  175. later, in the write-client procedure. Authors are advised not to rely
  176. on the procedure being called at any particular time."
  177. (cond
  178. ((list? response)
  179. (sanitize-response request
  180. (build-response #:version (request-version request)
  181. #:headers response)
  182. body))
  183. ((not (equal? (request-version request) (response-version response)))
  184. (sanitize-response request
  185. (adapt-response-version response
  186. (request-version request))
  187. body))
  188. ((not body)
  189. (values response #vu8()))
  190. ((string? body)
  191. (let* ((type (response-content-type response
  192. '(text/plain)))
  193. (declared-charset (assq-ref (cdr type) 'charset))
  194. (charset (or declared-charset "utf-8")))
  195. (sanitize-response
  196. request
  197. (if declared-charset
  198. response
  199. (extend-response response 'content-type
  200. `(,@type (charset . ,charset))))
  201. (string->bytevector body charset))))
  202. ((procedure? body)
  203. (let* ((type (response-content-type response
  204. '(text/plain)))
  205. (declared-charset (assq-ref (cdr type) 'charset))
  206. (charset (or declared-charset "utf-8")))
  207. (sanitize-response
  208. request
  209. (if declared-charset
  210. response
  211. (extend-response response 'content-type
  212. `(,@type (charset . ,charset))))
  213. (call-with-encoded-output-string charset body))))
  214. ((not (bytevector? body))
  215. (error "unexpected body type"))
  216. ((and (response-must-not-include-body? response)
  217. body
  218. ;; FIXME make this stricter: even an empty body should be prohibited.
  219. (not (zero? (bytevector-length body))))
  220. (error "response with this status code must not include body" response))
  221. (else
  222. ;; check length; assert type; add other required fields?
  223. (values (let ((rlen (response-content-length response))
  224. (blen (bytevector-length body)))
  225. (cond
  226. (rlen (if (= rlen blen)
  227. response
  228. (error "bad content-length" rlen blen)))
  229. (else (extend-response response 'content-length blen))))
  230. (if (eq? (request-method request) 'HEAD)
  231. ;; Responses to HEAD requests must not include bodies.
  232. ;; We could raise an error here, but it seems more
  233. ;; appropriate to just do something sensible.
  234. #f
  235. body)))))
  236. ;; -> response body state
  237. (define (handle-request handler request body state)
  238. "Handle a given request, returning the response and body.
  239. The response and response body are produced by calling the given
  240. HANDLER with REQUEST and BODY as arguments.
  241. The elements of STATE are also passed to HANDLER as
  242. arguments, and may be returned as additional values. The new
  243. STATE, collected from the HANDLER's return values, is then
  244. returned as a list. The idea is that a server loop receives a handler
  245. from the user, along with whatever state values the user is interested
  246. in, allowing the user's handler to explicitly manage its state."
  247. (call-with-error-handling
  248. (lambda ()
  249. (call-with-values (lambda ()
  250. (with-stack-and-prompt
  251. (lambda ()
  252. (apply handler request body state))))
  253. (lambda (response body . state)
  254. (call-with-values (lambda ()
  255. (debug-elapsed 'handler)
  256. (sanitize-response request response body))
  257. (lambda (response body)
  258. (debug-elapsed 'sanitize)
  259. (values response body state))))))
  260. #:pass-keys '(quit interrupt)
  261. #:on-error (if (batch-mode?) 'backtrace 'debug)
  262. #:post-error (lambda _
  263. (values (build-response #:code 500) #f state))))
  264. ;; -> unspecified values
  265. (define (write-client impl server client response body)
  266. "Write an HTTP response and body to CLIENT. If the server and
  267. client support persistent connections, it is the implementation's
  268. responsibility to keep track of the client thereafter, presumably by
  269. attaching it to the SERVER argument somehow."
  270. (call-with-error-handling
  271. (lambda ()
  272. ((server-impl-write impl) server client response body))
  273. #:pass-keys '(quit interrupt)
  274. #:on-error (if (batch-mode?) 'backtrace 'debug)
  275. #:post-error (lambda _ (values))))
  276. ;; -> unspecified values
  277. (define (close-server impl server)
  278. "Release resources allocated by a previous invocation of
  279. ‘open-server’."
  280. ((server-impl-close impl) server))
  281. (define call-with-sigint
  282. (if (not (provided? 'posix))
  283. (lambda (thunk handler-thunk) (thunk))
  284. (lambda (thunk handler-thunk)
  285. (let ((handler #f))
  286. (catch 'interrupt
  287. (lambda ()
  288. (dynamic-wind
  289. (lambda ()
  290. (set! handler
  291. (sigaction SIGINT (lambda (sig) (throw 'interrupt)))))
  292. thunk
  293. (lambda ()
  294. (if handler
  295. ;; restore Scheme handler, SIG_IGN or SIG_DFL.
  296. (sigaction SIGINT (car handler) (cdr handler))
  297. ;; restore original C handler.
  298. (sigaction SIGINT #f)))))
  299. (lambda (k . _) (handler-thunk)))))))
  300. (define (with-stack-and-prompt thunk)
  301. (call-with-prompt (default-prompt-tag)
  302. (lambda () (start-stack #t (thunk)))
  303. (lambda (k proc)
  304. (with-stack-and-prompt (lambda () (proc k))))))
  305. ;; -> new-state
  306. (define (serve-one-client handler impl server state)
  307. "Read one request from SERVER, call HANDLER on the request
  308. and body, and write the response to the client. Return the new state
  309. produced by the handler procedure."
  310. (debug-elapsed 'serve-again)
  311. (call-with-values
  312. (lambda ()
  313. (read-client impl server))
  314. (lambda (client request body)
  315. (debug-elapsed 'read-client)
  316. (if client
  317. (call-with-values
  318. (lambda ()
  319. (handle-request handler request body state))
  320. (lambda (response body state)
  321. (debug-elapsed 'handle-request)
  322. (write-client impl server client response body)
  323. (debug-elapsed 'write-client)
  324. state))
  325. state))))
  326. (define* (run-server handler #:optional (impl 'http) (open-params '())
  327. . state)
  328. "Run Guile's built-in web server.
  329. HANDLER should be a procedure that takes two or more arguments,
  330. the HTTP request and request body, and returns two or more values, the
  331. response and response body.
  332. For example, here is a simple \"Hello, World!\" server:
  333. @example
  334. (define (handler request body)
  335. (values '((content-type . (text/plain)))
  336. \"Hello, World!\"))
  337. (run-server handler)
  338. @end example
  339. The response and body will be run through ‘sanitize-response’
  340. before sending back to the client.
  341. Additional arguments to HANDLER are taken from
  342. STATE. Additional return values are accumulated into a new
  343. STATE, which will be used for subsequent requests. In this way a
  344. handler can explicitly manage its state.
  345. The default server implementation is ‘http’, which accepts
  346. OPEN-PARAMS like ‘(#:port 8081)’, among others. See \"Web
  347. Server\" in the manual, for more information."
  348. (let* ((impl (lookup-server-impl impl))
  349. (server (open-server impl open-params)))
  350. (call-with-sigint
  351. (lambda ()
  352. (let lp ((state state))
  353. (lp (serve-one-client handler impl server state))))
  354. (lambda ()
  355. (close-server impl server)
  356. (values)))))