moonbridge

view moonbridge_http.lua @ 203:a1907691f740

Fixes to timeout system in HTTP module
author jbe
date Sun Jun 21 02:42:27 2015 +0200 (2015-06-21)
parents 2ed3d94a0eb7
children 7d1cda1ed530
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 idle_timeout = default("idle_timeout", 65)
201 local stall_timeout = default("stall_timeout", 60)
202 local request_header_timeout = default("request_header_timeout", 120)
203 local response_timeout = default("response_timeout", 3600)
204 local drain_timeout = default("drain_timeout", 2)
205 local poll = options.poll_function or moonbridge_io.poll
206 -- return socket handler:
207 return function(socket)
208 local socket_set = {[socket] = true} -- used for poll function
209 local survive = true -- set to false if process shall be terminated later
210 local consume -- can be set to function that reads some input if possible
211 -- function that may be used as "consume" function
212 -- and which drains some input if possible:
213 local function drain()
214 local bytes, status = socket:drain_nb(input_chunk_size)
215 if not bytes or status == "eof" then
216 consume = nil
217 end
218 end
219 -- function trying to unblock socket by reading:
220 local function unblock()
221 if consume then
222 if not poll(socket_set, socket_set, stall_timeout) then
223 socket:reset()
224 error("Client connection stalled")
225 end
226 consume()
227 else
228 if not poll(nil, socket_set, stall_timeout) then
229 socket:reset()
230 error("Client connection stalled")
231 end
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 -- function to enable draining:
340 local function enable_drain()
341 consume = drain
342 process_body_chunk = nil -- allow for early garbage collection
343 end
344 -- local variables to track the state:
345 local state = "init" -- one of:
346 -- "init" (initial state)
347 -- "no_status_sent" (request body streaming config complete)
348 -- "info_status_sent" (1xx status code has been sent)
349 -- "bodyless_status_sent" (204/304 status code has been sent)
350 -- "status_sent" (regular status code has been sent)
351 -- "headers_sent" (headers have been terminated)
352 -- "finished" (request has been answered completely)
353 -- "faulty" (I/O or protocaol error)
354 local request_body_content_length -- Content-Length of request body
355 local close_requested = false -- "Connection: close" requested
356 local close_responded = false -- "Connection: close" sent
357 local content_length = nil -- value of Content-Length header sent
358 local bytes_sent = 0 -- number of bytes sent if Content-Length is set
359 local chunk_parts = {} -- list of chunks to send
360 local chunk_bytes = 0 -- sum of lengths of chunks to send
361 local streamed_post_params = {} -- mapping from POST field name to stream function
362 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
363 -- function to report an error:
364 local function request_error(throw_error, status, text)
365 if
366 state == "init" or
367 state == "no_status_sent" or
368 state == "info_status_sent"
369 then
370 local error_response_status, errmsg = pcall(function()
371 request:monologue()
372 request:send_status(status)
373 request:send_header("Content-Type", "text/plain")
374 request:send_data(status, "\n")
375 if text then
376 request:send_data("\n", text, "\n")
377 end
378 request:finish()
379 end)
380 if not error_response_status then
381 if text then
382 error("Error while sending error response (" .. status .. " / " .. text .. "): " .. errmsg)
383 else
384 error("Error while sending error response (" .. status .. "): " .. errmsg)
385 end
386 end
387 end
388 if throw_error then
389 local errmsg = "Error while reading request from client. Error response: " .. status
390 if text then
391 errmsg = errmsg .. " (" .. text .. ")"
392 end
393 error(errmsg)
394 else
395 return survive
396 end
397 end
398 -- function that enforces consumption of all input:
399 local function consume_all(timeout)
400 local starttime = timeout and moonbridge_io.timeref()
401 while consume do
402 if timeout then
403 -- passed timeout does not get reset but refers to starttime
404 if not poll(socket_set, nil, timeout-moonbridge_io.timeref(starttime)) then
405 return false
406 end
407 else
408 -- stall_timeout gets reset for every poll
409 if not poll(socket_set, nil, stall_timeout) then
410 request_error(true, "408 Request Timeout", "Timeout while waiting for request body")
411 end
412 end
413 consume()
414 end
415 return true
416 end
417 -- function to assert non-faulty handle:
418 local function assert_not_faulty()
419 assert(state ~= "faulty", "Tried to use faulty request handle")
420 end
421 -- functions to send data to the browser:
422 local function send(...)
423 local old_state = state; state = "faulty"
424 if not socket:write_call(unblock, ...) then
425 socket:reset()
426 error("Could not send data to client: " .. errmsg)
427 end
428 state = old_state
429 end
430 local function send_flush(...)
431 local old_state = state; state = "faulty"
432 if not socket:flush_call(unblock, ...) then
433 socket:reset()
434 error("Could not send data to client: " .. errmsg)
435 end
436 state = old_state
437 end
438 -- function to assert proper finish/close/reset:
439 local function assert_close(retval, errmsg)
440 if not retval then
441 error("Could not finish sending data to client: " .. errmsg)
442 end
443 end
444 -- function to finish request:
445 local function finish()
446 if close_responded then
447 -- discard any input:
448 enable_drain()
449 -- close output stream:
450 send_flush()
451 assert_close(socket:finish())
452 -- wait for EOF from peer to avoid immediate TCP RST condition:
453 if consume_all(drain_timeout) then
454 -- fully close socket:
455 assert_close(socket:close())
456 else
457 -- send TCP RST if draining input takes too long:
458 assert_close(socket:reset())
459 end
460 else
461 -- flush outgoing data:
462 send_flush()
463 -- consume incoming data:
464 consume_all()
465 end
466 end
467 -- function that writes out buffered chunks (without flushing the socket):
468 function send_chunk()
469 if chunk_bytes > 0 then
470 local old_state = state; state = "faulty"
471 send(string.format("%x\r\n", chunk_bytes))
472 for i = 1, #chunk_parts do
473 send(chunk_parts[i])
474 chunk_parts[i] = nil
475 end
476 chunk_bytes = 0
477 send("\r\n")
478 state = old_state
479 end
480 end
481 -- read functions
482 local function read(...)
483 local data, status = socket:read_yield(...)
484 if data == nil then
485 request_error(true, "400 Bad Request", "Read error")
486 end
487 if status == "eof" then
488 request_error(true, "400 Bad Request", "Unexpected EOF")
489 end
490 return data
491 end
492 local function read_eof(...)
493 local data, status = socket:read_yield(...)
494 if data == nil then
495 request_error(true, "400 Bad Request", "Read error")
496 end
497 if status == "eof" then
498 if data == "" then
499 return nil
500 else
501 request_error(true, "400 Bad Request", "Unexpected EOF")
502 end
503 end
504 return data
505 end
506 -- reads a number of bytes from the socket,
507 -- optionally feeding these bytes chunk-wise into
508 -- the "process_body_chunk" callback function:
509 local function read_body_bytes(remaining)
510 while remaining > 0 do
511 coroutine.yield() -- do not read more than necessary
512 local chunklen
513 if remaining > input_chunk_size then
514 chunklen = input_chunk_size
515 else
516 chunklen = remaining
517 end
518 local chunk = read(chunklen)
519 remaining = remaining - chunklen
520 if process_body_chunk then
521 process_body_chunk(chunk)
522 end
523 end
524 end
525 -- coroutine for request body processing:
526 local function read_body()
527 if request.headers_flags["Transfer-Encoding"]["chunked"] then
528 coroutine.yield() -- do not read on first invocation
529 local limit = body_size_limit
530 while true do
531 local line = read(32 + limit, "\n")
532 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
533 local chunkext
534 if lenstr then
535 chunkext = ""
536 else
537 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
538 end
539 if not lenstr or #lenstr > 13 then
540 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
541 end
542 local len = tonumber("0x" .. lenstr)
543 limit = limit - (#zeros + #chunkext + len)
544 if limit < 0 then
545 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
546 end
547 if len == 0 then break end
548 read_body_bytes(len)
549 local term = read(2, "\n")
550 if term ~= "\r\n" and term ~= "\n" then
551 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
552 end
553 end
554 while true do
555 local line = read(2 + limit, "\n")
556 if line == "\r\n" or line == "\n" then break end
557 limit = limit - #line
558 if limit < 0 then
559 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
560 end
561 end
562 elseif request_body_content_length then
563 read_body_bytes(request_body_content_length)
564 end
565 if process_body_chunk then
566 process_body_chunk(nil) -- signal EOF
567 end
568 consume = nil -- avoid further resumes
569 end
570 -- function to setup default request body handling:
571 local function default_request_body_handling()
572 local post_params_list, post_params = new_params_list()
573 local content_type = request.headers_value["Content-Type"]
574 if content_type then
575 if
576 content_type == "application/x-www-form-urlencoded" or
577 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
578 then
579 read_urlencoded_form(post_params_list, request.body)
580 else
581 local boundary = string.match(
582 content_type,
583 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
584 ) or string.match(
585 content_type,
586 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
587 )
588 if boundary then
589 local post_metadata_list, post_metadata = new_params_list()
590 boundary = "--" .. boundary
591 local headerdata = ""
592 local streamer
593 local field_name
594 local metadata = {}
595 local value_parts
596 local function default_streamer(chunk)
597 value_parts[#value_parts+1] = chunk
598 end
599 local function stream_part_finish()
600 if streamer == default_streamer then
601 local value = table.concat(value_parts)
602 value_parts = nil
603 if field_name then
604 local values = post_params_list[field_name]
605 values[#values+1] = value
606 local metadata_entries = post_metadata_list[field_name]
607 metadata_entries[#metadata_entries+1] = metadata
608 end
609 else
610 streamer()
611 end
612 headerdata = ""
613 streamer = nil
614 field_name = nil
615 metadata = {}
616 end
617 local function stream_part_chunk(chunk)
618 if streamer then
619 streamer(chunk)
620 else
621 headerdata = headerdata .. chunk
622 while true do
623 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
624 if not line then
625 break
626 end
627 if line == "" then
628 streamer = streamed_post_params[field_name]
629 if not streamer then
630 for i, rule in ipairs(streamed_post_param_patterns) do
631 if string.match(field_name, rule[1]) then
632 streamer = rule[2]
633 break
634 end
635 end
636 end
637 if not streamer then
638 value_parts = {}
639 streamer = default_streamer
640 end
641 streamer(remaining, field_name, metadata)
642 return
643 end
644 headerdata = remaining
645 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
646 if not header_key then
647 request_error(true, "400 Bad Request", "Invalid header in multipart/form-data part")
648 end
649 header_key = string.lower(header_key)
650 if header_key == "content-disposition" then
651 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
652 return string.gsub(str, "=", "==")
653 end)
654 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
655 if field_name then
656 field_name = string.gsub(field_name, "==", "=")
657 else
658 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
659 end
660 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
661 if metadata.file_name then
662 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
663 else
664 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
665 end
666 elseif header_key == "content-type" then
667 metadata.content_type = header_value
668 elseif header_key == "content-transfer-encoding" then
669 request_error(true, "400 Bad Request", "Content-transfer-encoding not supported by multipart/form-data parser")
670 end
671 end
672 end
673 end
674 local skippart = true -- ignore data until first boundary
675 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
676 local terminated = false -- final boundary read
677 local bigchunk = ""
678 request:stream_request_body(function(chunk)
679 if chunk == nil then
680 if not terminated then
681 request_error(true, "400 Bad Request", "Premature end of multipart/form-data request body")
682 end
683 request.post_params_list, request.post_params = post_params_list, post_params
684 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
685 end
686 if terminated then
687 return
688 end
689 bigchunk = bigchunk .. chunk
690 while true do
691 if afterbound then
692 if #bigchunk <= 2 then
693 return
694 end
695 local terminator = string.sub(bigchunk, 1, 2)
696 if terminator == "\r\n" then
697 afterbound = false
698 bigchunk = string.sub(bigchunk, 3)
699 elseif terminator == "--" then
700 terminated = true
701 bigchunk = nil
702 return
703 else
704 request_error(true, "400 Bad Request", "Error while parsing multipart body (expected CRLF or double minus)")
705 end
706 end
707 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
708 if not pos1 then
709 if not skippart then
710 local safe = #bigchunk-#boundary
711 if safe > 0 then
712 stream_part_chunk(string.sub(bigchunk, 1, safe))
713 bigchunk = string.sub(bigchunk, safe+1)
714 end
715 end
716 return
717 end
718 if not skippart then
719 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
720 stream_part_finish()
721 else
722 boundary = "\r\n" .. boundary
723 skippart = false
724 end
725 bigchunk = string.sub(bigchunk, pos2 + 1)
726 afterbound = true
727 end
728 end)
729 return -- finalization is executed in stream handler
730 else
731 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
732 end
733 end
734 end
735 request.post_params_list, request.post_params = post_params_list, post_params
736 end
737 -- function to prepare body processing:
738 local function prepare()
739 assert_not_faulty()
740 if state ~= "init" then
741 return
742 end
743 if process_body_chunk == nil then
744 default_request_body_handling()
745 end
746 if state ~= "init" then -- re-check if state is still "init"
747 return
748 end
749 consume = coroutine.wrap(read_body)
750 consume() -- call coroutine once to avoid hangup on empty body
751 state = "no_status_sent"
752 if request.headers_flags["Expect"]["100-continue"] then
753 request:send_status("100 Continue")
754 request:finish_headers()
755 end
756 end
757 -- method to ignore input and close connection after response:
758 function request:monologue()
759 assert_not_faulty()
760 if
761 state == "headers_sent" or
762 state == "finished"
763 then
764 error("All HTTP headers have already been sent")
765 end
766 local old_state = state; state = "faulty"
767 enable_drain()
768 close_requested = true
769 if old_state == "init" then
770 state = "no_status_sent"
771 else
772 state = old_state
773 end
774 end
775 -- method to send a HTTP response status (e.g. "200 OK"):
776 function request:send_status(status)
777 prepare()
778 local old_state = state; state = "faulty"
779 if old_state == "info_status_sent" then
780 send_flush("\r\n")
781 elseif old_state ~= "no_status_sent" then
782 state = old_state
783 error("HTTP status has already been sent")
784 end
785 local status1 = string.sub(status, 1, 1)
786 local status3 = string.sub(status, 1, 3)
787 send("HTTP/1.1 ", status, "\r\n", preamble)
788 local wrb = status_without_response_body[status3]
789 if wrb then
790 state = "bodyless_status_sent"
791 if wrb == "zero_content_length" then
792 request:send_header("Content-Length", 0)
793 end
794 elseif status1 == "1" then
795 state = "info_status_sent"
796 else
797 state = "status_sent"
798 end
799 end
800 -- method to send a HTTP response header:
801 -- (key and value must be provided as separate args)
802 function request:send_header(key, value)
803 assert_not_faulty()
804 if state == "init" or state == "no_status_sent" then
805 error("HTTP status has not been sent yet")
806 elseif
807 state == "headers_sent" or
808 state == "finished"
809 then
810 error("All HTTP headers have already been sent")
811 end
812 local old_state = state; state = "faulty"
813 local key_lower = string.lower(key)
814 if key_lower == "content-length" then
815 if old_state == "info_status_sent" then
816 state = old_state
817 error("Cannot set Content-Length for informational status response")
818 end
819 local cl = assert(tonumber(value), "Invalid content-length")
820 if content_length == nil then
821 content_length = cl
822 elseif content_length == cl then
823 return
824 else
825 error("Content-Length has been set multiple times with different values")
826 end
827 elseif key_lower == "connection" then
828 for entry in string.gmatch(string.lower(value), "[^,]+") do
829 if string.match(entry, "^[ \t]*close[ \t]*$") then
830 if old_state == "info_status_sent" then
831 state = old_state
832 error("Cannot set \"Connection: close\" for informational status response")
833 end
834 close_responded = true
835 break
836 end
837 end
838 end
839 send(key, ": ", value, "\r\n")
840 state = old_state
841 end
842 -- method to announce (and enforce) connection close after sending the
843 -- response:
844 function request:close_after_finish()
845 assert_not_faulty()
846 if state == "headers_sent" or state == "finished" then
847 error("All HTTP headers have already been sent")
848 end
849 close_requested = true
850 end
851 -- function to terminate header section in response, optionally flushing:
852 -- (may be called multiple times unless response is finished)
853 local function finish_headers(with_flush)
854 if state == "finished" then
855 error("Response has already been finished")
856 elseif state == "info_status_sent" then
857 state = "faulty"
858 send_flush("\r\n")
859 state = "no_status_sent"
860 elseif state == "bodyless_status_sent" then
861 if close_requested and not close_responded then
862 request:send_header("Connection", "close")
863 end
864 state = "faulty"
865 send("\r\n")
866 finish()
867 state = "finished"
868 elseif state == "status_sent" then
869 if not content_length then
870 request:send_header("Transfer-Encoding", "chunked")
871 end
872 if close_requested and not close_responded then
873 request:send_header("Connection", "close")
874 end
875 state = "faulty"
876 send("\r\n")
877 if request.method == "HEAD" then
878 finish()
879 elseif with_flush then
880 send_flush()
881 end
882 state = "headers_sent"
883 elseif state ~= "headers_sent" then
884 error("HTTP status has not been sent yet")
885 end
886 end
887 -- method to finish and flush headers:
888 function request:finish_headers()
889 assert_not_faulty()
890 finish_headers(true)
891 end
892 -- method to send body data:
893 function request:send_data(...)
894 assert_not_faulty()
895 if state == "info_status_sent" then
896 error("No (non-informational) HTTP status has been sent yet")
897 elseif state == "bodyless_status_sent" then
898 error("Cannot send response data for body-less status message")
899 end
900 finish_headers(false)
901 if state ~= "headers_sent" then
902 error("Unexpected internal status in HTTP engine")
903 end
904 if request.method == "HEAD" then
905 return
906 end
907 state = "faulty"
908 for i = 1, select("#", ...) do
909 local str = tostring(select(i, ...))
910 if #str > 0 then
911 if content_length then
912 local bytes_to_send = #str
913 if bytes_sent + bytes_to_send > content_length then
914 error("Content length exceeded")
915 else
916 send(str)
917 bytes_sent = bytes_sent + bytes_to_send
918 end
919 else
920 chunk_bytes = chunk_bytes + #str
921 chunk_parts[#chunk_parts+1] = str
922 end
923 end
924 end
925 if chunk_bytes >= output_chunk_size then
926 send_chunk()
927 end
928 state = "headers_sent"
929 end
930 -- method to flush output buffer:
931 function request:flush()
932 assert_not_faulty()
933 send_chunk()
934 send_flush()
935 end
936 -- method to finish response:
937 function request:finish()
938 assert_not_faulty()
939 if state == "finished" then
940 return
941 elseif state == "info_status_sent" then
942 error("Informational HTTP response can be finished with :finish_headers() method")
943 end
944 finish_headers(false)
945 if state == "headers_sent" then
946 if request.method ~= "HEAD" then
947 state = "faulty"
948 if content_length then
949 if bytes_sent ~= content_length then
950 error("Content length not used")
951 end
952 else
953 send_chunk()
954 send("0\r\n\r\n")
955 end
956 finish()
957 end
958 state = "finished"
959 elseif state ~= "finished" then
960 error("Unexpected internal status in HTTP engine")
961 end
962 end
963 -- method to register POST param stream handler for a single field name:
964 function request:stream_post_param(field_name, callback)
965 if state ~= "init" then
966 error("Cannot setup request body streamer at this stage anymore")
967 end
968 streamed_post_params[field_name] = callback
969 end
970 -- method to register POST param stream handler for a field name pattern:
971 function request:stream_post_params(pattern, callback)
972 if state ~= "init" then
973 error("Cannot setup request body streamer at this stage anymore")
974 end
975 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
976 end
977 -- method to register request body stream handler
978 function request:stream_request_body(callback)
979 if state ~= "init" then
980 error("Cannot setup request body streamer at this stage anymore")
981 end
982 local inprogress = false
983 local eof = false
984 local buffer = {}
985 process_body_chunk = function(chunk)
986 if inprogress then
987 if chunk == nil then
988 eof = true
989 else
990 buffer[#buffer+1] = chunk
991 end
992 else
993 inprogress = true
994 callback(chunk)
995 while #buffer > 0 do
996 chunk = table.concat(buffer)
997 buffer = {}
998 callback(chunk)
999 end
1000 if eof then
1001 callback() -- signal EOF
1002 end
1003 inprogress = false
1004 end
1005 end
1006 end
1007 -- method to start reading request body
1008 function request:consume_input()
1009 prepare()
1010 consume_all()
1011 end
1012 -- method to stream request body
1013 function request:stream_request_body_now(callback)
1014 request:stream_request_body(function(chunk)
1015 if chunk ~= nil then
1016 callback(chunk)
1017 end
1018 end)
1019 request:consume_input()
1020 end
1021 -- metamethod to read special attibutes of request object:
1022 function request_mt:__index(key, value)
1023 if key == "faulty" then
1024 return state == "faulty"
1025 elseif key == "fresh" then
1026 return state == "init" and process_body_chunk == nil
1027 elseif key == "body" then
1028 local chunks = {}
1029 request:stream_request_body_now(function(chunk)
1030 chunks[#chunks+1] = chunk
1031 end)
1032 self.body = table.concat(chunks)
1033 return self.body
1034 elseif
1035 key == "post_params_list" or key == "post_params" or
1036 key == "post_metadata_list" or key == "post_metadata"
1037 then
1038 prepare()
1039 consume_all()
1040 return rawget(self, key)
1041 end
1042 end
1043 -- variable to store request target
1044 local target
1045 -- coroutine for reading headers:
1046 local function read_headers()
1047 -- initialize limit:
1048 local limit = header_size_limit
1049 -- read and parse request line:
1050 local line = read_eof(limit, "\n")
1051 if not line then
1052 return false, survive
1053 end
1054 limit = limit - #line
1055 if limit == 0 then
1056 return false, request_error(false, "414 Request-URI Too Long")
1057 end
1058 local proto
1059 request.method, target, proto =
1060 line:match("^([^ \t\r]+)[ \t]+([^ \t\r]+)[ \t]*([^ \t\r]*)[ \t]*\r?\n$")
1061 if not request.method then
1062 return false, request_error(false, "400 Bad Request")
1063 elseif proto ~= "HTTP/1.1" then
1064 return false, request_error(false, "505 HTTP Version Not Supported")
1065 end
1066 -- read and parse headers:
1067 while true do
1068 local line = read(limit, "\n");
1069 limit = limit - #line
1070 if line == "\r\n" or line == "\n" then
1071 break
1072 end
1073 if limit == 0 then
1074 return false, request_error(false, "431 Request Header Fields Too Large")
1075 end
1076 local key, value = string.match(line, "^([^ \t\r]+):[ \t]*(.-)[ \t]*\r?\n$")
1077 if not key then
1078 return false, request_error(false, "400 Bad Request")
1079 end
1080 local values = request.headers[key]
1081 values[#values+1] = value
1082 end
1083 return true -- success
1084 end
1085 -- wait for input:
1086 if not poll(socket_set, nil, idle_timeout) then
1087 return request_error(false, "408 Request Timeout", "Idle connection timed out")
1088 end
1089 -- read headers (with timeout):
1090 do
1091 local coro = coroutine.wrap(read_headers)
1092 local starttime = request_header_timeout and moonbridge_io.timeref()
1093 while true do
1094 local status, retval = coro()
1095 if status == nil then
1096 local timeout
1097 if request_header_timeout then
1098 timeout = request_header_timeout - moonbridge_io.timeref(starttime)
1099 if stall_timeout and timeout > stall_timeout then
1100 timeout = stall_timeout
1101 end
1102 else
1103 timeout = stall_timeout
1104 end
1105 if not poll(socket_set, nil, timeout) then
1106 return request_error(false, "408 Request Timeout", "Timeout while receiving headers")
1107 end
1108 elseif status == false then
1109 return retval
1110 elseif status == true then
1111 break
1112 else
1113 error("Unexpected yield value")
1114 end
1115 end
1116 end
1117 -- process "Connection: close" header if existent:
1118 connection_close_requested = request.headers_flags["Connection"]["close"]
1119 -- process "Content-Length" header if existent:
1120 do
1121 local values = request.headers_csv_table["Content-Length"]
1122 if #values > 0 then
1123 request_body_content_length = tonumber(values[1])
1124 local proper_value = tostring(request_body_content_length)
1125 for i, value in ipairs(values) do
1126 value = string.match(value, "^0*(.*)")
1127 if value ~= proper_value then
1128 return request_error(false, "400 Bad Request", "Content-Length header(s) invalid")
1129 end
1130 end
1131 if request_body_content_length > body_size_limit then
1132 return request_error(false, "413 Request Entity Too Large", "Announced request body size is too big")
1133 end
1134 end
1135 end
1136 -- process "Transfer-Encoding" header if existent:
1137 do
1138 local flag = request.headers_flags["Transfer-Encoding"]["chunked"]
1139 local list = request.headers_csv_table["Transfer-Encoding"]
1140 if (flag and #list ~= 1) or (not flag and #list ~= 0) then
1141 return request_error(false, "400 Bad Request", "Unexpected Transfer-Encoding")
1142 end
1143 end
1144 -- process "Expect" header if existent:
1145 for i, value in ipairs(request.headers_csv_table["Expect"]) do
1146 if string.lower(value) ~= "100-continue" then
1147 return request_error(false, "417 Expectation Failed", "Unexpected Expect header")
1148 end
1149 end
1150 -- get mandatory Host header according to RFC 7230:
1151 request.host = request.headers_value["Host"]
1152 if not request.host then
1153 return request_error(false, "400 Bad Request", "No valid host header")
1154 end
1155 -- parse request target:
1156 request.path, request.query = string.match(target, "^/([^?]*)(.*)$")
1157 if not request.path then
1158 local host2
1159 host2, request.path, request.query = string.match(target, "^[Hh][Tt][Tt][Pp]://([^/?]+)/?([^?]*)(.*)$")
1160 if host2 then
1161 if request.host ~= host2 then
1162 return request_error(false, "400 Bad Request", "No valid host header")
1163 end
1164 elseif not (target == "*" and request.method == "OPTIONS") then
1165 return request_error(false, "400 Bad Request", "Invalid request target")
1166 end
1167 end
1168 -- parse GET params:
1169 request.get_params_list, request.get_params = new_params_list()
1170 if request.query then
1171 read_urlencoded_form(request.get_params_list, request.query)
1172 end
1173 -- parse cookies:
1174 for i, line in ipairs(request.headers["Cookie"]) do
1175 for rawkey, rawvalue in
1176 string.gmatch(line, "([^=; ]*)=([^=; ]*)")
1177 do
1178 request.cookies[decode_uri(rawkey)] = decode_uri(rawvalue)
1179 end
1180 end
1181 -- (re)set timeout for handler:
1182 timeout(response_timeout or 0)
1183 -- call underlying handler and remember boolean result:
1184 if handler(request) ~= true then survive = false end
1185 -- finish request (unless already done by underlying handler):
1186 request:finish()
1187 -- stop timeout timer:
1188 timeout(0)
1189 until close_responded
1190 return survive
1191 end
1192 end
1194 return _M

Impressum / About Us