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 send_response(request, response)
36 if response.body or response.headers then
37 local body = response.body and tostring(response.body);
38 log("debug", "Sending response to %s", request.id);
39 resp = { "HTTP/1.0 "..(response.status or "200 OK").."\r\n" };
40 local h = response.headers;
42 for k, v in pairs(h) do
43 t_insert(resp, k..": "..v.."\r\n");
46 if body and not (h and h["Content-Length"]) then
47 t_insert(resp, "Content-Length: "..#body.."\r\n");
49 t_insert(resp, "\r\n");
51 if body and request.method ~= "HEAD" then
54 request.write(t_concat(resp));
56 -- Response we have is just a string (the body)
57 log("debug", "Sending 200 response to %s", request.id or "<none>");
59 local resp = "HTTP/1.0 200 OK\r\n"
60 .. "Connection: close\r\n"
61 .. "Content-Type: text/html\r\n"
62 .. "Content-Length: "..#response.."\r\n"
68 if not request.stayopen then
73 local function call_callback(request, err)
74 if request.handled then return; end
75 request.handled = true;
76 local callback = request.callback;
77 if not callback and request.path then
78 local path = request.url.path;
79 local base = path:match("^/([^/?]+)");
81 base = path:match("^http://[^/?]+/([^/?]+)");
84 callback = (request.server and request.server.handlers[base]) or default_handler;
87 local _callback = callback;
88 function callback(method, body, request)
89 local ok, result = xpcall(function() return _callback(method, body, request) end, debug_traceback);
90 if ok then return result; end
91 log("error", "Error in HTTP server handler: %s", result);
92 -- TODO: When we support pipelining, request.destroyed
93 -- won't be the right flag - we just want to see if there
94 -- has been a response to this request yet.
95 if not request.destroyed then
97 status = "500 Internal Server Error";
98 headers = { ["Content-Type"] = "text/plain" };
99 body = "There was an error processing your request. See the error log for more details.";
104 log("debug", "Request error: "..err);
105 if not callback(nil, err, request) then
106 destroy_request(request);
111 local response = callback(request.method, request.body and t_concat(request.body), request);
113 if response == true and not request.destroyed then
114 -- Keep connection open, we will reply later
115 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
116 elseif response ~= true then
118 send_response(request, response);
119 destroy_request(request);
122 log("debug", "Request handler provided no response, destroying request...");
123 -- No response, close connection
124 destroy_request(request);
129 local function request_reader(request, data, startpos)
130 if not request.parser then
131 local function success_cb(r)
132 for k,v in pairs(r) do request[k] = v; end
133 request.url = url_parse(request.path);
134 request.url.path = request.url.path and request.url.path:gsub("%%(%x%x)", function(x) return x.char(tonumber(x, 16)) end);
135 request.body = { request.body };
136 call_callback(request);
138 local function error_cb(r)
139 log("error", "Error in HTTP server handler: %s", r or "connection-closed");
140 call_callback(request, r or "connection-closed");
141 destroy_request(request);
143 request.parser = httpstream_new(success_cb, error_cb);
145 request.parser:feed(data);
148 -- The default handler for requests
149 default_handler = function (method, body, request)
150 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
151 return { status = "404 Not Found",
152 headers = { ["Content-Type"] = "text/html" },
153 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
157 function new_request(handler)
158 return { handler = handler, conn = handler,
159 write = function (...) return handler:write(...); end, state = "request",
160 server = http_servers[handler:serverport()],
161 send = send_response,
162 destroy = destroy_request,
163 id = tostring{}:match("%x+$")
167 function destroy_request(request)
168 log("debug", "Destroying request %s", request.id);
169 listener = listener or connlisteners_get("httpserver");
170 if not request.destroyed then
171 request.destroyed = true;
172 if request.on_destroy then
173 log("debug", "Request has destroy callback");
174 request.on_destroy(request);
176 log("debug", "Request has no destroy callback");
178 request.handler:close()
180 listener.ondisconnect(request.conn, "closed");
186 local http_server = http_servers[params.port];
187 if not http_server then
188 http_server = { handlers = {} };
189 http_servers[params.port] = http_server;
190 -- We weren't already listening on this port, so start now
191 connlisteners_start("httpserver", params);
194 http_server.handlers[params.base] = params.handler;
198 function set_default_handler(handler)
199 default_handler = handler;
202 function new_from_config(ports, handle_request, default_options)
203 if type(handle_request) == "string" then -- COMPAT with old plugins
204 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
205 handle_request, default_options = default_options, { base = handle_request };
207 ports = ports or {5280};
208 for _, options in ipairs(ports) do
209 local port = default_options.port or 5280;
210 local base = default_options.base;
211 local ssl = default_options.ssl or false;
212 local interface = default_options.interface;
213 if type(options) == "number" then
215 elseif type(options) == "table" then
216 port = options.port or port;
217 base = options.path or base;
218 ssl = options.ssl or ssl;
219 interface = options.interface or interface;
220 elseif type(options) == "string" then
226 ssl.protocol = "sslv23";
227 ssl.options = "no_sslv2";
230 new{ port = port, interface = interface,
231 base = base, handler = handle_request,
232 ssl = ssl, type = (ssl and "ssl") or "tcp" };
236 _M.request_reader = request_reader;
237 _M.send_response = send_response;
238 _M.urlencode = urlencode;