net.httpserver: Make it possible to return responses with no body
[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 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-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                         log("warn", "Invalid HTTP status line, telling callback then closing");
179                         local ret = call_callback(request, "invalid-status-line");
180                         request:destroy();
181                         return ret;
182                 end
183                 
184                 request.method, request.path, request.httpversion = method, path, http;
185                 
186                 request.url = url_parse(request.path);
187                 
188                 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
189                 
190                 if request.onlystatus then
191                         if not call_callback(request) then
192                                 return;
193                         end
194                 end
195                 
196                 request.state = "headers";
197                 
198                 if #data > linelen then
199                         return request_reader(request, data:sub(linelen, -1));
200                 end
201         end
202 end
203
204 -- The default handler for requests
205 default_handler = function (method, body, request)
206         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
207         return { status = "404 Not Found", 
208                         headers = { ["Content-Type"] = "text/html" },
209                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
210 end
211
212
213 function new_request(handler)
214         return { handler = handler, conn = handler.socket, 
215                         write = handler.write, state = "request", 
216                         server = http_servers[handler.serverport()],
217                         send = send_response,
218                         destroy = destroy_request,
219                         id = tostring{}:match("%x+$")
220                          };
221 end
222
223 function destroy_request(request)
224         log("debug", "Destroying request %s", request.id);
225         listener = listener or connlisteners_get("httpserver");
226         if not request.destroyed then
227                 request.destroyed = true;
228                 if request.on_destroy then
229                         log("debug", "Request has destroy callback");
230                         request.on_destroy(request);
231                 else
232                         log("debug", "Request has no destroy callback");
233                 end
234                 request.handler.close()
235                 if request.conn then
236                         listener.disconnect(request.handler, "closed");
237                 end
238         end
239 end
240
241 function new(params)
242         local http_server = http_servers[params.port];
243         if not http_server then
244                 http_server = { handlers = {} };
245                 http_servers[params.port] = http_server;
246                 -- We weren't already listening on this port, so start now
247                 connlisteners_start("httpserver", params);
248         end
249         if params.base then
250                 http_server.handlers[params.base] = params.handler;
251         end
252 end
253
254 function set_default_handler(handler)
255         default_handler = handler;
256 end
257
258 function new_from_config(ports, handle_request, default_options)
259         if type(handle_request) == "string" then -- COMPAT with old plugins
260                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
261                 handle_request, default_options = default_options, { base = handle_request };
262         end
263         for _, options in ipairs(ports) do
264                 local port = default_options.port or 5280;
265                 local base = default_options.base;
266                 local ssl = default_options.ssl or false;
267                 local interface = default_options.interface;
268                 if type(options) == "number" then
269                         port = options;
270                 elseif type(options) == "table" then
271                         port = options.port or port;
272                         base = options.path or base;
273                         ssl = options.ssl or ssl;
274                         interface = options.interface or interface;
275                 elseif type(options) == "string" then
276                         base = options;
277                 end
278                 
279                 if ssl then
280                         ssl.mode = "server";
281                         ssl.protocol = "sslv23";
282                 end
283                 
284                 new{ port = port, interface = interface, 
285                         base = base, handler = handle_request, 
286                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
287         end
288 end
289
290 _M.request_reader = request_reader;
291 _M.send_response = send_response;
292 _M.urlencode = urlencode;
293
294 return _M;