moonbridge

view moonbridge_http.lua @ 197:efd1b4cfd2e9

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

Impressum / About Us