moonbridge

view moonbridge_http.lua @ 178:f6eea95879d4

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

Impressum / About Us