moonbridge

view moonbridge_http.lua @ 45:ab51824e139b

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

Impressum / About Us