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