moonbridge

view moonbridge_http.lua @ 33:59f485dc48ea

Removed method request:send_text_status_response(...); Added helloworld.lua
author jbe
date Tue Feb 17 13:15:08 2015 +0100 (2015-02-17)
parents fd542c33020b
children 2d7e3028d993
line source
1 #!/usr/bin/env lua
3 -- module preamble
4 local _G, _M = _ENV, {}
5 _ENV = setmetatable({}, {
6 __index = function(self, key)
7 local value = _M[key]; if value ~= nil then return value end
8 return _G[key]
9 end,
10 __newindex = function(self, key, value) _M[key] = value end
11 })
13 -- function that encodes certain HTML entities:
14 -- (not used by the library itself)
15 function encode_html(text)
16 return (
17 string.gsub(
18 text, '[<>&"]',
19 function(char)
20 if char == '<' then
21 return "&lt;"
22 elseif char == '>' then
23 return "&gt;"
24 elseif char == '&' then
25 return "&amp;"
26 elseif char == '"' then
27 return "&quot;"
28 end
29 end
30 )
31 )
33 end
35 -- function that encodes special characters for URIs:
36 -- (not used by the library itself)
37 function encode_uri(text)
38 return (
39 string.gsub(text, "[^0-9A-Za-z_%.~-]",
40 function (char)
41 return string.format("%%%02x", string.byte(char))
42 end
43 )
44 )
45 end
47 -- function undoing URL encoding:
48 do
49 local b0 = string.byte("0")
50 local b9 = string.byte("9")
51 local bA = string.byte("A")
52 local bF = string.byte("F")
53 local ba = string.byte("a")
54 local bf = string.byte("f")
55 function decode_uri(str)
56 return (
57 string.gsub(
58 string.gsub(str, "%+", " "),
59 "%%([0-9A-Fa-f][0-9A-Fa-f])",
60 function(hex)
61 local n1, n2 = string.byte(hex, 1, 2)
62 if n1 >= b0 and n1 <= b9 then n1 = n1 - b0
63 elseif n1 >= bA and n1 <= bF then n1 = n1 - bA + 10
64 elseif n1 >= ba and n1 <= bf then n1 = n1 - ba + 10
65 else error("Assertion failed") end
66 if n2 >= b0 and n2 <= b9 then n2 = n2 - b0
67 elseif n2 >= bA and n2 <= bF then n2 = n2 - bA + 10
68 elseif n2 >= ba and n2 <= bf then n2 = n2 - ba + 10
69 else error("Assertion failed") end
70 return string.char(n1 * 16 + n2)
71 end
72 )
73 )
74 end
75 end
77 -- status codes that carry no response body (in addition to 1xx):
78 -- (set to "zero_content_length" if Content-Length header is required)
79 status_without_response_body = {
80 ["101"] = true, -- list 101 to allow protocol switch
81 ["204"] = true,
82 ["205"] = "zero_content_length",
83 ["304"] = true
84 }
86 -- handling of GET/POST param tables:
87 local new_params_list -- defined later
88 do
89 local params_list_mapping = setmetatable({}, {__mode="k"})
90 local params_list_metatable = {
91 __index = function(self, key)
92 local tbl = {}
93 self[key] = tbl
94 return tbl
95 end
96 }
97 local params_metatable = {
98 __index = function(self, key)
99 local value = params_list_mapping[self][key][1]
100 self[key] = value
101 return value
102 end
103 }
104 -- returns a table to store key value-list pairs (i.e. multiple values),
105 -- and a second table automatically mapping keys to the first value
106 -- using the key value-list pairs in the first table:
107 new_params_list = function()
108 local params_list = setmetatable({}, params_list_metatable)
109 local params = setmetatable({}, params_metatable)
110 params_list_mapping[params] = params_list
111 return params_list, params
112 end
113 end
114 -- parses URL encoded form data and stores it in
115 -- a key value-list pairs structure that has to be
116 -- previously obtained by calling by new_params_list():
117 local function read_urlencoded_form(tbl, data)
118 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
119 local subtbl = tbl[decode_uri(rawkey)]
120 subtbl[#subtbl+1] = decode_uri(rawvalue)
121 end
122 end
124 -- function creating a HTTP handler:
125 function generate_handler(handler, options)
126 -- swap arguments if necessary (for convenience):
127 if type(handler) ~= "function" and type(options) == "function" then
128 handler, options = options, handler
129 end
130 -- process options:
131 options = options or {}
132 local preamble = "" -- preamble sent with every(!) HTTP response
133 do
134 -- named arg "static_headers" is used to create the preamble:
135 local s = options.static_headers
136 local t = {}
137 if s then
138 if type(s) == "string" then
139 for line in string.gmatch(s, "[^\r\n]+") do
140 t[#t+1] = line
141 end
142 else
143 for i, kv in ipairs(options.static_headers) do
144 if type(kv) == "string" then
145 t[#t+1] = kv
146 else
147 t[#t+1] = kv[1] .. ": " .. kv[2]
148 end
149 end
150 end
151 end
152 t[#t+1] = ""
153 preamble = table.concat(t, "\r\n")
154 end
155 -- return connect handler:
156 return function(socket)
157 local survive = true -- set to false if process shall be terminated later
158 repeat
159 -- desired chunk sizes:
160 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
161 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
162 -- process named arguments "request_header_size_limit" and "request_body_size_limit":
163 local remaining_header_size_limit = options.request_header_size_limit or 1024*1024
164 local remaining_body_size_limit = options.request_body_size_limit or 64*1024*1024
165 -- state variables for request handling:
166 local output_state = "no_status_sent" -- one of:
167 -- "no_status_sent" (initial state)
168 -- "info_status_sent" (1xx status code has been sent)
169 -- "bodyless_status_sent" (204/304 status code has been sent)
170 -- "status_sent" (regular status code has been sent)
171 -- "headers_sent" (headers have been terminated)
172 -- "finished" (request has been answered completely)
173 local content_length -- value of Content-Length header sent
174 local bytes_sent = 0 -- number of bytes sent if Content-Length is set
175 local chunk_parts = {} -- list of chunks to send
176 local chunk_bytes = 0 -- sum of lengths of chunks to send
177 local connection_close_requested = false
178 local connection_close_responded = false
179 local headers_value_nil = {} -- header values that are nil
180 local request_body_content_length -- Content-Length of request body
181 local input_state = "pending" -- one of:
182 -- "pending" (request body has not been processed yet)
183 -- "deferred" (request body processing is deferred)
184 -- "reading" (request body is currently being read)
185 -- "finished" (request body has been read)
186 local streamed_post_params = {} -- mapping from POST field name to stream function
187 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
188 -- object passed to handler (with methods, GET/POST params, etc.):
189 local request
190 -- reads a number of bytes from the socket,
191 -- optionally feeding these bytes chunk-wise
192 -- into a callback function:
193 local function read_body_bytes(remaining, callback)
194 while remaining > 0 do
195 local limit
196 if remaining > input_chunk_size then
197 limit = input_chunk_size
198 else
199 limit = remaining
200 end
201 local chunk = socket:read(limit)
202 if not chunk or #chunk ~= limit then
203 error("Unexpected EOF while reading chunk of request body")
204 end
205 remaining = remaining - limit
206 if callback then
207 callback(chunk)
208 end
209 end
210 end
211 -- flushes or closes the socket (depending on
212 -- whether "Connection: close" header was sent):
213 local function finish_response()
214 if connection_close_responded then
215 -- close output stream:
216 socket.output:close()
217 -- wait for EOF of peer to avoid immediate TCP RST condition:
218 timeout(2, function()
219 while socket.input:read(input_chunk_size) do end
220 end)
221 -- fully close socket:
222 socket:close()
223 else
224 socket:flush()
225 request:stream_request_body()
226 end
227 end
228 -- writes out buffered chunks (without flushing the socket):
229 local function send_chunk()
230 if chunk_bytes > 0 then
231 socket:write(string.format("%x\r\n", chunk_bytes))
232 for i = 1, #chunk_parts do
233 socket:write(chunk_parts[i])
234 end
235 chunk_parts = {}
236 chunk_bytes = 0
237 socket:write("\r\n")
238 end
239 end
240 -- terminate header section in response, optionally flushing:
241 -- (may be called multiple times unless response is finished)
242 local function finish_headers(flush)
243 if output_state == "no_status_sent" then
244 error("HTTP status has not been sent yet")
245 elseif output_state == "finished" then
246 error("Response has already been finished")
247 elseif output_state == "info_status_sent" then
248 socket:write("\r\n")
249 socket:flush()
250 output_state = "no_status_sent"
251 elseif output_state == "bodyless_status_sent" then
252 if connection_close_requested and not connection_close_responded then
253 request:send_header("Connection", "close")
254 end
255 socket:write("\r\n")
256 finish_response()
257 output_state = "finished"
258 elseif output_state == "status_sent" then
259 if not content_length then
260 socket:write("Transfer-Encoding: chunked\r\n")
261 end
262 if connection_close_requested and not connection_close_responded then
263 request:send_header("Connection", "close")
264 end
265 socket:write("\r\n")
266 if request.method == "HEAD" then
267 finish_response()
268 elseif flush then
269 socket:flush()
270 end
271 output_state = "headers_sent"
272 elseif output_state ~= "headers_sent" then
273 error("Unexpected internal status in HTTP engine")
274 end
275 end
276 -- create request object and set several functions and values:
277 request = {
278 -- allow raw socket access:
279 socket = socket,
280 -- parsed cookies:
281 cookies = {},
282 -- send a HTTP response status (e.g. "200 OK"):
283 send_status = function(self, value)
284 if input_state == "pending" then
285 request:process_request_body()
286 end
287 if output_state == "info_status_sent" then
288 socket:write("\r\n")
289 socket:flush()
290 elseif output_state ~= "no_status_sent" then
291 error("HTTP status has already been sent")
292 end
293 local status1 = string.sub(value, 1, 1)
294 local status3 = string.sub(value, 1, 3)
295 socket:write("HTTP/1.1 ", value, "\r\n", preamble)
296 local without_response_body = status_without_response_body[status3]
297 if without_response_body then
298 output_state = "bodyless_status_sent"
299 if without_response_body == "zero_content_length" then
300 request:send_header("Content-Length", 0)
301 end
302 elseif status1 == "1" then
303 output_state = "info_status_sent"
304 else
305 output_state = "status_sent"
306 end
307 end,
308 -- send a HTTP response header
309 -- (key and value as separate args):
310 send_header = function(self, key, value)
311 if output_state == "no_status_sent" then
312 error("HTTP status has not been sent yet")
313 elseif
314 output_state ~= "info_status_sent" and
315 output_state ~= "bodyless_status_sent" and
316 output_state ~= "status_sent"
317 then
318 error("All HTTP headers have already been sent")
319 end
320 local key_lower = string.lower(key)
321 if key_lower == "content-length" then
322 if output_state == "info_status_sent" then
323 error("Cannot set Content-Length for informational status response")
324 end
325 local new_content_length = assert(tonumber(value), "Invalid content-length")
326 if content_length == nil then
327 content_length = new_content_length
328 elseif content_length == new_content_length then
329 return
330 else
331 error("Content-Length has been set multiple times with different values")
332 end
333 elseif key_lower == "connection" then
334 for entry in string.gmatch(string.lower(value), "[^,]+") do
335 if string.match(entry, "^[ \t]*close[ \t]*$") then
336 if output_state == "info_status_sent" then
337 error("Cannot set \"Connection: close\" for informational status response")
338 end
339 if connection_close_responded then
340 return
341 else
342 connection_close_responded = true
343 break
344 end
345 end
346 end
347 end
348 socket:write(key, ": ", value, "\r\n")
349 end,
350 -- method to finish and flush headers:
351 finish_headers = function()
352 finish_headers(true)
353 end,
354 -- send data for response body:
355 send_data = function(self, ...)
356 if output_state == "info_status_sent" then
357 error("No (non-informational) HTTP status has been sent yet")
358 elseif output_state == "bodyless_status_sent" then
359 error("Cannot send response data for body-less status message")
360 end
361 finish_headers(false)
362 if output_state ~= "headers_sent" then
363 error("Unexpected internal status in HTTP engine")
364 end
365 if request.method == "HEAD" then
366 return
367 end
368 for i = 1, select("#", ...) do
369 local str = tostring(select(i, ...))
370 if #str > 0 then
371 if content_length then
372 local bytes_to_send = #str
373 if bytes_sent + bytes_to_send > content_length then
374 socket:write(string.sub(str, 1, content_length - bytes_sent))
375 bytes_sent = content_length
376 error("Content length exceeded")
377 else
378 socket:write(str)
379 bytes_sent = bytes_sent + bytes_to_send
380 end
381 else
382 chunk_bytes = chunk_bytes + #str
383 chunk_parts[#chunk_parts+1] = str
384 end
385 end
386 end
387 if chunk_bytes >= output_chunk_size then
388 send_chunk()
389 end
390 end,
391 -- flush output buffer:
392 flush = function(self)
393 send_chunk()
394 socket:flush()
395 end,
396 -- finish response:
397 finish = function(self)
398 if output_state == "finished" then
399 return
400 elseif output_state == "info_status_sent" then
401 error("Informational HTTP response can be finished with :finish_headers() method")
402 end
403 finish_headers(false)
404 if output_state == "headers_sent" then
405 if request.method ~= "HEAD" then
406 if content_length then
407 if bytes_sent ~= content_length then
408 error("Content length not used")
409 end
410 else
411 send_chunk()
412 socket:write("0\r\n\r\n")
413 end
414 finish_response()
415 end
416 output_state = "finished"
417 elseif output_state ~= "finished" then
418 error("Unexpected internal status in HTTP engine")
419 end
420 end,
421 -- table mapping header field names to value-lists
422 -- (raw access):
423 headers = setmetatable({}, {
424 __index = function(self, key)
425 local lowerkey = string.lower(key)
426 if lowerkey == key then
427 return
428 end
429 local result = rawget(self, lowerkey)
430 if result == nil then
431 result = {}
432 end
433 self[lowerkey] = result
434 self[key] = result
435 return result
436 end
437 }),
438 -- table mapping header field names to value-lists
439 -- (for headers with comma separated values):
440 headers_csv_table = setmetatable({}, {
441 __index = function(self, key)
442 local result = {}
443 for i, line in ipairs(request.headers[key]) do
444 for entry in string.gmatch(line, "[^,]+") do
445 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
446 if value then
447 result[#result+1] = value
448 end
449 end
450 end
451 self[key] = result
452 return result
453 end
454 }),
455 -- table mapping header field names to a comma separated string
456 -- (for headers with comma separated values):
457 headers_csv_string = setmetatable({}, {
458 __index = function(self, key)
459 local result = {}
460 for i, line in ipairs(request.headers[key]) do
461 result[#result+1] = line
462 end
463 result = string.concat(result, ", ")
464 self[key] = result
465 return result
466 end
467 }),
468 -- table mapping header field names to a single string value
469 -- (or false if header has been sent multiple times):
470 headers_value = setmetatable({}, {
471 __index = function(self, key)
472 if headers_value_nil[key] then
473 return nil
474 end
475 local result = nil
476 local values = request.headers_csv_table[key]
477 if #values == 0 then
478 headers_value_nil[key] = true
479 elseif #values == 1 then
480 result = values[1]
481 else
482 result = false
483 end
484 self[key] = result
485 return result
486 end
487 }),
488 -- table mapping header field names to a flag table,
489 -- indicating if the comma separated value contains certain entries:
490 headers_flags = setmetatable({}, {
491 __index = function(self, key)
492 local result = setmetatable({}, {
493 __index = function(self, key)
494 local lowerkey = string.lower(key)
495 local result = rawget(self, lowerkey) or false
496 self[lowerkey] = result
497 self[key] = result
498 return result
499 end
500 })
501 for i, value in ipairs(request.headers_csv_table[key]) do
502 result[string.lower(value)] = true
503 end
504 self[key] = result
505 return result
506 end
507 }),
508 -- register POST param stream handler for a single field name:
509 stream_post_param = function(self, field_name, callback)
510 if input_state == "inprogress" or input_state == "finished" then
511 error("Cannot register POST param streaming function if request body is already processed")
512 end
513 streamed_post_params[field_name] = callback
514 end,
515 -- register POST param stream handler for a field name pattern:
516 stream_post_params = function(self, pattern, callback)
517 if input_state == "inprogress" or input_state == "finished" then
518 error("Cannot register POST param streaming function if request body is already processed")
519 end
520 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
521 end,
522 -- disables automatic request body processing on write
523 -- (use with caution):
524 defer_reading = function(self)
525 if input_state == "pending" then
526 input_state = "deferred"
527 end
528 end,
529 -- processes the request body and sets the request.post_params,
530 -- request.post_params_list, request.meta_post_params, and
531 -- request.meta_post_params_list values (can be called manually or
532 -- automatically if post_params are accessed or data is written out)
533 process_request_body = function(self)
534 if input_state == "finished" then
535 return
536 end
537 local post_params_list, post_params = new_params_list()
538 local content_type = request.headers_value["Content-Type"]
539 if content_type then
540 if
541 content_type == "application/x-www-form-urlencoded" or
542 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
543 then
544 read_urlencoded_form(post_params_list, request.body)
545 else
546 local boundary = string.match(
547 content_type,
548 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
549 ) or string.match(
550 content_type,
551 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
552 )
553 if boundary then
554 local post_metadata_list, post_metadata = new_params_list()
555 boundary = "--" .. boundary
556 local headerdata = ""
557 local streamer
558 local field_name
559 local metadata = {}
560 local value_parts
561 local function default_streamer(chunk)
562 value_parts[#value_parts+1] = chunk
563 end
564 local function stream_part_finish()
565 if streamer == default_streamer then
566 local value = table.concat(value_parts)
567 value_parts = nil
568 if field_name then
569 local values = post_params_list[field_name]
570 values[#values+1] = value
571 local metadata_entries = post_metadata_list[field_name]
572 metadata_entries[#metadata_entries+1] = metadata
573 end
574 else
575 streamer()
576 end
577 headerdata = ""
578 streamer = nil
579 field_name = nil
580 metadata = {}
581 end
582 local function stream_part_chunk(chunk)
583 if streamer then
584 streamer(chunk)
585 else
586 headerdata = headerdata .. chunk
587 while true do
588 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
589 if not line then
590 break
591 end
592 if line == "" then
593 streamer = streamed_post_params[field_name]
594 if not streamer then
595 for i, rule in ipairs(streamed_post_param_patterns) do
596 if string.match(field_name, rule[1]) then
597 streamer = rule[2]
598 break
599 end
600 end
601 end
602 if not streamer then
603 value_parts = {}
604 streamer = default_streamer
605 end
606 streamer(remaining, field_name, metadata)
607 return
608 end
609 headerdata = remaining
610 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
611 if not header_key then
612 error("Invalid header in multipart/form-data part")
613 end
614 header_key = string.lower(header_key)
615 if header_key == "content-disposition" then
616 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
617 return string.gsub(str, "=", "==")
618 end)
619 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
620 if field_name then
621 field_name = string.gsub(field_name, "==", "=")
622 else
623 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
624 end
625 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
626 if metadata.file_name then
627 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
628 else
629 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
630 end
631 elseif header_key == "content-type" then
632 metadata.content_type = header_value
633 elseif header_key == "content-transfer-encoding" then
634 error("Content-transfer-encoding not supported by multipart/form-data parser")
635 end
636 end
637 end
638 end
639 local skippart = true -- ignore data until first boundary
640 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
641 local terminated = false -- final boundary read
642 local bigchunk = ""
643 request:stream_request_body(function(chunk)
644 if terminated then
645 return
646 end
647 bigchunk = bigchunk .. chunk
648 while true do
649 if afterbound then
650 if #bigchunk <= 2 then
651 return
652 end
653 local terminator = string.sub(bigchunk, 1, 2)
654 if terminator == "\r\n" then
655 afterbound = false
656 bigchunk = string.sub(bigchunk, 3)
657 elseif terminator == "--" then
658 terminated = true
659 bigchunk = nil
660 return
661 else
662 error("Error while parsing multipart body (expected CRLF or double minus)")
663 end
664 end
665 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
666 if not pos1 then
667 if not skippart then
668 local safe = #bigchunk-#boundary
669 if safe > 0 then
670 stream_part_chunk(string.sub(bigchunk, 1, safe))
671 bigchunk = string.sub(bigchunk, safe+1)
672 end
673 end
674 return
675 end
676 if not skippart then
677 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
678 stream_part_finish()
679 else
680 boundary = "\r\n" .. boundary
681 skippart = false
682 end
683 bigchunk = string.sub(bigchunk, pos2 + 1)
684 afterbound = true
685 end
686 end)
687 if not terminated then
688 error("Premature end of multipart/form-data request body")
689 end
690 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
691 else
692 error("Unknown Content-Type of request body")
693 end
694 end
695 end
696 request.post_params_list, request.post_params = post_params_list, post_params
697 end,
698 -- stream request body to an (optional) callback function
699 -- without processing it otherwise:
700 stream_request_body = function(self, callback)
701 if input_state ~= "pending" and input_state ~= "deferred" then
702 if callback then
703 if input_state == "inprogress" then
704 error("Request body is already being processed")
705 else
706 error("Request body has already been processed")
707 end
708 end
709 return
710 end
711 input_state = "inprogress"
712 if request.headers_flags["Expect"]["100-continue"] then
713 request:send_status("100 Continue")
714 request:finish_headers()
715 end
716 if request.headers_flags["Transfer-Encoding"]["chunked"] then
717 while true do
718 local line = socket:readuntil("\n", 32 + remaining_body_size_limit)
719 if not line then
720 error("Unexpected EOF while reading next chunk of request body")
721 end
722 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
723 local chunkext
724 if lenstr then
725 chunkext = ""
726 else
727 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
728 end
729 if not lenstr or #lenstr > 13 then
730 error("Encoding error or unexpected EOF while reading chunk of request body")
731 end
732 local len = tonumber("0x" .. lenstr)
733 remaining_body_size_limit = remaining_body_size_limit - (#zeros + #chunkext + len)
734 if remaining_body_size_limit < 0 then
735 error("Request body size limit exceeded")
736 end
737 if len == 0 then break end
738 read_body_bytes(len, callback)
739 local term = socket:readuntil("\n", 2)
740 if term ~= "\r\n" and term ~= "\n" then
741 error("Encoding error while reading chunk of request body")
742 end
743 end
744 while true do
745 local line = socket:readuntil("\n", 2 + remaining_body_size_limit)
746 if line == "\r\n" or line == "\n" then break end
747 remaining_body_size_limit = remaining_body_size_limit - #line
748 if remaining_body_size_limit < 0 then
749 error("Request body size limit exceeded while reading trailer section of chunked request body")
750 end
751 end
752 elseif request_body_content_length then
753 read_body_bytes(request_body_content_length, callback)
754 end
755 input_state = "finished"
756 end
757 }
758 -- initialize tables for GET params in request object:
759 request.get_params_list, request.get_params = new_params_list()
760 -- add meta table to request object to allow access to "body" and POST params:
761 setmetatable(request, {
762 __index = function(self, key)
763 if key == "body" then
764 local chunks = {}
765 request:stream_request_body(function(chunk)
766 chunks[#chunks+1] = chunk
767 end)
768 self.body = table.concat(chunks)
769 return self.body
770 elseif
771 key == "post_params_list" or key == "post_params" or
772 key == "post_metadata_list" or key == "post_metadata"
773 then
774 request:process_request_body()
775 return request[key]
776 end
777 end
778 })
779 -- sends a minimalistic error response and enforces closing of the
780 -- connection and returns the boolean value "survive"
781 local function error_response(...)
782 request:send_status(status)
783 request:send_header("Content-Type", "text/plain")
784 request:send_header("Connection", "close")
785 request:send_data(status, "\n")
786 if text then
787 request:send_data("\n", text, "\n")
788 end
789 request:finish()
790 return survive
791 end
792 -- read and parse request line:
793 local line = socket:readuntil("\n", remaining_header_size_limit)
794 if not line then return survive end
795 remaining_header_size_limit = remaining_header_size_limit - #line
796 if remaining_header_size_limit == 0 then
797 return error_response("413 Request Entity Too Large", "Request line too long")
798 end
799 local target, proto
800 request.method, target, proto =
801 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
802 if not request.method then
803 return error_response("400 Bad Request")
804 elseif proto ~= "HTTP/1.1" then
805 return error_response("505 HTTP Version Not Supported")
806 else
807 -- read and parse headers:
808 while true do
809 local line = socket:readuntil("\n", remaining_header_size_limit);
810 remaining_header_size_limit = remaining_header_size_limit - #line
811 if not line then
812 return error_response("400 Bad Request")
813 end
814 if line == "\r\n" or line == "\n" then
815 break
816 end
817 if remaining_header_size_limit == 0 then
818 return error_response("413 Request Entity Too Large", "Headers too long")
819 end
820 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
821 if not key then
822 return error_response("400 Bad Request")
823 end
824 local values = request.headers[key]
825 values[#values+1] = value
826 end
827 -- process "Connection: close" header if existent:
828 connection_close_requested = request.headers_flags["Connection"]["close"]
829 -- process "Content-Length" header if existent:
830 do
831 local values = request.headers_csv_table["Content-Length"]
832 if #values > 0 then
833 request_body_content_length = tonumber(values[1])
834 local proper_value = tostring(request_body_content_length)
835 for i, value in ipairs(values) do
836 value = string.match(value, "^0*(.*)")
837 if value ~= proper_value then
838 return error_response("400 Bad Request", "Content-Length header(s) invalid")
839 end
840 end
841 if request_body_content_length > remaining_body_size_limit then
842 return error_response("413 Request Entity Too Large", "Request body too big")
843 end
844 end
845 end
846 -- process "Transfer-Encoding" header if existent:
847 do
848 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
849 local list = request.headers_csv_table["Transfer-Encoding"]
850 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
851 return error_response("400 Bad Request", "Unexpected Transfer-Encoding")
852 end
853 end
854 -- process "Expect" header if existent:
855 for i, value in ipairs(request.headers_csv_table["Expect"]) do
856 if string.lower(value) ~= "100-continue" then
857 return error_response("417 Expectation Failed", "Unexpected Expect header")
858 end
859 end
860 -- get mandatory Host header according to RFC 7230:
861 request.host = request.headers_value["Host"]
862 if not request.host then
863 return error_response("400 Bad Request", "No valid host header")
864 end
865 -- parse request target:
866 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
867 if not request.path then
868 local host2
869 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
870 if host2 then
871 if request.host ~= host2 then
872 return error_response("400 Bad Request", "No valid host header")
873 end
874 elseif not (target == "*" and request.method == "OPTIONS") then
875 return error_response("400 Bad Request", "Invalid request target")
876 end
877 end
878 -- parse GET params:
879 if request.query then
880 read_urlencoded_form(request.get_params_list, request.query)
881 end
882 -- parse cookies:
883 for i, line in ipairs(request.headers["Cookie"]) do
884 for rawkey, rawvalue in
885 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
886 do
887 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
888 end
889 end
890 -- call underlying handler and remember boolean result:
891 if handler(request) ~= true then survive = false end
892 -- finish request (unless already done by underlying handler):
893 request:finish()
894 end
895 until connection_close_responded
896 return survive
897 end
898 end
900 return _M

Impressum / About Us