WebGate

Check-in [a62acea00c]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:@-expression support, distribution of code over several files
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: a62acea00c080c457ae3412e597653d162202ca2
User & Date: murphy 2011-10-07 19:41:07.757
Context
2011-10-08
10:01
better handling of normal datums in @-expressions check-in: aaa324e257 user: murphy tags: trunk
2011-10-07
19:41
@-expression support, distribution of code over several files check-in: a62acea00c user: murphy tags: trunk
2011-10-03
01:20
made static compilation optional check-in: f9257c7811 user: murphy tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
Changes to example.scm.
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
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.


(require-library
 webgate)




(import
 webgate (only webgate-utils uri-encode))

(define common-head
  '(head
    (meta ((charset "utf-8")))
    (title "WebGate")
    (meta ((name "description") (content "CHICKEN WebGate example")))
    (meta ((name "author") (content "Thomas Chust")))
    (link ((rel "stylesheet") (href "http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css")))
    (style ((type "text/css")) "body{padding-top:60px}")))


(define-resource (root parameters)
  (make-html-response
   200
   `(html
     ,common-head
     (body
      (div
       ((class "topbar"))
       (div
	((class "fill"))
	(div
	 ((class "container"))
	 (a ((class "brand") (href "#")) "WebGate")
	 (ul
	  ((class "nav"))
	  (li ((class "active")) (a ((href "#")) "Miscellaneous"))
	  (li (a ((href ,(resource-uri calc "add"))) "Suspensions"))))))
      (div




       ((class "container"))
       (div
	((class "hero-unit"))
	(h1 "Application Example")

	(p "This sample program just shows some information extracted from the incoming request."))
       (div



	((class "row"))
	(div
	 ((class "span8"))
	 (h2 "Present Context")
	 (table
	  ((class "zebra-striped"))
	  (thead (tr (th "Key") (th "Value")))


	  (tbody
	   ,@(let ((getenv (resource-context-getenv
			    (current-resource-context))))
	       `((tr (td "SCRIPT_NAME")
		     (td (code ,(or (getenv "SCRIPT_NAME") "<unknown>"))))
		 (tr (td "PATH_INFO")
		     (td (code ,(or (getenv "PATH_INFO") "<unknown>"))))
		 (tr (td "REQUEST_METHOD")
		     (td (code ,(or (getenv "REQUEST_METHOD") "<unknown>")))))))))
	(div



	 ((class "span8"))
	 (h2 "Present Parameters")
	 (table
	  ((class "zebra-striped"))

	  (thead (tr (th "Key") (th "Messages")))

	  (tbody
	   ,@(map
	      (lambda (key+msgs)
		(let-values (((key msgs) (car+cdr key+msgs)))
		  `(tr
		    (td ,key)
		    (td
		     (ol
		      ,@(map
			 (lambda (msg)
			   `(li
			     (p
			      ,(let ((type (message-type msg)))
				 (cond
				  ((string-prefix? "text/plain" type)
				   `(span
				     (span
				      ((class "label notice"))
				      "Text Content:")
				     " "
				     ,(message-body msg)))
				  ((string-prefix? "image/" type)
				   `(span
				     (span
				      ((class "label notice"))
				      "Image Content:")
				     " "
				     (img
				      ((src ,(string-append
					      "data:" type ","
					      (uri-encode
					       (message-body msg))))))))
				  (else
				   `(span
				     (span
				      ((class "label notice"))
				      "Omitted Content:")
				     " "
				     (code ,type)))))
			      ,@(map
				 (lambda (header)
				   (let-values (((key value) (car+cdr header)))
				     `(span
				       ", "
				       (span ((class "label")) ,key ":")
				       " "
				       (code ,value))))
				 (message-headers msg)))))
			 msgs))))))
	      (hash-table->alist parameters))))))
       (div




	((class "row"))
	(div
	 ((class "span8"))
	 (h2 "GET with Parameters")
	 (form
	  ((method "GET") (action ,(resource-uri root)))
	  (fieldset
	   (legend "Stuff")
	   (div
	    ((class "clearfix"))
	    (label ((for "some-thing")) "Some value")
	    (div
	     ((class "input"))
	     (input ((type "text") (id "some-thing") (class "medium")
		     (name "some-thing") (size "30")))))
	   (div


	    ((class "clearfix"))
	    (label ((for "other-things")) "Other values")
	    (div
	     ((class "input"))
	     (select
	      ((id "other-things") (class "medium")
	       (name "other-things") (multiple "multiple"))
	      (option "foobaz")
	      (option "dosh")
	      (option "gostak"))))
	   (div



	    ((class "actions"))







	    (input ((type "submit") (class "btn primary") (value "Submit")))
	    nbsp
	    (input ((type "reset") (class "btn") (value "Reset")))))))
	(div


	 ((class "span8"))
	 (h2 "POST with Parameters")
	 (form
	  ((method "POST") (enctype "multipart/form-data")
	   (action ,(resource-uri root)))
	  (fieldset
	   (legend "Upload")
	   (div
	    ((class "clearfix"))
	    (label ((for "some-thing")) "Some value")
	    (div
	     ((class "input"))
	     (input ((type "text") (id "some-thing") (class "medium")
		     (name "some-thing") (size "30")))))
	   (div


	    ((class "clearfix"))
	    (label ((for "file-thing")) "Some file")
	    (div
	     ((class "input"))
	     (input ((type "file") (id "file-thing") (class "medium")
		     (name "file-thing")))))
	   (div


	    ((class "actions"))
	    (input ((type "submit") (class "btn primary") (value "Submit")))

	    nbsp
	    (input ((type "reset") (class "btn") (value "Reset"))))))))






       (footer copy "2011 by Thomas Chust"))))))




