moonbridge

view moonbridge_http.lua @ 200:40a7bd08e304

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

Impressum / About Us