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