util.pposix: Fix return type of lc_abort to shush compiler warning
[prosody.git] / net / httpserver.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local socket = require "socket"
11 local server = require "net.server"
12 local url_parse = require "socket.url".parse;
13
14 local connlisteners_start = require "net.connlisteners".start;
15 local connlisteners_get = require "net.connlisteners".get;
16 local listener;
17
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;
21
22 local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end
23
24 local log = require "util.logger".init("httpserver");
25
26 -- TODO: Should we read this from /etc/mime.types if it exists? (startup time...?)
27 local mime_map = { html = "text/html", txt = "plain/text; charset=utf-8", js = "text/javascript" };
28
29 local http_servers = {};
30
31 module "httpserver"
32
33 local default_handler;
34
35 local function expectbody(reqt)
36     return reqt.method == "POST";
37 end
38
39 local function send_response(request, response)
40         -- Write status line
41         local resp;
42         if response.body then
43                 local body = tostring(response.body);
44                 log("debug", "Sending response to %s", request.id);
45                 resp = { "HTTP/1.0 ", response.status or "200 OK", "\r\n"};
46                 local h = response.headers;
47                 if h then
48                         for k, v in pairs(h) do
49                                 t_insert(resp, k);
50                                 t_insert(resp, ": ");
51                                 t_insert(resp, v);
52                                 t_insert(resp, "\r\n");
53                         end
54                 end
55                 if not (h and h["Content-Length"]) then
56                         t_insert(resp, "Content-Length: ");
57                         t_insert(resp, #body);
58                         t_insert(resp, "\r\n");
59                 end
60                 t_insert(resp, "\r\n");
61                 
62                 if request.method ~= "HEAD" then
63                         t_insert(resp, body);
64                 end
65         else
66                 -- Response we have is just a string (the body)
67                 log("debug", "Sending 200 response to %s", request.id or "<none>");
68                 
69                 resp = { "HTTP/1.0 200 OK\r\n" };
70                 t_insert(resp, "Connection: close\r\n");
71                 t_insert(resp, "Content-Type: ");
72                 t_insert(resp, mime_map[request.url.path:match("%.(%w+)")] or "application/octet-stream");
73                 t_insert(resp, "\r\n");
74                 t_insert(resp, "Content-Length: ");
75                 t_insert(resp, #response);
76                 t_insert(resp, "\r\n\r\n");
77                 
78                 t_insert(resp, response);
79         end
80         request.write(t_concat(resp));
81         if not request.stayopen then
82                 request:destroy();
83         end
84 end
85
86 local function call_callback(request, err)
87         if request.handled then return; end
88         request.handled = true;
89         local callback = request.callback;
90         if not callback and request.path then
91                 local path = request.url.path;
92                 local base = path:match("^/([^/?]+)");
93                 if not base then
94                         base = path:match("^http://[^/?]+/([^/?]+)");
95                 end
96                 
97                 callback = (request.server and request.server.handlers[base]) or default_handler;
98         end
99         if callback then
100                 if err then
101                         log("debug", "Request error: "..err);
102                         if not callback(nil, err, request) then
103                                 destroy_request(request);
104                         end
105                         return;
106                 end
107                 
108                 local response = callback(request.method, request.body and t_concat(request.body), request);
109                 if response then
110                         if response == true and not request.destroyed then
111                                 -- Keep connection open, we will reply later
112                                 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
113                         elseif response ~= true then
114                                 -- Assume response
115                                 send_response(request, response);
116                                 destroy_request(request);
117                         end
118                 else
119                         log("debug", "Request handler provided no response, destroying request...");
120                         -- No response, close connection
121                         destroy_request(request);
122                 end
123         end
124 end
125
126 local function request_reader(request, data, startpos)
127         if not data then
128                 if request.body then
129                         call_callback(request);
130                 else
131                         -- Error.. connection was closed prematurely
132                         call_callback(request, "connection-closed");
133                 end
134                 -- Here we force a destroy... the connection is gone, so we can't reply later
135                 destroy_request(request);
136                 return;
137         end
138         if request.state == "body" then
139                 log("debug", "Reading body...")
140                 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
141                 if startpos then
142                         data = data:sub(startpos, -1)
143                 end
144                 t_insert(request.body, data);
145                 if request.bodylength then
146                         request.havebodylength = request.havebodylength + #data;
147                         if request.havebodylength >= request.bodylength then
148                                 -- We have the body
149                                 call_callback(request);
150                         end
151                 end
152         elseif request.state == "headers" then
153                 log("debug", "Reading headers...")
154                 local pos = startpos;
155                 local headers = request.headers or {};
156                 for line in data:gmatch("(.-)\r\n") do
157                         startpos = (startpos or 1) + #line + 2;
158                         local k, v = line:match("(%S+): (.+)");
159                         if k and v then
160                                 headers[k:lower()] = v;
161 --                              log("debug", "Header: "..k:lower().." = "..v);
162                         elseif #line == 0 then
163                                 request.headers = headers;
164                                 break;
165                         else
166                                 log("debug", "Unhandled header line: "..line);
167                         end
168                 end
169                 
170                 if not expectbody(request) then 
171                         call_callback(request);
172                         return;
173                 end
174                 
175                 -- Reached the end of the headers
176                 request.state = "body";
177                 if #data > startpos then
178                         return request_reader(request, data:sub(startpos, -1));
179                 end
180         elseif request.state == "request" then
181                 log("debug", "Reading request line...")
182                 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
183                 if not method then
184                         return call_callback(request, "invalid-status-line");
185                 end
186                 
187                 request.method, request.path, request.httpversion = method, path, http;
188                 
189                 request.url = url_parse(request.path);
190                 
191                 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
192                 
193                 if request.onlystatus then
194                         if not call_callback(request) then
195                                 return;
196                         end
197                 end
198                 
199                 request.state = "headers";
200                 
201                 if #data > linelen then
202                         return request_reader(request, data:sub(linelen, -1));
203                 end
204         end
205 end
206
207 -- The default handler for requests
208 default_handler = function (method, body, request)
209         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
210         return { status = "404 Not Found", 
211                         headers = { ["Content-Type"] = "text/html" },
212                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
213 end
214
215
216 function new_request(handler)
217         return { handler = handler, conn = handler.socket, 
218                         write = function (...) return handler:write(...); end, state = "request", 
219                         server = http_servers[handler:serverport()],
220                         send = send_response,
221                         destroy = destroy_request,
222                         id = tostring{}:match("%x+$")
223                          };
224 end
225
226 function destroy_request(request)
227         log("debug", "Destroying request %s", request.id);
228         listener = listener or connlisteners_get("httpserver");
229         if not request.destroyed then
230                 request.destroyed = true;
231                 if request.on_destroy then
232                         log("debug", "Request has destroy callback");
233                         request.on_destroy(request);
234                 else
235                         log("debug", "Request has no destroy callback");
236                 end
237                 request.handler.close()
238                 if request.conn then
239                         listener.ondisconnect(request.handler, "closed");
240                 end
241         end
242 end
243
244 function new(params)
245         local http_server = http_servers[params.port];
246         if not http_server then
247                 http_server = { handlers = {} };
248                 http_servers[params.port] = http_server;
249                 -- We weren't already listening on this port, so start now
250                 connlisteners_start("httpserver", params);
251         end
252         if params.base then
253                 http_server.handlers[params.base] = params.handler;
254         end
255 end
256
257 function set_default_handler(handler)
258         default_handler = handler;
259 end
260
261 function new_from_config(ports, handle_request, default_options)
262         if type(handle_request) == "string" then -- COMPAT with old plugins
263                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
264                 handle_request, default_options = default_options, { base = handle_request };
265         end
266         for _, options in ipairs(ports) do
267                 local port = default_options.port or 5280;
268                 local base = default_options.base;
269                 local ssl = default_options.ssl or false;
270                 local interface = default_options.interface;
271                 if type(options) == "number" then
272                         port = options;
273                 elseif type(options) == "table" then
274                         port = options.port or port;
275                         base = options.path or base;
276                         ssl = options.ssl or ssl;
277                         interface = options.interface or interface;
278                 elseif type(options) == "string" then
279                         base = options;
280                 end
281                 
282                 if ssl then
283                         ssl.mode = "server";
284                         ssl.protocol = "sslv23";
285                 end
286                 
287                 new{ port = port, interface = interface, 
288                         base = base, handler = handle_request, 
289                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
290         end
291 end
292
293 _M.request_reader = request_reader;
294 _M.send_response = send_response;
295 _M.urlencode = urlencode;
296
297 return _M;