moonbridge

view moonbridge_http.lua @ 171:32d7423a6753

Removed "prepare" state and added 100-Continue header in local prepare() function in HTTP module
author jbe
date Tue Jun 16 02:49:34 2015 +0200 (2015-06-16)
parents 4d5cf5cacc68
children fb54c76e1484
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:
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 = string.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 -- local variables to track the state:
339 local state = "init" -- one of:
340 -- "init" (initial state)
341 -- "no_status_sent" (configuration complete)
342 -- "info_status_sent" (1xx status code has been sent)
343 -- "bodyless_status_sent" (204/304 status code has been sent)
344 -- "status_sent" (regular status code has been sent)
345 -- "headers_sent" (headers have been terminated)
346 -- "finished" (request has been answered completely)
347 -- "faulty" (I/O or protocaol error)
348 local close_requested = false -- "Connection: close" requested
349 local close_responded = false -- "Connection: close" sent
350 local content_length = nil -- value of Content-Length header sent
351 local chunk_parts = {} -- list of chunks to send
352 local chunk_bytes = 0 -- sum of lengths of chunks to send
353 -- functions to assert proper output/closing:
354 local function assert_output(...)
355 local retval, errmsg = ...
356 if retval then return ... end
357 state = "faulty"
358 socket:reset()
359 error("Could not send data to client: " .. errmsg)
360 end
361 local function assert_close(...)
362 local retval, errmsg = ...
363 if retval then return ... end
364 state = "faulty"
365 error("Could not finish sending data to client: " .. errmsg)
366 end
367 -- function to assert non-faulty handle:
368 local function assert_not_faulty()
369 assert(state ~= "faulty", "Tried to use faulty request handle")
370 end
371 -- functions to send data to the browser:
372 local function send(...)
373 assert_output(socket:write_call(unblock, ...))
374 end
375 local function send_flush(...)
376 assert_output(socket:flush_call(unblock, ...))
377 end
378 -- function to finish request:
379 local function finish()
380 if close_responded then
381 -- discard any input:
382 consume = drain
383 -- close output stream:
384 send_flush()
385 assert_close(socket:finish())
386 -- wait for EOF of peer to avoid immediate TCP RST condition:
387 consume_all()
388 -- fully close socket:
389 assert_close(socket:close())
390 else
391 send_flush()
392 consume_all()
393 end
394 end
395 -- function that writes out buffered chunks (without flushing the socket):
396 function send_chunk()
397 if chunk_bytes > 0 then
398 assert_output(socket:write(string.format("%x\r\n", chunk_bytes)))
399 for i = 1, #chunk_parts do -- TODO: evaluated only once?
400 send(chunk_parts[i])
401 chunk_parts[i] = nil
402 end
403 chunk_bytes = 0
404 send("\r\n")
405 end
406 end
407 -- function to report an error:
408 local function request_error(throw_error, status, text)
409 local errmsg = "Error while reading request from client. Error response: " .. status
410 if text then
411 errmsg = errmsg .. " (" .. text .. ")"
412 end
413 if
414 state == "init" or
415 state == "no_status_sent" or
416 state == "info_status_sent"
417 then
418 local error_response_status, errmsg2 = pcall(function()
419 request:monologue()
420 request:send_status(status)
421 request:send_header("Content-Type", "text/plain")
422 request:send_data(status, "\n")
423 if text then
424 request:send_data("\n", text, "\n")
425 end
426 request:finish()
427 end)
428 if not error_response_status then
429 error("Unexpected error while sending error response: " .. errmsg2)
430 end
431 elseif state ~= "faulty" then
432 state = "faulty"
433 assert_close(socket:reset())
434 end
435 if throw_error then
436 error(errmsg)
437 else
438 return survive
439 end
440 end
441 -- read function
442 local function read(...)
443 local data, status = socket:read_yield(...)
444 if data == nil then
445 request_error(true, "400 Bad Request", "Read error")
446 end
447 if status == "eof" then
448 request_error(true, "400 Bad Request", "Unexpected EOF")
449 end
450 return data
451 end
452 -- callback for request body streaming:
453 local process_body_chunk
454 -- reads a number of bytes from the socket,
455 -- optionally feeding these bytes chunk-wise
456 -- into a callback function:
457 local function read_body_bytes(remaining)
458 while remaining > 0 do
459 local limit
460 if remaining > input_chunk_size then
461 limit = input_chunk_size
462 else
463 limit = remaining
464 end
465 local chunk = read(limit)
466 remaining = remaining - limit
467 if process_body_chunk then
468 process_body_chunk(chunk)
469 end
470 end
471 end
472 -- coroutine for request body processing:
473 local function read_body()
474 if request.headers_flags["Transfer-Encoding"]["chunked"] then
475 while true do
476 local line = read(32 + remaining_body_size_limit, "\n")
477 local zeros, lenstr = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)\r?\n$")
478 local chunkext
479 if lenstr then
480 chunkext = ""
481 else
482 zeros, lenstr, chunkext = string.match(line, "^(0*)([1-9A-Fa-f]+[0-9A-Fa-f]*)([ \t;].-)\r?\n$")
483 end
484 if not lenstr or #lenstr > 13 then
485 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
486 end
487 local len = tonumber("0x" .. lenstr)
488 remaining_body_size_limit = remaining_body_size_limit - (#zeros + #chunkext + len)
489 if remaining_body_size_limit < 0 then
490 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded")
491 end
492 if len == 0 then break end
493 read_body_bytes(len)
494 local term = read(2, "\n")
495 if term ~= "\r\n" and term ~= "\n" then
496 request_error(true, "400 Bad Request", "Encoding error while reading chunk of request body")
497 end
498 end
499 while true do
500 local line = read(2 + remaining_body_size_limit, "\n")
501 if line == "\r\n" or line == "\n" then break end
502 remaining_body_size_limit = remaining_body_size_limit - #line
503 if remaining_body_size_limit < 0 then
504 request_error(true, "413 Request Entity Too Large", "Request body size limit exceeded while reading trailer section of chunked request body")
505 end
506 end
507 elseif request_body_content_length then
508 read_body_bytes(request_body_content_length)
509 end
510 end
511 -- function to prepare (or skip) body processing:
512 local function prepare()
513 assert_not_faulty()
514 if state ~= "init" then
515 return
516 end
517 consume = coroutine.wrap(read_body)
518 state = "no_status_sent"
519 if request.headers_flags["Expect"]["100-continue"] then
520 request:send_status("100 Continue")
521 request:finish_headers()
522 end
523 end
524 -- method to ignore input and close connection after response:
525 function request:monologue()
526 assert_not_faulty()
527 if
528 state == "headers_sent" or
529 state == "finished"
530 then
531 error("All HTTP headers have already been sent")
532 end
533 local old_state = state
534 state = "faulty"
535 consume = drain
536 close_requested = true
537 if old_state == "init" then
538 state = "no_status_sent"
539 else
540 state = old_state
541 end
542 end
543 --
544 -- method to send a HTTP response status (e.g. "200 OK"):
545 function request:send_status(status)
546 prepare()
547 local old_state = state
548 state = "faulty"
549 if old_state == "info_status_sent" then
550 send_flush("\r\n")
551 elseif old_state ~= "no_status_sent" then
552 error("HTTP status has already been sent")
553 end
554 local status1 = string.sub(status, 1, 1)
555 local status3 = string.sub(status, 1, 3)
556 send("HTTP/1.1 ", status, "\r\n", preamble)
557 local wrb = status_without_response_body[status3]
558 if wrb then
559 state = "bodyless_status_sent"
560 if wrb == "zero_content_length" then
561 request:send_header("Content-Length", 0)
562 end
563 elseif status1 == "1" then
564 state = "info_status_sent"
565 else
566 state = "status_sent"
567 end
568 end
569 -- method to send a HTTP response header:
570 -- (key and value must be provided as separate args)
571 function request:send_header(key, value)
572 assert_not_faulty()
573 if state == "init" or state == "no_status_sent" then
574 error("HTTP status has not been sent yet")
575 elseif
576 state == "headers_sent" or
577 state == "finished"
578 then
579 error("All HTTP headers have already been sent")
580 end
581 local key_lower = string.lower(key)
582 if key_lower == "content-length" then
583 if state == "info_status_sent" then
584 error("Cannot set Content-Length for informational status response")
585 end
586 local cl = assert(tonumber(value), "Invalid content-length")
587 if content_length == nil then
588 content_length = cl
589 elseif content_length == cl then
590 return
591 else
592 error("Content-Length has been set multiple times with different values")
593 end
594 elseif key_lower == "connection" then
595 for entry in string.gmatch(string.lower(value), "[^,]+") do
596 if string.match(entry, "^[ \t]*close[ \t]*$") then
597 if state == "info_status_sent" then
598 error("Cannot set \"Connection: close\" for informational status response")
599 end
600 close_responded = true
601 break
602 end
603 end
604 end
605 assert_output(socket:write(key, ": ", value, "\r\n"))
606 end
607 -- function to terminate header section in response, optionally flushing:
608 -- (may be called multiple times unless response is finished)
609 local function finish_headers(with_flush)
610 if state == "finished" then
611 error("Response has already been finished")
612 elseif state == "info_status_sent" then
613 send_flush("\r\n")
614 state = "no_status_sent"
615 elseif state == "bodyless_status_sent" then
616 if close_requested and not close_responded then
617 request:send_header("Connection", "close")
618 end
619 send("\r\n")
620 finish()
621 state = "finished"
622 elseif state == "status_sent" then
623 if not content_length then
624 request:send_header("Transfer-Encoding", "chunked")
625 end
626 if close_requested and not close_responded then
627 request:send_header("Connection", "close")
628 end
629 send("\r\n")
630 if request.method == "HEAD" then
631 finish()
632 elseif with_flush then
633 send_flush()
634 end
635 state = "headers_sent"
636 elseif state ~= "headers_sent" then
637 error("HTTP status has not been sent yet")
638 end
639 end
640 -- method to finish and flush headers:
641 function request:finish_headers()
642 assert_not_faulty()
643 finish_headers(true)
644 end
645 -- method to send body data:
646 function request:send_data(...)
647 assert_not_faulty()
648 if output_state == "info_status_sent" then
649 error("No (non-informational) HTTP status has been sent yet")
650 elseif output_state == "bodyless_status_sent" then
651 error("Cannot send response data for body-less status message")
652 end
653 finish_headers(false)
654 if output_state ~= "headers_sent" then
655 error("Unexpected internal status in HTTP engine")
656 end
657 if request.method == "HEAD" then
658 return
659 end
660 for i = 1, select("#", ...) do
661 local str = tostring(select(i, ...))
662 if #str > 0 then
663 if content_length then
664 local bytes_to_send = #str
665 if bytes_sent + bytes_to_send > content_length then
666 error("Content length exceeded")
667 else
668 send(str)
669 bytes_sent = bytes_sent + bytes_to_send
670 end
671 else
672 chunk_bytes = chunk_bytes + #str
673 chunk_parts[#chunk_parts+1] = str
674 end
675 end
676 end
677 if chunk_bytes >= output_chunk_size then
678 send_chunk()
679 end
680 end
681 -- method to flush output buffer:
682 function request:flush()
683 assert_not_faulty()
684 send_chunk()
685 send_flush()
686 end
687 -- method to finish response:
688 function request:finish()
689 assert_not_faulty()
690 if state == "finished" then
691 return
692 elseif state == "info_status_sent" then
693 error("Informational HTTP response can be finished with :finish_headers() method")
694 end
695 finish_headers(false)
696 if state == "headers_sent" then
697 if request.method ~= "HEAD" then
698 state = "faulty"
699 if content_length then
700 if bytes_sent ~= content_length then
701 error("Content length not used")
702 end
703 else
704 send_chunk()
705 send("0\r\n\r\n")
706 end
707 finish()
708 end
709 state = "finished"
710 elseif state ~= "finished" then
711 error("Unexpected internal status in HTTP engine")
712 end
713 end
714 -- wait for input:
715 if not poll(socket_set, nil, request_idle_timeout) then
716 return request_error(false, "408 Request Timeout", "Idle connection timed out")
717 end
718 until close_responded
719 return survive
720 end
721 end
723 return _M

Impressum / About Us