Update copyright headers for 2010
[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 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 or response.headers then
40                 local body = response.body and 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 body and 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 body and 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-Type: text/html\r\n");
69                 t_insert(resp, "Content-Length: ");
70                 t_insert(resp, #response);
71                 t_insert(resp, "\r\n\r\n");
72                 
73                 t_insert(resp, response);
74         end
75         request.write(t_concat(resp));
76         if not request.stayopen then
77                 request:destroy();
78         end
79 end
80
81 local function call_callback(request, err)
82         if request.handled then return; end
83         request.handled = true;
84         local callback = request.callback;
85         if not callback and request.path then
86                 local path = request.url.path;
87                 local base = path:match("^/([^/?]+)");
88                 if not base then
89                         base = path:match("^http://[^/?]+/([^/?]+)");
90                 end
91                 
92                 callback = (request.server and request.server.handlers[base]) or default_handler;
93         end
94         if callback then
95                 if err then
96                         log("debug", "Request error: "..err);
97                         if not callback(nil, err, request) then
98                                 destroy_request(request);
99                         end
100                         return;
101                 end
102                 
103                 local response = callback(request.method, request.body and t_concat(request.body), request);
104                 if response then
105                         if response == true and not request.destroyed then
106                                 -- Keep connection open, we will reply later
107                                 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
108                         elseif response ~= true then
109                                 -- Assume response
110                                 send_response(request, response);
111                                 destroy_request(request);
112                         end
113                 else
114                         log("debug", "Request handler provided no response, destroying request...");
115                         -- No response, close connection
116                         destroy_request(request);
117                 end
118         end
119 end
120
121 local function request_reader(request, data, startpos)
122         if not data then
123                 if request.body then
124                         call_callback(request);
125                 else
126                         -- Error.. connection was closed prematurely
127                         call_callback(request, "connection-closed");
128                 end
129                 -- Here we force a destroy... the connection is gone, so we can't reply later
130                 destroy_request(request);
131                 return;
132         end
133         if request.state == "body" then
134                 log("debug", "Reading body...")
135                 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
136                 if startpos then
137                         data = data:sub(startpos, -1)
138                 end
139                 t_insert(request.body, data);
140                 if request.bodylength then
141                         request.havebodylength = request.havebodylength + #data;
142                         if request.havebodylength >= request.bodylength then
143                                 -- We have the body
144                                 call_callback(request);
145                         end
146                 end
147         elseif request.state == "headers" then
148                 log("debug", "Reading headers...")
149                 local pos = startpos;
150                 local headers, headers_complete = request.headers;
151                 if not headers then
152                         headers = {};
153                         request.headers = headers;
154                 end
155                 
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                                 headers_complete = true;
164                                 break;
165                         else
166                                 log("debug", "Unhandled header line: "..line);
167                         end
168                 end
169                 
170                 if not headers_complete then return; end
171                 
172                 if not expectbody(request) then
173                         call_callback(request);
174                         return;
175                 end
176                 
177                 -- Reached the end of the headers
178                 request.state = "body";
179                 if #data > startpos then
180                         return request_reader(request, data:sub(startpos, -1));
181                 end
182         elseif request.state == "request" then
183                 log("debug", "Reading request line...")
184                 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
185                 if not method then
186                         log("warn", "Invalid HTTP status line, telling callback then closing");
187                         local ret = call_callback(request, "invalid-status-line");
188                         request:destroy();
189                         return ret;
190                 end
191                 
192                 request.method, request.path, request.httpversion = method, path, http;
193                 
194                 request.url = url_parse(request.path);
195                 
196                 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
197                 
198                 if request.onlystatus then
199                         if not call_callback(request) then
200                                 return;
201                         end
202                 end
203                 
204                 request.state = "headers";
205                 
206                 if #data > linelen then
207                         return request_reader(request, data:sub(linelen, -1));
208                 end
209         end
210 end
211
212 -- The default handler for requests
213 default_handler = function (method, body, request)
214         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
215         return { status = "404 Not Found", 
216                         headers = { ["Content-Type"] = "text/html" },
217                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
218 end
219
220
221 function new_request(handler)
222         return { handler = handler, conn = handler.socket, 
223                         write = handler.write, state = "request", 
224                         server = http_servers[handler.serverport()],
225                         send = send_response,
226                         destroy = destroy_request,
227                         id = tostring{}:match("%x+$")
228                          };
229 end
230
231 function destroy_request(request)
232         log("debug", "Destroying request %s", request.id);
233         listener = listener or connlisteners_get("httpserver");
234         if not request.destroyed then
235                 request.destroyed = true;
236                 if request.on_destroy then
237                         log("debug", "Request has destroy callback");
238                         request.on_destroy(request);
239                 else
240                         log("debug", "Request has no destroy callback");
241                 end
242                 request.handler.close()
243                 if request.conn then
244                         listener.disconnect(request.handler, "closed");
245                 end
246         end
247 end
248
249 function new(params)
250         local http_server = http_servers[params.port];
251         if not http_server then
252                 http_server = { handlers = {} };
253                 http_servers[params.port] = http_server;
254                 -- We weren't already listening on this port, so start now
255                 connlisteners_start("httpserver", params);
256         end
257         if params.base then
258                 http_server.handlers[params.base] = params.handler;
259         end
260 end
261
262 function set_default_handler(handler)
263         default_handler = handler;
264 end
265
266 function new_from_config(ports, handle_request, default_options)
267         if type(handle_request) == "string" then -- COMPAT with old plugins
268                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
269                 handle_request, default_options = default_options, { base = handle_request };
270         end
271         for _, options in ipairs(ports) do
272                 local port = default_options.port or 5280;
273                 local base = default_options.base;
274                 local ssl = default_options.ssl or false;
275                 local interface = default_options.interface;
276                 if type(options) == "number" then
277                         port = options;
278                 elseif type(options) == "table" then
279                         port = options.port or port;
280                         base = options.path or base;
281                         ssl = options.ssl or ssl;
282                         interface = options.interface or interface;
283                 elseif type(options) == "string" then
284                         base = options;
285                 end
286                 
287                 if ssl then
288                         ssl.mode = "server";
289                         ssl.protocol = "sslv23";
290                         ssl.options = "no_sslv2";
291                 end
292                 
293                 new{ port = port, interface = interface, 
294                         base = base, handler = handle_request, 
295                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
296         end
297 end
298
299 _M.request_reader = request_reader;
300 _M.send_response = send_response;
301 _M.urlencode = urlencode;
302
303 return _M;