moonbridge

view moonbridge_http.lua @ 233:8593a1f2c15d

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

Impressum / About Us