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 log("debug", "Sending response to %s", request.id);
41 resp = { "HTTP/1.0 ", response.status or "200 OK", "\r\n"};
42 local h = response.headers;
44 for k, v in pairs(h) do
48 t_insert(resp, "\r\n");
51 if response.body and not (h and h["Content-Length"]) then
52 t_insert(resp, "Content-Length: ");
53 t_insert(resp, #response.body);
54 t_insert(resp, "\r\n");
56 t_insert(resp, "\r\n");
58 if response.body and request.method ~= "HEAD" then
59 t_insert(resp, response.body);
62 -- Response we have is just a string (the body)
63 log("debug", "Sending response to %s: %s", request.id or "<none>", response or "<none>");
65 resp = { "HTTP/1.0 200 OK\r\n" };
66 t_insert(resp, "Connection: close\r\n");
67 t_insert(resp, "Content-Length: ");
68 t_insert(resp, #response);
69 t_insert(resp, "\r\n\r\n");
71 t_insert(resp, response);
73 request.write(t_concat(resp));
74 if not request.stayopen then
79 local function call_callback(request, err)
80 if request.handled then return; end
81 request.handled = true;
82 local callback = request.callback;
83 if not callback and request.path then
84 local path = request.url.path;
85 local base = path:match("^/([^/?]+)");
87 base = path:match("^http://[^/?]+/([^/?]+)");
90 callback = (request.server and request.server.handlers[base]) or default_handler;
91 if callback == default_handler then
92 log("debug", "Default callback for this request (base: "..tostring(base)..")")
97 log("debug", "Request error: "..err);
98 if not callback(nil, err, request) then
99 destroy_request(request);
104 local response = callback(request.method, request.body and t_concat(request.body), request);
106 if response == true and not request.destroyed then
107 -- Keep connection open, we will reply later
108 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
109 elseif response ~= true then
111 send_response(request, response);
112 destroy_request(request);
115 log("debug", "Request handler provided no response, destroying request...");
116 -- No response, close connection
117 destroy_request(request);
122 local function request_reader(request, data, startpos)
125 call_callback(request);
127 -- Error.. connection was closed prematurely
128 call_callback(request, "connection-closed");
130 -- Here we force a destroy... the connection is gone, so we can't reply later
131 destroy_request(request);
134 if request.state == "body" then
135 log("debug", "Reading body...")
136 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
138 data = data:sub(startpos, -1)
140 t_insert(request.body, data);
141 if request.bodylength then
142 request.havebodylength = request.havebodylength + #data;
143 if request.havebodylength >= request.bodylength then
145 call_callback(request);
148 elseif request.state == "headers" then
149 log("debug", "Reading headers...")
150 local pos = startpos;
151 local headers = request.headers or {};
152 for line in data:gmatch("(.-)\r\n") do
153 startpos = (startpos or 1) + #line + 2;
154 local k, v = line:match("(%S+): (.+)");
156 headers[k:lower()] = v;
157 -- log("debug", "Header: "..k:lower().." = "..v);
158 elseif #line == 0 then
159 request.headers = headers;
162 log("debug", "Unhandled header line: "..line);
166 if not expectbody(request) then
167 call_callback(request);
171 -- Reached the end of the headers
172 request.state = "body";
173 if #data > startpos then
174 return request_reader(request, data:sub(startpos, -1));
176 elseif request.state == "request" then
177 log("debug", "Reading request line...")
178 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
180 return call_callback(request, "invalid-status-line");
183 request.method, request.path, request.httpversion = method, path, http;
185 request.url = url_parse(request.path);
187 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
189 if request.onlystatus then
190 if not call_callback(request) then
195 request.state = "headers";
197 if #data > linelen then
198 return request_reader(request, data:sub(linelen, -1));
203 -- The default handler for requests
204 default_handler = function (method, body, request)
205 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
206 return { status = "404 Not Found",
207 headers = { ["Content-Type"] = "text/html" },
208 body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
212 function new_request(handler)
213 return { handler = handler, conn = handler.socket,
214 write = handler.write, state = "request",
215 server = http_servers[handler.serverport()],
216 send = send_response,
217 destroy = destroy_request,
218 id = tostring{}:match("%x+$")
222 function destroy_request(request)
223 log("debug", "Destroying request %s", request.id);
224 listener = listener or connlisteners_get("httpserver");
225 if not request.destroyed then
226 request.destroyed = true;
227 if request.on_destroy then
228 log("debug", "Request has destroy callback");
229 request.on_destroy(request);
231 log("debug", "Request has no destroy callback");
233 request.handler.close()
235 listener.disconnect(request.conn, "closed");
241 local http_server = http_servers[params.port];
242 if not http_server then
243 http_server = { handlers = {} };
244 http_servers[params.port] = http_server;
245 -- We weren't already listening on this port, so start now
246 connlisteners_start("httpserver", params);
249 http_server.handlers[params.base] = params.handler;
253 function new_from_config(ports, default_base, handle_request)
254 for _, options in ipairs(ports) do
255 local port, base, ssl, interface = 5280, default_base, false, nil;
256 if type(options) == "number" then
258 elseif type(options) == "table" then
259 port, base, ssl, interface = options.port or 5280, options.path or default_base, options.ssl or false, options.interface;
260 elseif type(options) == "string" then
266 ssl.protocol = "sslv23";
269 new{ port = port, base = base, handler = handle_request, ssl = ssl, type = (ssl and "ssl") or "tcp" }
273 _M.request_reader = request_reader;
274 _M.send_response = send_response;
275 _M.urlencode = urlencode;