moonbridge

view moonbridge_http.lua @ 172:fb54c76e1484

Completed new HTTP module implementation (untested yet)
author jbe
date Tue Jun 16 21:44:32 2015 +0200 (2015-06-16)
parents 32d7423a6753
children 6e80bcf89bd5
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 key = next(tbl, key)
104 if key == nil then
105 return nil
106 end
107 return key, tbl[key][1]
108 end
109 local params_list_metatable = {
110 __index = function(self, key)
111 local tbl = {}
112 self[key] = tbl
113 return tbl
114 end,
115 __pairs = function(self)
116 return nextnonempty, self, nil
117 end
118 }
119 local params_metatable = {
120 __index = function(self, key)
121 return params_list_mapping[self][key][1]
122 end,
123 __newindex = function(self, key, value)
124 params_list_mapping[self][key] = {value}
125 end,
126 __pairs = function(self)
127 return nextvalue, params_list_mapping[self], nil
128 end
129 }
130 -- returns a table to store key value-list pairs (i.e. multiple values),
131 -- and a second table automatically mapping keys to the first value
132 -- using the key value-list pairs in the first table:
133 new_params_list = function()
134 local params_list = setmetatable({}, params_list_metatable)
135 local params = setmetatable({}, params_metatable)
136 params_list_mapping[params] = params_list
137 return params_list, params
138 end
139 end
141 -- parses URL encoded form data and stores it in
142 -- a key value-list pairs structure that has to be
143 -- previously obtained by calling by new_params_list():
144 local function read_urlencoded_form(tbl, data)
145 for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do
146 local subtbl = tbl[decode_uri(rawkey)]
147 subtbl[#subtbl+1] = decode_uri(rawvalue)
148 end
149 end
151 -- extracts first value from each subtable:
152 local function get_first_values(tbl)
153 local newtbl = {}
154 for key, subtbl in pairs(tbl) do
155 newtbl[key] = subtbl[1]
156 end
157 return newtbl
158 end
160 function generate_handler(handler, options)
161 -- swap arguments if necessary (for convenience):
162 if type(handler) ~= "function" and type(options) == "function" then
163 handler, options = options, handler
164 end
165 -- helper function to process options:
166 local function default(name, default_value)
167 local value = options[name]
168 if value == nil then
169 return default_value
170 else
171 return value or nil
172 end
173 end
174 -- process options:
175 options = options or {}
176 local preamble = "" -- preamble sent with every(!) HTTP response
177 do
178 -- named arg "static_headers" is used to create the preamble:
179 local s = options.static_headers
180 local t = {}
181 if s then
182 if type(s) == "string" then
183 for line in string.gmatch(s, "[^\r\n]+") do
184 t[#t+1] = line
185 end
186 else
187 for i, kv in ipairs(options.static_headers) do
188 if type(kv) == "string" then
189 t[#t+1] = kv
190 else
191 t[#t+1] = kv[1] .. ": " .. kv[2]
192 end
193 end
194 end
195 end
196 t[#t+1] = ""
197 preamble = table.concat(t, "\r\n")
198 end
199 local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384
200 local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024
201 local header_size_limit = options.header_size_limit or 1024*1024
202 local body_size_limit = options.body_size_limit or 64*1024*1024
203 local request_idle_timeout = default("request_idle_timeout", 330)
204 local request_header_timeout = default("request_header_timeout", 30)
205 local request_body_timeout = default("request_body_timeout", 60)
206 local request_response_timeout = default("request_response_timeout", 1800)
207 local poll = options.poll_function or moonbridge_io.poll
208 -- return socket handler:
209 return function(socket)
210 local socket_set = {[socket] = true} -- used for poll function
211 local survive = true -- set to false if process shall be terminated later
212 local consume -- function that reads some input if possible
213 -- function that drains some input if possible:
214 local function drain()
215 local bytes, status = socket:drain_nb(input_chunk_size)
216 if not bytes or status == "eof" then
217 consume = nil
218 end
219 end
220 -- function trying to unblock socket by reading:
221 local function unblock()
222 if consume then
223 poll(socket_set, socket_set)
224 consume()
225 else
226 poll(nil, socket_set)
227 end
228 end
229 -- function that enforces consumption of all input:
230 local function consume_all()
231 while consume do
232 poll(socket_set, nil)
233 consume()
234 end
235 end
236 -- handle requests in a loop:
237 repeat
238 -- copy limits:
239 local remaining_header_size_limit = header_size_limit
240 local remaining_body_size_limit = body_size_limit
241 -- table for caching nil values:
242 local headers_value_nil = {}
243 -- create a new request object with metatable:
244 local request -- allow references to local variable
245 request = {
246 -- allow access to underlying socket:
247 socket = socket,
248 -- cookies are simply stored in a table:
249 cookies = {},
250 -- table mapping header field names to value-lists
251 -- (raw access, but case-insensitive):
252 headers = setmetatable({}, {
253 __index = function(self, key)
254 local lowerkey = string.lower(key)
255 if lowerkey == key then
256 return
257 end
258 local result = rawget(self, lowerkey)
259 if result == nil then
260 result = {}
261 end
262 self[lowerkey] = result
263 self[key] = result
264 return result
265 end
266 }),
267 -- table mapping header field names to value-lists
268 -- (for headers with comma separated values):
269 headers_csv_table = setmetatable({}, {
270 __index = function(self, key)
271 local result = {}
272 for i, line in ipairs(request.headers[key]) do
273 for entry in string.gmatch(line, "[^,]+") do
274 local value = string.match(entry, "^[ \t]*(..-)[ \t]*$")
275 if value then
276 result[#result+1] = value
277 end
278 end
279 end
280 self[key] = result
281 return result
282 end
283 }),
284 -- table mapping header field names to a comma separated string
285 -- (for headers with comma separated values):
286 headers_csv_string = setmetatable({}, {
287 __index = function(self, key)
288 local result = {}
289 for i, line in ipairs(request.headers[key]) do
290 result[#result+1] = line
291 end
292 result = table.concat(result, ", ")
293 self[key] = result
294 return result
295 end
296 }),
297 -- table mapping header field names to a single string value
298 -- (or false if header has been sent multiple times):
299 headers_value = setmetatable({}, {
300 __index = function(self, key)
301 if headers_value_nil[key] then
302 return nil
303 end
304 local result = nil
305 local values = request.headers_csv_table[key]
306 if #values == 0 then
307 headers_value_nil[key] = true
308 elseif #values == 1 then
309 result = values[1]
310 else
311 result = false
312 end
313 self[key] = result
314 return result
315 end
316 }),
317 -- table mapping header field names to a flag table,
318 -- indicating if the comma separated value contains certain entries:
319 headers_flags = setmetatable({}, {
320 __index = function(self, key)
321 local result = setmetatable({}, {
322 __index = function(self, key)
323 local lowerkey = string.lower(key)
324 local result = rawget(self, lowerkey) or false
325 self[lowerkey] = result
326 self[key] = result
327 return result
328 end
329 })
330 for i, value in ipairs(request.headers_csv_table[key]) do
331 result[string.lower(value)] = true
332 end
333 self[key] = result
334 return result
335 end
336 })
337 }
338 -- create metatable for request object:
339 local request_mt = {}
340 setmetatable(request, request_mt)
341 -- callback for request body streaming:
342 local process_body_chunk
343 -- local variables to track the state:
344 local state = "init" -- one of:
345 -- "init" (initial state)
346 -- "no_status_sent" (configuration complete)
347 -- "info_status_sent" (1xx status code has been sent)
348 -- "bodyless_status_sent" (204/304 status code has been sent)
349 -- "status_sent" (regular status code has been sent)
350 -- "headers_sent" (headers have been terminated)
351 -- "finished" (request has been answered completely)
352 -- "faulty" (I/O or protocaol error)
353 local close_requested = false -- "Connection: close" requested
354 local close_responded = false -- "Connection: close" sent
355 local content_length = nil -- value of Content-Length header sent
356 local chunk_parts = {} -- list of chunks to send
357 local chunk_bytes = 0 -- sum of lengths of chunks to send
358 local streamed_post_params = {} -- mapping from POST field name to stream function
359 local streamed_post_param_patterns = {} -- list of POST field pattern and stream function pairs
360 -- functions to assert proper output/closing:
361 local function assert_output(...)
362 local retval, errmsg = ...
363 if retval then return ... end
364 state = "faulty"
365 socket:reset()
366 error("Could not send data to client: " .. errmsg)
367 end
368 local function assert_close(...)
369 local retval, errmsg = ...
370 if retval then return ... end
371 state = "faulty"
372 error("Could not finish sending data to client: " .. errmsg)
373 end
374 -- function to assert non-faulty handle:
375 local function assert_not_faulty()
376 assert(state ~= "faulty", "Tried to use faulty request handle")
377 end
378 -- functions to send data to the browser:
379 local function send(...)
380 assert_output(socket:write_call(unblock, ...))
381 end
382 local function send_flush(...)
383 assert_output(socket:flush_call(unblock, ...))
384 end
385 -- function to finish request:
386 local function finish()
387 if close_responded then
388 -- discard any input:
389 consume = drain
390 -- close output stream:
391 send_flush()
392 assert_close(socket:finish())
393 -- wait for EOF of peer to avoid immediate TCP RST condition:
394 consume_all()
395 -- fully close socket:
396 assert_close(socket:close())
397 else
398 send_flush()
399 process_body_chunk = nil
400 consume_all()
401 end
402 end
403 -- function that writes out buffered chunks (without flushing the socket):
404 function send_chunk()
405 if chunk_bytes > 0 then
406 assert_output(socket:write(string.format("%x\r\n", chunk_bytes)))
407 for i = 1, #chunk_parts do -- TODO: evaluated only once?
408 send(chunk_parts[i])
409 chunk_parts[i] = nil
410 end
411 chunk_bytes = 0
412 send("\r\n")
413 end
414 end
415 -- function to report an error:
416 local function request_error(throw_error, status, text)
417 local errmsg = "Error while reading request from client. Error response: " .. status
418 if text then
419 errmsg = errmsg .. " (" .. text .. ")"
420 end
421 if
422 state == "init" or
423 state == "no_status_sent" or
424 state == "info_status_sent"
425 then
426 local error_response_status, errmsg2 = pcall(function()
427 request:monologue()
428 request:send_status(status)
429 request:send_header("Content-Type", "text/plain")
430 request:send_data(status, "\n")
431 if text then
432 request:send_data("\n", text, "\n")
433 end
434 request:finish()
435 end)
436 if not error_response_status then
437 error("Unexpected error while sending error response: " .. errmsg2)
438 end
439 elseif state ~= "faulty" then
440 state = "faulty"
441 assert_close(socket:reset())
442 end
443 if throw_error then
444 error(errmsg)
445 else
446 return survive
447 end
448 end
449 -- read function
450 local function read(...)
451 local data, status = socket:read_yield(...)
452 if data == nil then
453 request_error(true, "400 Bad Request", "Read error")
454 end
455 if status == "eof" then
456 request_error(true, "400 Bad Request", "Unexpected EOF")
457 end
458 return data
459 end
460 -- reads a number of bytes from the socket,
461 -- optionally feeding these bytes chunk-wise
462 -- into a callback function:
463 local function read_body_bytes(remaining)
464 while remaining > 0 do
465 local limit
466 if remaining > input_chunk_size then
467 limit = input_chunk_size
468 else
469 limit = remaining
470 end
471 local chunk = read(limit)
472 remaining = remaining - limit
473 if process_body_chunk then
474 process_body_chunk(chunk)
475 end
476 end
477 end
478 -- coroutine for request body processing:
479 local function read_body()
480 if request.headers_flags["Transfer-Encoding"]["chunked"] then
481 while true do
482 local line = read(32 + remaining_body_size_limit, "\n")
483 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
484 local chunkext
485 if lenstr then
486 chunkext = ""
487 else
488 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
489 end
490 if not lenstr or #lenstr > 13 then
491 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
492 end
493 local len = tonumber("0x" .. lenstr)
494 remaining_body_size_limit = remaining_body_size_limit - (#zeros + #chunkext + len)
495 if remaining_body_size_limit < 0 then
496 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
497 end
498 if len == 0 then break end
499 read_body_bytes(len)
500 local term = read(2, "\n")
501 if term ~= "\r\n" and term ~= "\n" then
502 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
503 end
504 end
505 while true do
506 local line = read(2 + remaining_body_size_limit, "\n")
507 if line == "\r\n" or line == "\n" then break end
508 remaining_body_size_limit = remaining_body_size_limit - #line
509 if remaining_body_size_limit < 0 then
510 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
511 end
512 end
513 elseif request_body_content_length then
514 read_body_bytes(request_body_content_length)
515 end
516 end
517 -- function to setup default request body handling:
518 local function default_request_body_handling()
519 local post_params_list, post_params = new_params_list()
520 local content_type = request.headers_value["Content-Type"]
521 if content_type then
522 if
523 content_type == "application/x-www-form-urlencoded" or
524 string.match(content_type, "^application/x%-www%-form%-urlencoded *;")
525 then
526 read_urlencoded_form(post_params_list, request.body)
527 request.post_params_list, request.post_params = post_params_list, post_params
528 else
529 local boundary = string.match(
530 content_type,
531 '^multipart/form%-data[ \t]*[;,][ \t]*boundary="([^"]+)"$'
532 ) or string.match(
533 content_type,
534 '^multipart/form%-data[ \t]*[;,][ \t]*boundary=([^"; \t]+)$'
535 )
536 if boundary then
537 local post_metadata_list, post_metadata = new_params_list()
538 boundary = "--" .. boundary
539 local headerdata = ""
540 local streamer
541 local field_name
542 local metadata = {}
543 local value_parts
544 local function default_streamer(chunk)
545 value_parts[#value_parts+1] = chunk
546 end
547 local function stream_part_finish()
548 if streamer == default_streamer then
549 local value = table.concat(value_parts)
550 value_parts = nil
551 if field_name then
552 local values = post_params_list[field_name]
553 values[#values+1] = value
554 local metadata_entries = post_metadata_list[field_name]
555 metadata_entries[#metadata_entries+1] = metadata
556 end
557 else
558 streamer()
559 end
560 headerdata = ""
561 streamer = nil
562 field_name = nil
563 metadata = {}
564 end
565 local function stream_part_chunk(chunk)
566 if streamer then
567 streamer(chunk)
568 else
569 headerdata = headerdata .. chunk
570 while true do
571 local line, remaining = string.match(headerdata, "^(.-)\r?\n(.*)$")
572 if not line then
573 break
574 end
575 if line == "" then
576 streamer = streamed_post_params[field_name]
577 if not streamer then
578 for i, rule in ipairs(streamed_post_param_patterns) do
579 if string.match(field_name, rule[1]) then
580 streamer = rule[2]
581 break
582 end
583 end
584 end
585 if not streamer then
586 value_parts = {}
587 streamer = default_streamer
588 end
589 streamer(remaining, field_name, metadata)
590 return
591 end
592 headerdata = remaining
593 local header_key, header_value = string.match(line, "^([^:]*):[ \t]*(.-)[ \t]*$")
594 if not header_key then
595 request_error(true, "400 Bad Request", "Invalid header in multipart/form-data part")
596 end
597 header_key = string.lower(header_key)
598 if header_key == "content-disposition" then
599 local escaped_header_value = string.gsub(header_value, '"[^"]*"', function(str)
600 return string.gsub(str, "=", "==")
601 end)
602 field_name = string.match(escaped_header_value, ';[ \t]*name="([^"]*)"')
603 if field_name then
604 field_name = string.gsub(field_name, "==", "=")
605 else
606 field_name = string.match(header_value, ';[ \t]*name=([^"; \t]+)')
607 end
608 metadata.file_name = string.match(escaped_header_value, ';[ \t]*filename="([^"]*)"')
609 if metadata.file_name then
610 metadata.file_name = string.gsub(metadata.file_name, "==", "=")
611 else
612 string.match(header_value, ';[ \t]*filename=([^"; \t]+)')
613 end
614 elseif header_key == "content-type" then
615 metadata.content_type = header_value
616 elseif header_key == "content-transfer-encoding" then
617 request_error(true, "400 Bad Request", "Content-transfer-encoding not supported by multipart/form-data parser")
618 end
619 end
620 end
621 end
622 local skippart = true -- ignore data until first boundary
623 local afterbound = false -- interpret 2 bytes after boundary ("\r\n" or "--")
624 local terminated = false -- final boundary read
625 local bigchunk = ""
626 request:set_request_body_streamer(function(chunk)
627 if chunk == nil then
628 if not terminated then
629 request_error(true, "400 Bad Request", "Premature end of multipart/form-data request body")
630 end
631 request.post_metadata_list, request.post_metadata = post_metadata_list, post_metadata
632 end
633 if terminated then
634 return
635 end
636 bigchunk = bigchunk .. chunk
637 while true do
638 if afterbound then
639 if #bigchunk <= 2 then
640 return
641 end
642 local terminator = string.sub(bigchunk, 1, 2)
643 if terminator == "\r\n" then
644 afterbound = false
645 bigchunk = string.sub(bigchunk, 3)
646 elseif terminator == "--" then
647 terminated = true
648 bigchunk = nil
649 return
650 else
651 request_error(true, "400 Bad Request", "Error while parsing multipart body (expected CRLF or double minus)")
652 end
653 end
654 local pos1, pos2 = string.find(bigchunk, boundary, 1, true)
655 if not pos1 then
656 if not skippart then
657 local safe = #bigchunk-#boundary
658 if safe > 0 then
659 stream_part_chunk(string.sub(bigchunk, 1, safe))
660 bigchunk = string.sub(bigchunk, safe+1)
661 end
662 end
663 return
664 end
665 if not skippart then
666 stream_part_chunk(string.sub(bigchunk, 1, pos1 - 1))
667 stream_part_finish()
668 else
669 boundary = "\r\n" .. boundary
670 skippart = false
671 end
672 bigchunk = string.sub(bigchunk, pos2 + 1)
673 afterbound = true
674 end
675 end)
676 else
677 request_error(true, "415 Unsupported Media Type", "Unknown Content-Type of request body")
678 end
679 end
680 end
681 end
682 -- function to prepare body processing:
683 local function prepare()
684 assert_not_faulty()
685 if process_body_chunk == nil then
686 default_request_body_handling()
687 end
688 if state ~= "init" then
689 return
690 end
691 consume = coroutine.wrap(read_body)
692 state = "no_status_sent"
693 if request.headers_flags["Expect"]["100-continue"] then
694 request:send_status("100 Continue")
695 request:finish_headers()
696 end
697 end
698 -- method to ignore input and close connection after response:
699 function request:monologue()
700 assert_not_faulty()
701 if
702 state == "headers_sent" or
703 state == "finished"
704 then
705 error("All HTTP headers have already been sent")
706 end
707 local old_state = state
708 state = "faulty"
709 consume = drain
710 close_requested = true
711 if old_state == "init" then
712 state = "no_status_sent"
713 else
714 state = old_state
715 end
716 end
717 --
718 -- method to send a HTTP response status (e.g. "200 OK"):
719 function request:send_status(status)
720 prepare()
721 local old_state = state
722 state = "faulty"
723 if old_state == "info_status_sent" then
724 send_flush("\r\n")
725 elseif old_state ~= "no_status_sent" then
726 error("HTTP status has already been sent")
727 end
728 local status1 = string.sub(status, 1, 1)
729 local status3 = string.sub(status, 1, 3)
730 send("HTTP/1.1 ", status, "\r\n", preamble)
731 local wrb = status_without_response_body[status3]
732 if wrb then
733 state = "bodyless_status_sent"
734 if wrb == "zero_content_length" then
735 request:send_header("Content-Length", 0)
736 end
737 elseif status1 == "1" then
738 state = "info_status_sent"
739 else
740 state = "status_sent"
741 end
742 end
743 -- method to send a HTTP response header:
744 -- (key and value must be provided as separate args)
745 function request:send_header(key, value)
746 assert_not_faulty()
747 if state == "init" or state == "no_status_sent" then
748 error("HTTP status has not been sent yet")
749 elseif
750 state == "headers_sent" or
751 state == "finished"
752 then
753 error("All HTTP headers have already been sent")
754 end
755 local key_lower = string.lower(key)
756 if key_lower == "content-length" then
757 if state == "info_status_sent" then
758 error("Cannot set Content-Length for informational status response")
759 end
760 local cl = assert(tonumber(value), "Invalid content-length")
761 if content_length == nil then
762 content_length = cl
763 elseif content_length == cl then
764 return
765 else
766 error("Content-Length has been set multiple times with different values")
767 end
768 elseif key_lower == "connection" then
769 for entry in string.gmatch(string.lower(value), "[^,]+") do
770 if string.match(entry, "^[ \t]*close[ \t]*$") then
771 if state == "info_status_sent" then
772 error("Cannot set \"Connection: close\" for informational status response")
773 end
774 close_responded = true
775 break
776 end
777 end
778 end
779 assert_output(socket:write(key, ": ", value, "\r\n"))
780 end
781 -- function to terminate header section in response, optionally flushing:
782 -- (may be called multiple times unless response is finished)
783 local function finish_headers(with_flush)
784 if state == "finished" then
785 error("Response has already been finished")
786 elseif state == "info_status_sent" then
787 send_flush("\r\n")
788 state = "no_status_sent"
789 elseif state == "bodyless_status_sent" then
790 if close_requested and not close_responded then
791 request:send_header("Connection", "close")
792 end
793 send("\r\n")
794 finish()
795 state = "finished"
796 elseif state == "status_sent" then
797 if not content_length then
798 request:send_header("Transfer-Encoding", "chunked")
799 end
800 if close_requested and not close_responded then
801 request:send_header("Connection", "close")
802 end
803 send("\r\n")
804 if request.method == "HEAD" then
805 finish()
806 elseif with_flush then
807 send_flush()
808 end
809 state = "headers_sent"
810 elseif state ~= "headers_sent" then
811 error("HTTP status has not been sent yet")
812 end
813 end
814 -- method to finish and flush headers:
815 function request:finish_headers()
816 assert_not_faulty()
817 finish_headers(true)
818 end
819 -- method to send body data:
820 function request:send_data(...)
821 assert_not_faulty()
822 if output_state == "info_status_sent" then
823 error("No (non-informational) HTTP status has been sent yet")
824 elseif output_state == "bodyless_status_sent" then
825 error("Cannot send response data for body-less status message")
826 end
827 finish_headers(false)
828 if output_state ~= "headers_sent" then
829 error("Unexpected internal status in HTTP engine")
830 end
831 if request.method == "HEAD" then
832 return
833 end
834 for i = 1, select("#", ...) do
835 local str = tostring(select(i, ...))
836 if #str > 0 then
837 if content_length then
838 local bytes_to_send = #str
839 if bytes_sent + bytes_to_send > content_length then
840 error("Content length exceeded")
841 else
842 send(str)
843 bytes_sent = bytes_sent + bytes_to_send
844 end
845 else
846 chunk_bytes = chunk_bytes + #str
847 chunk_parts[#chunk_parts+1] = str
848 end
849 end
850 end
851 if chunk_bytes >= output_chunk_size then
852 send_chunk()
853 end
854 end
855 -- method to flush output buffer:
856 function request:flush()
857 assert_not_faulty()
858 send_chunk()
859 send_flush()
860 end
861 -- method to finish response:
862 function request:finish()
863 assert_not_faulty()
864 if state == "finished" then
865 return
866 elseif state == "info_status_sent" then
867 error("Informational HTTP response can be finished with :finish_headers() method")
868 end
869 finish_headers(false)
870 if state == "headers_sent" then
871 if request.method ~= "HEAD" then
872 state = "faulty"
873 if content_length then
874 if bytes_sent ~= content_length then
875 error("Content length not used")
876 end
877 else
878 send_chunk()
879 send("0\r\n\r\n")
880 end
881 finish()
882 end
883 state = "finished"
884 elseif state ~= "finished" then
885 error("Unexpected internal status in HTTP engine")
886 end
887 end
888 -- method to register POST param stream handler for a single field name:
889 function request:stream_post_param(field_name, callback)
890 if state ~= "init" then
891 error("Cannot setup request body streamer at this stage")
892 end
893 streamed_post_params[field_name] = callback
894 end
895 -- method to register POST param stream handler for a field name pattern:
896 function request:stream_post_params(pattern, callback)
897 if state ~= "init" then
898 error("Cannot setup request body streamer at this stage")
899 end
900 streamed_post_param_patterns[#streamed_post_param_patterns+1] = {pattern, callback}
901 end
902 -- method to register request body stream handler
903 function request:set_request_body_streamer(callback)
904 if state ~= "init" then
905 error("Cannot setup request body streamer at this stage")
906 end
907 local inprogress = false
908 local buffer = {}
909 process_body_chunk = function(chunk)
910 if inprogress then
911 buffer[#buffer+1] = chunk
912 else
913 inprogress = true
914 callback(chunk)
915 while #buffer > 0 do
916 chunk = table.concat(buffer)
917 buffer = {}
918 callback(chunk)
919 end
920 inprogress = false
921 end
922 end
923 end
924 -- method to start reading request body
925 function request:consume_input()
926 prepare()
927 consume_all()
928 end
929 -- method to stream request body
930 function request:stream_request_body(callback)
931 request:set_request_body_streamer(function(chunk)
932 if chunk ~= nil then
933 callback(chunk)
934 end
935 end)
936 request:consume_input()
937 end
938 -- metamethod to read special attibutes of request object:
939 function request_mt:__index(key, value)
940 if key == "body" then
941 local chunks = {}
942 request:stream_request_body(function(chunk)
943 chunks[#chunks+1] = chunk
944 end)
945 self.body = table.concat(chunks)
946 return self.body
947 elseif
948 key == "post_params_list" or key == "post_params" or
949 key == "post_metadata_list" or key == "post_metadata"
950 then
951 prepare()
952 consume_all()
953 return self[key]
954 end
955 end
956 -- wait for input:
957 if not poll(socket_set, nil, request_idle_timeout) then
958 return request_error(false, "408 Request Timeout", "Idle connection timed out")
959 end
960 until close_responded
961 return survive
962 end
963 end
965 return _M

Impressum / About Us