moonbridge

view moonbridge_http.lua @ 180:31820816f554

Code cleanup and added "request_body_content_length" declaration in HTTP module
author jbe
date Fri Jun 19 00:44:01 2015 +0200 (2015-06-19)
parents 77d8fdd124e6
children f0dc143f510a
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 while true do
104 key = next(tbl, key)
105 if key == nil then
106 return nil
107 end
108 local value = tbl[key][1]
109 if value ~= nil then
110 return key, value
111 end
112 end
113 end
114 local params_list_metatable = {
115 __index = function(self, key)
116 local tbl = {}
117 self[key] = tbl
118 return tbl
119 end,
120 __pairs = function(self)
121 return nextnonempty, self, nil
122 end
123 }
124 local params_metatable = {
125 __index = function(self, key)
126 return params_list_mapping[self][key][1]
127 end,
128 __newindex = function(self, key, value)
129 params_list_mapping[self][key] = {value}
130 end,
131 __pairs = function(self)
132 return nextvalue, params_list_mapping[self], nil
133 end
134 }
135 -- function that returns a table to store key value-list pairs,
136 -- and a second table automatically mapping keys to the first value
137 -- using the key value-list pairs in the first table:
138 new_params_list = function()
139 local params_list = setmetatable({}, params_list_metatable)
140 local params = setmetatable({}, params_metatable)
141 params_list_mapping[params] = params_list
142 return params_list, params
143 end
144 end
146 -- function parsing URL encoded form data and storing it in
147 -- a key value-list pairs structure that has to be
148 -- previously obtained by calling by new_params_list():
149 local function read_urlencoded_form(tbl, data)
150 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
151 local subtbl = tbl[decode_uri(rawkey)]
152 subtbl[#subtbl+1] = decode_uri(rawvalue)
153 end
154 end
156 -- function to convert a HTTP request handler to a socket handler:
157 function generate_handler(handler, options)
158 -- swap arguments if necessary (for convenience):
159 if type(handler) ~= "function" and type(options) == "function" then
160 handler, options = options, handler
161 end
162 -- helper function to process options:
163 local function default(name, default_value)
164 local value = options[name]
165 if value == nil then
166 return default_value
167 else
168 return value or nil
169 end
170 end
171 -- process options:
172 options = options or {}
173 local preamble = "" -- preamble sent with every(!) HTTP response
174 do
175 -- named arg "static_headers" is used to create the preamble:
176 local s = options.static_headers
177 local t = {}
178 if s then
179 if type(s) == "string" then
180 for line in string.gmatch(s, "[^\r\n]+") do
181 t[#t+1] = line
182 end
183 else
184 for i, kv in ipairs(s) do
185 if type(kv) == "string" then
186 t[#t+1] = kv
187 else
188 t[#t+1] = kv[1] .. ": " .. kv[2]
189 end
190 end
191 end
192 end
193 t[#t+1] = ""
194 preamble = table.concat(t, "\r\n")
195 end
196 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
197 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
198 local header_size_limit = options.header_size_limit or 1024*1024
199 local body_size_limit = options.body_size_limit or 64*1024*1024
200 local request_idle_timeout = default("request_idle_timeout", 65)
201 local request_header_timeout = default("request_header_timeout", 30)
202 local request_body_timeout = default("request_body_timeout", 300)
203 local response_timeout = default("response_timeout", 1800)
204 local poll = options.poll_function or moonbridge_io.poll
205 -- return socket handler:
206 return function(socket)
207 local socket_set = {[socket] = true} -- used for poll function
208 local survive = true -- set to false if process shall be terminated later
209 local consume -- can be set to function that reads some input if possible
210 -- function that may be used as "consume" function
211 -- and which drains some input if possible:
212 local function drain()
213 local bytes, status = socket:drain_nb(input_chunk_size)
214 if not bytes or status == "eof" then
215 consume = nil
216 end
217 end
218 -- function trying to unblock socket by reading:
219 local function unblock()
220 if consume then
221 poll(socket_set, socket_set)
222 consume()
223 else
224 poll(nil, socket_set)
225 end
226 end
227 -- function that enforces consumption of all input:
228 local function consume_all()
229 while consume do
230 poll(socket_set, nil)
231 consume()
232 end
233 end
234 -- handle requests in a loop:
235 repeat
236 -- table for caching nil values:
237 local headers_value_nil = {}
238 -- create a new request object (methods are added later):
239 local request -- allow references to local variable
240 request = {
241 -- allow access to underlying socket:
242 socket = socket,
243 -- cookies are simply stored in a table:
244 cookies = {},
245 -- table mapping header field names to value-lists
246 -- (raw access, but case-insensitive):
247 headers = setmetatable({}, {
248 __index = function(self, key)
249 assert(type(key) == "string", "Attempted to index headers table with a non-string key")
250 local lowerkey = string.lower(key)
251 local result = rawget(self, lowerkey)
252 if result == nil then
253 result = {}
254 rawset(self, lowerkey, result)
255 end
256 rawset(self, key, result)
257 return result
258 end
259 }),
260 -- table mapping header field names to value-lists
261 -- (for headers with comma separated values):
262 headers_csv_table = setmetatable({}, {
263 __index = function(self, key)
264 local result = {}
265 for i, line in ipairs(request.headers[key]) do
266 for entry in string.gmatch(line, "[^,]+") do
267 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
268 if value then
269 result[#result+1] = value
270 end
271 end
272 end
273 self[key] = result
274 return result
275 end
276 }),
277 -- table mapping header field names to a comma separated string
278 -- (for headers with comma separated values):
279 headers_csv_string = setmetatable({}, {
280 __index = function(self, key)
281 local result = {}
282 for i, line in ipairs(request.headers[key]) do
283 result[#result+1] = line
284 end
285 result = table.concat(result, ", ")
286 self[key] = result
287 return result
288 end
289 }),
290 -- table mapping header field names to a single string value
291 -- (or false if header has been sent multiple times):
292 headers_value = setmetatable({}, {
293 __index = function(self, key)
294 if headers_value_nil[key] then
295 return nil
296 end
297 local values = request.headers_csv_table[key]
298 if #values == 0 then
299 headers_value_nil[key] = true
300 else
301 local result
302 if #values == 1 then
303 result = values[1]
304 else
305 result = false
306 end
307 self[key] = result
308 return result
309 end
310 end
311 }),
312 -- table mapping header field names to a flag table,
313 -- indicating if the comma separated value contains certain entries:
314 headers_flags = setmetatable({}, {
315 __index = function(self, key)
316 local result = setmetatable({}, {
317 __index = function(self, key)
318 assert(type(key) == "string", "Attempted to index header flag table with a non-string key")
319 local lowerkey = string.lower(key)
320 local result = rawget(self, lowerkey) or false
321 self[lowerkey] = result
322 self[key] = result
323 return result
324 end
325 })
326 for i, value in ipairs(request.headers_csv_table[key]) do
327 result[string.lower(value)] = true
328 end
329 self[key] = result
330 return result
331 end
332 })
333 }
334 -- create metatable for request object:
335 local request_mt = {}
336 setmetatable(request, request_mt)
337 -- callback for request body streaming:
338 local process_body_chunk
339 -- local variables to track the state:
340 local state = "init" -- one of:
341 -- "init" (initial state)
342 -- "no_status_sent" (request body streaming config complete)
343 -- "info_status_sent" (1xx status code has been sent)
344 -- "bodyless_status_sent" (204/304 status code has been sent)
345 -- "status_sent" (regular status code has been sent)
346 -- "headers_sent" (headers have been terminated)
347 -- "finished" (request has been answered completely)
348 -- "faulty" (I/O or protocaol error)
349 local request_body_content_length -- Content-Length of request body
350 local close_requested = false -- "Connection: close" requested
351 local close_responded = false -- "Connection: close" sent
352 local content_length = nil -- value of Content-Length header sent
353 local chunk_parts = {} -- list of chunks to send
354 local chunk_bytes = 0 -- sum of lengths of chunks to send
355 local streamed_post_params = {} -- mapping from POST field name to stream function
356 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
357 -- functions to assert proper output/closing:
358 local function assert_output(...)
359 local retval, errmsg = ...
360 if retval then return ... end
361 state = "faulty"
362 socket:reset()
363 error("Could not send data to client: " .. errmsg)
364 end
365 local function assert_close(...)
366 local retval, errmsg = ...
367 if retval then return ... end
368 state = "faulty"
369 error("Could not finish sending data to client: " .. errmsg)
370 end
371 -- function to assert non-faulty handle:
372 local function assert_not_faulty()
373 assert(state ~= "faulty", "Tried to use faulty request handle")
374 end
375 -- functions to send data to the browser:
376 local function send(...)
377 assert_output(socket:write_call(unblock, ...))
378 end
379 local function send_flush(...)
380 assert_output(socket:flush_call(unblock, ...))
381 end
382 -- function to finish request:
383 local function finish()
384 if close_responded then
385 -- discard any input:
386 consume = drain
387 -- close output stream:
388 send_flush()
389 assert_close(socket:finish())
390 -- wait for EOF of peer to avoid immediate TCP RST condition:
391 consume_all()
392 -- fully close socket:
393 assert_close(socket:close())
394 else
395 send_flush()
396 process_body_chunk = nil
397 consume_all()
398 end
399 end
400 -- function that writes out buffered chunks (without flushing the socket):
401 function send_chunk()
402 if chunk_bytes > 0 then
403 assert_output(socket:write(string.format("%x\r\n", chunk_bytes)))
404 for i = 1, #chunk_parts do -- TODO: evaluated only once?
405 send(chunk_parts[i])
406 chunk_parts[i] = nil
407 end
408 chunk_bytes = 0
409 send("\r\n")
410 end
411 end
412 -- function to report an error:
413 local function request_error(throw_error, status, text)
414 local errmsg = "Error while reading request from client. Error response: " .. status
415 if text then
416 errmsg = errmsg .. " (" .. text .. ")"
417 end
418 if
419 state == "init" or
420 state == "no_status_sent" or
421 state == "info_status_sent"
422 then
423 local error_response_status, errmsg2 = pcall(function()
424 request:monologue()
425 request:send_status(status)
426 request:send_header("Content-Type", "text/plain")
427 request:send_data(status, "\n")
428 if text then
429 request:send_data("\n", text, "\n")
430 end
431 request:finish()
432 end)
433 if not error_response_status then
434 error("Unexpected error while sending error response: " .. errmsg2)
435 end
436 elseif state ~= "faulty" then
437 state = "faulty"
438 assert_close(socket:reset())
439 end
440 if throw_error then
441 error(errmsg)
442 else
443 return survive
444 end
445 end
446 -- read functions
447 local function read(...)
448 local data, status = socket:read_yield(...)
449 if data == nil then
450 request_error(true, "400 Bad Request", "Read error")
451 end
452 if status == "eof" then
453 request_error(true, "400 Bad Request", "Unexpected EOF")
454 end
455 return data
456 end
457 local function read_eof(...)
458 local data, status = socket:read_yield(...)
459 if data == nil then
460 request_error(true, "400 Bad Request", "Read error")
461 end
462 if status == "eof" then
463 if data == "" then
464 return nil
465 else
466 request_error(true, "400 Bad Request", "Unexpected EOF")
467 end
468 end
469 return data
470 end
471 -- reads a number of bytes from the socket,
472 -- optionally feeding these bytes chunk-wise
473 -- into a callback function:
474 local function read_body_bytes(remaining)
475 while remaining > 0 do
476 local limit
477 if remaining > input_chunk_size then
478 limit = input_chunk_size
479 else
480 limit = remaining
481 end
482 local chunk = read(limit)
483 remaining = remaining - limit
484 if process_body_chunk then
485 process_body_chunk(chunk)
486 end
487 end
488 end
489 -- coroutine for request body processing:
490 local function read_body()
491 if request.headers_flags["Transfer-Encoding"]["chunked"] then
492 local limit = body_size_limit
493 while true do
494 local line = read(32 + limit, "\n")
495 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
496 local chunkext
497 if lenstr then
498 chunkext = ""
499 else
500 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
501 end
502 if not lenstr or #lenstr > 13 then
503 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
504 end
505 local len = tonumber("0x" .. lenstr)
506 limit = limit - (#zeros + #chunkext + len)
507 if limit < 0 then
508 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
509 end
510 if len == 0 then break end
511 read_body_bytes(len)
512 local term = read(2, "\n")
513 if term ~= "\r\n" and term ~= "\n" then
514 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
515 end
516 end
517 while true do
518 local line = read(2 + limit, "\n")
519 if line == "\r\n" or line == "\n" then break end
520 limit = limit - #line
521 if limit < 0 then
522 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
523 end
524 end
525 elseif request_body_content_length then
526 read_body_bytes(request_body_content_length)
527 end
528 end
529 -- function to setup default request body handling:
530 local function default_request_body_handling()
531 local post_params_list, post_params = new_params_list()
532 local content_type = request.headers_value["Content-Type"]
533 if content_type then
534 if
535 content_type == "application/x-www-form-urlencoded" or
536 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
537 then
538 read_urlencoded_form(post_params_list, request.body)
539 request.post_params_list, request.post_params = post_params_list, post_params
540 else
541 local boundary = string.match(
542 content_type,
543 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
544 ) or string.match(
545 content_type,
546 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
547 )
548 if boundary then
549 local post_metadata_list, post_metadata = new_params_list()
550 boundary = "--" .. boundary
551 local headerdata = ""
552 local streamer
553 local field_name
554 local metadata = {}
555 local value_parts
556 local function default_streamer(chunk)
557 value_parts[#value_parts+1] = chunk
558 end
559 local function stream_part_finish()
560 if streamer == default_streamer then
561 local value = table.concat(value_parts)
562 value_parts = nil
563 if field_name then
564 local values = post_params_list[field_name]
565 values[#values+1] = value
566 local metadata_entries = post_metadata_list[field_name]
567 metadata_entries[#metadata_entries+1] = metadata
568 end
569 else
570 streamer()
571 end
572 headerdata = ""
573 streamer = nil
574 field_name = nil
575 metadata = {}
576 end
577 local function stream_part_chunk(chunk)
578 if streamer then
579 streamer(chunk)
580 else
581 headerdata = headerdata .. chunk
582 while true do
583 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
584 if not line then
585 break
586 end
587 if line == "" then
588 streamer = streamed_post_params[field_name]
589 if not streamer then
590 for i, rule in ipairs(streamed_post_param_patterns) do
591 if string.match(field_name, rule[1]) then
592 streamer = rule[2]
593 break
594 end
595 end
596 end
597 if not streamer then
598 value_parts = {}
599 streamer = default_streamer
600 end
601 streamer(remaining, field_name, metadata)
602 return
603 end
604 headerdata = remaining
605 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
606 if not header_key then
607 request_error(true, "400 Bad Request", "Invalid header in multipart/form-data part")
608 end
609 header_key = string.lower(header_key)
610 if header_key == "content-disposition" then
611 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
612 return string.gsub(str, "=", "==")
613 end)
614 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
615 if field_name then
616 field_name = string.gsub(field_name, "==", "=")
617 else
618 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
619 end
620 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
621 if metadata.file_name then
622 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
623 else
624 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
625 end
626 elseif header_key == "content-type" then
627 metadata.content_type = header_value
628 elseif header_key == "content-transfer-encoding" then
629 request_error(true, "400 Bad Request", "Content-transfer-encoding not supported by multipart/form-data parser")
630 end
631 end
632 end
633 end
634 local skippart = true -- ignore data until first boundary
635 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
636 local terminated = false -- final boundary read
637 local bigchunk = ""
638 request:set_request_body_streamer(function(chunk)
639 if chunk == nil then
640 if not terminated then
641 request_error(true, "400 Bad Request", "Premature end of multipart/form-data request body")
642 end
643 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
644 end
645 if terminated then
646 return
647 end
648 bigchunk = bigchunk .. chunk
649 while true do
650 if afterbound then
651 if #bigchunk <= 2 then
652 return
653 end
654 local terminator = string.sub(bigchunk, 1, 2)
655 if terminator == "\r\n" then
656 afterbound = false
657 bigchunk = string.sub(bigchunk, 3)
658 elseif terminator == "--" then
659 terminated = true
660 bigchunk = nil
661 return
662 else
663 request_error(true, "400 Bad Request", "Error while parsing multipart body (expected CRLF or double minus)")
664 end
665 end
666 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
667 if not pos1 then
668 if not skippart then
669 local safe = #bigchunk-#boundary
670 if safe > 0 then
671 stream_part_chunk(string.sub(bigchunk, 1, safe))
672 bigchunk = string.sub(bigchunk, safe+1)
673 end
674 end
675 return
676 end
677 if not skippart then
678 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
679 stream_part_finish()
680 else
681 boundary = "\r\n" .. boundary
682 skippart = false
683 end
684 bigchunk = string.sub(bigchunk, pos2 + 1)
685 afterbound = true
686 end
687 end)
688 else
689 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
690 end
691 end
692 end
693 end
694 -- function to prepare body processing:
695 local function prepare()
696 assert_not_faulty()
697 if process_body_chunk == nil then
698 default_request_body_handling()
699 end
700 if state ~= "init" then
701 return
702 end
703 consume = coroutine.wrap(read_body)
704 state = "no_status_sent"
705 if request.headers_flags["Expect"]["100-continue"] then
706 request:send_status("100 Continue")
707 request:finish_headers()
708 end
709 end
710 -- method to ignore input and close connection after response:
711 function request:monologue()
712 assert_not_faulty()
713 if
714 state == "headers_sent" or
715 state == "finished"
716 then
717 error("All HTTP headers have already been sent")
718 end
719 local old_state = state
720 state = "faulty"
721 consume = drain
722 close_requested = true
723 if old_state == "init" then
724 state = "no_status_sent"
725 else
726 state = old_state
727 end
728 end
729 --
730 -- method to send a HTTP response status (e.g. "200 OK"):
731 function request:send_status(status)
732 prepare()
733 local old_state = state
734 state = "faulty"
735 if old_state == "info_status_sent" then
736 send_flush("\r\n")
737 elseif old_state ~= "no_status_sent" then
738 error("HTTP status has already been sent")
739 end
740 local status1 = string.sub(status, 1, 1)
741 local status3 = string.sub(status, 1, 3)
742 send("HTTP/1.1 ", status, "\r\n", preamble)
743 local wrb = status_without_response_body[status3]
744 if wrb then
745 state = "bodyless_status_sent"
746 if wrb == "zero_content_length" then
747 request:send_header("Content-Length", 0)
748 end
749 elseif status1 == "1" then
750 state = "info_status_sent"
751 else
752 state = "status_sent"
753 end
754 end
755 -- method to send a HTTP response header:
756 -- (key and value must be provided as separate args)
757 function request:send_header(key, value)
758 assert_not_faulty()
759 if state == "init" or state == "no_status_sent" then
760 error("HTTP status has not been sent yet")
761 elseif
762 state == "headers_sent" or
763 state == "finished"
764 then
765 error("All HTTP headers have already been sent")
766 end
767 local key_lower = string.lower(key)
768 if key_lower == "content-length" then
769 if state == "info_status_sent" then
770 error("Cannot set Content-Length for informational status response")
771 end
772 local cl = assert(tonumber(value), "Invalid content-length")
773 if content_length == nil then
774 content_length = cl
775 elseif content_length == cl then
776 return
777 else
778 error("Content-Length has been set multiple times with different values")
779 end
780 elseif key_lower == "connection" then
781 for entry in string.gmatch(string.lower(value), "[^,]+") do
782 if string.match(entry, "^[ \t]*close[ \t]*$") then
783 if state == "info_status_sent" then
784 error("Cannot set \"Connection: close\" for informational status response")
785 end
786 close_responded = true
787 break
788 end
789 end
790 end
791 assert_output(socket:write(key, ": ", value, "\r\n"))
792 end
793 -- function to terminate header section in response, optionally flushing:
794 -- (may be called multiple times unless response is finished)
795 local function finish_headers(with_flush)
796 if state == "finished" then
797 error("Response has already been finished")
798 elseif state == "info_status_sent" then
799 send_flush("\r\n")
800 state = "no_status_sent"
801 elseif state == "bodyless_status_sent" then
802 if close_requested and not close_responded then
803 request:send_header("Connection", "close")
804 end
805 send("\r\n")
806 finish()
807 state = "finished"
808 elseif state == "status_sent" then
809 if not content_length then
810 request:send_header("Transfer-Encoding", "chunked")
811 end
812 if close_requested and not close_responded then
813 request:send_header("Connection", "close")
814 end
815 send("\r\n")
816 if request.method == "HEAD" then
817 finish()
818 elseif with_flush then
819 send_flush()
820 end
821 state = "headers_sent"
822 elseif state ~= "headers_sent" then
823 error("HTTP status has not been sent yet")
824 end
825 end
826 -- method to finish and flush headers:
827 function request:finish_headers()
828 assert_not_faulty()
829 finish_headers(true)
830 end
831 -- method to send body data:
832 function request:send_data(...)
833 assert_not_faulty()
834 if output_state == "info_status_sent" then
835 error("No (non-informational) HTTP status has been sent yet")
836 elseif output_state == "bodyless_status_sent" then
837 error("Cannot send response data for body-less status message")
838 end
839 finish_headers(false)
840 if output_state ~= "headers_sent" then
841 error("Unexpected internal status in HTTP engine")
842 end
843 if request.method == "HEAD" then
844 return
845 end
846 for i = 1, select("#", ...) do
847 local str = tostring(select(i, ...))
848 if #str > 0 then
849 if content_length then
850 local bytes_to_send = #str
851 if bytes_sent + bytes_to_send > content_length then
852 error("Content length exceeded")
853 else
854 send(str)
855 bytes_sent = bytes_sent + bytes_to_send
856 end
857 else
858 chunk_bytes = chunk_bytes + #str
859 chunk_parts[#chunk_parts+1] = str
860 end
861 end
862 end
863 if chunk_bytes >= output_chunk_size then
864 send_chunk()
865 end
866 end
867 -- method to flush output buffer:
868 function request:flush()
869 assert_not_faulty()
870 send_chunk()
871 send_flush()
872 end
873 -- method to finish response:
874 function request:finish()
875 assert_not_faulty()
876 if state == "finished" then
877 return
878 elseif state == "info_status_sent" then
879 error("Informational HTTP response can be finished with :finish_headers() method")
880 end
881 finish_headers(false)
882 if state == "headers_sent" then
883 if request.method ~= "HEAD" then
884 state = "faulty"
885 if content_length then
886 if bytes_sent ~= content_length then
887 error("Content length not used")
888 end
889 else
890 send_chunk()
891 send("0\r\n\r\n")
892 end
893 finish()
894 end
895 state = "finished"
896 elseif state ~= "finished" then
897 error("Unexpected internal status in HTTP engine")
898 end
899 end
900 -- method to register POST param stream handler for a single field name:
901 function request:stream_post_param(field_name, callback)
902 if state ~= "init" then
903 error("Cannot setup request body streamer at this stage")
904 end
905 streamed_post_params[field_name] = callback
906 end
907 -- method to register POST param stream handler for a field name pattern:
908 function request:stream_post_params(pattern, callback)
909 if state ~= "init" then
910 error("Cannot setup request body streamer at this stage")
911 end
912 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
913 end
914 -- method to register request body stream handler
915 function request:set_request_body_streamer(callback)
916 if state ~= "init" then
917 error("Cannot setup request body streamer at this stage")
918 end
919 local inprogress = false
920 local buffer = {}
921 process_body_chunk = function(chunk)
922 if inprogress then
923 buffer[#buffer+1] = chunk
924 else
925 inprogress = true
926 callback(chunk)
927 while #buffer > 0 do
928 chunk = table.concat(buffer)
929 buffer = {}
930 callback(chunk)
931 end
932 inprogress = false
933 end
934 end
935 end
936 -- method to start reading request body
937 function request:consume_input()
938 prepare()
939 consume_all()
940 end
941 -- method to stream request body
942 function request:stream_request_body(callback)
943 request:set_request_body_streamer(function(chunk)
944 if chunk ~= nil then
945 callback(chunk)
946 end
947 end)
948 request:consume_input()
949 end
950 -- metamethod to read special attibutes of request object:
951 function request_mt:__index(key, value)
952 if key == "body" then
953 local chunks = {}
954 request:stream_request_body(function(chunk)
955 chunks[#chunks+1] = chunk
956 end)
957 self.body = table.concat(chunks)
958 return self.body
959 elseif
960 key == "post_params_list" or key == "post_params" or
961 key == "post_metadata_list" or key == "post_metadata"
962 then
963 prepare()
964 consume_all()
965 return self[key]
966 end
967 end
968 -- coroutine for reading headers:
969 local function read_headers()
970 -- initialize limit:
971 local limit = header_size_limit
972 -- read and parse request line:
973 local line = read_eof(limit, "\n")
974 if not line then
975 return false, survive
976 end
977 limit = limit - #line
978 if limit == 0 then
979 return false, request_error(false, "414 Request-URI Too Long")
980 end
981 local target, proto
982 request.method, target, proto =
983 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
984 if not request.method then
985 return false, request_error(false, "400 Bad Request")
986 elseif proto ~= "HTTP/1.1" then
987 return false, request_error(false, "505 HTTP Version Not Supported")
988 end
989 -- read and parse headers:
990 while true do
991 local line = read(limit, "\n");
992 limit = limit - #line
993 if line == "\r\n" or line == "\n" then
994 break
995 end
996 if limit == 0 then
997 return false, request_error(false, "431 Request Header Fields Too Large")
998 end
999 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
1000 if not key then
1001 return false, request_error(false, "400 Bad Request")
1002 end
1003 local values = request.headers[key]
1004 values[#values+1] = value
1005 end
1006 return true -- success
1007 end
1008 -- wait for input:
1009 if not poll(socket_set, nil, request_idle_timeout) then
1010 return request_error(false, "408 Request Timeout", "Idle connection timed out")
1011 end
1012 -- read headers (with timeout):
1013 do
1014 local coro = coroutine.wrap(read_headers)
1015 local starttime = request_header_timeout and moonbridge_io.timeref()
1016 while true do
1017 local status, retval = coro()
1018 if status == nil then
1019 local remaining
1020 if request_header_timeout then
1021 remaining = request_header_timeout - moonbridge_io.timeref(starttime)
1022 end
1023 if not poll(socket_set, nil, remaining) then
1024 return request_error(false, "408 Request Timeout", "Timeout while receiving headers")
1025 end
1026 elseif status == false then
1027 return retval
1028 elseif status == true then
1029 break
1030 else
1031 error("Unexpected yield value")
1032 end
1033 end
1034 end
1035 -- process "Connection: close" header if existent:
1036 connection_close_requested = request.headers_flags["Connection"]["close"]
1037 -- process "Content-Length" header if existent:
1038 do
1039 local values = request.headers_csv_table["Content-Length"]
1040 if #values > 0 then
1041 request_body_content_length = tonumber(values[1])
1042 local proper_value = tostring(request_body_content_length)
1043 for i, value in ipairs(values) do
1044 value = string.match(value, "^0*(.*)")
1045 if value ~= proper_value then
1046 return request_error(false, "400 Bad Request", "Content-Length header(s) invalid")
1047 end
1048 end
1049 if request_body_content_length > body_size_limit then
1050 return request_error(false, "413 Request Entity Too Large", "Announced request body size is too big")
1051 end
1052 end
1053 end
1054 -- process "Transfer-Encoding" header if existent:
1055 do
1056 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
1057 local list = request.headers_csv_table["Transfer-Encoding"]
1058 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
1059 return request_error(false, "400 Bad Request", "Unexpected Transfer-Encoding")
1060 end
1061 end
1062 -- process "Expect" header if existent:
1063 for i, value in ipairs(request.headers_csv_table["Expect"]) do
1064 if string.lower(value) ~= "100-continue" then
1065 return request_error(false, "417 Expectation Failed", "Unexpected Expect header")
1066 end
1067 end
1068 -- get mandatory Host header according to RFC 7230:
1069 request.host = request.headers_value["Host"]
1070 if not request.host then
1071 return request_error(false, "400 Bad Request", "No valid host header")
1072 end
1073 -- parse request target:
1074 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
1075 if not request.path then
1076 local host2
1077 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
1078 if host2 then
1079 if request.host ~= host2 then
1080 return request_error(false, "400 Bad Request", "No valid host header")
1081 end
1082 elseif not (target == "*" and request.method == "OPTIONS") then
1083 return request_error(false, "400 Bad Request", "Invalid request target")
1084 end
1085 end
1086 -- parse GET params:
1087 if request.query then
1088 read_urlencoded_form(request.get_params_list, request.query)
1089 end
1090 -- parse cookies:
1091 for i, line in ipairs(request.headers["Cookie"]) do
1092 for rawkey, rawvalue in
1093 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
1094 do
1095 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
1096 end
1097 end
1098 -- (re)set timeout for handler:
1099 timeout(response_timeout or 0)
1100 -- call underlying handler and remember boolean result:
1101 if handler(request) ~= true then survive = false end
1102 -- finish request (unless already done by underlying handler):
1103 request:finish()
1104 -- stop timeout timer:
1105 timeout(0)
1106 until close_responded
1107 return survive
1108 end
1109 end
1111 return _M

Impressum / About Us