| 1 |
#!/usr/bin/env ikarus --r6rs-script |
| 2 |
|
| 3 |
(import (ikarus)) |
| 4 |
|
| 5 |
(define (get-headers ip escape) |
| 6 |
(let f ([ls '()]) |
| 7 |
(let ([key (get-line ip)]) |
| 8 |
(cond |
| 9 |
[(eof-object? key) (escape)] |
| 10 |
[(string=? key "end") ls] |
| 11 |
[else |
| 12 |
(let ([val (get-line ip)]) |
| 13 |
(when (eof-object? val) (escape)) |
| 14 |
(f (cons (cons key val) ls)))])))) |
| 15 |
|
| 16 |
(define (put-headers ls op) |
| 17 |
(for-each |
| 18 |
(lambda (p) |
| 19 |
(display (car p) op) |
| 20 |
(newline op) |
| 21 |
(display (cdr p) op) |
| 22 |
(newline op)) |
| 23 |
ls) |
| 24 |
(display "end\n" op)) |
| 25 |
|
| 26 |
(define (alist->string ls) |
| 27 |
(let-values ([(p e) (open-string-output-port)]) |
| 28 |
(for-each |
| 29 |
(lambda (x) |
| 30 |
(fprintf p "~s => ~s\n" (car x) (cdr x))) |
| 31 |
ls) |
| 32 |
(e))) |
| 33 |
|
| 34 |
(define (serve-client ip op) |
| 35 |
(call/cc |
| 36 |
(lambda (k) |
| 37 |
(with-exception-handler |
| 38 |
(lambda (con) |
| 39 |
(cond |
| 40 |
[(interrupted-condition? con) |
| 41 |
(raise-continuable con)] |
| 42 |
[else |
| 43 |
(print-condition con (current-error-port)) |
| 44 |
(k)])) |
| 45 |
(lambda () |
| 46 |
(let loop () |
| 47 |
(let* ([headers (get-headers ip k)] |
| 48 |
[response (alist->string headers)]) |
| 49 |
(put-headers |
| 50 |
`(("Content-type" . "text/plain") |
| 51 |
("Keep-Socket" . "1") |
| 52 |
("Content-length" . ,(string-length response))) |
| 53 |
op) |
| 54 |
(display response op) |
| 55 |
(flush-output-port op)) |
| 56 |
(loop))))))) |
| 57 |
|
| 58 |
(define cgi-server |
| 59 |
(case-lambda |
| 60 |
[(who port) |
| 61 |
(let ([s (tcp-server-socket-nonblocking |
| 62 |
(or (string->number port) |
| 63 |
(error who "invalid port number" port)))]) |
| 64 |
(printf "Listening on port ~a\n" port) |
| 65 |
(call/cc |
| 66 |
(lambda (k) |
| 67 |
(with-exception-handler |
| 68 |
(lambda (con) |
| 69 |
(print-condition con) |
| 70 |
(k)) |
| 71 |
(lambda () |
| 72 |
(let f () |
| 73 |
(let-values ([(op ip) |
| 74 |
(accept-connection-nonblocking s)]) |
| 75 |
(printf "got a connection\n") |
| 76 |
(let ([op (transcoded-port op (native-transcoder))] |
| 77 |
[ip (transcoded-port ip (native-transcoder))]) |
| 78 |
(register-callback op |
| 79 |
(lambda () (serve-client ip op))))) |
| 80 |
(f)))))) |
| 81 |
(printf "\nClosing server ...\n") |
| 82 |
(close-tcp-server-socket s))] |
| 83 |
[(who) |
| 84 |
(error who "missing port number")] |
| 85 |
[(who . args) |
| 86 |
(error who "too many arguments")])) |
| 87 |
|
| 88 |
(apply cgi-server (command-line)) |