source: project/release/4/spiffy/trunk/spiffy.scm @ 12023

Last change on this file since 12023 was 12023, checked in by sjamaan, 13 years ago

Implement request restarting

File size: 9.7 KB
Line 
1;;
2;; Spiffy the web server
3;;
4; Copyright (c) 2007-2008, Peter Bex
5; Copyright (c) 2000-2005, Felix L. Winkelmann
6; All rights reserved.
7;
8; Redistribution and use in source and binary forms, with or without
9; modification, are permitted provided that the following conditions
10; are met:
11;
12; 1. Redistributions of source code must retain the above copyright
13;    notice, this list of conditions and the following disclaimer.
14; 2. Redistributions in binary form must reproduce the above copyright
15;    notice, this list of conditions and the following disclaimer in the
16;    documentation and/or other materials provided with the distribution.
17; 3. Neither the name of the author nor the names of its
18;    contributors may be used to endorse or promote products derived
19;    from this software without specific prior written permission.
20;
21; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
25; COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
26; INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
27; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
28; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29; HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
30; STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
32; OF THE POSSIBILITY OF SUCH DAMAGE.
33;
34; Please report bugs, suggestions and ideas to the Chicken Trac
35; ticket tracking system (assign tickets to user 'sjamaan'):
36; http://trac.callcc.org
37
38(module spiffy
39  (start-server with-headers send-status send-static-file
40   current-request current-response current-file current-pathinfo
41   root-path server-port index-files mime-type-map default-mime-type default-host
42   handle-directory handle-not-found
43   restart-request)
44
45(import chicken scheme extras ports files data-structures)
46(require-extension srfi-1 srfi-18 posix tcp
47                   intarweb uri-generic sendfile matchable)
48
49(define version 4)
50(define release 0)
51
52;;; Request processing information
53(define current-request  (make-parameter #f))
54(define current-response (make-parameter #f))
55(define current-file     (make-parameter #f))
56(define current-pathinfo (make-parameter #f))
57
58;;; Configuration
59(define root-path        (make-parameter "./web"))
60(define server-port      (make-parameter 8080))
61(define index-files      (make-parameter '("index.html" "index.htm")))
62(define mime-type-map
63  (make-parameter
64   '(("txt" . text/plain)
65     ("xml" . text/xml)
66     ("xul" . application/vnd.mozilla.xul+xml)
67     ("htm" . text/html)
68     ("html" . text/html)
69     ("js"  . text/javascript)
70     ("pdf" . application/pdf)
71     ("css" . text/css)
72     ("bmp" . image/bmp)
73     ("ico" . image/x-icon)
74     ("gif" . image/gif)
75     ("jpg" . image/jpeg)
76     ("jpeg" . image/jpeg)
77     ("png" . image/png))))
78(define default-mime-type (make-parameter 'application/octet-stream))
79(define default-host (make-parameter "localhost")) ;; XXX Can we do without?
80
81;;; Custom handlers
82(define handle-directory
83  (make-parameter
84   (lambda (path)
85     (send-status 403 "Forbidden"))))
86(define handle-file
87  (make-parameter
88   (lambda (path)
89     (with-headers `((content-type ,(extension->mime-type
90                                     (pathname-extension path))))
91       (lambda ()
92         (send-static-file path))))))
93(define handle-not-found
94  (make-parameter
95   (lambda ()
96     (send-status 404 "Not found"
97                  "The resource you requested could not be found"))))
98
99
100;;; Internal parameters
101(define request-restarter (make-parameter #f))
102
103(define (send-status code reason #!optional text)
104  (parameterize ((current-response (update-response (current-response)
105                                                    code: code
106                                                    reason: reason)))
107    (write-response (current-response))
108    (with-output-to-port (response-port (current-response))
109      (lambda ()
110        (print "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>")
111        (print "<!DOCTYPE html")
112        (print "  PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"")
113        (print "         \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">")
114        (print "<html xmlns=\"http://www.w3.org/1999/xhtml\" ")
115        (print "      xml:lang=\"en\" lang=\"en\">")
116        (print "  <head>")
117        (printf "    <title>~A - ~A</title>\n" code reason)
118        (print "  </head>")
119        (print "  <body>")
120        (printf "    <h1>~A - ~A</h1>\n" code reason)
121        (if text (printf "    <p>~A</p>" text))
122        (print "  </body>")
123        (print "</html>")))))
124
125(define (send-static-file filename)
126  (with-headers `((content-length ,(file-size filename)))
127    (lambda ()
128      (write-response (current-response))
129      (let ([fd (file-open filename (+ open/binary open/rdonly))])
130              (handle-exceptions exn (begin
131                                       (file-close fd)
132                                       (signal exn))
133                (sendfile fd (response-port (current-response))))
134              (file-close fd)))))
135
136(define (extension->mime-type ext)
137  (alist-ref (or ext "") (mime-type-map) string-ci=? (default-mime-type)))
138
139(define (with-headers new-headers thunk)
140  (parameterize ((current-response
141                  (update-response
142                   (current-response)
143                   headers: (headers new-headers
144                                     (response-headers (current-response))))))
145    (thunk)))
146
147(define (process-directory path)
148  (let ((index-page (find (lambda (ip)
149                            (file-exists?
150                             (make-pathname (list (root-path) path) ip)))
151                          (index-files))))
152    (if index-page
153        (process-entry (make-pathname path index-page) '())
154        ((handle-directory) path))))
155
156;; If an URL is missing a trailing slash, instead of directly serving
157;; its index-file, redirect to the URL _with_ trailing slash.  This
158;; prevents problems with relative references since the directory
159;; would be seen as the file component in the path and get replaced.
160(define (redirect-directory-root path)
161  (let* ((newloc (make-pathname path "/"))
162         (url (uri-relative-to (uri-reference newloc)
163                               (request-uri (current-request)))))
164    (with-headers `((location ,url))
165      (lambda () (send-status 301 "Moved permanently")))))
166
167(define (process-entry current-path remaining-path)
168  (let ((path (make-pathname (root-path) current-path)))
169    (cond
170     ;; TODO Check if there's a registered URI-handler first
171     ((directory? path)
172      (match remaining-path
173       (()    (redirect-directory-root current-path))
174       (("/") (process-directory current-path))
175       (else  (process-entry (make-pathname current-path (car remaining-path))
176                             (cdr remaining-path)))))
177     ((file-exists? path)
178      ((handle-file) path))
179     (else ((handle-not-found))))))
180
181;; Determine the vhost and port to use. This follows RFC 2616, section 5.2:
182;; If request URL is absolute, use that.  Otherwise, look at the Host header.
183;; In HTTP >= 1.1, a Host line is required, as per section 14.23 of
184;; RFC 2616.  If no host line is present, it returns the default host
185;; for HTTP/1.0.
186(define (determine-vhost/port)
187  (let* ((request-uri (request-uri (current-request)))
188         (request-host (uri-host request-uri))
189         (host-header (header-value 'host (request-headers (current-request)))))
190    (if request-host
191        (values request-host (or (uri-port request-uri) 80))
192        (if host-header
193            (values (car host-header) (cdr host-header))
194            (if (and (= (request-major (current-request)) 1)
195                     (>= (request-minor (current-request)) 1))
196                (values #f #f)
197                (values (default-host) 80))))))
198
199(define (normalize-current-request-uri)
200  (receive (host port) (determine-vhost/port)
201    (if host
202        (update-request (current-request)
203                        uri: (uri-relative-to
204                              (request-uri (current-request))
205                              ;; XXX
206                              (absolute-uri (conc "http://" host ":" port))))
207        (current-request))))
208
209(define (restart-request req)
210  ((request-restarter) req (request-restarter)))
211
212(define (handle-incoming-request in out)
213  (parameterize ((current-request (read-request in))
214                 (current-response
215                  (make-response port: out
216                                 headers: (headers
217                                           `((content-type text/html))))))
218    (let ((path (uri-path (request-uri (current-request)))))
219      (receive (req cont)
220        (call/cc (lambda (c) (values (normalize-current-request-uri) c)))
221        (parameterize ((current-request req)
222                       (request-restarter cont))
223          (if (and (uri-host (request-uri (current-request))) (pair? path))
224              (process-entry "" path)
225              ;; No host in the request? That's an error.
226              (send-status 400 "Bad request"
227                           "Your client sent a request that the server did not understand"))))
228      ;; For now, just close the ports and allow the thread to exit
229      (close-output-port out)
230      (close-input-port in))))
231
232(define (start-server #!key (port (server-port)))
233  (letrec ((listener (tcp-listen port))
234           (accept-loop (lambda ()
235                          (receive (in out)
236                            (tcp-accept listener)
237                            (thread-start!
238                             (make-thread (lambda ()
239                                            (handle-incoming-request in out))))
240                            (accept-loop)))))
241    (accept-loop)))
242
243)
Note: See TracBrowser for help on using the repository browser.