moonbridge

view moonbridge_http.lua @ 177:b03857995d57

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

Impressum / About Us