moonbridge

view moonbridge_http.lua @ 71:4628be0a7b98

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

Impressum / About Us