Merge with trunk
[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 local http_servers = {};
27
28 module "httpserver"
29
30 local default_handler;
31
32 local function expectbody(reqt)
33     return reqt.method == "POST";
34 end
35
36 local function send_response(request, response)
37         -- Write status line
38         local resp;
39         if response.body then
40                 local body = 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;
44                 if h then
45                         for k, v in pairs(h) do
46                                 t_insert(resp, k);
47                                 t_insert(resp, ": ");
48                                 t_insert(resp, v);
49                                 t_insert(resp, "\r\n");
50                         end
51                 end
52                 if not (h and h["Content-Length"]) then
53                         t_insert(resp, "Content-Length: ");
54                         t_insert(resp, #body);
55                         t_insert(resp, "\r\n");
56                 end
57                 t_insert(resp, "\r\n");
58                 
59                 if request.method ~= "HEAD" then
60                         t_insert(resp, body);
61                 end
62         else
63                 -- Response we have is just a string (the body)
64                 log("debug", "Sending 200 response to %s", request.id or "<none>");
65                 
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");
71                 
72                 t_insert(resp, response);
73         end
74         request.write(t_concat(resp));
75         if not request.stayopen then
76                 request:destroy();
77         end
78 end
79
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("^/([^/?]+)");
87                 if not base then
88                         base = path:match("^http://[^/?]+/([^/?]+)");
89                 end
90                 
91                 callback = (request.server and request.server.handlers[base]) or default_handler;
92         end
93         if callback then
94                 if err then
95                         log("debug", "Request error: "..err);
96                         if not callback(nil, err, request) then
97                                 destroy_request(request);
98                         end
99                         return;
100                 end
101                 
102                 local response = callback(request.method, request.body and t_concat(request.body), request);
103                 if response then
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
108                                 -- Assume response
109                                 send_response(request, response);
110                                 destroy_request(request);
111                         end
112                 else
113                         log("debug", "Request handler provided no response, destroying request...");
114                         -- No response, close connection
115                         destroy_request(request);
116                 end
117         end
118 end
119
120 local function request_reader(request, data, startpos)
121         if not data then
122                 if request.body then
123                         call_callback(request);
124                 else
125                         -- Error.. connection was closed prematurely
126                         call_callback(request, "connection-closed");
127                 end
128                 -- Here we force a destroy... the connection is gone, so we can't reply later
129                 destroy_request(request);
130                 return;
131         end
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
135                 if startpos then
136                         data = data:sub(startpos, -1)
137                 end
138                 t_insert(request.body, data);
139                 if request.bodylength then
140                         request.havebodylength = request.havebodylength + #data;
141                         if request.havebodylength >= request.bodylength then
142                                 -- We have the body
143                                 call_callback(request);
144                         end
145                 end
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+): (.+)");
153                         if k and v then
154                                 headers[k:lower()] = v;
155 --                              log("debug", "Header: "..k:lower().." = "..v);
156                         elseif #line == 0 then
157                                 request.headers = headers;
158                                 break;
159                         else
160                                 log("debug", "Unhandled header line: "..line);
161                         end
162                 end
163                 
164                 if not expectbody(request) then 
165                         call_callback(request);
166                         return;
167                 end
168                 
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));
173                 end
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);
177                 if not method then
178                         return call_callback(request, "invalid-status-line");
179                 end
180                 
181                 request.method, request.path, request.httpversion = method, path, http;
182                 
183                 request.url = url_parse(request.path);
184                 
185                 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
186                 
187                 if request.onlystatus then
188                         if not call_callback(request) then
189                                 return;
190                         end
191                 end
192                 
193                 request.state = "headers";
194                 
195                 if #data > linelen then
196                         return request_reader(request, data:sub(linelen, -1));
197                 end
198         end
199 end
200
201 -- The default handler for requests
202 default_handler = function (method, body, request)
203         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
204         return { status = "404 Not Found", 
205                         headers = { ["Content-Type"] = "text/html" },
206                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
207 end
208
209
210 function new_request(handler)
211         return { handler = handler, conn = handler.socket, 
212                         write = function (...) return handler:write(...); end, state = "request", 
213                         server = http_servers[handler.serverport()],
214                         send = send_response,
215                         destroy = destroy_request,
216                         id = tostring{}:match("%x+$")
217                          };
218 end
219
220 function destroy_request(request)
221         log("debug", "Destroying request %s", request.id);
222         listener = listener or connlisteners_get("httpserver");
223         if not request.destroyed then
224                 request.destroyed = true;
225                 if request.on_destroy then
226                         log("debug", "Request has destroy callback");
227                         request.on_destroy(request);
228                 else
229                         log("debug", "Request has no destroy callback");
230                 end
231                 request.handler.close()
232                 if request.conn then
233                         listener.ondisconnect(request.handler, "closed");
234                 end
235         end
236 end
237
238 function new(params)
239         local http_server = http_servers[params.port];
240         if not http_server then
241                 http_server = { handlers = {} };
242                 http_servers[params.port] = http_server;
243                 -- We weren't already listening on this port, so start now
244                 connlisteners_start("httpserver", params);
245         end
246         if params.base then
247                 http_server.handlers[params.base] = params.handler;
248         end
249 end
250
251 function set_default_handler(handler)
252         default_handler = handler;
253 end
254
255 function new_from_config(ports, handle_request, default_options)
256         if type(handle_request) == "string" then -- COMPAT with old plugins
257                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
258                 handle_request, default_options = default_options, { base = handle_request };
259         end
260         for _, options in ipairs(ports) do
261                 local port = default_options.port or 5280;
262                 local base = default_options.base;
263                 local ssl = default_options.ssl or false;
264                 local interface = default_options.interface;
265                 if type(options) == "number" then
266                         port = options;
267                 elseif type(options) == "table" then
268                         port = options.port or port;
269                         base = options.path or base;
270                         ssl = options.ssl or ssl;
271                         interface = options.interface or interface;
272                 elseif type(options) == "string" then
273                         base = options;
274                 end
275                 
276                 if ssl then
277                         ssl.mode = "server";
278                         ssl.protocol = "sslv23";
279                 end
280                 
281                 new{ port = port, interface = interface, 
282                         base = base, handler = handle_request, 
283                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
284         end
285 end
286
287 _M.request_reader = request_reader;
288 _M.send_response = send_response;
289 _M.urlencode = urlencode;
290
291 return _M;