server.scm 15 KB

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