moonbridge

view moonbridge_http.lua @ 84:8a6e2a80fcad

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

Impressum / About Us