moonbridge

view moonbridge_http.lua @ 44:e835cda61478

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

Impressum / About Us