Merge 0.6.2/waqas with 0.6.2/MattJ
[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 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 pairs(requests) do
67                         if r == request then requests[i] = nil; break; end
68                 end
69                 
70                 -- If this session now has no requests open, mark it as inactive
71                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
72                         inactive_sessions[session] = os_time();
73                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
74                 end
75         end
76 end
77
78 function handle_request(method, body, request)
79         if (not body) or request.method ~= "POST" then
80                 if request.method == "OPTIONS" then
81                         return { headers = default_headers, body = "" };
82                 else
83                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
84                 end
85         end
86         if not method then
87                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
88                 return;
89         end
90         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
91         request.notopen = true;
92         request.log = log;
93         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "\1");
94         
95         parser:parse(body);
96         
97         local session = sessions[request.sid];
98         if session then
99                 local r = session.requests;
100                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
101                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
102                 if #r > session.bosh_hold then
103                         -- We are holding too many requests, send what's in the buffer,
104                         log("debug", "We are holding too many requests, so...");
105                         if #session.send_buffer > 0 then
106                                 log("debug", "...sending what is in the buffer")
107                                 session.send(t_concat(session.send_buffer));
108                                 session.send_buffer = {};
109                         else
110                                 -- or an empty response
111                                 log("debug", "...sending an empty response");
112                                 session.send("");
113                         end
114                 elseif #session.send_buffer > 0 then
115                         log("debug", "Session has data in the send buffer, will send now..");
116                         local resp = t_concat(session.send_buffer);
117                         session.send_buffer = {};
118                         session.send(resp);
119                 end
120                 
121                 if not request.destroyed and session.bosh_wait then
122                         request.reply_before = os_time() + session.bosh_wait;
123                         request.on_destroy = on_destroy_request;
124                         waiting_requests[request] = true;
125                 end
126                 
127                 log("debug", "Have nothing to say, so leaving request unanswered for now");
128                 return true;
129         end
130 end
131
132
133 local function bosh_reset_stream(session) session.notopen = true; end
134
135 local function bosh_close_stream(session, reason)
136         (session.log or log)("info", "BOSH client disconnected");
137         session_close_reply.attr.condition = reason;
138         for _, held_request in ipairs(session.requests) do
139                 held_request:send(session_close_reply);
140                 held_request:destroy();
141         end
142         sessions[session.sid]  = nil;
143         sm_destroy_session(session);
144 end
145
146 function stream_callbacks.streamopened(request, attr)
147         log("debug", "BOSH body open (sid: %s)", attr.sid);
148         local sid = attr.sid
149         if not sid then
150                 -- New session request
151                 request.notopen = nil; -- Signals that we accept this opening tag
152                 
153                 -- TODO: Sanity checks here (rid, to, known host, etc.)
154                 if not hosts[attr.to] then
155                         -- Unknown host
156                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
157                         session_close_reply.body.attr.condition = "host-unknown";
158                         request:send(session_close_reply);
159                         request.notopen = nil
160                         return;
161                 end
162                 
163                 -- New session
164                 sid = new_uuid();
165                 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, 
166                                                 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
167                                                 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream, close = bosh_close_stream, 
168                                                 dispatch_stanza = core_process_stanza, log = logger.init("bosh"..sid), secure = request.secure };
169                 sessions[sid] = session;
170                 
171                 log("info", "New BOSH session, assigned it sid '%s'", sid);
172                 local r, send_buffer = session.requests, session.send_buffer;
173                 local response = { headers = default_headers }
174                 function session.send(s)
175                         --log("debug", "Sending BOSH data: %s", tostring(s));
176                         local oldest_request = r[1];
177                         while oldest_request and oldest_request.destroyed do
178                                 t_remove(r, 1);
179                                 waiting_requests[oldest_request] = nil;
180                                 oldest_request = r[1];
181                         end
182                         if oldest_request then
183                                 log("debug", "We have an open request, so sending on that");
184                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
185                                 oldest_request:send(response);
186                                 --log("debug", "Sent");
187                                 if oldest_request.stayopen then
188                                         if #r>1 then
189                                                 -- Move front request to back
190                                                 t_insert(r, oldest_request);
191                                                 t_remove(r, 1);
192                                         end
193                                 else
194                                         log("debug", "Destroying the request now...");
195                                         oldest_request:destroy();
196                                         t_remove(r, 1);
197                                 end
198                         elseif s ~= "" then
199                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
200                                 -- Hmm, no requests are open :(
201                                 t_insert(session.send_buffer, tostring(s));
202                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
203                         end
204                 end
205                 
206                 -- Send creation response
207                 
208                 local features = st.stanza("stream:features");
209                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = 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                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
262                 fire_event("stream-features", session, features);
263                 session.send(features);
264                 session.notopen = nil;
265         end
266         
267         request.notopen = nil; -- Signals that we accept this opening tag
268         t_insert(session.requests, request);
269         request.sid = sid;
270 end
271
272 function stream_callbacks.handlestanza(request, stanza)
273         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
274         local session = sessions[request.sid];
275         if session then
276                 if stanza.attr.xmlns == xmlns_bosh then
277                         stanza.attr.xmlns = "jabber:client";
278                 end
279                 session.ip = request.handler:ip();
280                 core_process_stanza(session, stanza);
281         end
282 end
283
284 local dead_sessions = {};
285 function on_timer()
286         -- log("debug", "Checking for requests soon to timeout...");
287         -- Identify requests timing out within the next few seconds
288         local now = os_time() + 3;
289         for request in pairs(waiting_requests) do
290                 if request.reply_before <= now then
291                         log("debug", "%s was soon to timeout, sending empty response", request.id);
292                         -- Send empty response to let the
293                         -- client know we're still here
294                         if request.conn then
295                                 sessions[request.sid].send("");
296                         end
297                 end
298         end
299         
300         now = now - 3;
301         local n_dead_sessions = 0;
302         for session, inactive_since in pairs(inactive_sessions) do
303                 if session.bosh_max_inactive then
304                         if now - inactive_since > session.bosh_max_inactive then
305                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
306                                 sessions[session.sid]  = nil;
307                                 inactive_sessions[session] = nil;
308                                 n_dead_sessions = n_dead_sessions + 1;
309                                 dead_sessions[n_dead_sessions] = session;
310                         end
311                 else
312                         inactive_sessions[session] = nil;
313                 end
314         end
315
316         for i=1,n_dead_sessions do
317                 local session = dead_sessions[i];
318                 dead_sessions[i] = nil;
319                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
320         end
321 end
322
323
324 local function setup()
325         local ports = module:get_option("bosh_ports") or { 5280 };
326         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
327         server.addtimer(on_timer);
328 end
329 if prosody.start_time then -- already started
330         setup();
331 else
332         prosody.events.add_handler("server-started", setup);
333 end