(define (numeric-parameter parameters key)
  (cond
   ((hash-table-ref/default parameters key #f)
    => (lambda (msgs)
	 (and (not (null? msgs))
	      (string->number (message-body (car msgs))))))
   (else
    #f)))

(define-resource (calc "calc" op parameters)
  (if (string=? op "add")
      (let* ((common-topbar
	      `(div
		((class "topbar"))
		(div
		 ((class "fill"))
		 (div
		  ((class "container"))
		  (a ((class "brand") (href "#")) "WebGate")
		  (ul
		   ((class "nav"))
		   (li (a ((href ,(resource-uri root))) "Miscellaneous"))
		   (li ((class "active")) (a ((href "#")) "Suspensions")))))))




	     (parameters
	      (send/suspend
	       (lambda (resume-uri)
		 (make-html-response
		  200
		  `(html
		    ,common-head
		    (body
		     ,common-topbar
		     (div
		      ((class "container"))
		      (form
		       ((method "GET") (action ,resume-uri))
		       (fieldset
			(legend "Add Numbers")
			(div
			 ((class "clearfix"))
			 (label ((for "a")) "First Summand")
			 (div
			  ((class "input"))
			  (input ((type "text") (id "a") (class "medium")
				  (name "a") (size "30")))))
			(div


			 ((class "clearfix"))
			 (label ((for "a")) "Second Summand")
			 (div
			  ((class "input"))
			  (input ((type "text") (id "b") (class "medium")
				  (name "b") (size "30")))))
			(div


			 ((class "actions"))
			 (input ((type "submit") (class "btn primary")
				 (value "Submit")))
			 nbsp
			 (input ((type "reset") (class "btn")
				 (value "Reset")))))))))))))






	     (a
	      (or (numeric-parameter parameters "a") 0))
	     (b
	      (or (numeric-parameter parameters "b") 0)))
	(make-html-response
	 200
	 `(html
	   ,common-head
	   (body
	    ,common-topbar
	    (div
	     ((class "container"))
	     (div
	      ((class "hero-unit"))
	      (h1 ,(number->string (+ a b)))
	      (p hellip "is the answer")))))))




      (make-error-response
       400 "Don't know how to perform the requested calculation.")))

(webgate-main)







>
|
|
>
>
>





|
|
|
|
|
|
|
>




|
|
|
<
|
<
|
<
|
|
<
|
|
|
<
>
>
>
>
|
<
|
|
>
|
<
>
>
>
|
<
|
|
<
|
|
>
>
|
|
|
|
|
|
|
|
|
<
>
>
>
|
|
<
|
>
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
>
>
>
|
<
|
|
<
|
|
|
<
|
|
<
|
|
|
<
>
>
|
|
<
|
<
|
|
|
|
|
<
>
>
>
|
>
>
>
>
>
>
>
<
<
<
<
>
>
|
|
<
|
|
|
|
<
|
|
<
|
|
|
<
>
>
|
|
<
|
|
|
<
>
>
|
|
>
|
|
>
>
>
>
>
>
|
>
>
>













<
|
<
|
<
|
|
<
|
|
|
>
>
>
>





|
|
|
|
<
|
<
|
|
|
<
|
|
<
|
|
|
<
>
>
|
|
<
|
|
|
<
>
>
|
|
|
|
|
|
>
>
>
>
>
>






|
|
|
|
<
|
<
|
|
|
>
>
>
>




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
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

(eval-when (compile eval load)
  (require-library webgate))

(eval-when (compile eval)
  (import (only webgate-utils use-at-read-table))
  (use-at-read-table #:list-arguments? #t))

(import
 webgate (only webgate-utils uri-encode))

(define common-head
  '@head{
     @meta[(charset "utf-8")]
     @title{WebGate}
     @meta[(name "description") (content "CHICKEN WebGate example")]
     @meta[(name "author") (content "Thomas Chust")]
     @link[(rel "stylesheet") (href "http://twitter.github.com/bootstrap/1.3.0/bootstrap.min.css")]
     @style[(type "text/css")]{body{padding-top:60px}}
   })

(define-resource (root parameters)
  (make-html-response
   200
   `@html{
      @,common-head
      @body{

        @div[(class "topbar")]{

          @div[(class "fill")]{

	    @div[(class "container")]{
	      @a[(class "brand") (href "#")]{WebGate}

	      @ul[(class "nav")]{
	        @li[(class "active")]{@a[(href "#")]{Miscellaneous}}
	        @li{@a[(href ,(resource-uri calc "add"))]{Suspensions}}

	      }
	    }
	  }
        }
        @div[(class "container")]{

          @div[(class "hero-unit")]{
	    @h1{Application Example}
	    @p{
	      This sample program just shows some information

              extracted from the incoming request.
	    }
	  }
	  @div[(class "row")]{

	    @div[(class "span8")]{
	      @h2{Present Context}

	      @table[(class "zebra-striped")]{
	        @thead{
		  @tr{@th{Key} @th{Value}}
		}
		@tbody{
		  @,@(let ((getenv (resource-context-getenv
				    (current-resource-context))))
		       `((tr (td "SCRIPT_NAME")
			     (td (code ,(or (getenv "SCRIPT_NAME") "<unknown>"))))
			 (tr (td "PATH_INFO")
			     (td (code ,(or (getenv "PATH_INFO") "<unknown>"))))
			 (tr (td "REQUEST_METHOD")
			     (td (code ,(or (getenv "REQUEST_METHOD") "<unknown>"))))))

		}
	      }
	    }
	    @div[(class "span8")]{
	      @h2{Present Parameters}

	      @table[(class "zebra-striped")]{
	        @thead{
		  @tr{@th{Key} @th{Messages}}
		}
		@tbody{
		  @,@(map
		      (lambda (key+msgs)
			(let-values (((key msgs) (car+cdr key+msgs)))
			  `(tr
			    (td ,key)
			    (td
			     (ol
			      ,@(map
				 (lambda (msg)
				   `(li
				     (p
				      ,(let ((type (message-type msg)))
					 (cond
					  ((string-prefix? "text/plain" type)
					   `(span
					     (span
					      ((class "label notice"))
					      "Text Content:")
					     " "
					     ,(message-body msg)))
					  ((string-prefix? "image/" type)
					   `(span
					     (span
					      ((class "label notice"))
					      "Image Content:")
					     " "
					     (img
					      ((src ,(string-append
						      "data:" type ","
						      (uri-encode
						       (message-body msg))))))))
					  (else
					   `(span
					     (span
					      ((class "label notice"))
					      "Omitted Content:")
					     " "
					     (code ,type)))))
				      ,@(map
					 (lambda (header)
					   (let-values (((key value) (car+cdr header)))
					     `(span
					       ", "
					       (span ((class "label")) ,key ":")
					       " "
					       (code ,value))))
					 (message-headers msg)))))
				 msgs))))))
		      (hash-table->alist parameters))

		}
	      }
	    }
	  }
	  @div[(class "row")]{

	    @div[(class "span8")]{
	      @h2{GET with Parameters}

	      @form[(method "GET") (action ,(resource-uri root))]{
	        @fieldset{
		  @legend{Stuff}

		  @div[(class "clearfix")]{
		    @label[(for "some-thing0")]{Some value}

		    @div[(class "input")]{
		      @input[(type "text") (id "some-thing0") (class "medium")
			     (name "some-thing") (size "30")]

		    }
		  }
		  @div[(class "clearfix")]{
		    @label[(for "other-things0")]{Other values}

		    @div[(class "input")]{

		      @select[(id "other-things0") (class "medium")
			      (name "other-things") (multiple "multiple")]{
		        @option{foobaz}
			@option{dosh}
			@option{gostak}

		      }
		    }
		  }
		  @div[(class "actions")]{
		    @input[(type "submit") (class "btn primary")
			   (value "Submit")]
		    @nbsp
		    @input[(type "reset") (class "btn")
			   (value "Reset")]
		  }
		}




	      }
	    }
	    @div[(class "span8")]{
	      @h2{POST with Parameters}

	      @form[(method "POST") (enctype "multipart/form-data")
		    (action ,(resource-uri root))]{
	        @fieldset{
		  @legend{Upload}

		  @div[(class "clearfix")]{
		    @label[(for "some-thing1")]{Some value}

		    @div[(class "input")]{
		      @input[(type "text") (id "some-thing1") (class "medium")
			     (name "some-thing") (size "30")]

		    }
		  }
		  @div[(class "clearfix")]{
		    @label[(for "file-thing1")]{Some file}

		    @div[(class "input")]{
		      @input[(type "file") (id "file-thing1") (class "medium")
			     (name "file-thing")]

		    }
		  }
		  @div[(class "actions")]{
		    @input[(type "submit") (class "btn primary")
			   (value "Submit")]
		    @nbsp
		    @input[(type "reset") (class "btn")
			   (value "Reset")]
		  }
		}
	      }
	    }
	  }
	  @footer{@copy 2011 by Thomas Chust}
	}
      }
    }))

(define (numeric-parameter parameters key)
  (cond
   ((hash-table-ref/default parameters key #f)
    => (lambda (msgs)
	 (and (not (null? msgs))
	      (string->number (message-body (car msgs))))))
   (else
    #f)))

(define-resource (calc "calc" op parameters)
  (if (string=? op "add")
      (let* ((common-topbar

	      `@div[(class "topbar")]{

		 @div[(class "fill")]{

		   @div[(class "container")]{
		     @a[(class "brand") (href "#")]{WebGate}

		     @ul[(class "nav")]{
		       @li{@a[(href ,(resource-uri root))]{Miscellaneous}}
		       @li[(class "active")]{@a[(href "#")]{Suspensions}}
		     }
		   }
		 }
	       })
	     (parameters
	      (send/suspend
	       (lambda (resume-uri)
		 (make-html-response
		  200
		  `@html{
		     @,common-head
		     @body{
		       @,common-topbar

		       @div[(class "container")]{

		         @form[(method "GET") (action ,resume-uri)]{
			   @fieldset{
			     @legend{Add Numbers}

			     @div[(class "clearfix")]{
			       @label[(for "a")]{First Summand}

			       @div[(class "input")]{
			         @input[(type "text") (id "a") (class "medium")
					(name "a") (size "30")]

			       }
			     }
			     @div[(class "clearfix")]{
			       @label[(for "a")]{Second Summand}

			       @div[(class "input")]{
			         @input[(type "text") (id "b") (class "medium")
					(name "b") (size "30")]

			       }
			     }
			     @div[(class "actions")]{
			       @input[(type "submit") (class "btn primary")
				      (value "Submit")]
			       @nbsp
			       @input[(type "reset") (class "btn")
				      (value "Reset")]
			     }
			   }
			 }
		       }
		     }
		   }))))
	     (a
	      (or (numeric-parameter parameters "a") 0))
	     (b
	      (or (numeric-parameter parameters "b") 0)))
	(make-html-response
	 200
	 `@html{
	    @,common-head
	    @body{
	      @,common-topbar

	      @div[(class "container")]{

	        @div[(class "hero-unit")]{
		  @h1{@,(number->string (+ a b))}
		  @p{@hellip is the answer}
		}
	      }
	    }
	  }))
      (make-error-response
       400 "Don't know how to perform the requested calculation.")))

(webgate-main)
Added webgate-cgi.scm.






























































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; -*- mode: Scheme; -*-
;;
;; This file is part of WebGate for CHICKEN.
;; Copyright (c) 2011 by Thomas Chust.  All rights reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the Software), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify,
;; merge, publish, distribute, sublicense, and/or sell copies of the
;; Software, and to permit persons to whom the Software is furnished
;; to do so, subject to the following conditions:
;; 
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; 
;; THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;;; CGI server "loop"

(define (cgi-main-loop handle-request)
  (handle-request 
   get-environment-variable
   (current-input-port) (current-output-port)))
Added webgate-core.scm.






































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
;; -*- mode: Scheme; -*-
;;
;; This file is part of WebGate for CHICKEN.
;; Copyright (c) 2011 by Thomas Chust.  All rights reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the Software), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify,
;; merge, publish, distribute, sublicense, and/or sell copies of the
;; Software, and to permit persons to whom the Software is furnished
;; to do so, subject to the following conditions:
;; 
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; 
;; THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;;; Message base type

(define-record-type message
  %make-message #t
  type headers
  body)

(define (make-message
	 body #!key
	 (type "application/octet-stream") (headers '()))
  (%make-message type headers body))

(define (write-message msg #!optional (port (current-output-port)))
  (let ((type (message-type msg))
	(body (message-body msg)))
    (when type
      (fprintf port "Content-type: ~a\r\n" type))
    (when body
      (fprintf port "Content-length: ~a\r\n" (string-length body)))
    (for-each
     (lambda (header)
       (call-with-values (cut car+cdr header)
	 (cut fprintf port "~a: ~a\r\n" <> <>)))
     (message-headers msg))
    (display "\r\n" port)
    (when body
      (display body port))))

;;; Request processing infrastructure

(define max-request-size
  (make-parameter #xffff))

(define-values (request-method-handler handled-request-methods)
  (let ((handlers (make-hash-table #:test string-ci=? #:hash string-ci-hash)))
    (values
     (case-lambda
       ((name)
	(hash-table-ref/default handlers name #f))
       ((name proc)
	(hash-table-set! handlers name proc)))
     (cut hash-table-keys handlers))))

(define request-body-handler
  (let ((handlers (make-hash-table #:test string-ci=? #:hash string-ci-hash)))
    (case-lambda
      ((name)
       (hash-table-ref/default handlers name #f))
      ((name proc)
       (hash-table-set! handlers name proc)))))

(define request-parameter-handler
  (let ((handler
	 (lambda (parameters key msg)
	   (hash-table-update!/default
	    parameters key (cut append! <> (list msg)) '()))))
    (case-lambda
     (()
      handler)
     ((proc)
      (set! handler proc)))))

;;; Response processing infrastructure

(define-record-type resource-context
  %make-resource-context #t
  getenv return)

(define (current-resource-context)
  (let ((ctx (thread-specific (current-thread))))
    (and (resource-context? ctx) ctx)))

(define status-table
  (alist->hash-table
   '((100 . "Continue")
     (101 . "Switching Protocols")
     (200 . "Ok")
     (201 . "Created")
     (202 . "Accepted")
     (203 . "Non-Authoritative Information")
     (204 . "No Content")
     (205 . "Reset Content")
     (206 . "Partial Content")
     (300 . "Multiple Choices")
     (301 . "Moved Permanently")
     (302 . "Found")
     (303 . "See Other")
     (304 . "Not Modified")
     (305 . "Use Proxy")
     (307 . "Temporary Redirect")
     (400 . "Bad Request")
     (401 . "Unauthorized")
     (402 . "Payment Required")
     (403 . "Forbidden")
     (404 . "Not Found")
     (405 . "Method Not Allowed")
     (406 . "Not Acceptable")
     (407 . "Proxy Authentication Required")
     (408 . "Request Timeout")
     (409 . "Conflict")
     (410 . "Gone")
     (411 . "Length Required")
     (412 . "Precondition Failed")
     (413 . "Request Entity Too Large")
     (414 . "Request-URI Too Long")
     (415 . "Unsupported Media Type")
     (416 . "Requested Range Not Satisfiable")
     (417 . "Expectation Failed")
     (500 . "Internal Server Error")
     (501 . "Not Implemented")
     (502 . "Bad Gateway")
     (503 . "Service Unavailable")
     (504 . "Gateway Timeout")
     (505 . "HTTP Version Not Supported"))
   #:test = #:hash number-hash))

(define-record-type (response message)
  %make-response #t
  status status-message)

(define (make-response
	 status body #!key
	 (type (and body "application/octet-stream"))
	 (headers '())
	 (status-message
	  (hash-table-ref/default status-table status "Unknown")))
  (%make-response
   type headers body
   status status-message))

(define (collect-response
	 status thunk #!key
	 (type "application/octet-stream")
	 (headers '())
	 (status-message
	  (hash-table-ref/default status-table status "Unknown")))
  (%make-response
   type headers (with-output-to-string thunk)
   status status-message))

(define (make-html-response
	 status html #!key
	 (status-message
	  (hash-table-ref/default status-table status "Unknown"))
	 (headers '()))
  (%make-response
   "text/html" headers (call-with-output-string (cut write-html html <>))
   status status-message))

(define (make-error-response
	 status message #!key
	 (status-message
	  (hash-table-ref/default status-table status "Unknown"))
	 (headers '()))
  (make-html-response
   status
   (let ((status-line (sprintf "~a ~a" status status-message)))
     `(html
       (head
	(meta ((name "robots") (content "noindex")))
	(title ,status-line))
       (body
	(h1 ,status-line)
	(p ,message))))
   #:status-message status-message
   #:headers headers))

(define (write-response rsp #!optional (port (current-output-port)))
  (fprintf
   port "Status: ~a ~a\r\n"
   (response-status rsp) (response-status-message rsp))
  (write-message rsp port))

(define resource-handler
  (let ((handlers (make-hash-table)))
    (case-lambda
      ((path)
       (let next ((handlers handlers) (args '()) (path path))
	 (if (pair? path)
	     (let-values (((step path) (car+cdr path)))
	       (cond
		((hash-table-ref/default handlers step #f)
		 => (cut next <> args path))
		((hash-table-ref/default handlers #f #f)
		 => (cut next <> (cons step args) path))
		(else
		 #f)))
	     (cond
	      ((hash-table-ref/default handlers #t #f)
	       => (lambda (proc)
		    (lambda (parameters)
		      (apply proc (reverse! (cons* parameters args))))))
	      (else
	       #f)))))
      ((path proc)
       (let next ((handlers handlers) (path path))
	 (if (pair? path)
	     (let-values (((step path) (car+cdr path)))
	       (hash-table-update!
		handlers step (cut next <> path) make-hash-table))
	     (hash-table-set! handlers #t proc))
	 handlers)
       (void)))))

(define-syntax define-resource
  (syntax-rules ()
    ((define-resource (name step/arg ... parameters)
       expr ...)
     (begin
       (define name
	 (let-syntax ((path
		       (ir-macro-transformer
			(lambda (stx inject id=?)
			  (let ((steps (cdr stx)))
			    `(list ,@(map
				      (lambda (step)
					(and (string? step) step))
				      steps))))))
		      (path-lambda
		       (ir-macro-transformer
			(lambda (stx inject id=?)
			  (let ((steps (cadr stx))
				(body (cddr stx)))
			    `(lambda ,(filter-map
				       (lambda (step)
					 (and (symbol? step) step))
				       steps)
			       ,@body))))))
	   (extend-procedure
	    (path-lambda (step/arg ... parameters)
	      expr ...)
	    (path step/arg ...))))
       (resource-handler (procedure-data name) name)))))

(define (resource-uri res . args)
  (uri-encode
   (call-with-output-string
    (lambda (port)
      (for-each
       (cut fprintf port "/~a" <>)
       (string-split
	(or ((resource-context-getenv (current-resource-context)) "SCRIPT_NAME")
	    "")
	"/"))
      (let next ((steps (procedure-data res)) (args args))
	(if (pair? steps)
	    (let-values (((step steps) (car+cdr steps)))
	      (if step
		  (begin
		    (fprintf port "/~a" step)
		    (next steps args))
		  (if (pair? args)
		      (let-values (((arg args) (car+cdr args)))
			(fprintf port "/~a" arg)
			(next steps args))
		      (error 'resource-uri "too few arguments"))))
	    (unless (null? args)
	      (error 'resource-uri "too many arguments" args))))))))

;;; Pre-installed default handlers (and directly related stuff)
	
(define (handle-query-parameters parameters query)
  (for-each
   (lambda (key+value)
     (let-optionals (map uri-decode (string-split key+value "="))
		    ((key #f) (value ""))
       (when key
	 ((request-parameter-handler)
	  parameters key
	  (make-message value #:type "text/plain")))))
   (string-split query "&;"))
  #f)

(request-body-handler "application/x-www-form-urlencoded"
  (lambda (parameters type size port)
    (handle-query-parameters parameters (read-string size port))))

(request-body-handler "multipart/form-data"
  (letrec ((boundary-rx
	    (irregex '(: bow "boundary=" ($ (+ (~ (" ;\n\r\t")))))))
	   (multipart-boundary
	    (lambda (s)
	      (cond
	       ((irregex-search boundary-rx s)
		=> (cut irregex-match-substring <> 1))
	       (else
		#f))))
	   (header-rx
	    (irregex '(: ($ (+ (~ #\:))) #\: (* space) ($ (*? any))
			 (or "\r\n" eos))))
	   (special+regular-headers
	    (lambda (s start end special)
	      (partition
	       (lambda (key+value)
		 (member (car key+value) special string-ci=?))
	       (irregex-fold
		header-rx
		(lambda (start m seed)
		  (cons (cons (irregex-match-substring m 1)
			      (irregex-match-substring m 2))
			seed))
		'() s
		(lambda (start seed)
		  (reverse! seed))
		start end))))
	   (name-rx
	    (irregex '(: bow "name=" #\" ($ (*? (~ #\"))) #\")))
	   (disposition-name
	    (lambda (s default)
	      (cond
	       ((irregex-search name-rx s)
		=> (cut irregex-match-substring <> 1))
	       (else
	        default))))
	   (handle-messages
	    (lambda (parameters name data boundary)
	      (let ((boundary-rx
		     (irregex `(: (or bos "\r\n") "--"
				  ,boundary
				  (? "--") "\r\n"))))
		(irregex-fold
		 boundary-rx
		 (lambda (start m skip?)
		   (and-let* (((not skip?))
			      (end
			       (irregex-match-start-index m))
			      (header-end
			       (string-contains data "\r\n\r\n" start end))
			      (body
			       (substring/shared data (+ header-end 4) end)))
		     (let-values (((specials headers)
				   (special+regular-headers
				    data start header-end
				    '("Content-type" "Content-length"))))
		       (let ((type
			      (alist-ref
			       "Content-type" specials string-ci=?
			       "text/plain"))
			     (name
			      (disposition-name
			       (alist-ref
				"Content-disposition" headers string-ci=?)
			       name)))
			 (when name
			   (cond
			    ((multipart-boundary type)
			     => (cut handle-messages parameters name body <>))
			    (else
			     ((request-parameter-handler)
			      parameters name
			      (make-message
			       body #:type type #:headers headers))))))))
		   #f)
		 #t data))
	      #f)))
    (lambda (parameters type size port)
      (cond
       ((multipart-boundary type)
	=> (cut handle-messages
		parameters #f (read-string size port) <>))
       (else
	(make-error-response
	 501 "The server doesn't know how to parse request parameters from the content type sent."))))))

(request-method-handler "GET"
  (lambda (parameters method getenv port)
    (handle-query-parameters parameters (or (getenv "QUERY_STRING") ""))))
  
(request-method-handler "POST"
  (lambda (parameters method getenv port)
    (or
     (handle-query-parameters parameters (or (getenv "QUERY_STRING") ""))
     (let ((type (or
		  (getenv "CONTENT_TYPE")
		  "application/octet-stream"))
	   (size (cond
		  ((getenv "CONTENT_LENGTH")
		   => string->number)
		  (else
		   #f))))
       (cond
	((not size)
	 (make-error-response
	  411 "The server refuses processing as no content length was sent with the request."))
	((cond ((max-request-size) => (cut > size <>)) (else #f))
	 (make-error-response
	  413 "The server refuses processing as the request's content length is too large."))
	((request-body-handler (substring/shared
				type 0 (or (string-index type #\;)
					   (string-length type))))
	 => (cut <> parameters type size port))
	(else
	 (make-error-response
	  501 "The server doesn't know how to parse request parameters from the content type sent.")))))))

;;; Central server routine

(define (handle-request getenv input-port output-port)
  (write-response
   (handle-exceptions
    exn (begin
	  (when (uncaught-exception? exn)
	    (set! exn (uncaught-exception-reason exn)))
	  (print-error-message
	   exn (current-error-port)
	   (sprintf "[~a] Request Handling Error" (current-seconds)))
	  (print-call-chain)
	  (make-error-response
	   500 "The server encountered an internal error handling the request."))
    (let ((parameters (make-hash-table))
	  (method (or (getenv "REQUEST_METHOD") "GET"))
	  (path (string-split (uri-decode (or (getenv "PATH_INFO") "")) "/")))
      (or
       (cond
	((request-method-handler method)
	 => (cut <> parameters method getenv input-port))
	(else
	 (make-error-response
	  405 "The access method used to request the document is not supported."
	  #:headers
	  (list
	   (cons "Allow" (string-join (handled-request-methods) ", "))))))
       (cond
	((resource-handler path)
	 => (lambda (proc)
	      (thread-join!
	       (thread-start!
		(make-thread
		 (lambda ()
		   (call-with-current-continuation
		    (lambda (return)
		      (thread-specific-set!
		       (current-thread)
		       (%make-resource-context getenv return))
		      (let ((rsp (proc parameters)))
			((resource-context-return (current-resource-context))
			 rsp))))))))))
	(else
	 (make-error-response
	  404 "The requested resource was not found by the server.")))
       (make-response 204 '()))))
   output-port))
Added webgate-scgi.scm.






































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; -*- mode: Scheme; -*-
;;
;; This file is part of WebGate for CHICKEN.
;; Copyright (c) 2011 by Thomas Chust.  All rights reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the Software), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify,
;; merge, publish, distribute, sublicense, and/or sell copies of the
;; Software, and to permit persons to whom the Software is furnished
;; to do so, subject to the following conditions:
;; 
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; 
;; THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;;; SCGI server loop (and directly related stuff)

(define (scgi-main-loop handle-request listener)
  (let ((environment-rx
	 (irregex '(: ($ (* (~ #\nul))) #\nul ($ (* (~ #\nul))) #\nul))))
    (let loop ()
      (let-values (((input-port output-port) (tcp-accept listener)))
	(thread-start!
	 (make-thread
	  (lambda ()
	    (let ((environment
		   (irregex-fold
		    environment-rx
		    (lambda (start m environment)
		      (hash-table-set!
		       environment (irregex-match-substring m 1)
		       (irregex-match-substring m 2))
		      environment)
		    (make-hash-table #:test string=? #:hash string-hash)
		    (read-netstring input-port))))
	      (handle-request
	       (cut hash-table-ref/default environment <> #f)
	       input-port output-port))
	    (close-input-port input-port)
	    (close-output-port output-port))))
	(loop)))))
Added webgate-suspend.scm.


































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; -*- mode: Scheme; -*-
;;
;; This file is part of WebGate for CHICKEN.
;; Copyright (c) 2011 by Thomas Chust.  All rights reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the Software), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify,
;; merge, publish, distribute, sublicense, and/or sell copies of the
;; Software, and to permit persons to whom the Software is furnished
;; to do so, subject to the following conditions:
;; 
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; 
;; THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;;; Support for suspended computations (and directly related stuff)

(define max-suspended-resources
  (make-parameter 1024))

(define max-suspended-resources-load
  (make-parameter 0.75))

(define suspended-resource-handler
  (let ((handler
	 (let ((mutex (make-mutex 'suspended-resources)))
	   (mutex-specific-set!
	    mutex (make-hash-table #:test string-ci=? #:hash string-ci-hash))
	   (lambda (resume/uuid)
	     (dynamic-wind
		 (cut mutex-lock! mutex)
		 (lambda ()
		   (let ((table (mutex-specific mutex)))
		     (if (procedure? resume/uuid)
			 (let ((size (hash-table-size table))
			       (max-size (max-suspended-resources)))
			   (when (>= size max-size)
			     (let* ((max-load (max-suspended-resources-load))
				    (num-drop (- size (* max-size max-load))))
			       (for-each
				(cut hash-table-delete! table <>)
				(take
				 (sort! (hash-table-keys table)
					(lambda (a b)
					  (< (uuid-time a) (uuid-time b))))
				 (inexact->exact (ceiling num-drop))))))
			   (let ((uuid (make-uuid 'time)))
			     (hash-table-set! table uuid resume/uuid)
			     uuid))
			 (hash-table-ref/default table resume/uuid #f))))
		 (cut mutex-unlock! mutex))))))
    (case-lambda
     (()
      handler)
     ((proc)
      (set! handler proc)))))

(define-resource (suspended "suspended" uuid parameters)
  (cond
   (((suspended-resource-handler) uuid)
    => (cut <> parameters))
   (else
    (make-error-response
     404 "The requested suspended resource was not found on the server."))))

(define (send/suspend proc)
  (call-with-current-continuation
   (lambda (resume)
     (let ((uuid ((suspended-resource-handler) resume)))
       ((resource-context-return (current-resource-context))
	(proc (resource-uri suspended uuid)))))))
Added webgate-utils.scm.




















































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
;; -*- mode: Scheme; -*-
;;
;; This file is part of WebGate for CHICKEN.
;; Copyright (c) 2011 by Thomas Chust.  All rights reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the Software), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify,
;; merge, publish, distribute, sublicense, and/or sell copies of the
;; Software, and to permit persons to whom the Software is furnished
;; to do so, subject to the following conditions:
;; 
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; 
;; THE SOFTWARE IS PROVIDED ASIS, WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

;;; UUIDs

(foreign-declare "#include <uuid/uuid.h>")

(define-foreign-type uuid-generator
  (function void ("uuid_t")))

(define (make-uuid #!optional mode)
  (let ((buf (make-string 36)))
    ((foreign-lambda* void ((uuid-generator generate)
			    (nonnull-scheme-pointer buf))
       "uuid_t uuid;"
       "generate(uuid);"
       "uuid_unparse_lower(uuid, buf);")
     (case mode
       ((random)
	(foreign-value "uuid_generate_random" uuid-generator))
       ((time)
	(foreign-value "uuid_generate_time" uuid-generator))
       (else
	(foreign-value "uuid_generate" uuid-generator)))
     buf)
    buf))

(define (uuid? v)
  (and (string? v)
       ((foreign-lambda* bool ((nonnull-c-string buf))
	  "uuid_t uuid;"
	  "C_return(uuid_parse(buf, uuid) == 0);")
	v)))

(define (uuid-time uuid)
  ((foreign-lambda* double ((nonnull-c-string buf))
     "uuid_t uuid;"
     "struct timeval time;"
     "if (uuid_parse(buf, uuid) != 0) C_return(nan(\"bad uuid\"));"
     "uuid_time(uuid, &time);"
     "C_return(((double)time.tv_sec) + ((double)time.tv_usec) / 1.0e6);")
   uuid))

;;; Netstrings

(define (write-netstring s #!optional (port (current-output-port)))
  (fprintf port "~a:~a," (string-length s) s))

(define (read-netstring #!optional (port (current-input-port)))
  (let ((l (string->number (read-token char-numeric? port))))
    (unless l
      (error
       'read-netstring
       "client side protocol error: malformed netstring (bad length)"))
    (unless (eq? (read-char port) #\:)
      (error
       'read-netstring
       "client side protocol error: malformed netstring (bad delimiter)"))
    (let ((s (read-string l port)))
      (unless (eq? (read-char port) #\,)
	(error
	 'read-netstring
	 "client side protocol error: malformed netstring (bad terminal)"))
      s)))

;;; @-expressions

(define (make-at-reader #!key
			(command-char #\@)
			(trim-whitespace? #t)
			(condense-whitespace? #t)
			(list-arguments? #f)
			(inside? #f))
  (letrec ((char-normal?
	    (cute char-set-contains?
		  (char-set-complement
		   (char-set command-char #\{ #\} #\return #\newline))
		  <>))
	   (char-group?
	    (cute char-set-contains?
		  (char-set #\[ #\{)
		  <>))
	   (skip-whitespace
	    (lambda (port)
	      (when (char-whitespace? (peek-char port))
		(read-char port)
		(skip-whitespace port))))
	   (read-whitespace
	    (if condense-whitespace?
		(lambda (port)
		  (skip-whitespace port)
		  " ")
		(cut read-token char-whitespace? <>)))
	   (read-at-exp
	    (lambda (port)
	      (skip-whitespace port)
	      (let ((char (peek-char port)))
		(cond
		 ((eof-object? char)
		  (read-char port))
		 (else
		  (when (eqv? char command-char)
		    (read-char port))
		  (let* ((head (and (not (char-group? (peek-char port)))
				    (read port)))
			 (args (and (eqv? (peek-char port) #\[)
				    (read port)))
			 (body (and (eqv? (peek-char port) #\{)
				    (read-inside-at-exp 'skip port))))
		    (if (or args body)
			(append!
			 (cond
			  (head => list)
			  (else '()))
			 (cond
			  ((and list-arguments? args) => list)
			  (else (or args '())))
			 (or body '()))
			head)))))))
	   (read-inside-at-exp
	    (lambda (brace-mode port)
	      (append!
	       (let ((head
		      (case brace-mode
			((none)
			 '())
			((skip)
			 (and (eqv? (peek-char port) #\{)
			      (begin (read-char port) '())))
			(else
			 (and (eqv? (peek-char port) #\{)
			      (list (string (read-char port))))))))
		 (if head
		     (begin
		       (when trim-whitespace? (skip-whitespace port))
		       head)
		     (syntax-error
		      'read-inside-at-exp "expected @-expression body, found"
		      (peek-char port))))
	       (let more ()
		 (let ((char (peek-char port)))
		   (cond
		    ((eqv? char #\{)
		     (case brace-mode
		       ((none)
			(cons (string (read-char port)) (more)))
		       (else
			(append! (read-inside-at-exp 'keep port) (more)))))
		    ((eqv? char #\})
		     (case brace-mode
		       ((none)
			(cons (string (read-char port)) (more)))
		       ((skip)
			(read-char port)
			'())
		       (else
			(list (string (read-char port))))))
		    ((eof-object? char)
		     (case brace-mode
		       ((none)
			(read-char port)
			'())
		       (else
			(syntax-error
			 'read-inside-at-exp "@-expression body not closed"))))
		    ((eqv? char command-char)
		     (cons (read-at-exp port) (more)))
		    ((char-whitespace? char)
		     (let* ((head (read-whitespace port))
			    (tail (more)))
		       (if (or (pair? tail) (not trim-whitespace?))
			   (cons head tail)
			   tail)))
		    (else
		     (cons (read-token char-normal? port) (more))))))))))
    (if inside?
	(lambda (#!optional (port (current-input-port)))
	  (read-inside-at-exp 'none port))
	(lambda (#!optional (port (current-input-port)))
	  (read-at-exp port)))))

(define (use-at-read-table #!rest args #!key
			   (command-char #\@)
			   (read-table (current-read-table)))
  (current-read-table (copy-read-table read-table))
  (set-read-syntax! command-char (apply make-at-reader #:inside? #f args)))

(define (make-at-read-table #!rest args #!key
			    (read-table (current-read-table)))
  (parameterize ((current-read-table read-table))
    (apply use-at-read-table args)
    (current-read-table)))

;;; URI encoding

(define uri-encode
  (let ((problematic-rx (irregex '(~ (or alphanumeric
					 "!#$&'()*,-./:;?@_~")))))
    (lambda (s)
      (irregex-replace/all
       problematic-rx s
       (lambda (m)
	 (string-append
	  "%"
	  (string-pad
	   (number->string
	    (char->integer (string-ref (irregex-match-substring m) 0)) 16)
	   2 #\0)))))))

(define uri-decode
  (let ((escape-rx (irregex '(or #\+ (: #\% ($ (= 2 hex-digit)))))))
    (lambda (s)
      (irregex-replace/all
       escape-rx s
       (lambda (m)
	 (case (string-ref s (irregex-match-start-index m))
	   ((#\+)
	    " ")
	   ((#\%) 
	    (string
	     (integer->char
	      (string->number (irregex-match-substring m 1) 16))))))))))

;;; HTML output

(define write-html
  (letrec ((tag-rules
	    (alist->hash-table
	     '((area . void)
	       (base . void)
	       (br . void)
	       (col . void)
	       (command . void)
	       (embed . void)
	       (hr . void)
	       (img . void)
	       (input . void)
	       (keygen . void)
	       (link . void)
	       (meta . void)
	       (param . void)
	       (source . void)
	       (track . void)
	       (wbr . void)
	       (script . raw)
	       (style . raw))
	     #:test eq? #:hash eq?-hash))
	   (problematic-rx
	    (irregex '("\"&<>")))
	   (html-escape
	    (lambda (s)
	      (irregex-replace/all
	       problematic-rx s
	       (lambda (m)
		 (case (string-ref (irregex-match-substring m) 0)
		   ((#\") "&quot;")
		   ((#\&) "&amp;")
		   ((#\<) "&lt;")
		   ((#\>) "&gt;"))))))
	   (write-element
	    (lambda (elt port)
	      (unless (and (pair? elt) (symbol? (car elt)) (list? (cdr elt)))
		(error
		 'write-html "not a proper element"
		 elt))
	      (let-values (((tag attributes+contents)
			    (car+cdr elt)))
		(fprintf port "<~a" tag)
		(let-values (((rule)
			      (hash-table-ref/default tag-rules tag 'normal))
			     ((attributes contents)
			      (cond
			       ((null? attributes+contents)
				(values '() '()))
			       ((and (list? (car attributes+contents))
				     (every list? (car attributes+contents)))
				(car+cdr attributes+contents))
			       (else
				(values '() attributes+contents)))))
		  (for-each (cut write-attribute <> port) attributes)
		  (display #\> port)
		  (case rule
		    ((normal)
		     (for-each (cut write-content #t <> port) contents))
		    ((raw)
		     (for-each (cut write-content #f <> port) contents))
		    ((void)
		     (unless (null? contents)
		       (error
			'write-html "void elements cannot have contents"
			elt))))
		  (case rule
		    ((normal raw)
		     (fprintf port "</~a>" tag)))))))
	   (write-attribute
	    (lambda (attr port)
	      (unless (and (pair? attr) (symbol? (car attr)) (list? (cdr attr)))
		(error
		 'write-html "not a proper attribute"
		 attr))
	      (let-values (((key contents) (car+cdr attr)))
		(fprintf port " ~a=\"" key)
		(for-each (cut write-content #f <> port) contents)
		(display #\" port))))
	   (write-content
	    (lambda (allow-elements? v port)
	      (cond
	       ((symbol? v)
		(fprintf port "&~a;" v))
	       ((and (integer? v) (positive? v))
		(fprintf port "&#~a;" v))
	       ((string? v)
		(display (html-escape v) port))
	       (allow-elements?
		(write-element v port))
	       (else
		(error
		 'write-html "element not allowed in this context"
		 v))))))
    (lambda (html #!optional (port (current-output-port)))
      (display "<!DOCTYPE html>" port)
      (newline port)
      (write-element html port)
      (newline port))))
Changes to webgate.meta.
1
2
3
4
5
6
7





;; -*- mode: Scheme; -*-
((category net)
 (license "BSD")
 (author "Thomas Chust")
 (synopsis "(S)CGI web application framework")
 (needs srfi-99)
 (files "webgate.scm"))











|
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
;; -*- mode: Scheme; -*-
((category net)
 (license "BSD")
 (author "Thomas Chust")
 (synopsis "(S)CGI web application framework")
 (needs srfi-99)
 (files "webgate.scm"
	"webgate-utils.scm"
	"webgate-core.scm"
	"webgate-suspend.scm"
	"webgate-cgi.scm"
	"webgate-scgi.scm"))
Changes to webgate.scm.
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
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

(require-library
 srfi-1 srfi-4 srfi-13 srfi-18 srfi-69 srfi-99
 data-structures ports extras lolevel irregex tcp)

(module webgate-utils
  (make-uuid uuid?
   uuid-time
   write-netstring read-netstring

   uri-encode uri-decode
   write-html)
  (import
   scheme chicken foreign
   srfi-1 srfi-13 srfi-69
   extras irregex)

;;; UUIDs

(foreign-declare "#include <uuid/uuid.h>")

(define-foreign-type uuid-generator
  (function void ("uuid_t")))

(define (make-uuid #!optional mode)
  (let ((buf (make-string 36)))
    ((foreign-lambda* void ((uuid-generator generate)
			    (nonnull-scheme-pointer buf))
       "uuid_t uuid;"
       "generate(uuid);"
       "uuid_unparse_lower(uuid, buf);")
     (case mode
       ((random)
	(foreign-value "uuid_generate_random" uuid-generator))
       ((time)
	(foreign-value "uuid_generate_time" uuid-generator))
       (else
	(foreign-value "uuid_generate" uuid-generator)))
     buf)
    buf))

(define (uuid? v)
  (and (string? v)
       ((foreign-lambda* bool ((nonnull-c-string buf))
	  "uuid_t uuid;"
	  "C_return(uuid_parse(buf, uuid) == 0);")
	v)))

(define (uuid-time uuid)
  ((foreign-lambda* double ((nonnull-c-string buf))
     "uuid_t uuid;"
     "struct timeval time;"
     "if (uuid_parse(buf, uuid) != 0) C_return(nan(\"bad uuid\"));"
     "uuid_time(uuid, &time);"
     "C_return(((double)time.tv_sec) + ((double)time.tv_usec) / 1.0e6);")
   uuid))

;;; Netstrings

(define (write-netstring s #!optional (port (current-output-port)))
  (fprintf port "~a:~a," (string-length s) s))

(define (read-netstring #!optional (port (current-input-port)))
  (let ((l (string->number (read-token char-numeric? port))))
    (unless l
      (error
       'read-netstring
       "client side protocol error: malformed netstring (bad length)"))
    (unless (eq? (read-char port) #\:)
      (error
       'read-netstring
       "client side protocol error: malformed netstring (bad delimiter)"))
    (let ((s (read-string l port)))
      (unless (eq? (read-char port) #\,)
	(error
	 'read-netstring
	 "client side protocol error: malformed netstring (bad terminal)"))
      s)))

;;; URI encoding

(define uri-encode
  (let ((problematic-rx (irregex '(~ (or alphanumeric
					 "!#$&'()*,-./:;?@_~")))))
    (lambda (s)
      (irregex-replace/all
       problematic-rx s
       (lambda (m)
	 (string-append
	  "%"
	  (string-pad
	   (number->string
	    (char->integer (string-ref (irregex-match-substring m) 0)) 16)
	   2 #\0)))))))

(define uri-decode
  (let ((escape-rx (irregex '(or #\+ (: #\% ($ (= 2 hex-digit)))))))
    (lambda (s)
      (irregex-replace/all
       escape-rx s
       (lambda (m)
	 (case (string-ref s (irregex-match-start-index m))
	   ((#\+)
	    " ")
	   ((#\%) 
	    (string
	     (integer->char
	      (string->number (irregex-match-substring m 1) 16))))))))))

;;; HTML output

(define write-html
  (letrec ((tag-rules
	    (alist->hash-table
	     '((area . void)
	       (base . void)
	       (br . void)
	       (col . void)
	       (command . void)
	       (embed . void)
	       (hr . void)
	       (img . void)
	       (input . void)
	       (keygen . void)
	       (link . void)
	       (meta . void)
	       (param . void)
	       (source . void)
	       (track . void)
	       (wbr . void)
	       (script . raw)
	       (style . raw))
	     #:test eq? #:hash eq?-hash))
	   (problematic-rx
	    (irregex '("\"&<>")))
	   (html-escape
	    (lambda (s)
	      (irregex-replace/all
	       problematic-rx s
	       (lambda (m)
		 (case (string-ref (irregex-match-substring m) 0)
		   ((#\") "&quot;")
		   ((#\&) "&amp;")
		   ((#\<) "&lt;")
		   ((#\>) "&gt;"))))))
	   (write-element
	    (lambda (elt port)
	      (unless (and (pair? elt) (symbol? (car elt)) (list? (cdr elt)))
		(error
		 'write-html "not a proper element"
		 elt))
	      (let-values (((tag attributes+contents)
			    (car+cdr elt)))
		(fprintf port "<~a" tag)
		(let-values (((rule)
			      (hash-table-ref/default tag-rules tag 'normal))
			     ((attributes contents)
			      (cond
			       ((null? attributes+contents)
				(values '() '()))
			       ((and (list? (car attributes+contents))
				     (every list? (car attributes+contents)))
				(car+cdr attributes+contents))
			       (else
				(values '() attributes+contents)))))
		  (for-each (cut write-attribute <> port) attributes)
		  (display #\> port)
		  (case rule
		    ((normal)
		     (for-each (cut write-content #t <> port) contents))
		    ((raw)
		     (for-each (cut write-content #f <> port) contents))
		    ((void)
		     (unless (null? contents)
		       (error
			'write-html "void elements cannot have contents"
			elt))))
		  (case rule
		    ((normal raw)
		     (fprintf port "</~a>" tag)))))))
	   (write-attribute
	    (lambda (attr port)
	      (unless (and (pair? attr) (symbol? (car attr)) (list? (cdr attr)))
		(error
		 'write-html "not a proper attribute"
		 attr))
	      (let-values (((key contents) (car+cdr attr)))
		(fprintf port " ~a=\"" key)
		(for-each (cut write-content #f <> port) contents)
		(display #\" port))))
	   (write-content
	    (lambda (allow-elements? v port)
	      (cond
	       ((symbol? v)
		(fprintf port "&~a;" v))
	       ((and (integer? v) (positive? v))
		(fprintf port "&#~a;" v))
	       ((string? v)
		(display (html-escape v) port))
	       (allow-elements?
		(write-element v port))
	       (else
		(error
		 'write-html "element not allowed in this context"
		 v))))))
    (lambda (html #!optional (port (current-output-port)))
      (display "<!DOCTYPE html>" port)
      (newline port)
      (write-element html port)
      (newline port))))

)

(module webgate-core
  (message make-message message?
   message-type message-headers message-body
   write-message
   max-request-size
   request-method-handler







|






>




|
|
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







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
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.

(require-library
 srfi-1 srfi-4 srfi-13 srfi-14 srfi-18 srfi-69 srfi-99
 data-structures ports extras lolevel irregex tcp)

(module webgate-utils
  (make-uuid uuid?
   uuid-time
   write-netstring read-netstring
   make-at-reader make-at-read-table use-at-read-table
   uri-encode uri-decode
   write-html)
  (import
   scheme chicken foreign
   srfi-1 srfi-13 srfi-14 srfi-69
   data-structures extras irregex)
  (include

   "webgate-utils.scm"))


































































































































































































(module webgate-core
  (message make-message message?
   message-type message-headers message-body
   write-message
   max-request-size
   request-method-handler
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
   resource-handler define-resource resource-uri
   handle-query-parameters
   handle-request)
  (import
   scheme chicken
   srfi-1 srfi-4 srfi-13 srfi-18 srfi-69 srfi-99
   data-structures ports extras lolevel irregex webgate-utils)

;;; Message base type

(define-record-type message
  %make-message #t
  type headers
  body)

(define (make-message
	 body #!key
	 (type "application/octet-stream") (headers '()))
  (%make-message type headers body))

(define (write-message msg #!optional (port (current-output-port)))
  (let ((type (message-type msg))
	(body (message-body msg)))
    (when type
      (fprintf port "Content-type: ~a\r\n" type))
    (when body
      (fprintf port "Content-length: ~a\r\n" (string-length body)))
    (for-each
     (lambda (header)
       (call-with-values (cut car+cdr header)
	 (cut fprintf port "~a: ~a\r\n" <> <>)))
     (message-headers msg))
    (display "\r\n" port)
    (when body
      (display body port))))

;;; Request processing infrastructure

(define max-request-size
  (make-parameter #xffff))

(define-values (request-method-handler handled-request-methods)
  (let ((handlers (make-hash-table #:test string-ci=? #:hash string-ci-hash)))
    (values
     (case-lambda
       ((name)
	(hash-table-ref/default handlers name #f))
       ((name proc)
	(hash-table-set! handlers name proc)))
     (cut hash-table-keys handlers))))

(define request-body-handler
  (let ((handlers (make-hash-table #:test string-ci=? #:hash string-ci-hash)))
    (case-lambda
      ((name)
       (hash-table-ref/default handlers name #f))
      ((name proc)
       (hash-table-set! handlers name proc)))))

(define request-parameter-handler
  (let ((handler
	 (lambda (parameters key msg)
	   (hash-table-update!/default
	    parameters key (cut append! <> (list msg)) '()))))
    (case-lambda
     (()
      handler)
     ((proc)
      (set! handler proc)))))

;;; Response processing infrastructure

(define-record-type resource-context
  %make-resource-context #t
  getenv return)

(define (current-resource-context)
  (let ((ctx (thread-specific (current-thread))))
    (and (resource-context? ctx) ctx)))

(define status-table
  (alist->hash-table
   '((100 . "Continue")
     (101 . "Switching Protocols")
     (200 . "Ok")
     (201 . "Created")
     (202 . "Accepted")
     (203 . "Non-Authoritative Information")
     (204 . "No Content")
     (205 . "Reset Content")
     (206 . "Partial Content")
     (300 . "Multiple Choices")
     (301 . "Moved Permanently")
     (302 . "Found")
     (303 . "See Other")
     (304 . "Not Modified")
     (305 . "Use Proxy")
     (307 . "Temporary Redirect")
     (400 . "Bad Request")
     (401 . "Unauthorized")
     (402 . "Payment Required")
     (403 . "Forbidden")
     (404 . "Not Found")
     (405 . "Method Not Allowed")
     (406 . "Not Acceptable")
     (407 . "Proxy Authentication Required")
     (408 . "Request Timeout")
     (409 . "Conflict")
     (410 . "Gone")
     (411 . "Length Required")
     (412 . "Precondition Failed")
     (413 . "Request Entity Too Large")
     (414 . "Request-URI Too Long")
     (415 . "Unsupported Media Type")
     (416 . "Requested Range Not Satisfiable")
     (417 . "Expectation Failed")
     (500 . "Internal Server Error")
     (501 . "Not Implemented")
     (502 . "Bad Gateway")
     (503 . "Service Unavailable")
     (504 . "Gateway Timeout")
     (505 . "HTTP Version Not Supported"))
   #:test = #:hash number-hash))

(define-record-type (response message)
  %make-response #t
  status status-message)

(define (make-response
	 status body #!key
	 (type (and body "application/octet-stream"))
	 (headers '())
	 (status-message
	  (hash-table-ref/default status-table status "Unknown")))
  (%make-response
   type headers body
   status status-message))

(define (collect-response
	 status thunk #!key
	 (type "application/octet-stream")
	 (headers '())
	 (status-message
	  (hash-table-ref/default status-table status "Unknown")))
  (%make-response
   type headers (with-output-to-string thunk)
   status status-message))

(define (make-html-response
	 status html #!key
	 (status-message
	  (hash-table-ref/default status-table status "Unknown"))
	 (headers '()))
  (%make-response
   "text/html" headers (call-with-output-string (cut write-html html <>))
   status status-message))

(define (make-error-response
	 status message #!key
	 (status-message
	  (hash-table-ref/default status-table status "Unknown"))
	 (headers '()))
  (make-html-response
   status
   (let ((status-line (sprintf "~a ~a" status status-message)))
     `(html
       (head
	(meta ((name "robots") (content "noindex")))
	(title ,status-line))
       (body
	(h1 ,status-line)
	(p ,message))))
   #:status-message status-message
   #:headers headers))

(define (write-response rsp #!optional (port (current-output-port)))
  (fprintf
   port "Status: ~a ~a\r\n"
   (response-status rsp) (response-status-message rsp))
  (write-message rsp port))

(define resource-handler
  (let ((handlers (make-hash-table)))
    (case-lambda
      ((path)
       (let next ((handlers handlers) (args '()) (path path))
	 (if (pair? path)
	     (let-values (((step path) (car+cdr path)))
	       (cond
		((hash-table-ref/default handlers step #f)
		 => (cut next <> args path))
		((hash-table-ref/default handlers #f #f)
		 => (cut next <> (cons step args) path))
		(else
		 #f)))
	     (cond
	      ((hash-table-ref/default handlers #t #f)
	       => (lambda (proc)
		    (lambda (parameters)
		      (apply proc (reverse! (cons* parameters args))))))
	      (else
	       #f)))))
      ((path proc)
       (let next ((handlers handlers) (path path))
	 (if (pair? path)
	     (let-values (((step path) (car+cdr path)))
	       (hash-table-update!
		handlers step (cut next <> path) make-hash-table))
	     (hash-table-set! handlers #t proc))
	 handlers)
       (void)))))

(define-syntax define-resource
  (syntax-rules ()
    ((define-resource (name step/arg ... parameters)
       expr ...)
     (begin
       (define name
	 (let-syntax ((path
		       (ir-macro-transformer
			(lambda (stx inject id=?)
			  (let ((steps (cdr stx)))
			    `(list ,@(map
				      (lambda (step)
					(and (string? step) step))
				      steps))))))
		      (path-lambda
		       (ir-macro-transformer
			(lambda (stx inject id=?)
			  (let ((steps (cadr stx))
				(body (cddr stx)))
			    `(lambda ,(filter-map
				       (lambda (step)
					 (and (symbol? step) step))
				       steps)
			       ,@body))))))
	   (extend-procedure
	    (path-lambda (step/arg ... parameters)
	      expr ...)
	    (path step/arg ...))))
       (resource-handler (procedure-data name) name)))))

(define (resource-uri res . args)
  (uri-encode
   (call-with-output-string
    (lambda (port)
      (for-each
       (cut fprintf port "/~a" <>)
       (string-split
	(or ((resource-context-getenv (current-resource-context)) "SCRIPT_NAME")
	    "")
	"/"))
      (let next ((steps (procedure-data res)) (args args))
	(if (pair? steps)
	    (let-values (((step steps) (car+cdr steps)))
	      (if step
		  (begin
		    (fprintf port "/~a" step)
		    (next steps args))
		  (if (pair? args)
		      (let-values (((arg args) (car+cdr args)))
			(fprintf port "/~a" arg)
			(next steps args))
		      (error 'resource-uri "too few arguments"))))
	    (unless (null? args)
	      (error 'resource-uri "too many arguments" args))))))))

;;; Pre-installed default handlers (and directly related stuff)
	
(define (handle-query-parameters parameters query)
  (for-each
   (lambda (key+value)
     (let-optionals (map uri-decode (string-split key+value "="))
		    ((key #f) (value ""))
       (when key
	 ((request-parameter-handler)
	  parameters key
	  (make-message value #:type "text/plain")))))
   (string-split query "&;"))
  #f)

(request-body-handler "application/x-www-form-urlencoded"
  (lambda (parameters type size port)
    (handle-query-parameters parameters (read-string size port))))

(request-body-handler "multipart/form-data"
  (letrec ((boundary-rx
	    (irregex '(: bow "boundary=" ($ (+ (~ (" ;\n\r\t")))))))
	   (multipart-boundary
	    (lambda (s)
	      (cond
	       ((irregex-search boundary-rx s)
		=> (cut irregex-match-substring <> 1))
	       (else
		#f))))
	   (header-rx
	    (irregex '(: ($ (+ (~ #\:))) #\: (* space) ($ (*? any))
			 (or "\r\n" eos))))
	   (special+regular-headers
	    (lambda (s start end special)
	      (partition
	       (lambda (key+value)
		 (member (car key+value) special string-ci=?))
	       (irregex-fold
		header-rx
		(lambda (start m seed)
		  (cons (cons (irregex-match-substring m 1)
			      (irregex-match-substring m 2))
			seed))
		'() s
		(lambda (start seed)
		  (reverse! seed))
		start end))))
	   (name-rx
	    (irregex '(: bow "name=" #\" ($ (*? (~ #\"))) #\")))
	   (disposition-name
	    (lambda (s default)
	      (cond
	       ((irregex-search name-rx s)
		=> (cut irregex-match-substring <> 1))
	       (else
	        default))))
	   (handle-messages
	    (lambda (parameters name data boundary)
	      (let ((boundary-rx
		     (irregex `(: (or bos "\r\n") "--"
				  ,boundary
				  (? "--") "\r\n"))))
		(irregex-fold
		 boundary-rx
		 (lambda (start m skip?)
		   (and-let* (((not skip?))
			      (end
			       (irregex-match-start-index m))
			      (header-end
			       (string-contains data "\r\n\r\n" start end))
			      (body
			       (substring/shared data (+ header-end 4) end)))
		     (let-values (((specials headers)
				   (special+regular-headers
				    data start header-end
				    '("Content-type" "Content-length"))))
		       (let ((type
			      (alist-ref
			       "Content-type" specials string-ci=?
			       "text/plain"))
			     (name
			      (disposition-name
			       (alist-ref
				"Content-disposition" headers string-ci=?)
			       name)))
			 (when name
			   (cond
			    ((multipart-boundary type)
			     => (cut handle-messages parameters name body <>))
			    (else
			     ((request-parameter-handler)
			      parameters name
			      (make-message
			       body #:type type #:headers headers))))))))
		   #f)
		 #t data))
	      #f)))
    (lambda (parameters type size port)
      (cond
       ((multipart-boundary type)
	=> (cut handle-messages
		parameters #f (read-string size port) <>))
       (else
	(make-error-response
	 501 "The server doesn't know how to parse request parameters from the content type sent."))))))

(request-method-handler "GET"
  (lambda (parameters method getenv port)
    (handle-query-parameters parameters (or (getenv "QUERY_STRING") ""))))
  
(request-method-handler "POST"
  (lambda (parameters method getenv port)
    (or
     (handle-query-parameters parameters (or (getenv "QUERY_STRING") ""))
     (let ((type (or
		  (getenv "CONTENT_TYPE")
		  "application/octet-stream"))
	   (size (cond
		  ((getenv "CONTENT_LENGTH")
		   => string->number)
		  (else
		   #f))))
       (cond
	((not size)
	 (make-error-response
	  411 "The server refuses processing as no content length was sent with the request."))
	((cond ((max-request-size) => (cut > size <>)) (else #f))
	 (make-error-response
	  413 "The server refuses processing as the request's content length is too large."))
	((request-body-handler (substring/shared
				type 0 (or (string-index type #\;)
					   (string-length type))))
	 => (cut <> parameters type size port))
	(else
	 (make-error-response
	  501 "The server doesn't know how to parse request parameters from the content type sent.")))))))

;;; Central server routine

(define (handle-request getenv input-port output-port)
  (write-response
   (handle-exceptions
    exn (begin
	  (when (uncaught-exception? exn)
	    (set! exn (uncaught-exception-reason exn)))
	  (print-error-message
	   exn (current-error-port)
	   (sprintf "[~a] Request Handling Error" (current-seconds)))
	  (print-call-chain)
	  (make-error-response
	   500 "The server encountered an internal error handling the request."))
    (let ((parameters (make-hash-table))
	  (method (or (getenv "REQUEST_METHOD") "GET"))
	  (path (string-split (uri-decode (or (getenv "PATH_INFO") "")) "/")))
      (or
       (cond
	((request-method-handler method)
	 => (cut <> parameters method getenv input-port))
	(else
	 (make-error-response
	  405 "The access method used to request the document is not supported."
	  #:headers
	  (list
	   (cons "Allow" (string-join (handled-request-methods) ", "))))))
       (cond
	((resource-handler path)
	 => (lambda (proc)
	      (thread-join!
	       (thread-start!
		(make-thread
		 (lambda ()
		   (call-with-current-continuation
		    (lambda (return)
		      (thread-specific-set!
		       (current-thread)
		       (%make-resource-context getenv return))
		      (let ((rsp (proc parameters)))
			((resource-context-return (current-resource-context))
			 rsp))))))))))
	(else
	 (make-error-response
	  404 "The requested resource was not found by the server.")))
       (make-response 204 '()))))
   output-port))

)

(module webgate-suspend
  (max-suspended-resources max-suspended-resources-load
   suspended-resource-handler
   suspended
   send/suspend)
  (import
   scheme chicken
   srfi-1 srfi-18 srfi-69
   data-structures webgate-utils webgate-core)

;;; Support for suspended computations (and directly related stuff)

(define max-suspended-resources
  (make-parameter 1024))

(define max-suspended-resources-load
  (make-parameter 0.75))

(define suspended-resource-handler
  (let ((handler
	 (let ((mutex (make-mutex 'suspended-resources)))
	   (mutex-specific-set!
	    mutex (make-hash-table #:test string-ci=? #:hash string-ci-hash))
	   (lambda (resume/uuid)
	     (dynamic-wind
		 (cut mutex-lock! mutex)
		 (lambda ()
		   (let ((table (mutex-specific mutex)))
		     (if (procedure? resume/uuid)
			 (let ((size (hash-table-size table))
			       (max-size (max-suspended-resources)))
			   (when (>= size max-size)
			     (let* ((max-load (max-suspended-resources-load))
				    (num-drop (- size (* max-size max-load))))
			       (for-each
				(cut hash-table-delete! table <>)
				(take
				 (sort! (hash-table-keys table)
					(lambda (a b)
					  (< (uuid-time a) (uuid-time b))))
				 (inexact->exact (ceiling num-drop))))))
			   (let ((uuid (make-uuid 'time)))
			     (hash-table-set! table uuid resume/uuid)
			     uuid))
			 (hash-table-ref/default table resume/uuid #f))))
		 (cut mutex-unlock! mutex))))))
    (case-lambda
     (()
      handler)
     ((proc)
      (set! handler proc)))))

(define-resource (suspended "suspended" uuid parameters)
  (cond
   (((suspended-resource-handler) uuid)
    => (cut <> parameters))
   (else
    (make-error-response
     404 "The requested suspended resource was not found on the server."))))

(define (send/suspend proc)
  (call-with-current-continuation
   (lambda (resume)
     (let ((uuid ((suspended-resource-handler) resume)))
       ((resource-context-return (current-resource-context))
	(proc (resource-uri suspended uuid)))))))

)

(module webgate-cgi
  (cgi-main-loop)
  (import
   scheme chicken)

;;; CGI server "loop"

(define (cgi-main-loop handle-request)
  (handle-request 
   get-environment-variable
   (current-input-port) (current-output-port)))

)

(module webgate-scgi
  (scgi-main-loop)
  (import
   scheme chicken
   srfi-13 srfi-18 srfi-69
   data-structures irregex webgate-utils tcp)

;;; SCGI server loop (and directly related stuff)

(define (scgi-main-loop handle-request listener)
  (let ((environment-rx
	 (irregex '(: ($ (* (~ #\nul))) #\nul ($ (* (~ #\nul))) #\nul))))
    (let loop ()
      (let-values (((input-port output-port) (tcp-accept listener)))
	(thread-start!
	 (make-thread
	  (lambda ()
	    (let ((environment
		   (irregex-fold
		    environment-rx
		    (lambda (start m environment)
		      (hash-table-set!
		       environment (irregex-match-substring m 1)
		       (irregex-match-substring m 2))
		      environment)
		    (make-hash-table #:test string=? #:hash string-hash)
		    (read-netstring input-port))))
	      (handle-request
	       (cut hash-table-ref/default environment <> #f)
	       input-port output-port))
	    (close-input-port input-port)
	    (close-output-port output-port))))
	(loop)))))

)

(module webgate
  (message make-message message?
   message-type message-headers message-body
   max-request-size
   request-method-handler
   request-body-handler







|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










|
<
|
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




|
<
|
<
<
<
<
<
<







|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







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
   resource-handler define-resource resource-uri
   handle-query-parameters
   handle-request)
  (import
   scheme chicken
   srfi-1 srfi-4 srfi-13 srfi-18 srfi-69 srfi-99
   data-structures ports extras lolevel irregex webgate-utils)
  (include

   "webgate-core.scm"))



























































































































































































































































































































































































































































(module webgate-suspend
  (max-suspended-resources max-suspended-resources-load
   suspended-resource-handler
   suspended
   send/suspend)
  (import
   scheme chicken
   srfi-1 srfi-18 srfi-69
   data-structures webgate-utils webgate-core)
  (include

   "webgate-suspend.scm"))

























































(module webgate-cgi
  (cgi-main-loop)
  (import
   scheme chicken)
  (include

   "webgate-cgi.scm"))







(module webgate-scgi
  (scgi-main-loop)
  (import
   scheme chicken
   srfi-13 srfi-18 srfi-69
   data-structures irregex webgate-utils tcp)
  (include

   "webgate-scgi.scm"))



























(module webgate
  (message make-message message?
   message-type message-headers message-body
   max-request-size
   request-method-handler
   request-body-handler