3c2b55d53638cf5ca052dc5b3cf4f8c5ba67e6d1
[prosody.git] / net / http / server.lua
1
2 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
3 local parser_new = require "net.http.parser".new;
4 local events = require "util.events".new();
5 local addserver = require "net.server".addserver;
6 local log = require "util.logger".init("http.server");
7 local os_date = os.date;
8 local pairs = pairs;
9 local s_upper = string.upper;
10 local setmetatable = setmetatable;
11 local xpcall = xpcall;
12 local debug = debug;
13 local tostring = tostring;
14 local codes = require "net.http.codes";
15
16 local _M = {};
17
18 local sessions = {};
19 local listener = {};
20 local hosts = {};
21 local default_host;
22
23 local function is_wildcard_event(event)
24         return event:sub(-2, -1) == "/*";
25 end
26 local function is_wildcard_match(wildcard_event, event)
27         return wildcard_event:sub(1, -2) == event:sub(1, #wildcard_event-1);
28 end
29
30 local recent_wildcard_events, max_cached_wildcard_events = {}, 10000;
31
32 local event_map = events._event_map;
33 setmetatable(events._handlers, {
34         __index = function (handlers, curr_event)
35                 if is_wildcard_event(curr_event) then return; end -- Wildcard events cannot be fired
36                 -- Find all handlers that could match this event, sort them
37                 -- and then put the array into handlers[curr_event] (and return it)
38                 local matching_handlers_set = {};
39                 local handlers_array = {};
40                 for event, handlers_set in pairs(event_map) do
41                         if event == curr_event or
42                         is_wildcard_event(event) and is_wildcard_match(event, curr_event) then
43                                 for handler, priority in pairs(handlers_set) do
44                                         matching_handlers_set[handler] = { (select(2, event:gsub("/", "%1"))), is_wildcard_event(event) and 0 or 1, priority };
45                                         table.insert(handlers_array, handler);
46                                 end
47                         end
48                 end
49                 if #handlers_array > 0 then
50                         table.sort(handlers_array, function(b, a)
51                                 local a_score, b_score = matching_handlers_set[a], matching_handlers_set[b];
52                                 for i = 1, #a_score do
53                                         if a_score[i] ~= b_score[i] then -- If equal, compare next score value
54                                                 return a_score[i] < b_score[i];
55                                         end
56                                 end
57                                 return false;
58                         end);
59                 else
60                         handlers_array = false;
61                 end
62                 rawset(handlers, curr_event, handlers_array);
63                 if not event_map[curr_event] then -- Only wildcard handlers match, if any
64                         table.insert(recent_wildcard_events, curr_event);
65                         if #recent_wildcard_events > max_cached_wildcard_events then
66                                 rawset(handlers, table.remove(recent_wildcard_events, 1), nil);
67                         end
68                 end
69                 return handlers_array;
70         end;
71         __newindex = function (handlers, curr_event, handlers_array)
72                 if handlers_array == nil
73                 and is_wildcard_event(curr_event) then
74                         -- Invalidate the indexes of all matching events
75                         for event in pairs(handlers) do
76                                 if is_wildcard_match(curr_event, event) then
77                                         handlers[event] = nil;
78                                 end
79                         end
80                 end
81                 rawset(handlers, curr_event, handlers_array);
82         end;
83 });
84
85 local handle_request;
86 local _1, _2, _3;
87 local function _handle_request() return handle_request(_1, _2, _3); end
88
89 local last_err;
90 local function _traceback_handler(err) last_err = err; log("error", "Traceback[http]: %s: %s", tostring(err), debug.traceback()); end
91 events.add_handler("http-error", function (error)
92         return "Error processing request: "..codes[error.code]..". Check your error log for more information.";
93 end, -1);
94
95 function listener.onconnect(conn)
96         local secure = conn:ssl() and true or nil;
97         local pending = {};
98         local waiting = false;
99         local function process_next()
100                 if waiting then log("debug", "can't process_next, waiting"); return; end
101                 waiting = true;
102                 while sessions[conn] and #pending > 0 do
103                         local request = t_remove(pending);
104                         --log("debug", "process_next: %s", request.path);
105                         --handle_request(conn, request, process_next);
106                         _1, _2, _3 = conn, request, process_next;
107                         if not xpcall(_handle_request, _traceback_handler) then
108                                 conn:write("HTTP/1.0 500 Internal Server Error\r\n\r\n"..events.fire_event("http-error", { code = 500, private_message = last_err }));
109                                 conn:close();
110                         end
111                 end
112                 --log("debug", "ready for more");
113                 waiting = false;
114         end
115         local function success_cb(request)
116                 --log("debug", "success_cb: %s", request.path);
117                 if waiting then
118                         log("error", "http connection handler is not reentrant: %s", request.path);
119                         assert(false, "http connection handler is not reentrant");
120                 end
121                 request.secure = secure;
122                 t_insert(pending, request);
123                 process_next();
124         end
125         local function error_cb(err)
126                 log("debug", "error_cb: %s", err or "<nil>");
127                 -- FIXME don't close immediately, wait until we process current stuff
128                 -- FIXME if err, send off a bad-request response
129                 sessions[conn] = nil;
130                 conn:close();
131         end
132         sessions[conn] = parser_new(success_cb, error_cb);
133 end
134
135 function listener.ondisconnect(conn)
136         local open_response = conn._http_open_response;
137         if open_response and open_response.on_destroy then
138                 open_response.finished = true;
139                 open_response:on_destroy();
140         end
141         sessions[conn] = nil;
142 end
143
144 function listener.onincoming(conn, data)
145         sessions[conn]:feed(data);
146 end
147
148 local headerfix = setmetatable({}, {
149         __index = function(t, k)
150                 local v = "\r\n"..k:gsub("_", "-"):gsub("%f[%w].", s_upper)..": ";
151                 t[k] = v;
152                 return v;
153         end
154 });
155
156 function _M.hijack_response(response, listener)
157         error("TODO");
158 end
159 function handle_request(conn, request, finish_cb)
160         --log("debug", "handler: %s", request.path);
161         local headers = {};
162         for k,v in pairs(request.headers) do headers[k:gsub("-", "_")] = v; end
163         request.headers = headers;
164         request.conn = conn;
165
166         local date_header = os_date('!%a, %d %b %Y %H:%M:%S GMT'); -- FIXME use
167         local conn_header = request.headers.connection;
168         conn_header = conn_header and ","..conn_header:gsub("[ \t]", ""):lower().."," or ""
169         local httpversion = request.httpversion
170         local persistent = conn_header:find(",Keep-Alive,", 1, true)
171                 or (httpversion == "1.1" and not conn_header:find(",close,", 1, true));
172
173         local response_conn_header;
174         if persistent then
175                 response_conn_header = "Keep-Alive";
176         else
177                 response_conn_header = httpversion == "1.1" and "close" or nil
178         end
179
180         local response = {
181                 request = request;
182                 status_code = 200;
183                 headers = { date = date_header, connection = response_conn_header };
184                 persistent = persistent;
185                 conn = conn;
186                 send = _M.send_response;
187                 finish_cb = finish_cb;
188         };
189         conn._http_open_response = response;
190
191         local host = (request.headers.host or ""):match("[^:]+");
192
193         -- Some sanity checking
194         local err_code, err;
195         if not request.path then
196                 err_code, err = 400, "Invalid path";
197         elseif not hosts[host] then
198                 if hosts[default_host] then
199                         host = default_host;
200                 elseif host then
201                         err_code, err = 404, "Unknown host: "..host;
202                 else
203                         err_code, err = 400, "Missing or invalid 'Host' header";
204                 end
205         end
206         
207         if err then
208                 response.status_code = err_code;
209                 response:send(events.fire_event("http-error", { code = err_code, message = err }));
210                 return;
211         end
212
213         local event = request.method.." "..host..request.path:match("[^?]*");
214         local payload = { request = request, response = response };
215         --log("debug", "Firing event: %s", event);
216         local result = events.fire_event(event, payload);
217         if result ~= nil then
218                 if result ~= true then
219                         local body;
220                         local result_type = type(result);
221                         if result_type == "number" then
222                                 response.status_code = result;
223                                 if result >= 400 then
224                                         body = events.fire_event("http-error", { code = result });
225                                 end
226                         elseif result_type == "string" then
227                                 body = result;
228                         elseif result_type == "table" then
229                                 for k, v in pairs(result) do
230                                         if k ~= "headers" then
231                                                 response[k] = v;
232                                         else
233                                                 for header_name, header_value in pairs(v) do
234                                                         response.headers[header_name] = header_value;
235                                                 end
236                                         end
237                                 end
238                         end
239                         response:send(body);
240                 end
241                 return;
242         end
243
244         -- if handler not called, return 404
245         response.status_code = 404;
246         response:send(events.fire_event("http-error", { code = 404 }));
247 end
248 function _M.send_response(response, body)
249         if response.finished then return; end
250         response.finished = true;
251         response.conn._http_open_response = nil;
252         
253         local status_line = "HTTP/"..response.request.httpversion.." "..(response.status or codes[response.status_code]);
254         local headers = response.headers;
255         body = body or response.body or "";
256         headers.content_length = #body;
257
258         local output = { status_line };
259         for k,v in pairs(headers) do
260                 t_insert(output, headerfix[k]..v);
261         end
262         t_insert(output, "\r\n\r\n");
263         t_insert(output, body);
264
265         response.conn:write(t_concat(output));
266         if response.on_destroy then
267                 response:on_destroy();
268                 response.on_destroy = nil;
269         end
270         if response.persistent then
271                 response:finish_cb();
272         else
273                 response.conn:close();
274         end
275 end
276 function _M.add_handler(event, handler, priority)
277         events.add_handler(event, handler, priority);
278 end
279 function _M.remove_handler(event, handler)
280         events.remove_handler(event, handler);
281 end
282
283 function _M.listen_on(port, interface, ssl)
284         addserver(interface or "*", port, listener, "*a", ssl);
285 end
286 function _M.add_host(host)
287         hosts[host] = true;
288 end
289 function _M.remove_host(host)
290         hosts[host] = nil;
291 end
292 function _M.set_default_host(host)
293         default_host = host;
294 end
295 function _M.fire_event(event, ...)
296         return events.fire_event(event, ...);
297 end
298
299 _M.listener = listener;
300 _M.codes = codes;
301 _M._events = events;
302 return _M;