File: web-server.scm

package info (click to toggle)
gambc 4.8.8-3.1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 79,972 kB
  • sloc: ansic: 997,617; lisp: 221,772; perl: 19,020; sh: 6,173; makefile: 5,934; objc: 3,757; cpp: 2,143; sed: 498; java: 305; awk: 177
file content (383 lines) | stat: -rw-r--r-- 12,017 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/env gsi-script

; File: "web-server.scm", Time-stamp: <2008-12-17 13:41:03 feeley>

; Copyright (c) 2004-2008 by Marc Feeley, All Rights Reserved.

; A minimal web server which implements a web-site with a few
; interesting examples.

;==============================================================================

(##include "~~lib/gambit#.scm") ;; import Gambit procedures and variables
(##include "http#.scm")         ;; import HTTP procedures and variables
(##include "html#.scm")         ;; import HTML procedures and variables
(##include "base64#.scm")       ;; import BASE64 procedures and variables

(declare (block)) ;; required for serializing continuations
                  ;; (for the web-continuation example)

;==============================================================================

(define main
  (lambda (arg)
    (let ((port-number
           (string->number arg)))
      (http-server-start!
       (make-http-server
        port-number: port-number
        threaded?: #t
        GET: GET/POST
        POST: GET/POST)))))

(define page-generators (make-table test: string=?))

(define show-exceptions
  (lambda (thunk)
    (with-exception-catcher
     (lambda (exc)
       (reply-html
        (<html>
         (<head> (<title> "Scheme exception"))
         (<body>
          (<p> "The following Scheme exception occurred while processing the request:")
          (<pre>
           (call-with-output-string
            ""
            (lambda (port) (##display-exception exc port))))))))
     thunk)))

(define GET/POST
  (lambda ()
    (show-exceptions
     (lambda ()
       (let* ((request (current-request))
              (uri (request-uri request))
              (path (uri-path uri))
              (generator (table-ref page-generators path unknown-page)))
         (generator))))))

(define unknown-page
  (lambda ()
    (let* ((request (current-request))
           (uri (request-uri request))
           (path (uri-path uri)))
      (get-filesys-path path))))

(define get-filesys-path
  (lambda (path)
    (let ((type (file-type path)))
      (case type

        ((directory)
         (reply-html
          (<html>
           (<head> (<title> "Files in directory " path))
           (<body>

            (<h1> "Files in " path)

            (<ol>
             (map (lambda (fn)
                    (<li>
                     (<a> href: (object->string (path-expand fn path)) fn)
                     " ("
                     (object->string
                      (with-exception-catcher
                       (lambda (exc) 'other)
                       (lambda () (file-type (path-expand fn path)))))
                     ")"))
                  (directory-files
                   (list path: path ignore-hidden: #f))))))))

        ((regular)
         (let* ((port (open-input-file path))
                (file (read-line port #f)))
           (close-input-port port)
           (let ((ext (path-extension path)))
             (if (or (string-ci=? ext ".htm")
                     (string-ci=? ext ".html"))
                 (reply (lambda () (display file)))
                 (reply-html
                  (<html>
                   (<head> (<title> "File " path))
                   (<body> (<pre> file))))))))

        (else
         (reply-html
          (<html>
           (<head> (<title> "Error"))
           (<body>
            "Only directories and regular files can be displayed"))))))))

;==============================================================================

; Main web page.

(define page-main
  (lambda ()
    (reply-html
     (<html>
      (<head> (<title> "Main page"))
      (<body>
       (<center> (<b> "Welcome to the " (<i> "web-server") " example"))
       (<p> "Please choose one of these examples:")
       (<ul>
        (<li> (<a> href: (object->string (current-directory))
                   "Browse the web server's filesystem"))
        (<li> (<a> href: "/web-continuation"
                   "Web-continuation based calculator"))
        (<li> (<a> href: "/terminate-server"
                   "Terminate server"))))))))

(table-set! page-generators "/"           page-main)
(table-set! page-generators "/index.html" page-main)
(table-set! page-generators "/index.htm"  page-main)

;==============================================================================

; Web pages for web-continuation example.

(define page-web-continuation
  (lambda ()
    (obtain-store-cont-on-server title-embed)))

(table-set! page-generators "/web-continuation" page-web-continuation)

(define page-calculator
  (lambda ()

    ; check if we are resuming a continuation or starting the example

    (let* ((request (current-request))
           (query (request-query request)))

      (cond ((and query (assoc "cont" query))
             =>
             (lambda (x)
               ; we're resuming a continuation
               (resume-continuation (cdr x) query)))

            ((and query (assoc "submit" query))
             =>
             (lambda (x)
               ; we're starting the calculator
               (let* ((x (assoc "store_cont_on_server" query))
                      (on-server? (and x (string=? (cdr x) "yes"))))
                 (parameterize ((store-cont-on-server? on-server?))
                   (calculator-start)))))

            (else
             (reply-html
              (<html>
               (<head> (<title> "Error"))
               (<body>
                (<h1> "Something's wrong with the request...")))))))))

(table-set! page-generators "/calculator" page-calculator)

; BUG: parameters lose their identity when serialized/deserialized so
; we can't store this information in a parameter.
(define store-cont-on-server? (make-parameter #f))

(define calculator-start
  (lambda ()
    (let ((new-number
           (show-sum-and-obtain-number
            '()
            first-number-embed)))
      (calculator-loop (list new-number)))))

(define calculator-loop
  (lambda (numbers-previously-entered)
    (let ((new-number
           (show-sum-and-obtain-number
            numbers-previously-entered
            plain-embed)))
      (calculator-loop (append numbers-previously-entered
                               (list new-number))))))

(define show-sum-and-obtain-number
  (lambda (numbers-previously-entered embed)
    (let ((sum (apply + numbers-previously-entered)))
      (obtain-number
       (lambda (stuff)
         (embed
          (<table>
           (if (null? numbers-previously-entered)
               '()
               (list
                (map (lambda (x)
                       (<tr> (<td>)
                             (<td> align: 'right x)))
                     numbers-previously-entered)
                (<tr> (<td>)
                      (<td> align: 'right "---------------------"))
                (<tr> (<td> "TOTAL:")
                      (<td> align: 'right bgcolor: "yellow" sum))))
           (<tr> (<td>)
                 (<td> stuff)))))))))

(define title-embed
  (lambda (stuff)
    (<html>
     (<head> (<title> "Web-continuation example"))
     (<body>
      (<h1> "Web-continuation example")
      (<p> "This page implements a simple calculator that adds the "
           "numbers that are entered by the user.")
      (<p> "You can use the " (<strong> "back") " button to undo the "
           "additions.  You can also clone the window and copy "
           "the URL to a different browser to start an independent "
            " branch of calculation.")
      (<p> "The web-server can be run interpreted or compiled.  It is "
           "much more efficient to use a compiled web-server because "
           "the continuations in the HTML file sent back to the browser "
           "will be much more compact.")
      (<p> "Please indicate if you want the continuation to be stored "
           "on the web browser or on the web server.  It is more "
           "efficient to store the continuation on the server but it "
           "introduces the problem of web-continuation garbage-collection "
           "(each continuation will be saved as a file on the server's file "
           "system; the issue is: when can these files be deleted?)")
      stuff))))

(define first-number-embed
  (lambda (stuff)
    (<html>
     (<head> (<title> "Web-continuation example"))
     (<body>
      (<h1> "Web-continuation example")
      (<p> "Enter the first number here: " stuff)))))

(define plain-embed
  (lambda (stuff)
    (<html>
     (<head> (<title> "Web-continuation example"))
     (<body>
      (<h1> "Web-continuation example")
      stuff))))

(define form-method "GET") ; can be "GET" or "POST"

(define obtain-number
  (lambda (embed)
    (let ((number-str
           (obtain
            "number"
            (lambda (cont)
              (embed
               (<form>
                action: "/calculator"
                method: form-method
                (<input> type: 'hidden
                         name: "cont"
                         value: cont)
                (<input> type: 'text name: "number")
                (<input> type: 'submit
                         name: "submit"
                         value: "ADD")))))))
      (or (string->number number-str)
          (obtain-number embed)))))

(define obtain-store-cont-on-server
  (lambda (embed)
    (obtain
     "store_cont_on_server"
     (lambda (cont) ; continuation is ignored
       (embed
        (<form>
         action: "/calculator"
         method: form-method
         (<input> type: 'checkbox
                  name: "store_cont_on_server"
                  value: "yes"
                  "Store continuation on server")
         (<input> type: 'submit
                  name: "submit"
                  value: "\"START CALCULATOR\"")))))))

(define obtain
  (lambda (name embed)
    (let ((query
           (capture-continuation
            (lambda (cont)
              (reply-html (embed cont))
              (thread-terminate! (current-thread))))))
      (cdr (assoc name query)))))

(define capture-continuation
  (lambda (receiver)
    (call/cc
     (lambda (k)
       (let* ((k-str
               (u8vector->base64-string (object->u8vector k)))
              (cont
               (if (store-cont-on-server?)
                   (let loop () ; find a unique filename
                     (let* ((rn (random-integer (expt 2 64)))
                            (fn (string-append "_cont"
                                               (number->string rn 16))))
                       (if (file-exists? fn)
                           (loop)
                           (begin
                             (with-output-to-file fn
                               (lambda ()
                                 (display k-str)))
                             fn))))
                   k-str)))
         (receiver cont))))))

(define resume-continuation
  (lambda (cont val)
    (let* ((k-str
            (if (and (> (string-length cont) 0)
                     (char=? (string-ref cont 0) #\_))
                (with-input-from-file cont read-line)
                cont))
           (k
            (u8vector->object (base64-string->u8vector k-str))))
      (k val))))

;==============================================================================

; Web-IDE page.

(define page-web-ide
  (lambda ()
    (reply-html
     (<html>
      (<head>
       (<title> "Web-IDE page")
       (<style> web-ide-style)
       (<script> web-ide-script))
      (<body>
       (<p> "This example is not complete"))))))

(table-set! page-generators "/web-ide" page-web-ide)

(define web-ide-style #<<EOF

web ide style

EOF
)

(define web-ide-script #<<EOF

web ide script

EOF
)

;==============================================================================

; Web-server termination.

(define page-terminate-server
  (lambda ()
    (exit)))

(table-set! page-generators "/terminate-server" page-terminate-server)

;==============================================================================