mod_bosh: Support for cross-domain access control using CORS
[prosody.git] / plugins / mod_bosh.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 module.host = "*" -- Global module
10
11 local hosts = _G.hosts;
12 local lxp = require "lxp";
13 local init_xmlhandlers = require "core.xmlhandlers"
14 local server = require "net.server";
15 local httpserver = require "net.httpserver";
16 local sm = require "core.sessionmanager";
17 local sm_destroy_session = sm.destroy_session;
18 local new_uuid = require "util.uuid".generate;
19 local fire_event = require "core.eventmanager".fire_event;
20 local core_process_stanza = core_process_stanza;
21 local st = require "util.stanza";
22 local logger = require "util.logger";
23 local log = logger.init("mod_bosh");
24
25 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
26 local stream_callbacks = { stream_ns = "http://jabber.org/protocol/httpbind", stream_tag = "body", default_ns = xmlns_bosh };
27
28 local BOSH_DEFAULT_HOLD = tonumber(module:get_option("bosh_default_hold")) or 1;
29 local BOSH_DEFAULT_INACTIVITY = tonumber(module:get_option("bosh_max_inactivity")) or 60;
30 local BOSH_DEFAULT_POLLING = tonumber(module:get_option("bosh_max_polling")) or 5;
31 local BOSH_DEFAULT_REQUESTS = tonumber(module:get_option("bosh_max_requests")) or 2;
32 local BOSH_DEFAULT_MAXPAUSE = tonumber(module:get_option("bosh_max_pause")) or 300;
33
34 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
35 local session_close_reply = { headers = default_headers, body = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate" }), attr = {} };
36
37 local http_options, http_denied_options = { headers = {} }, { headers = {} };
38 local cross_domain = module:get_option("cross_domain_bosh");
39 if cross_domain ~= false then
40         http_options.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
41         http_options.headers["Access-Control-Allow-Headers"] = "Content-Type";
42         http_options.headers["Access-Control-Max-Age"] = "86400";
43
44         if cross_domain == true then
45                 http_options.headers["Access-Control-Allow-Origin"] = "*";
46         elseif type(cross_domain) == "table" then
47                 cross_domain = table.concat(cross_domain, ", ");
48         end
49         if type(cross_domain) == "string" then
50                 http_options.headers["Access-Control-Allow-Origin"] = cross_domain;
51         end
52 end
53
54 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
55 local os_time = os.time;
56
57 local sessions = {};
58 local inactive_sessions = {}; -- Sessions which have no open requests
59
60 -- Used to respond to idle sessions (those with waiting requests)
61 local waiting_requests = {};
62 function on_destroy_request(request)
63         waiting_requests[request] = nil;
64         local session = sessions[request.sid];
65         if session then
66                 local requests = session.requests;
67                 for i,r in pairs(requests) do
68                         if r == request then requests[i] = nil; break; end
69                 end
70                 
71                 -- If this session now has no requests open, mark it as inactive
72                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
73                         inactive_sessions[session] = os_time();
74                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
75                 end
76         end
77 end
78
79 local function send_options_headers(request)
80         if cross_domain == nil then
81                 local host = request.headers.host and request.headers.host:match("^[^:]+");
82                 if hosts[host] then
83                         http_options.headers["Access-Control-Allow-Origin"] = "http://"..host;
84                 else
85                         return http_denied_options; -- We don't want to reveal the hosts we serve
86                 end
87         end
88         return http_options;
89 end
90
91 function handle_request(method, body, request)
92         if (not body) or request.method ~= "POST" then
93                 if request.method == "OPTIONS" then
94                         return send_options_headers(request);
95                 else
96                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
97                 end
98         end
99         if not method then
100                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
101                 return;
102         end
103         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
104         request.notopen = true;
105         request.log = log;
106         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "\1");
107         
108         parser:parse(body);
109         
110         local session = sessions[request.sid];
111         if session then
112                 local r = session.requests;
113                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
114                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
115                 if #r > session.bosh_hold then
116                         -- We are holding too many requests, send what's in the buffer,
117                         log("debug", "We are holding too many requests, so...");
118                         if #session.send_buffer > 0 then
119                                 log("debug", "...sending what is in the buffer")
120                                 session.send(t_concat(session.send_buffer));
121                                 session.send_buffer = {};
122                         else
123                                 -- or an empty response
124                                 log("debug", "...sending an empty response");
125                                 session.send("");
126                         end
127                 elseif #session.send_buffer > 0 then
128                         log("debug", "Session has data in the send buffer, will send now..");
129                         local resp = t_concat(session.send_buffer);
130                         session.send_buffer = {};
131                         session.send(resp);
132                 end
133                 
134                 if not request.destroyed and session.bosh_wait then
135                         request.reply_before = os_time() + session.bosh_wait;
136                         request.on_destroy = on_destroy_request;
137                         waiting_requests[request] = true;
138                 end
139                 
140                 log("debug", "Have nothing to say, so leaving request unanswered for now");
141                 return true;
142         end
143 end
144
145
146 local function bosh_reset_stream(session) session.notopen = true; end
147
148 local function bosh_close_stream(session, reason)
149         (session.log or log)("info", "BOSH client disconnected");
150         session_close_reply.attr.condition = reason;
151         for _, held_request in ipairs(session.requests) do
152                 held_request:send(session_close_reply);
153                 held_request:destroy();
154         end
155         sessions[session.sid]  = nil;
156         sm_destroy_session(session);
157 end
158
159 function stream_callbacks.streamopened(request, attr)
160         log("debug", "BOSH body open (sid: %s)", attr.sid);
161         local sid = attr.sid
162         if not sid then
163                 -- New session request
164                 request.notopen = nil; -- Signals that we accept this opening tag
165                 
166                 -- TODO: Sanity checks here (rid, to, known host, etc.)
167                 if not hosts[attr.to] then
168                         -- Unknown host
169                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
170                         session_close_reply.body.attr.condition = "host-unknown";
171                         request:send(session_close_reply);
172                         request.notopen = nil
173                         return;
174                 end
175                 
176                 -- New session
177                 sid = new_uuid();
178                 local session = { type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to, bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid, 
179                                                 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
180                                                 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream, close = bosh_close_stream, 
181                                                 dispatch_stanza = core_process_stanza, log = logger.init("bosh"..sid), secure = request.secure };
182                 sessions[sid] = session;
183                 
184                 log("info", "New BOSH session, assigned it sid '%s'", sid);
185                 local r, send_buffer = session.requests, session.send_buffer;
186                 local response = { headers = default_headers }
187                 function session.send(s)
188                         --log("debug", "Sending BOSH data: %s", tostring(s));
189                         local oldest_request = r[1];
190                         while oldest_request and oldest_request.destroyed do
191                                 t_remove(r, 1);
192                                 waiting_requests[oldest_request] = nil;
193                                 oldest_request = r[1];
194                         end
195                         if oldest_request then
196                                 log("debug", "We have an open request, so sending on that");
197                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
198                                 oldest_request:send(response);
199                                 --log("debug", "Sent");
200                                 if oldest_request.stayopen then
201                                         if #r>1 then
202                                                 -- Move front request to back
203                                                 t_insert(r, oldest_request);
204                                                 t_remove(r, 1);
205                                         end
206                                 else
207                                         log("debug", "Destroying the request now...");
208                                         oldest_request:destroy();
209                                         t_remove(r, 1);
210                                 end
211                         elseif s ~= "" then
212                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
213                                 -- Hmm, no requests are open :(
214                                 t_insert(session.send_buffer, tostring(s));
215                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
216                         end
217                 end
218                 
219                 -- Send creation response
220                 
221                 local features = st.stanza("stream:features");
222                 fire_event("stream-features", session, features);
223                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
224                 local response = st.stanza("body", { xmlns = xmlns_bosh,
225                                                                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY), polling = tostring(BOSH_DEFAULT_POLLING), requests = tostring(BOSH_DEFAULT_REQUESTS), hold = tostring(session.bosh_hold), maxpause = "120",
226                                                                         sid = sid, authid = sid, ver  = '1.6', from = session.host, secure = 'true', ["xmpp:version"] = "1.0",
227                                                                         ["xmlns:xmpp"] = "urn:xmpp:xbosh", ["xmlns:stream"] = "http://etherx.jabber.org/streams" }):add_child(features);
228                 request:send{ headers = default_headers, body = tostring(response) };
229                 
230                 request.sid = sid;
231                 return;
232         end
233         
234         local session = sessions[sid];
235         if not session then
236                 -- Unknown sid
237                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
238                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
239                 request.notopen = nil;
240                 return;
241         end
242         
243         if session.rid then
244                 local rid = tonumber(attr.rid);
245                 local diff = rid - session.rid;
246                 if diff > 1 then
247                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
248                 elseif diff <= 0 then
249                         -- Repeated, ignore
250                         session.log("debug", "rid repeated (on request %s), ignoring: %d", request.id, session.rid);
251                         request.notopen = nil;
252                         t_insert(session.requests, request);
253                         return;
254                 end
255                 session.rid = rid;
256         end
257         
258         if attr.type == "terminate" then
259                 -- Client wants to end this session
260                 session:close();
261                 request.notopen = nil;
262                 return;
263         end
264         
265         -- If session was inactive, make sure it is now marked as not
266         if #session.requests == 0 then
267                 (session.log or log)("debug", "BOSH client now active again at %d", os_time());
268                 inactive_sessions[session] = nil;
269         end
270         
271         if session.notopen then
272                 local features = st.stanza("stream:features");
273                 fire_event("stream-features", session, features);
274                 session.send(features);
275                 session.notopen = nil;
276         end
277         
278         request.notopen = nil; -- Signals that we accept this opening tag
279         t_insert(session.requests, request);
280         request.sid = sid;
281 end
282
283 function stream_callbacks.handlestanza(request, stanza)
284         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
285         local session = sessions[request.sid];
286         if session then
287                 if stanza.attr.xmlns == xmlns_bosh then
288                         stanza.attr.xmlns = "jabber:client";
289                 end
290                 session.ip = request.handler:ip();
291                 core_process_stanza(session, stanza);
292         end
293 end
294
295 local dead_sessions = {};
296 function on_timer()
297         -- log("debug", "Checking for requests soon to timeout...");
298         -- Identify requests timing out within the next few seconds
299         local now = os_time() + 3;
300         for request in pairs(waiting_requests) do
301                 if request.reply_before <= now then
302                         log("debug", "%s was soon to timeout, sending empty response", request.id);
303                         -- Send empty response to let the
304                         -- client know we're still here
305                         if request.conn then
306                                 sessions[request.sid].send("");
307                         end
308                 end
309         end
310         
311         now = now - 3;
312         local n_dead_sessions = 0;
313         for session, inactive_since in pairs(inactive_sessions) do
314                 if session.bosh_max_inactive then
315                         if now - inactive_since > session.bosh_max_inactive then
316                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
317                                 sessions[session.sid]  = nil;
318                                 inactive_sessions[session] = nil;
319                                 n_dead_sessions = n_dead_sessions + 1;
320                                 dead_sessions[n_dead_sessions] = session;
321                         end
322                 else
323                         inactive_sessions[session] = nil;
324                 end
325         end
326
327         for i=1,n_dead_sessions do
328                 local session = dead_sessions[i];
329                 dead_sessions[i] = nil;
330                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
331         end
332 end
333
334
335 local function setup()
336         local ports = module:get_option("bosh_ports") or { 5280 };
337         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
338         server.addtimer(on_timer);
339 end
340 if prosody.start_time then -- already started
341         setup();
342 else
343         prosody.events.add_handler("server-started", setup);
344 end