2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local socket = require "socket"
11 local server = require "net.server"
12 local url_parse = require "socket.url".parse;
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 s_match, s_gmatch = string.match, string.gmatch;
20 local tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type;
22 local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end
24 local log = require "util.logger".init("httpserver");
26 local http_servers = {};
30 local default_handler;
32 local function expectbody(reqt)
33 return reqt.method == "POST";
36 local function send_response(request, response)
39 if response.body or response.headers then
40 local body = response.body and tostring(response.body);
41 log("debug", "Sending response to %s", request.id);
42 resp = { "HTTP/1.0 ", response.status or "200 OK", "\r\n"};
43 local h = response.headers;
45 for k, v in pairs(h) do
49 t_insert(resp, "\r\n");
52 if body and not (h and h["Content-Length"]) then
53 t_insert(resp, "Content-Length: ");
54 t_insert(resp, #body);
55 t_insert(resp, "\r\n");
57 t_insert(resp, "\r\n");
59 if body and request.method ~= "HEAD" then
63 -- Response we have is just a string (the body)
64 log("debug", "Sending 200 response to %s", request.id or "<none>");
66 resp = { "HTTP/1.0 200 OK\r\n" };
67 t_insert(resp, "Connection: close\r\n");
68 t_insert(resp, "Content-Length: ");
69 t_insert(resp, #response);
70 t_insert(resp, "\r\n\r\n");
72 t_insert(resp, response);
74 request.write(t_concat(resp));
75 if not request.stayopen then
80 local function call_callback(request, err)
81 if request.handled then return; end
82 request.handled = true;
83 local callback = request.callback;
84 if not callback and request.path then
85 local path = request.url.path;
86 local base = path:match("^/([^/?]+)");
88 base = path:match("^http://[^/?]+/([^/?]+)");
91 callback = (request.server and request.server.handlers[base]) or default_handler;
95 log("debug", "Request error: "..err);
96 if not callback(nil, err, request) then
97 destroy_request(request);
102 local response = callback(request.method, request.body and t_concat(request.body), request);
104 if response == true and not request.destroyed then
105 -- Keep connection open, we will reply later
106 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
107 elseif response ~= true then
109 send_response(request, response);
110 destroy_request(request);
113 log("debug", "Request handler provided no response, destroying request...");
114 -- No response, close connection
115 destroy_request(request);
120 local function request_reader(request, data, startpos)
123 call_callback(request);
125 -- Error.. connection was closed prematurely
126 call_callback(request, "connection-closed");
128 -- Here we force a destroy... the connection is gone, so we can't reply later
129 destroy_request(request);
132 if request.state == "body" then
133 log("debug", "Reading body...")
134 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
136 data = data:sub(startpos, -1)
138 t_insert(request.body, data);
139 if request.bodylength then
140 request.havebodylength = request.havebodylength + #data;
141 if request.havebodylength >= request.bodylength then
143 call_callback(request);
146 elseif request.state == "headers" then
147 log("debug", "Reading headers...")
148 local pos = startpos;
149 local headers, headers_complete = request.headers;
152 request.headers = headers;
155 for line in data:gmatch("(.-)\r\n") do
156 startpos = (startpos or 1) + #line + 2;
157 local k, v = line:match("(%S+): (.+)");
159 headers[k:lower()] = v;
160 --log("debug", "Header: '"..k:lower().."' = '"..v.."'");
161 elseif #line == 0 then
162 headers_complete = true;
165 log("debug", "Unhandled header line: "..line);
169 if not headers_complete then return; end
171 if not expectbody(request) then
172 call_callback(request);
176 -- Reached the end of the headers
177 request.state = "body";
178 if #data > startpos then
179 return request_reader(request, data:sub(startpos, -1));
181 elseif request.state == "request" then
182 log("debug", "Reading request line...")
183 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
185 log("warn", "Invalid HTTP status line, telling callback then closing");
186 local ret = call_callback(request, "invalid-status-line");
191 request.method, request.path, request.httpversion = method, path, http;
193 request.url = url_parse(request.path);
195 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
197 if request.onlystatus then
198 if not call_callback(request) then
203 request.state = "headers";
205 if #data > linelen then
206 return request_reader(request, data:sub(linelen, -1));
211 -- The default handler for requests
212 default_handler = function (method, body, request)
213 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
214 return { status = "404 Not Found",
215 headers = { ["Content-Type"] = "text/html" },
216 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
220 function new_request(handler)
221 return { handler = handler, conn = handler.socket,
222 write = handler.write, state = "request",
223 server = http_servers[handler.serverport()],
224 send = send_response,
225 destroy = destroy_request,
226 id = tostring{}:match("%x+$")
230 function destroy_request(request)
231 log("debug", "Destroying request %s", request.id);
232 listener = listener or connlisteners_get("httpserver");
233 if not request.destroyed then
234 request.destroyed = true;
235 if request.on_destroy then
236 log("debug", "Request has destroy callback");
237 request.on_destroy(request);
239 log("debug", "Request has no destroy callback");
241 request.handler.close()
243 listener.disconnect(request.handler, "closed");
249 local http_server = http_servers[params.port];
250 if not http_server then
251 http_server = { handlers = {} };
252 http_servers[params.port] = http_server;
253 -- We weren't already listening on this port, so start now
254 connlisteners_start("httpserver", params);
257 http_server.handlers[params.base] = params.handler;
261 function set_default_handler(handler)
262 default_handler = handler;
265 function new_from_config(ports, handle_request, default_options)
266 if type(handle_request) == "string" then -- COMPAT with old plugins
267 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
268 handle_request, default_options = default_options, { base = handle_request };
270 for _, options in ipairs(ports) do
271 local port = default_options.port or 5280;
272 local base = default_options.base;
273 local ssl = default_options.ssl or false;
274 local interface = default_options.interface;
275 if type(options) == "number" then
277 elseif type(options) == "table" then
278 port = options.port or port;
279 base = options.path or base;
280 ssl = options.ssl or ssl;
281 interface = options.interface or interface;
282 elseif type(options) == "string" then
288 ssl.protocol = "sslv23";
291 new{ port = port, interface = interface,
292 base = base, handler = handle_request,
293 ssl = ssl, type = (ssl and "ssl") or "tcp" };
297 _M.request_reader = request_reader;
298 _M.send_response = send_response;
299 _M.urlencode = urlencode;