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