net.httpserver: Catch errors thrown in HTTP handlers.
[prosody.git] / net / httpserver.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 server = require "net.server"
11 local url_parse = require "socket.url".parse;
12 local httpstream_new = require "util.httpstream".new;
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 tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type;
20 local xpcall = xpcall;
21 local debug_traceback = debug.traceback;
22
23 local urlencode = function (s) return s and (s:gsub("%W", function (c) return ("%%%02x"):format(c:byte()); end)); end
24
25 local log = require "util.logger".init("httpserver");
26
27 local http_servers = {};
28
29 module "httpserver"
30
31 local default_handler;
32
33 local function expectbody(reqt)
34         return reqt.method == "POST";
35 end
36
37 local function send_response(request, response)
38         -- Write status line
39         local resp;
40         if response.body or response.headers then
41                 local body = response.body and tostring(response.body);
42                 log("debug", "Sending response to %s", request.id);
43                 resp = { "HTTP/1.0 "..(response.status or "200 OK").."\r\n" };
44                 local h = response.headers;
45                 if h then
46                         for k, v in pairs(h) do
47                                 t_insert(resp, k..": "..v.."\r\n");
48                         end
49                 end
50                 if body and not (h and h["Content-Length"]) then
51                         t_insert(resp, "Content-Length: "..#body.."\r\n");
52                 end
53                 t_insert(resp, "\r\n");
54                 
55                 if body and request.method ~= "HEAD" then
56                         t_insert(resp, body);
57                 end
58                 request.write(t_concat(resp));
59         else
60                 -- Response we have is just a string (the body)
61                 log("debug", "Sending 200 response to %s", request.id or "<none>");
62                 
63                 local resp = "HTTP/1.0 200 OK\r\n"
64                         .. "Connection: close\r\n"
65                         .. "Content-Type: text/html\r\n"
66                         .. "Content-Length: "..#response.."\r\n"
67                         .. "\r\n"
68                         .. response;
69                 
70                 request.write(resp);
71         end
72         if not request.stayopen then
73                 request:destroy();
74         end
75 end
76
77 local function call_callback(request, err)
78         if request.handled then return; end
79         request.handled = true;
80         local callback = request.callback;
81         if not callback and request.path then
82                 local path = request.url.path;
83                 local base = path:match("^/([^/?]+)");
84                 if not base then
85                         base = path:match("^http://[^/?]+/([^/?]+)");
86                 end
87                 
88                 callback = (request.server and request.server.handlers[base]) or default_handler;
89         end
90         if callback then
91                 local _callback = callback;
92                 function callback(a, b, c)
93                         local status, result = xpcall(function() _callback(a, b, c) end, debug_traceback);
94                         if status then return result; end
95                         log("error", "Error in HTTP server handler: %s", result);
96                 end
97                 if err then
98                         log("debug", "Request error: "..err);
99                         if not callback(nil, err, request) then
100                                 destroy_request(request);
101                         end
102                         return;
103                 end
104                 
105                 local response = callback(request.method, request.body and t_concat(request.body), request);
106                 if response then
107                         if response == true and not request.destroyed then
108                                 -- Keep connection open, we will reply later
109                                 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
110                         elseif response ~= true then
111                                 -- Assume response
112                                 send_response(request, response);
113                                 destroy_request(request);
114                         end
115                 else
116                         log("debug", "Request handler provided no response, destroying request...");
117                         -- No response, close connection
118                         destroy_request(request);
119                 end
120         end
121 end
122
123 local function request_reader(request, data, startpos)
124         if not request.parser then
125                 local function success_cb(r)
126                         for k,v in pairs(r) do request[k] = v; end
127                         request.url = url_parse(request.path);
128                         request.url.path = request.url.path and request.url.path:gsub("%%(%x%x)", function(x) return x.char(tonumber(x, 16)) end);
129                         request.body = { request.body };
130                         call_callback(request);
131                 end
132                 local function error_cb(r)
133                         log("error", "Error in HTTP server handler: %s", r or "connection-closed");
134                         call_callback(request, r or "connection-closed");
135                         destroy_request(request);
136                 end
137                 request.parser = httpstream_new(success_cb, error_cb);
138         end
139         request.parser:feed(data);
140 end
141
142 -- The default handler for requests
143 default_handler = function (method, body, request)
144         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
145         return { status = "404 Not Found",
146                         headers = { ["Content-Type"] = "text/html" },
147                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
148 end
149
150
151 function new_request(handler)
152         return { handler = handler, conn = handler,
153                         write = function (...) return handler:write(...); end, state = "request",
154                         server = http_servers[handler:serverport()],
155                         send = send_response,
156                         destroy = destroy_request,
157                         id = tostring{}:match("%x+$")
158                          };
159 end
160
161 function destroy_request(request)
162         log("debug", "Destroying request %s", request.id);
163         listener = listener or connlisteners_get("httpserver");
164         if not request.destroyed then
165                 request.destroyed = true;
166                 if request.on_destroy then
167                         log("debug", "Request has destroy callback");
168                         request.on_destroy(request);
169                 else
170                         log("debug", "Request has no destroy callback");
171                 end
172                 request.handler:close()
173                 if request.conn then
174                         listener.ondisconnect(request.conn, "closed");
175                 end
176         end
177 end
178
179 function new(params)
180         local http_server = http_servers[params.port];
181         if not http_server then
182                 http_server = { handlers = {} };
183                 http_servers[params.port] = http_server;
184                 -- We weren't already listening on this port, so start now
185                 connlisteners_start("httpserver", params);
186         end
187         if params.base then
188                 http_server.handlers[params.base] = params.handler;
189         end
190 end
191
192 function set_default_handler(handler)
193         default_handler = handler;
194 end
195
196 function new_from_config(ports, handle_request, default_options)
197         if type(handle_request) == "string" then -- COMPAT with old plugins
198                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
199                 handle_request, default_options = default_options, { base = handle_request };
200         end
201         ports = ports or {5280};
202         for _, options in ipairs(ports) do
203                 local port = default_options.port or 5280;
204                 local base = default_options.base;
205                 local ssl = default_options.ssl or false;
206                 local interface = default_options.interface;
207                 if type(options) == "number" then
208                         port = options;
209                 elseif type(options) == "table" then
210                         port = options.port or port;
211                         base = options.path or base;
212                         ssl = options.ssl or ssl;
213                         interface = options.interface or interface;
214                 elseif type(options) == "string" then
215                         base = options;
216                 end
217                 
218                 if ssl then
219                         ssl.mode = "server";
220                         ssl.protocol = "sslv23";
221                         ssl.options = "no_sslv2";
222                 end
223                 
224                 new{ port = port, interface = interface,
225                         base = base, handler = handle_request,
226                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
227         end
228 end
229
230 _M.request_reader = request_reader;
231 _M.send_response = send_response;
232 _M.urlencode = urlencode;
233
234 return _M;