Debian Codegraph @

lab/cgi.ss

raw
1
2 #| http://tools.ietf.org/html/rfc3986
3
4 query = *( pchar / "/" / "?" )
5 pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
6
7 pct-encoded = "%" HEXDIG HEXDIG
8
9 unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
10 sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
11 / "*" / "+" / "," / ";" / "="
12 |#
13
14
15
16 (module cgi (params param)
17 (define (parse-query-string str)
18 ; parse string as (key=value) separated by &s:
19 (define (hex->integer c err)
20 (let ([n (char->integer c)])
21 (cond
22 [(fx<= (char->integer #\0) n (char->integer #\9))
23 (fx- n (char->integer #\0))]
24 [(fx<= (char->integer #\A) n (char->integer #\F))
25 (fx+ 10 (fx- n (char->integer #\A)))]
26 [(fx<= (char->integer #\a) n (char->integer #\f))
27 (fx+ 10 (fx- n (char->integer #\a)))]
28 [else (err)])))
29 (define (f str i n ac key err)
30 (cond
31 [(fx= i n)
32 (if key
33 (list (cons key (list->string (reverse ac))))
34 (if (null? ac)
35 '()
36 (err)))]
37 [else
38 (let ([c (string-ref str i)])
39 (cond
40 [(char=? c #\&)
41 (if key
42 (cons (cons key (list->string (reverse ac)))
43 (f str (fxadd1 i) n '() #f err))
44 (if (null? ac)
45 (f str (fxadd1 i) n '() #f err)
46 (err)))]
47 [(char=? c #\=)
48 (if key
49 (f str (fxadd1 i) n (cons c ac) key err)
50 (f str (fxadd1 i) n '() (list->string (reverse ac)) err))]
51 [(char=? c #\%)
52 (if (fx< (fx+ i 2) n)
53 (f str (fx+ i 3)
54 (cons (integer->char
55 (let ([n0 (hex->integer
56 (string-ref str (fx+ i 1))
57 err)]
58 [n1 (hex->integer
59 (string-ref str (fx+ i 2))
60 err)])
61 (fxlogor (fxsll n0 8) n1)))
62 ac)
63 n key err)
64 (err))]
65 [(char=? c #\+)
66 (f str (fxadd1 i) n (cons #\space ac) key err)]
67 [(or (char<=? #\a c #\z)
68 (char<=? #\A c #\Z)
69 (char<=? #\0 c #\9)
70 (memq c '(#\- #\. #\_ #\~ #\! #\$ #\& #\'
71 #\( #\) #\* #\, #\; #\= #\: #\@)))
72 (f str (fx+ i 1) n (cons c ac) key err)]
73 [else (err)]))]))
74 (f str 0 (string-length str) '() #f
75 (lambda ()
76 (error 'parse-query-string "invalid query string ~s" str))))
77 (define (params)
78 (map car cgi-env))
79 (define (param x)
80 (cond
81 [(assoc x cgi-env) => cdr]
82 [else #f]))
83 (define cgi-env
84 (parse-query-string (env "QUERY_STRING")))
85 #|cgi-module|#)
86