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