Add copyright header to those files missing one
[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 = tonumber, tostring, pairs;
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                 log("debug", "Sending response to %s", request.id);
41                 resp = { "HTTP/1.0 ", response.status or "200 OK", "\r\n"};
42                 local h = response.headers;
43                 if h then
44                         for k, v in pairs(h) do
45                                 t_insert(resp, k);
46                                 t_insert(resp, ": ");
47                                 t_insert(resp, v);
48                                 t_insert(resp, "\r\n");
49                         end
50                 end
51                 if response.body and not (h and h["Content-Length"]) then
52                         t_insert(resp, "Content-Length: ");
53                         t_insert(resp, #response.body);
54                         t_insert(resp, "\r\n");
55                 end
56                 t_insert(resp, "\r\n");
57                 
58                 if response.body and request.method ~= "HEAD" then
59                         t_insert(resp, response.body);
60                 end
61         else
62                 -- Response we have is just a string (the body)
63                 log("debug", "Sending response to %s: %s", request.id or "<none>", response or "<none>");
64                 
65                 resp = { "HTTP/1.0 200 OK\r\n" };
66                 t_insert(resp, "Connection: close\r\n");
67                 t_insert(resp, "Content-Length: ");
68                 t_insert(resp, #response);
69                 t_insert(resp, "\r\n\r\n");
70                 
71                 t_insert(resp, response);
72         end
73         request.write(t_concat(resp));
74         if not request.stayopen then
75                 request:destroy();
76         end
77 end
78
79 local function call_callback(request, err)
80         if request.handled then return; end
81         request.handled = true;
82         local callback = request.callback;
83         if not callback and request.path then
84                 local path = request.url.path;
85                 local base = path:match("^/([^/?]+)");
86                 if not base then
87                         base = path:match("^http://[^/?]+/([^/?]+)");
88                 end
89                 
90                 callback = (request.server and request.server.handlers[base]) or default_handler;
91                 if callback == default_handler then
92                         log("debug", "Default callback for this request (base: "..tostring(base)..")")
93                 end
94         end
95         if callback then
96                 if err then
97                         log("debug", "Request error: "..err);
98                         if not callback(nil, err, request) then
99                                 destroy_request(request);
100                         end
101                         return;
102                 end
103                 
104                 local response = callback(request.method, request.body and t_concat(request.body), request);
105                 if response then
106                         if response == true and not request.destroyed then
107                                 -- Keep connection open, we will reply later
108                                 log("warn", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
109                         elseif response ~= true then
110                                 -- Assume response
111                                 send_response(request, response);
112                                 destroy_request(request);
113                         end
114                 else
115                         log("debug", "Request handler provided no response, destroying request...");
116                         -- No response, close connection
117                         destroy_request(request);
118                 end
119         end
120 end
121
122 local function request_reader(request, data, startpos)
123         if not data then
124                 if request.body then
125                         call_callback(request);
126                 else
127                         -- Error.. connection was closed prematurely
128                         call_callback(request, "connection-closed");
129                 end
130                 -- Here we force a destroy... the connection is gone, so we can't reply later
131                 destroy_request(request);
132                 return;
133         end
134         if request.state == "body" then
135                 log("debug", "Reading body...")
136                 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.headers["content-length"]); end
137                 if startpos then
138                         data = data:sub(startpos, -1)
139                 end
140                 t_insert(request.body, data);
141                 if request.bodylength then
142                         request.havebodylength = request.havebodylength + #data;
143                         if request.havebodylength >= request.bodylength then
144                                 -- We have the body
145                                 call_callback(request);
146                         end
147                 end
148         elseif request.state == "headers" then
149                 log("debug", "Reading headers...")
150                 local pos = startpos;
151                 local headers = request.headers or {};
152                 for line in data:gmatch("(.-)\r\n") do
153                         startpos = (startpos or 1) + #line + 2;
154                         local k, v = line:match("(%S+): (.+)");
155                         if k and v then
156                                 headers[k:lower()] = v;
157 --                              log("debug", "Header: "..k:lower().." = "..v);
158                         elseif #line == 0 then
159                                 request.headers = headers;
160                                 break;
161                         else
162                                 log("debug", "Unhandled header line: "..line);
163                         end
164                 end
165                 
166                 if not expectbody(request) then 
167                         call_callback(request);
168                         return;
169                 end
170                 
171                 -- Reached the end of the headers
172                 request.state = "body";
173                 if #data > startpos then
174                         return request_reader(request, data:sub(startpos, -1));
175                 end
176         elseif request.state == "request" then
177                 log("debug", "Reading request line...")
178                 local method, path, http, linelen = data:match("^(%S+) (%S+) HTTP/(%S+)\r\n()", startpos);
179                 if not method then
180                         return call_callback(request, "invalid-status-line");
181                 end
182                 
183                 request.method, request.path, request.httpversion = method, path, http;
184                 
185                 request.url = url_parse(request.path);
186                 
187                 log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
188                 
189                 if request.onlystatus then
190                         if not call_callback(request) then
191                                 return;
192                         end
193                 end
194                 
195                 request.state = "headers";
196                 
197                 if #data > linelen then
198                         return request_reader(request, data:sub(linelen, -1));
199                 end
200         end
201 end
202
203 -- The default handler for requests
204 default_handler = function (method, body, request)
205         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler.serverport());
206         return { status = "404 Not Found", 
207                         headers = { ["Content-Type"] = "text/html" },
208                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
209 end
210
211
212 function new_request(handler)
213         return { handler = handler, conn = handler.socket, 
214                         write = handler.write, state = "request", 
215                         server = http_servers[handler.serverport()],
216                         send = send_response,
217                         destroy = destroy_request,
218                         id = tostring{}:match("%x+$")
219                          };
220 end
221
222 function destroy_request(request)
223         log("debug", "Destroying request %s", request.id);
224         listener = listener or connlisteners_get("httpserver");
225         if not request.destroyed then
226                 request.destroyed = true;
227                 if request.on_destroy then
228                         log("debug", "Request has destroy callback");
229                         request.on_destroy(request);
230                 else
231                         log("debug", "Request has no destroy callback");
232                 end
233                 request.handler.close()
234                 if request.conn then
235                         listener.disconnect(request.conn, "closed");
236                 end
237         end
238 end
239
240 function new(params)
241         local http_server = http_servers[params.port];
242         if not http_server then
243                 http_server = { handlers = {} };
244                 http_servers[params.port] = http_server;
245                 -- We weren't already listening on this port, so start now
246                 connlisteners_start("httpserver", params);
247         end
248         if params.base then
249                 http_server.handlers[params.base] = params.handler;
250         end
251 end
252
253 _M.request_reader = request_reader;
254 _M.send_response = send_response;
255 _M.urlencode = urlencode;
256
257 return _M;