moonbridge

view moonbridge_http.lua @ 181:f0dc143f510a

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

Impressum / About Us