jbe@0: #!/usr/bin/env lua jbe@0: jbe@0: -- module preamble jbe@0: local _G, _M = _ENV, {} jbe@0: _ENV = setmetatable({}, { jbe@0: __index = function(self, key) jbe@0: local value = _M[key]; if value ~= nil then return value end jbe@0: return _G[key] jbe@0: end, jbe@63: __newindex = _M jbe@0: }) jbe@0: jbe@0: -- function that encodes certain HTML entities: jbe@0: -- (not used by the library itself) jbe@0: function encode_html(text) jbe@0: return ( jbe@0: string.gsub( jbe@0: text, '[<>&"]', jbe@0: function(char) jbe@0: if char == '<' then jbe@0: return "<" jbe@0: elseif char == '>' then jbe@0: return ">" jbe@0: elseif char == '&' then jbe@0: return "&" jbe@0: elseif char == '"' then jbe@0: return """ jbe@0: end jbe@0: end jbe@0: ) jbe@0: ) jbe@0: jbe@0: end jbe@0: jbe@0: -- function that encodes special characters for URIs: jbe@0: -- (not used by the library itself) jbe@0: function encode_uri(text) jbe@0: return ( jbe@0: string.gsub(text, "[^0-9A-Za-z_%.~-]", jbe@0: function (char) jbe@0: return string.format("%%%02x", string.byte(char)) jbe@0: end jbe@0: ) jbe@0: ) jbe@0: end jbe@0: jbe@0: -- function undoing URL encoding: jbe@0: do jbe@0: local b0 = string.byte("0") jbe@0: local b9 = string.byte("9") jbe@0: local bA = string.byte("A") jbe@0: local bF = string.byte("F") jbe@0: local ba = string.byte("a") jbe@0: local bf = string.byte("f") jbe@0: function decode_uri(str) jbe@0: return ( jbe@0: string.gsub( jbe@0: string.gsub(str, "%+", " "), jbe@0: "%%([0-9A-Fa-f][0-9A-Fa-f])", jbe@0: function(hex) jbe@0: local n1, n2 = string.byte(hex, 1, 2) jbe@0: if n1 >= b0 and n1 <= b9 then n1 = n1 - b0 jbe@0: elseif n1 >= bA and n1 <= bF then n1 = n1 - bA + 10 jbe@0: elseif n1 >= ba and n1 <= bf then n1 = n1 - ba + 10 jbe@0: else error("Assertion failed") end jbe@0: if n2 >= b0 and n2 <= b9 then n2 = n2 - b0 jbe@0: elseif n2 >= bA and n2 <= bF then n2 = n2 - bA + 10 jbe@0: elseif n2 >= ba and n2 <= bf then n2 = n2 - ba + 10 jbe@0: else error("Assertion failed") end jbe@0: return string.char(n1 * 16 + n2) jbe@0: end jbe@0: ) jbe@0: ) jbe@0: end jbe@0: end jbe@0: jbe@0: -- status codes that carry no response body (in addition to 1xx): jbe@0: -- (set to "zero_content_length" if Content-Length header is required) jbe@0: status_without_response_body = { jbe@5: ["101"] = true, -- list 101 to allow protocol switch jbe@0: ["204"] = true, jbe@0: ["205"] = "zero_content_length", jbe@0: ["304"] = true jbe@0: } jbe@0: jbe@154: -- parses URL encoded form data: jbe@154: local function read_urlencoded_form(data) jbe@154: local tbl = {} jbe@154: for rawkey, rawvalue in string.gmatch(data, "([^?=&]*)=([^?=&]*)") do jbe@154: local key = decode_uri(rawkey) jbe@154: local value = decode_uri(rawvalue) jbe@154: local subtbl = tbl[key] jbe@154: if subtbl then jbe@154: subtbl[#subtbl+1] = value jbe@154: else jbe@154: tbl[key] = {value} jbe@35: end jbe@35: end jbe@154: return tbl jbe@0: end jbe@0: jbe@154: -- extracts first value from each subtable: jbe@154: local function get_first_values(tbl) jbe@154: local newtbl = {} jbe@154: for key, subtbl in pairs(tbl) do jbe@154: newtbl[key] = subtbl[1] jbe@0: end jbe@154: return newtbl jbe@154: end jbe@154: jbe@0: function generate_handler(handler, options) jbe@0: -- swap arguments if necessary (for convenience): jbe@0: if type(handler) ~= "function" and type(options) == "function" then jbe@0: handler, options = options, handler jbe@0: end jbe@160: -- helper function to process options: jbe@160: local function default(name, default_value) jbe@160: local value = options[name] jbe@160: if value == nil then jbe@160: return default_value jbe@160: else jbe@160: return value or nil jbe@159: end jbe@160: end jbe@0: -- process options: jbe@0: options = options or {} jbe@0: local preamble = "" -- preamble sent with every(!) HTTP response jbe@0: do jbe@0: -- named arg "static_headers" is used to create the preamble: jbe@0: local s = options.static_headers jbe@0: local t = {} jbe@0: if s then jbe@0: if type(s) == "string" then jbe@0: for line in string.gmatch(s, "[^\r\n]+") do jbe@0: t[#t+1] = line jbe@0: end jbe@0: else jbe@0: for i, kv in ipairs(options.static_headers) do jbe@0: if type(kv) == "string" then jbe@0: t[#t+1] = kv jbe@0: else jbe@0: t[#t+1] = kv[1] .. ": " .. kv[2] jbe@0: end jbe@0: end jbe@0: end jbe@0: end jbe@0: t[#t+1] = "" jbe@0: preamble = table.concat(t, "\r\n") jbe@0: end jbe@160: local input_chunk_size = options.maximum_input_chunk_size or options.chunk_size or 16384 jbe@44: local output_chunk_size = options.minimum_output_chunk_size or options.chunk_size or 1024 jbe@160: local header_size_limit = options.header_size_limit or 1024*1024 jbe@160: local body_size_limit = options.body_size_limit or 64*1024*1024 jbe@160: local request_idle_timeout = default("request_idle_timeout", 330) jbe@160: local request_header_timeout = default("request_header_timeout", 30) jbe@160: local request_body_timeout = default("request_body_timeout", 60) jbe@160: local request_response_timeout = default("request_response_timeout", 1800) jbe@160: local poll = options.poll_function or moonbridge_io.poll jbe@160: -- return socket handler: jbe@0: return function(socket) jbe@160: local socket_set = {[socket] = true} -- used for poll function jbe@0: local survive = true -- set to false if process shall be terminated later jbe@160: local consume -- function that reads some input if possible jbe@160: -- function that drains some input if possible: jbe@160: local function drain() jbe@163: local bytes, status = socket:drain_nb(input_chunk_size) jbe@163: if not bytes or status == "eof" then jbe@160: consume = nil jbe@50: end jbe@159: end jbe@163: -- function trying to unblock socket by reading: jbe@160: local function unblock() jbe@160: if consume then jbe@160: poll(socket_set, socket_set) jbe@160: consume() jbe@160: else jbe@160: poll(nil, socket_set) jbe@0: end jbe@154: end jbe@163: -- function that enforces consumption of all input: jbe@162: local function consume_all() jbe@162: while consume do jbe@163: poll(socket_set, nil) jbe@162: consume() jbe@162: end jbe@162: end jbe@163: -- handle requests in a loop: jbe@160: repeat jbe@162: -- create a new request object: jbe@160: local request = { jbe@0: socket = socket, jbe@160: cookies = {} jbe@0: } jbe@162: -- local variables to track the state: jbe@162: local state = "init" -- one of: jbe@162: -- "init" (initial state) jbe@163: -- "prepare" (configureation in preparation) jbe@162: -- "no_status_sent" (configuration complete) jbe@162: -- "info_status_sent" (1xx status code has been sent) jbe@162: -- "bodyless_status_sent" (204/304 status code has been sent) jbe@162: -- "status_sent" (regular status code has been sent) jbe@162: -- "headers_sent" (headers have been terminated) jbe@162: -- "finished" (request has been answered completely) jbe@163: -- "faulty" (I/O or protocaol error) jbe@162: local close_requested = false -- "Connection: close" requested jbe@162: local close_responded = false -- "Connection: close" sent jbe@162: local content_length = nil -- value of Content-Length header sent jbe@163: -- functions to assert proper output/closing: jbe@163: local function assert_output(...) jbe@163: local retval, errmsg = ... jbe@163: if retval then return ... end jbe@163: state = "faulty" jbe@163: socket:reset() jbe@163: error("Could not send data to client: " .. errmsg) jbe@163: end jbe@163: local function assert_close(...) jbe@163: local retval, errmsg = ... jbe@163: if retval then return ... end jbe@163: state = "faulty" jbe@163: error("Could not finish sending data to client: " .. errmsg) jbe@163: end jbe@162: -- functions to send data to the browser: jbe@160: local function send(...) jbe@163: assert_output(socket:write_call(unblock, ...)) jbe@38: end jbe@162: local function send_flush(...) jbe@163: assert_output(socket:flush_call(unblock, ...)) jbe@162: end jbe@163: -- function to finish request: jbe@163: local function finish() jbe@163: if close_responded then jbe@163: -- discard any input: jbe@163: consume = drain jbe@163: -- close output stream: jbe@163: send_flush() jbe@163: assert_close(socket:finish()) jbe@163: -- wait for EOF of peer to avoid immediate TCP RST condition: jbe@163: consume_all() jbe@163: -- fully close socket: jbe@163: assert_close(socket:close()) jbe@163: else jbe@163: send_flush() jbe@163: consume_all() jbe@163: end jbe@163: end jbe@163: -- function to prepare body processing: jbe@162: local function prepare() jbe@162: if state == "prepare" then jbe@162: error("Unexpected internal status in HTTP engine") jbe@162: elseif state ~= "init" then jbe@162: return jbe@162: end jbe@162: state = "prepare" jbe@162: -- TODO jbe@162: state = "no_status_sent" jbe@162: end jbe@163: -- method to ignore input and close connection after response: jbe@163: function request:monologue() jbe@163: prepare() jbe@163: if jbe@163: state == "headers_sent" or jbe@163: state == "finished" jbe@163: then jbe@163: error("All HTTP headers have already been sent") jbe@163: end jbe@163: consume = drain jbe@163: close_requested = true jbe@163: if state == "init" or state == "prepare" then -- TODO: ok? jbe@163: state = "no_status_sent" jbe@162: end jbe@162: end jbe@163: -- jbe@162: -- method to send a HTTP response status (e.g. "200 OK"): jbe@162: function request:send_status(status) jbe@162: prepare() jbe@162: if state == "info_status_sent" then jbe@162: send_flush("\r\n") jbe@162: elseif state ~= "no_status_sent" then jbe@162: error("HTTP status has already been sent") jbe@162: end jbe@162: local status1 = string.sub(status, 1, 1) jbe@162: local status3 = string.sub(status, 1, 3) jbe@162: send("HTTP/1.1 ", status, "\r\n", preamble) jbe@162: local wrb = status_without_response_body[status3] jbe@162: if wrb then jbe@162: state = "bodyless_status_sent" jbe@162: if wrb == "zero_content_length" then jbe@162: request:send_header("Content-Length", 0) jbe@162: end jbe@162: elseif status1 == "1" then jbe@162: state = "info_status_sent" jbe@162: else jbe@162: state = "status_sent" jbe@162: end jbe@162: end jbe@162: -- method to send a HTTP response header: jbe@162: -- (key and value must be provided as separate args) jbe@162: function request:send_header(key, value) jbe@162: prepare() jbe@162: if state == "no_status_sent" then jbe@162: error("HTTP status has not been sent yet") jbe@162: elseif jbe@162: state ~= "info_status_sent" and jbe@162: state ~= "bodyless_status_sent" and jbe@162: state ~= "status_sent" jbe@162: then jbe@162: error("All HTTP headers have already been sent") jbe@162: end jbe@162: local key_lower = string.lower(key) jbe@162: if key_lower == "content-length" then jbe@162: if state == "info_status_sent" then jbe@162: error("Cannot set Content-Length for informational status response") jbe@162: end jbe@162: local cl = assert(tonumber(value), "Invalid content-length") jbe@162: if content_length == nil then jbe@162: content_length = cl jbe@162: elseif content_length == cl then jbe@162: return jbe@162: else jbe@162: error("Content-Length has been set multiple times with different values") jbe@162: end jbe@162: elseif key_lower == "connection" then jbe@162: for entry in string.gmatch(string.lower(value), "[^,]+") do jbe@162: if string.match(entry, "^[ \t]*close[ \t]*$") then jbe@162: if state == "info_status_sent" then jbe@162: error("Cannot set \"Connection: close\" for informational status response") jbe@162: end jbe@162: close_responded = true jbe@162: break jbe@162: end jbe@162: end jbe@162: end jbe@162: assert_output(socket:write(key, ": ", value, "\r\n")) jbe@162: end jbe@162: -- function to terminate header section in response, optionally flushing: jbe@162: -- (may be called multiple times unless response is finished) jbe@162: local function finish_headers(with_flush) jbe@162: if state == "finished" then jbe@162: error("Response has already been finished") jbe@162: elseif state == "info_status_sent" then jbe@162: send_flush("\r\n") jbe@162: state = "no_status_sent" jbe@162: elseif state == "bodyless_status_sent" then jbe@162: if close_requested and not close_responded then jbe@162: request:send_header("Connection", "close") jbe@162: end jbe@162: send("\r\n") jbe@163: finish() jbe@162: state = "finished" jbe@162: elseif state == "status_sent" then jbe@162: if not content_length then jbe@162: request:send_header("Transfer-Encoding", "chunked") jbe@162: end jbe@162: if close_requested and not close_responded then jbe@162: request:send_header("Connection", "close") jbe@162: end jbe@162: send("\r\n") jbe@162: if request.method == "HEAD" then jbe@163: finish() jbe@162: elseif with_flush then jbe@162: send_flush() jbe@162: end jbe@162: state = "headers_sent" jbe@162: elseif state ~= "headers_sent" then jbe@162: error("HTTP status has not been sent yet") jbe@162: end jbe@162: end jbe@162: -- method to finish and flush headers: jbe@162: function request:finish_headers() jbe@162: prepare() jbe@162: finish_headers(true) jbe@162: end jbe@163: -- function to report an error: jbe@163: local function request_error(throw_error, status, text) jbe@163: local errmsg = "Error while reading request from client. Error response: " .. status jbe@163: if text then jbe@163: errmsg = errmsg .. " (" .. text .. ")" jbe@163: end jbe@163: if jbe@163: state == "init" or jbe@163: state == "prepare" or jbe@163: state == "no_status_sent" or jbe@163: state == "info_status_sent" jbe@163: then jbe@163: local error_response_status, errmsg2 = pcall(function() jbe@163: request:monologue() jbe@163: request:send_status(status) jbe@163: request:send_header("Content-Type", "text/plain") jbe@163: request:send_data(status, "\n") jbe@163: if text then jbe@163: request:send_data("\n", text, "\n") jbe@163: end jbe@163: request:finish() jbe@163: end) jbe@163: if not error_response_status then jbe@163: error("Unexpected error while sending error response: " .. errmsg2) jbe@163: end jbe@163: elseif state ~= "faulty" then jbe@163: assert_close(socket:reset()) jbe@163: end jbe@163: if throw_error then jbe@163: error(errmsg) jbe@163: else jbe@163: return survive jbe@163: end jbe@163: end jbe@160: -- wait for input: jbe@160: if not poll(socket_set, nil, request_idle_timeout) then jbe@163: return request_error(false, "408 Request Timeout", "Idle connection timed out") jbe@38: end jbe@162: until close_responded jbe@0: return survive jbe@0: end jbe@0: end jbe@0: jbe@0: return _M jbe@0: