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