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