server.scm 15 KB

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