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 = request.headers or {};
150 for line in data:gmatch("(.-)\r\n") do
151 startpos = (startpos or 1) + #line + 2;
152 local k, v = line:match("(%S+): (.+)");
154 headers[k:lower()] = v;
155 -- log("debug", "Header: "..k:lower().." = "..v);
156 elseif #line == 0 then
157 request.headers = headers;
160 log("debug", "Unhandled header line: "..line);
164 if not expectbody(request) then
165 call_callback(request);
169 -- Reached the end of the headers
170 request.state = "body";
171 if #data > startpos then
172 return request_reader(request, data:sub(startpos, -1));
174 elseif request.state == "request" then
175 log("debug", "Reading request line...")
176 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
178 log("warn", "Invalid HTTP status line, telling callback then closing");
179 local ret = call_callback(request, "invalid-status-line");
184 request.method, request.path, request.httpversion = method, path, http;
186 request.url = url_parse(request.path);
188 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
190 if request.onlystatus then
191 if not call_callback(request) then
196 request.state = "headers";
198 if #data > linelen then
199 return request_reader(request, data:sub(linelen, -1));
204 -- The default handler for requests
205 default_handler = function (method, body, request)
206 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
207 return { status = "404 Not Found",
208 headers = { ["Content-Type"] = "text/html" },
209 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
213 function new_request(handler)
214 return { handler = handler, conn = handler.socket,
215 write = handler.write, state = "request",
216 server = http_servers[handler.serverport()],
217 send = send_response,
218 destroy = destroy_request,
219 id = tostring{}:match("%x+$")
223 function destroy_request(request)
224 log("debug", "Destroying request %s", request.id);
225 listener = listener or connlisteners_get("httpserver");
226 if not request.destroyed then
227 request.destroyed = true;
228 if request.on_destroy then
229 log("debug", "Request has destroy callback");
230 request.on_destroy(request);
232 log("debug", "Request has no destroy callback");
234 request.handler.close()
236 listener.disconnect(request.handler, "closed");
242 local http_server = http_servers[params.port];
243 if not http_server then
244 http_server = { handlers = {} };
245 http_servers[params.port] = http_server;
246 -- We weren't already listening on this port, so start now
247 connlisteners_start("httpserver", params);
250 http_server.handlers[params.base] = params.handler;
254 function set_default_handler(handler)
255 default_handler = handler;
258 function new_from_config(ports, handle_request, default_options)
259 if type(handle_request) == "string" then -- COMPAT with old plugins
260 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
261 handle_request, default_options = default_options, { base = handle_request };
263 for _, options in ipairs(ports) do
264 local port = default_options.port or 5280;
265 local base = default_options.base;
266 local ssl = default_options.ssl or false;
267 local interface = default_options.interface;
268 if type(options) == "number" then
270 elseif type(options) == "table" then
271 port = options.port or port;
272 base = options.path or base;
273 ssl = options.ssl or ssl;
274 interface = options.interface or interface;
275 elseif type(options) == "string" then
281 ssl.protocol = "sslv23";
284 new{ port = port, interface = interface,
285 base = base, handler = handle_request,
286 ssl = ssl, type = (ssl and "ssl") or "tcp" };
290 _M.request_reader = request_reader;
291 _M.send_response = send_response;
292 _M.urlencode = urlencode;