moonbridge

view moonbridge_http.lua @ 223:d544e8379691

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

Impressum / About Us