2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local server = require "net.server"
11 local url_parse = require "socket.url".parse;
12 local httpstream_new = require "util.httpstream".new;
14 local connlisteners_start = require "net.connlisteners".start;
15 local connlisteners_get = require "net.connlisteners".get;
18 local t_insert, t_concat = table.insert, table.concat;
19 local tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type;
20 local xpcall = xpcall;
21 local debug_traceback = debug.traceback;
23 local urlencode = function (s) return s and (s:gsub("%W", function (c) return ("%%%02x"):format(c:byte()); end)); end
25 local log = require "util.logger".init("httpserver");
27 local http_servers = {};
31 local default_handler;
33 local function expectbody(reqt)
34 return reqt.method == "POST";
37 local function send_response(request, response)
40 if response.body or response.headers then
41 local body = response.body and tostring(response.body);
42 log("debug", "Sending response to %s", request.id);
43 resp = { "HTTP/1.0 "..(response.status or "200 OK").."\r\n" };
44 local h = response.headers;
46 for k, v in pairs(h) do
47 t_insert(resp, k..": "..v.."\r\n");
50 if body and not (h and h["Content-Length"]) then
51 t_insert(resp, "Content-Length: "..#body.."\r\n");
53 t_insert(resp, "\r\n");
55 if body and request.method ~= "HEAD" then
58 request.write(t_concat(resp));
60 -- Response we have is just a string (the body)
61 log("debug", "Sending 200 response to %s", request.id or "<none>");
63 local resp = "HTTP/1.0 200 OK\r\n"
64 .. "Connection: close\r\n"
65 .. "Content-Type: text/html\r\n"
66 .. "Content-Length: "..#response.."\r\n"
72 if not request.stayopen then
77 local function call_callback(request, err)
78 if request.handled then return; end
79 request.handled = true;
80 local callback = request.callback;
81 if not callback and request.path then
82 local path = request.url.path;
83 local base = path:match("^/([^/?]+)");
85 base = path:match("^http://[^/?]+/([^/?]+)");
88 callback = (request.server and request.server.handlers[base]) or default_handler;
91 local _callback = callback;
92 function callback(method, body, request)
93 local ok, result = xpcall(function() return _callback(method, body, request) end, debug_traceback);
94 if ok then return result; end
95 log("error", "Error in HTTP server handler: %s", result);
96 -- TODO: When we support pipelining, request.destroyed
97 -- won't be the right flag - we just want to see if there
98 -- has been a response to this request yet.
99 if not request.destroyed then
101 status = "500 Internal Server Error";
102 headers = { ["Content-Type"] = "text/plain" };
103 body = "There was an error processing your request. See the error log for more details.";
108 log("debug", "Request error: "..err);
109 if not callback(nil, err, request) then
110 destroy_request(request);
115 local response = callback(request.method, request.body and t_concat(request.body), request);
117 if response == true and not request.destroyed then
118 -- Keep connection open, we will reply later
119 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
120 elseif response ~= true then
122 send_response(request, response);
123 destroy_request(request);
126 log("debug", "Request handler provided no response, destroying request...");
127 -- No response, close connection
128 destroy_request(request);
133 local function request_reader(request, data, startpos)
134 if not request.parser then
135 local function success_cb(r)
136 for k,v in pairs(r) do request[k] = v; end
137 request.url = url_parse(request.path);
138 request.url.path = request.url.path and request.url.path:gsub("%%(%x%x)", function(x) return x.char(tonumber(x, 16)) end);
139 request.body = { request.body };
140 call_callback(request);
142 local function error_cb(r)
143 log("error", "Error in HTTP server handler: %s", r or "connection-closed");
144 call_callback(request, r or "connection-closed");
145 destroy_request(request);
147 request.parser = httpstream_new(success_cb, error_cb);
149 request.parser:feed(data);
152 -- The default handler for requests
153 default_handler = function (method, body, request)
154 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
155 return { status = "404 Not Found",
156 headers = { ["Content-Type"] = "text/html" },
157 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
161 function new_request(handler)
162 return { handler = handler, conn = handler,
163 write = function (...) return handler:write(...); end, state = "request",
164 server = http_servers[handler:serverport()],
165 send = send_response,
166 destroy = destroy_request,
167 id = tostring{}:match("%x+$")
171 function destroy_request(request)
172 log("debug", "Destroying request %s", request.id);
173 listener = listener or connlisteners_get("httpserver");
174 if not request.destroyed then
175 request.destroyed = true;
176 if request.on_destroy then
177 log("debug", "Request has destroy callback");
178 request.on_destroy(request);
180 log("debug", "Request has no destroy callback");
182 request.handler:close()
184 listener.ondisconnect(request.conn, "closed");
190 local http_server = http_servers[params.port];
191 if not http_server then
192 http_server = { handlers = {} };
193 http_servers[params.port] = http_server;
194 -- We weren't already listening on this port, so start now
195 connlisteners_start("httpserver", params);
198 http_server.handlers[params.base] = params.handler;
202 function set_default_handler(handler)
203 default_handler = handler;
206 function new_from_config(ports, handle_request, default_options)
207 if type(handle_request) == "string" then -- COMPAT with old plugins
208 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
209 handle_request, default_options = default_options, { base = handle_request };
211 ports = ports or {5280};
212 for _, options in ipairs(ports) do
213 local port = default_options.port or 5280;
214 local base = default_options.base;
215 local ssl = default_options.ssl or false;
216 local interface = default_options.interface;
217 if type(options) == "number" then
219 elseif type(options) == "table" then
220 port = options.port or port;
221 base = options.path or base;
222 ssl = options.ssl or ssl;
223 interface = options.interface or interface;
224 elseif type(options) == "string" then
230 ssl.protocol = "sslv23";
231 ssl.options = "no_sslv2";
234 new{ port = port, interface = interface,
235 base = base, handler = handle_request,
236 ssl = ssl, type = (ssl and "ssl") or "tcp" };
240 _M.request_reader = request_reader;
241 _M.send_response = send_response;
242 _M.urlencode = urlencode;