Merge sasl branch
[prosody.git] / net / http / server.lua
index 86d729f0050a718604aa7b735e5968fd6599b53f..dec7da1999c22c4cb6ae57ae83512b06bef369d7 100644 (file)
@@ -9,17 +9,16 @@ local pairs = pairs;
 local s_upper = string.upper;
 local setmetatable = setmetatable;
 local xpcall = xpcall;
-local debug = debug;
+local traceback = debug.traceback;
 local tostring = tostring;
 local codes = require "net.http.codes";
-local _G = _G;
-local legacy_httpserver = require "net.httpserver";
 
 local _M = {};
 
 local sessions = {};
-
 local listener = {};
+local hosts = {};
+local default_host;
 
 local function is_wildcard_event(event)
        return event:sub(-2, -1) == "/*";
@@ -28,8 +27,11 @@ local function is_wildcard_match(wildcard_event, event)
        return wildcard_event:sub(1, -2) == event:sub(1, #wildcard_event-1);
 end
 
+local recent_wildcard_events, max_cached_wildcard_events = {}, 10000;
+
 local event_map = events._event_map;
 setmetatable(events._handlers, {
+       -- Called when firing an event that doesn't exist (but may match a wildcard handler)
        __index = function (handlers, curr_event)
                if is_wildcard_event(curr_event) then return; end -- Wildcard events cannot be fired
                -- Find all handlers that could match this event, sort them
@@ -59,12 +61,18 @@ setmetatable(events._handlers, {
                        handlers_array = false;
                end
                rawset(handlers, curr_event, handlers_array);
+               if not event_map[curr_event] then -- Only wildcard handlers match, if any
+                       table.insert(recent_wildcard_events, curr_event);
+                       if #recent_wildcard_events > max_cached_wildcard_events then
+                               rawset(handlers, table.remove(recent_wildcard_events, 1), nil);
+                       end
+               end
                return handlers_array;
        end;
        __newindex = function (handlers, curr_event, handlers_array)
                if handlers_array == nil
                and is_wildcard_event(curr_event) then
-                       -- Invalidate all matching
+                       -- Invalidate the indexes of all matching events
                        for event in pairs(handlers) do
                                if is_wildcard_match(curr_event, event) then
                                        handlers[event] = nil;
@@ -80,7 +88,7 @@ local _1, _2, _3;
 local function _handle_request() return handle_request(_1, _2, _3); end
 
 local last_err;
-local function _traceback_handler(err) last_err = err; log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end
+local function _traceback_handler(err) last_err = err; log("error", "Traceback[httpserver]: %s", traceback(tostring(err), 2)); end
 events.add_handler("http-error", function (error)
        return "Error processing request: "..codes[error.code]..". Check your error log for more information.";
 end, -1);
@@ -89,30 +97,31 @@ function listener.onconnect(conn)
        local secure = conn:ssl() and true or nil;
        local pending = {};
        local waiting = false;
-       local function process_next(last_response)
-               --if waiting then log("debug", "can't process_next, waiting"); return; end
-               if sessions[conn] and #pending > 0 then
+       local function process_next()
+               if waiting then log("debug", "can't process_next, waiting"); return; end
+               waiting = true;
+               while sessions[conn] and #pending > 0 do
                        local request = t_remove(pending);
                        --log("debug", "process_next: %s", request.path);
-                       waiting = true;
                        --handle_request(conn, request, process_next);
                        _1, _2, _3 = conn, request, process_next;
                        if not xpcall(_handle_request, _traceback_handler) then
                                conn:write("HTTP/1.0 500 Internal Server Error\r\n\r\n"..events.fire_event("http-error", { code = 500, private_message = last_err }));
                                conn:close();
                        end
-               else
-                       --log("debug", "ready for more");
-                       waiting = false;
                end
+               --log("debug", "ready for more");
+               waiting = false;
        end
        local function success_cb(request)
                --log("debug", "success_cb: %s", request.path);
+               if waiting then
+                       log("error", "http connection handler is not reentrant: %s", request.path);
+                       assert(false, "http connection handler is not reentrant");
+               end
                request.secure = secure;
                t_insert(pending, request);
-               if not waiting then
-                       process_next();
-               end
+               process_next();
        end
        local function error_cb(err)
                log("debug", "error_cb: %s", err or "<nil>");
@@ -157,66 +166,85 @@ function handle_request(conn, request, finish_cb)
 
        local date_header = os_date('!%a, %d %b %Y %H:%M:%S GMT'); -- FIXME use
        local conn_header = request.headers.connection;
-       local keep_alive = conn_header == "Keep-Alive" or (request.httpversion == "1.1" and conn_header ~= "close");
+       conn_header = conn_header and ","..conn_header:gsub("[ \t]", ""):lower().."," or ""
+       local httpversion = request.httpversion
+       local persistent = conn_header:find(",Keep-Alive,", 1, true)
+               or (httpversion == "1.1" and not conn_header:find(",close,", 1, true));
+
+       local response_conn_header;
+       if persistent then
+               response_conn_header = "Keep-Alive";
+       else
+               response_conn_header = httpversion == "1.1" and "close" or nil
+       end
 
        local response = {
                request = request;
                status_code = 200;
-               headers = { date = date_header, connection = (keep_alive and "Keep-Alive" or "close") };
+               headers = { date = date_header, connection = response_conn_header };
+               persistent = persistent;
                conn = conn;
                send = _M.send_response;
                finish_cb = finish_cb;
        };
        conn._http_open_response = response;
 
-       local err;
-       if not request.headers.host then
-               err = "No 'Host' header";
-       elseif not request.path then
-               err = "Invalid path";
+       local host = (request.headers.host or ""):match("[^:]+");
+
+       -- Some sanity checking
+       local err_code, err;
+       if not request.path then
+               err_code, err = 400, "Invalid path";
+       elseif not hosts[host] then
+               if hosts[default_host] then
+                       host = default_host;
+               elseif host then
+                       err_code, err = 404, "Unknown host: "..host;
+               else
+                       err_code, err = 400, "Missing or invalid 'Host' header";
+               end
        end
        
        if err then
-               response.status_code = 400;
-               response.headers.content_type = "text/html";
-               response:send(events.fire_event("http-error", { code = 400, message = err }));
-       else
-               local host = request.headers.host;
-               if host then
-                       host = host:match("[^:]*"):lower();
-                       local event = request.method.." "..host..request.path:match("[^?]*");
-                       local payload = { request = request, response = response };
-                       --log("debug", "Firing event: %s", event);
-                       local result = events.fire_event(event, payload);
-                       if result ~= nil then
-                               if result ~= true then
-                                       local code, body = 200, "";
-                                       local result_type = type(result);
-                                       if result_type == "number" then
-                                               response.status_code = result;
-                                               if result >= 400 then
-                                                       body = events.fire_event("http-error", { code = result });
-                                               end
-                                       elseif result_type == "string" then
-                                               body = result;
-                                       elseif result_type == "table" then
-                                               body = result.body;
-                                               result.body = nil;
-                                               for k, v in pairs(result) do
-                                                       response[k] = v;
+               response.status_code = err_code;
+               response:send(events.fire_event("http-error", { code = err_code, message = err }));
+               return;
+       end
+
+       local event = request.method.." "..host..request.path:match("[^?]*");
+       local payload = { request = request, response = response };
+       --log("debug", "Firing event: %s", event);
+       local result = events.fire_event(event, payload);
+       if result ~= nil then
+               if result ~= true then
+                       local body;
+                       local result_type = type(result);
+                       if result_type == "number" then
+                               response.status_code = result;
+                               if result >= 400 then
+                                       body = events.fire_event("http-error", { code = result });
+                               end
+                       elseif result_type == "string" then
+                               body = result;
+                       elseif result_type == "table" then
+                               for k, v in pairs(result) do
+                                       if k ~= "headers" then
+                                               response[k] = v;
+                                       else
+                                               for header_name, header_value in pairs(v) do
+                                                       response.headers[header_name] = header_value;
                                                end
                                        end
-                                       response:send(body);
                                end
-                               return;
                        end
+                       response:send(body);
                end
-
-               -- if handler not called, return 404
-               response.status_code = 404;
-               response.headers.content_type = "text/html";
-               response:send(events.fire_event("http-error", { code = 404 }));
+               return;
        end
+
+       -- if handler not called, return 404
+       response.status_code = 404;
+       response:send(events.fire_event("http-error", { code = 404 }));
 end
 function _M.send_response(response, body)
        if response.finished then return; end
@@ -225,7 +253,7 @@ function _M.send_response(response, body)
        
        local status_line = "HTTP/"..response.request.httpversion.." "..(response.status or codes[response.status_code]);
        local headers = response.headers;
-       body = body or "";
+       body = body or response.body or "";
        headers.content_length = #body;
 
        local output = { status_line };
@@ -240,7 +268,7 @@ function _M.send_response(response, body)
                response:on_destroy();
                response.on_destroy = nil;
        end
-       if headers.connection == "Keep-Alive" then
+       if response.persistent then
                response:finish_cb();
        else
                response.conn:close();
@@ -256,6 +284,18 @@ end
 function _M.listen_on(port, interface, ssl)
        addserver(interface or "*", port, listener, "*a", ssl);
 end
+function _M.add_host(host)
+       hosts[host] = true;
+end
+function _M.remove_host(host)
+       hosts[host] = nil;
+end
+function _M.set_default_host(host)
+       default_host = host;
+end
+function _M.fire_event(event, ...)
+       return events.fire_event(event, ...);
+end
 
 _M.listener = listener;
 _M.codes = codes;