3 ;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
5 ;; This library is free software; you can redistribute it and/or
6 ;; modify it under the terms of the GNU Lesser General Public
7 ;; License as published by the Free Software Foundation; either
8 ;; version 3 of the License, or (at your option) any later version.
10 ;; This library is distributed in the hope that it will be useful,
11 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;; Lesser General Public License for more details.
15 ;; You should have received a copy of the GNU Lesser General Public
16 ;; License along with this library; if not, write to the Free Software
17 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 ;;; (web server) is a generic web server interface, along with a main
23 ;;; loop implementation for web servers controlled by Guile.
25 ;;; The lowest layer is the <server-impl> object, which defines a set of
26 ;;; hooks to open a server, read a request from a client, write a
27 ;;; response to a client, and close a server. These hooks -- open,
28 ;;; read, write, and close, respectively -- are bound together in a
29 ;;; <server-impl> object. Procedures in this module take a
30 ;;; <server-impl> object, if needed.
32 ;;; A <server-impl> may also be looked up by name. If you pass the
33 ;;; `http' symbol to `run-server', Guile looks for a variable named
34 ;;; `http' in the `(web server http)' module, which should be bound to a
35 ;;; <server-impl> object. Such a binding is made by instantiation of
36 ;;; the `define-server-impl' syntax. In this way the run-server loop can
37 ;;; automatically load other backends if available.
39 ;;; The life cycle of a server goes as follows:
41 ;;; * The `open' hook is called, to open the server. `open' takes 0 or
42 ;;; more arguments, depending on the backend, and returns an opaque
43 ;;; server socket object, or signals an error.
45 ;;; * The `read' hook is called, to read a request from a new client.
46 ;;; The `read' hook takes one arguments, the server socket. It
47 ;;; should return three values: an opaque client socket, the
48 ;;; request, and the request body. The request should be a
49 ;;; `<request>' object, from `(web request)'. The body should be a
50 ;;; string or a bytevector, or `#f' if there is no body.
52 ;;; If the read failed, the `read' hook may return #f for the client
53 ;;; socket, request, and body.
55 ;;; * A user-provided handler procedure is called, with the request
56 ;;; and body as its arguments. The handler should return two
57 ;;; values: the response, as a `<response>' record from `(web
58 ;;; response)', and the response body as a string, bytevector, or
59 ;;; `#f' if not present. We also allow the reponse to be simply an
60 ;;; alist of headers, in which case a default response object is
61 ;;; constructed with those headers.
63 ;;; * The `write' hook is called with three arguments: the client
64 ;;; socket, the response, and the body. The `write' hook returns no
67 ;;; * At this point the request handling is complete. For a loop, we
68 ;;; loop back and try to read a new request.
70 ;;; * If the user interrupts the loop, the `close' hook is called on
71 ;;; the server socket.
75 (define-module (web server)
76 #:use-module (srfi srfi-9)
77 #:use-module (rnrs bytevectors)
78 #:use-module (ice-9 binary-ports)
79 #:use-module (web request)
80 #:use-module (web response)
81 #:use-module (system repl error-handling)
82 #:use-module (ice-9 control)
83 #:export (define-server-impl
94 (define *timer* (gettimeofday))
95 (define (print-elapsed who)
96 (let ((t (gettimeofday)))
97 (pk who (+ (* (- (car t) (car *timer*)) 1000000)
98 (- (cdr t) (cdr *timer*))))
102 (define *time-debug?* #f))
104 (define-syntax debug-elapsed
109 #'(print-elapsed who)
112 (define-record-type server-impl
113 (make-server-impl name open read write close)
115 (name server-impl-name)
116 (open server-impl-open)
117 (read server-impl-read)
118 (write server-impl-write)
119 (close server-impl-close))
121 (define-syntax define-server-impl
123 ((_ name open read write close)
125 (make-server-impl 'name open read write close)))))
127 (define (lookup-server-impl impl)
128 "Look up a server implementation. If @var{impl} is a server
129 implementation already, it is returned directly. If it is a symbol, the
130 binding named @var{impl} in the @code{(web server @var{impl})} module is
131 looked up. Otherwise an error is signaled.
133 Currently a server implementation is a somewhat opaque type, useful only
134 for passing to other procedures in this module, like
137 ((server-impl? impl) impl)
139 (let ((impl (module-ref (resolve-module `(web server ,impl)) impl)))
140 (if (server-impl? impl)
142 (error "expected a server impl in module" `(web server ,impl)))))
144 (error "expected a server-impl or a symbol" impl))))
147 (define (open-server impl open-params)
148 "Open a server for the given implementation. Returns one value, the
149 new server object. The implementation's @code{open} procedure is
150 applied to @var{open-params}, which should be a list."
151 (apply (server-impl-open impl) open-params))
153 ;; -> (client request body | #f #f #f)
154 (define (read-client impl server)
155 "Read a new client from @var{server}, by applying the implementation's
156 @code{read} procedure to the server. If successful, returns three
157 values: an object corresponding to the client, a request object, and the
158 request body. If any exception occurs, returns @code{#f} for all three
160 (call-with-error-handling
162 ((server-impl-read impl) server))
163 #:pass-keys '(quit interrupt)
164 #:on-error (if (batch-mode?) 'pass 'debug)
167 (warn "Error while accepting client" k args)
170 ;; like call-with-output-string, but actually closes the port (doh)
171 (define (call-with-output-string* proc)
172 (let ((port (open-output-string)))
174 (let ((str (get-output-string port)))
178 (define (call-with-output-bytevector* proc)
181 (open-bytevector-output-port))
182 (lambda (port get-bytevector)
184 (let ((bv (get-bytevector)))
188 (define (call-with-encoded-output-string charset proc)
189 (if (string-ci=? charset "utf-8")
190 ;; I don't know why, but this appears to be faster; at least for
191 ;; examples/debug-sxml.scm (1464 reqs/s versus 850 reqs/s).
192 (string->utf8 (call-with-output-string* proc))
193 (call-with-output-bytevector*
195 (set-port-encoding! port charset)
198 (define (encode-string str charset)
199 (if (string-ci=? charset "utf-8")
201 (call-with-encoded-output-string charset
203 (display str port)))))
205 (define (extend-response r k v . additional)
206 (let ((r (build-response #:version (response-version r)
207 #:code (response-code r)
209 (assoc-set! (copy-tree (response-headers r))
211 #:port (response-port r))))
212 (if (null? additional)
214 (apply extend-response r additional))))
217 (define (sanitize-response request response body)
218 "\"Sanitize\" the given response and body, making them appropriate for
221 As a convenience to web handler authors, @var{response} may be given as
222 an alist of headers, in which case it is used to construct a default
223 response. Ensures that the response version corresponds to the request
224 version. If @var{body} is a string, encodes the string to a bytevector,
225 in an encoding appropriate for @var{response}. Adds a
226 @code{content-length} and @code{content-type} header, as necessary.
228 If @var{body} is a procedure, it is called with a port as an argument,
229 and the output collected as a bytevector. In the future we might try to
230 instead use a compressing, chunk-encoded port, and call this procedure
231 later, in the write-client procedure. Authors are advised not to rely
232 on the procedure being called at any particular time."
235 (sanitize-response request
236 (build-response #:version (request-version request)
239 ((not (equal? (request-version request) (response-version response)))
240 (sanitize-response request
241 (adapt-response-version response
242 (request-version request))
245 (values response #vu8()))
247 (let* ((type (response-content-type response
249 (declared-charset (assq-ref (cdr type) 'charset))
250 (charset (or declared-charset "utf-8")))
255 (extend-response response 'content-type
256 `(,@type (charset . ,charset))))
257 (encode-string body charset))))
259 (let* ((type (response-content-type response
261 (declared-charset (assq-ref (cdr type) 'charset))
262 (charset (or declared-charset "utf-8")))
267 (extend-response response 'content-type
268 `(,@type (charset . ,charset))))
269 (call-with-encoded-output-string charset body))))
271 ;; check length; assert type; add other required fields?
272 (values (let ((rlen (response-content-length response))
273 (blen (bytevector-length body)))
275 (rlen (if (= rlen blen)
277 (error "bad content-length" rlen blen)))
278 ((zero? blen) response)
279 (else (extend-response response 'content-length blen))))
282 (error "unexpected body type"))))
284 ;; -> response body state
285 (define (handle-request handler request body state)
286 "Handle a given request, returning the response and body.
288 The response and response body are produced by calling the given
289 @var{handler} with @var{request} and @var{body} as arguments.
291 The elements of @var{state} are also passed to @var{handler} as
292 arguments, and may be returned as additional values. The new
293 @var{state}, collected from the @var{handler}'s return values, is then
294 returned as a list. The idea is that a server loop receives a handler
295 from the user, along with whatever state values the user is interested
296 in, allowing the user's handler to explicitly manage its state."
297 (call-with-error-handling
299 (call-with-values (lambda ()
300 (with-stack-and-prompt
302 (apply handler request body state))))
303 (lambda (response body . state)
304 (call-with-values (lambda ()
305 (debug-elapsed 'handler)
306 (sanitize-response request response body))
307 (lambda (response body)
308 (debug-elapsed 'sanitize)
309 (values response body state))))))
310 #:pass-keys '(quit interrupt)
311 #:on-error (if (batch-mode?) 'pass 'debug)
314 (warn "Error handling request" k args)
315 (values (build-response #:code 500) #f state))))
317 ;; -> unspecified values
318 (define (write-client impl server client response body)
319 "Write an HTTP response and body to @var{client}. If the server and
320 client support persistent connections, it is the implementation's
321 responsibility to keep track of the client thereafter, presumably by
322 attaching it to the @var{server} argument somehow."
323 (call-with-error-handling
325 ((server-impl-write impl) server client response body))
326 #:pass-keys '(quit interrupt)
327 #:on-error (if (batch-mode?) 'pass 'debug)
330 (warn "Error while writing response" k args)
333 ;; -> unspecified values
334 (define (close-server impl server)
335 "Release resources allocated by a previous invocation of
337 ((server-impl-close impl) server))
339 (define call-with-sigint
340 (if (not (provided? 'posix))
341 (lambda (thunk handler-thunk) (thunk))
342 (lambda (thunk handler-thunk)
349 (sigaction SIGINT (lambda (sig) (throw 'interrupt)))))
353 ;; restore Scheme handler, SIG_IGN or SIG_DFL.
354 (sigaction SIGINT (car handler) (cdr handler))
355 ;; restore original C handler.
356 (sigaction SIGINT #f)))))
357 (lambda (k . _) (handler-thunk)))))))
359 (define (with-stack-and-prompt thunk)
360 (call-with-prompt (default-prompt-tag)
361 (lambda () (start-stack #t (thunk)))
363 (with-stack-and-prompt (lambda () (proc k))))))
366 (define (serve-one-client handler impl server state)
367 "Read one request from @var{server}, call @var{handler} on the request
368 and body, and write the response to the client. Returns the new state
369 produced by the handler procedure."
370 (debug-elapsed 'serve-again)
373 (read-client impl server))
374 (lambda (client request body)
375 (debug-elapsed 'read-client)
379 (handle-request handler request body state))
380 (lambda (response body state)
381 (debug-elapsed 'handle-request)
382 (write-client impl server client response body)
383 (debug-elapsed 'write-client)
387 (define* (run-server handler #:optional (impl 'http) (open-params '())
389 "Run Guile's built-in web server.
391 @var{handler} should be a procedure that takes two or more arguments,
392 the HTTP request and request body, and returns two or more values, the
393 response and response body.
395 For example, here is a simple \"Hello, World!\" server:
398 (define (handler request body)
399 (values '((content-type . (text/plain)))
404 The response and body will be run through @code{sanitize-response}
405 before sending back to the client.
407 Additional arguments to @var{handler} are taken from
408 @var{state}. Additional return values are accumulated into a new
409 @var{state}, which will be used for subsequent requests. In this way a
410 handler can explicitly manage its state.
412 The default server implementation is @code{http}, which accepts
413 @var{open-params} like @code{(#:port 8081)}, among others. See \"Web
414 Server\" in the manual, for more information."
415 (let* ((impl (lookup-server-impl impl))
416 (server (open-server impl open-params)))
419 (let lp ((state state))
420 (lp (serve-one-client handler impl server state))))
422 (close-server impl server)