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