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)
40 local body = 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
46 t_insert(resp, k..": "..v.."\r\n");
49 if not (h and h["Content-Length"]) then
50 t_insert(resp, "Content-Length: "..#body.."\r\n");
52 t_insert(resp, "\r\n");
54 if request.method ~= "HEAD" then
57 request.write(t_concat(resp));
59 -- Response we have is just a string (the body)
60 log("debug", "Sending 200 response to %s", request.id or "<none>");
62 local resp = "HTTP/1.0 200 OK\r\n"
63 .. "Connection: close\r\n"
64 .. "Content-Type: text/html\r\n"
65 .. "Content-Length: "..#response.."\r\n"
71 if not request.stayopen then
76 local function call_callback(request, err)
77 if request.handled then return; end
78 request.handled = true;
79 local callback = request.callback;
80 if not callback and request.path then
81 local path = request.url.path;
82 local base = path:match("^/([^/?]+)");
84 base = path:match("^http://[^/?]+/([^/?]+)");
87 callback = (request.server and request.server.handlers[base]) or default_handler;
91 log("debug", "Request error: "..err);
92 if not callback(nil, err, request) then
93 destroy_request(request);
98 local response = callback(request.method, request.body and t_concat(request.body), request);
100 if response == true and not request.destroyed then
101 -- Keep connection open, we will reply later
102 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
103 elseif response ~= true then
105 send_response(request, response);
106 destroy_request(request);
109 log("debug", "Request handler provided no response, destroying request...");
110 -- No response, close connection
111 destroy_request(request);
116 local function request_reader(request, data, startpos)
119 call_callback(request);
121 -- Error.. connection was closed prematurely
122 call_callback(request, "connection-closed");
124 -- Here we force a destroy... the connection is gone, so we can't reply later
125 destroy_request(request);
128 if request.state == "body" then
129 log("debug", "Reading body...")
130 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
132 data = data:sub(startpos, -1)
134 t_insert(request.body, data);
135 if request.bodylength then
136 request.havebodylength = request.havebodylength + #data;
137 if request.havebodylength >= request.bodylength then
139 call_callback(request);
142 elseif request.state == "headers" then
143 log("debug", "Reading headers...")
144 local pos = startpos;
145 local headers = request.headers or {};
146 for line in data:gmatch("(.-)\r\n") do
147 startpos = (startpos or 1) + #line + 2;
148 local k, v = line:match("(%S+): (.+)");
150 headers[k:lower()] = v;
151 -- log("debug", "Header: "..k:lower().." = "..v);
152 elseif #line == 0 then
153 request.headers = headers;
156 log("debug", "Unhandled header line: "..line);
160 if not expectbody(request) then
161 call_callback(request);
165 -- Reached the end of the headers
166 request.state = "body";
167 if #data > startpos then
168 return request_reader(request, data:sub(startpos, -1));
170 elseif request.state == "request" then
171 log("debug", "Reading request line...")
172 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
174 return call_callback(request, "invalid-status-line");
177 request.method, request.path, request.httpversion = method, path, http;
179 request.url = url_parse(request.path);
181 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
183 if request.onlystatus then
184 if not call_callback(request) then
189 request.state = "headers";
191 if #data > linelen then
192 return request_reader(request, data:sub(linelen, -1));
197 -- The default handler for requests
198 default_handler = function (method, body, request)
199 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
200 return { status = "404 Not Found",
201 headers = { ["Content-Type"] = "text/html" },
202 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
206 function new_request(handler)
207 return { handler = handler, conn = handler.socket,
208 write = function (...) return handler:write(...); end, state = "request",
209 server = http_servers[handler:serverport()],
210 send = send_response,
211 destroy = destroy_request,
212 id = tostring{}:match("%x+$")
216 function destroy_request(request)
217 log("debug", "Destroying request %s", request.id);
218 listener = listener or connlisteners_get("httpserver");
219 if not request.destroyed then
220 request.destroyed = true;
221 if request.on_destroy then
222 log("debug", "Request has destroy callback");
223 request.on_destroy(request);
225 log("debug", "Request has no destroy callback");
227 request.handler:close()
229 listener.ondisconnect(request.handler, "closed");
235 local http_server = http_servers[params.port];
236 if not http_server then
237 http_server = { handlers = {} };
238 http_servers[params.port] = http_server;
239 -- We weren't already listening on this port, so start now
240 connlisteners_start("httpserver", params);
243 http_server.handlers[params.base] = params.handler;
247 function set_default_handler(handler)
248 default_handler = handler;
251 function new_from_config(ports, handle_request, default_options)
252 if type(handle_request) == "string" then -- COMPAT with old plugins
253 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
254 handle_request, default_options = default_options, { base = handle_request };
256 for _, options in ipairs(ports) do
257 local port = default_options.port or 5280;
258 local base = default_options.base;
259 local ssl = default_options.ssl or false;
260 local interface = default_options.interface;
261 if type(options) == "number" then
263 elseif type(options) == "table" then
264 port = options.port or port;
265 base = options.path or base;
266 ssl = options.ssl or ssl;
267 interface = options.interface or interface;
268 elseif type(options) == "string" then
274 ssl.protocol = "sslv23";
275 ssl.options = "no_sslv2";
278 new{ port = port, interface = interface,
279 base = base, handler = handle_request,
280 ssl = ssl, type = (ssl and "ssl") or "tcp" };
284 _M.request_reader = request_reader;
285 _M.send_response = send_response;
286 _M.urlencode = urlencode;