Fixed: User resources not disconnected correctly on account delete
[prosody.git] / plugins / mod_bosh.lua
1
2 module.host = "*" -- Global module
3
4 local lxp = require "lxp";
5 local init_xmlhandlers = require "core.xmlhandlers"
6 local server = require "net.server";
7 local httpserver = require "net.httpserver";
8 local sm = require "core.sessionmanager";
9 local sm_destroy_session = sm.destroy_session;
10 local new_uuid = require "util.uuid".generate;
11 local fire_event = require "core.eventmanager".fire_event;
12 local core_process_stanza = core_process_stanza;
13 local st = require "util.stanza";
14 local log = require "util.logger".init("bosh");
15 local stream_callbacks = { stream_tag = "http://jabber.org/protocol/httpbind|body" };
16 local config = require "core.configmanager";
17 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
18
19 local BOSH_DEFAULT_HOLD = tonumber(config.get("*", "core", "bosh_default_hold")) or 1;
20 local BOSH_DEFAULT_INACTIVITY = tonumber(config.get("*", "core", "bosh_max_inactivity")) or 60;
21 local BOSH_DEFAULT_POLLING = tonumber(config.get("*", "core", "bosh_max_polling")) or 5;
22 local BOSH_DEFAULT_REQUESTS = tonumber(config.get("*", "core", "bosh_max_requests")) or 2;
23 local BOSH_DEFAULT_MAXPAUSE = tonumber(config.get("*", "core", "bosh_max_pause")) or 300;
24
25 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
26 local os_time = os.time;
27
28 local sessions = {};
29 local inactive_sessions = {}; -- Sessions which have no open requests
30
31 -- Used to respond to idle sessions (those with waiting requests)
32 local waiting_requests = {};
33 function on_destroy_request(request)
34         waiting_requests[request] = nil;
35 end
36
37 function handle_request(method, body, request)
38         if (not body) or request.method ~= "POST" then
39                 return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
40         end
41         if not method then 
42                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
43                 return;
44         end
45         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
46         request.notopen = true;
47         request.log = log;
48         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "|");
49         
50         parser:parse(body);
51         
52         local session = sessions[request.sid];
53         if session then
54                 local r = session.requests;
55                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
56                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
57                 if #r > session.bosh_hold then
58                         -- We are holding too many requests, send what's in the buffer,
59                         log("debug", "We are holding too many requests, so...");
60                         if #session.send_buffer > 0 then
61                                 log("debug", "...sending what is in the buffer")
62                                 session.send(t_concat(session.send_buffer));
63                                 session.send_buffer = {};
64                         else
65                                 -- or an empty response
66                                 log("debug", "...sending an empty response");
67                                 session.send("");
68                         end
69                 elseif #session.send_buffer > 0 then
70                         log("debug", "Session has data in the send buffer, will send now..");
71                         local resp = t_concat(session.send_buffer);
72                         session.send_buffer = {};
73                         session.send(resp);
74                 end
75                 
76                 if not request.destroyed and session.bosh_wait then
77                         request.reply_before = os_time() + session.bosh_wait;
78                         request.on_destroy = on_destroy_request;
79                         waiting_requests[request] = true;
80                 end
81                 
82                 log("debug", "Have nothing to say, so leaving request unanswered for now");
83                 return true;
84         end
85 end
86
87
88 local function bosh_reset_stream(session) session.notopen = true; end
89
90 local session_close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate" });
91 local function bosh_close_stream(session, reason)
92         (session.log or log)("info", "BOSH client disconnected");
93         session_close_reply.attr.condition = reason;
94         local session_close_reply = tostring(session_close_reply);
95         for _, held_request in ipairs(session.requests) do
96                 held_request:send(session_close_reply);
97                 held_request:destroy();
98         end
99         sessions[session.sid]  = nil;
100         sm_destroy_session(session);
101 end
102
103 function stream_callbacks.streamopened(request, attr)
104         log("debug", "BOSH body open (sid: %s)", attr.sid);
105         local sid = attr.sid
106         if not sid then
107                 -- New session request
108                 request.notopen = nil; -- Signals that we accept this opening tag
109                 
110                 -- TODO: Sanity checks here (rid, to, known host, etc.)
111                 if not hosts[attr.to] then
112                         -- Unknown host
113                         session_close_reply.attr.condition = "host-unknown";
114                         request:send(tostring(session_close_reply));
115                         request.notopen = nil
116                         return;
117                 end
118                 
119                 -- New session
120                 sid = new_uuid();
121                 local session = { type = "c2s_unauthed", conn = {}, sid = sid, rid = attr.rid, host = attr.to, bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid, 
122                                                 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
123                                                 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream, close = bosh_close_stream, dispatch_stanza = core_process_stanza };
124                 sessions[sid] = session;
125                 log("info", "New BOSH session, assigned it sid '%s'", sid);
126                 local r, send_buffer = session.requests, session.send_buffer;
127                 local response = { }
128                 function session.send(s)
129                         log("debug", "Sending BOSH data: %s", tostring(s));
130                         local oldest_request = r[1];
131                         while oldest_request and oldest_request.destroyed do
132                                 t_remove(r, 1);
133                                 waiting_requests[oldest_request] = nil;
134                                 oldest_request = r[1];
135                         end
136                         if oldest_request then
137                                 log("debug", "We have an open request, so using that to send with");
138                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
139                                 oldest_request:send(response);
140                                 --log("debug", "Sent");
141                                 if oldest_request.stayopen then
142                                         if #r>1 then
143                                                 -- Move front request to back
144                                                 t_insert(r, oldest_request);
145                                                 t_remove(r, 1);
146                                         end
147                                 else
148                                         log("debug", "Destroying the request now...");
149                                         oldest_request:destroy();
150                                         t_remove(r, 1);
151                                 end
152                         elseif s ~= "" then
153                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
154                                 if session.bosh_max_inactive and not inactive_sessions[session] then
155                                         inactive_sessions[session] = os_time();
156                                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
157                                 end
158                                 -- Hmm, no requests are open :(
159                                 t_insert(session.send_buffer, tostring(s));
160                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
161                         end
162                 end
163                 
164                 -- Send creation response
165                 
166                 local features = st.stanza("stream:features");
167                 fire_event("stream-features", session, features);
168                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
169                 local response = st.stanza("body", { xmlns = xmlns_bosh, 
170                                                                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY), polling = tostring(BOSH_DEFAULT_POLLING), requests = tostring(BOSH_DEFAULT_REQUESTS), hold = tostring(session.bosh_hold), maxpause = "120", 
171                                                                         sid = sid, ver  = '1.6', from = session.host, secure = 'true', ["xmpp:version"] = "1.0", 
172                                                                         ["xmlns:xmpp"] = "urn:xmpp:xbosh", ["xmlns:stream"] = "http://etherx.jabber.org/streams" }):add_child(features);
173                 request:send(tostring(response));
174                                 
175                 request.sid = sid;
176                 return;
177         end
178         
179         local session = sessions[sid];
180         if not session then
181                 -- Unknown sid
182                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
183                 request:send(tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })));
184                 request.notopen = nil;
185                 return;
186         end
187         
188         if attr.type == "terminate" then
189                 -- Client wants to end this session
190                 session:close();
191                 request.notopen = nil;
192                 return;
193         end
194         
195         -- If session was inactive, make sure it is now marked as not
196         if #session.requests == 0 then
197                 (session.log or log)("debug", "BOSH client now active again at %d", os_time());
198                 inactive_sessions[session] = nil;
199         end
200         
201         if session.notopen then
202                 local features = st.stanza("stream:features");
203                 fire_event("stream-features", session, features);
204                 session.send(features);
205                 session.notopen = nil;
206         end
207         
208         request.notopen = nil; -- Signals that we accept this opening tag
209         t_insert(session.requests, request);
210         request.sid = sid;
211 end
212
213 function stream_callbacks.handlestanza(request, stanza)
214         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
215         local session = sessions[request.sid];
216         if session then
217                 if stanza.attr.xmlns == xmlns_bosh then
218                         stanza.attr.xmlns = "jabber:client";
219                 end
220                 core_process_stanza(session, stanza);
221         end
222 end
223
224 function on_timer()
225         -- log("debug", "Checking for requests soon to timeout...");
226         -- Identify requests timing out within the next few seconds
227         local now = os_time() + 3;
228         for request in pairs(waiting_requests) do
229                 if request.reply_before <= now then
230                         log("debug", "%s was soon to timeout, sending empty response", request.id);
231                         -- Send empty response to let the
232                         -- client know we're still here
233                         if request.conn then
234                                 sessions[request.sid].send("");
235                         end
236                 end
237         end
238         
239         now = now - 3;
240         for session, inactive_since in pairs(inactive_sessions) do
241                 if session.bosh_max_inactive then
242                         if now - inactive_since > session.bosh_max_inactive then
243                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
244                                 sessions[session.sid]  = nil;
245                                 inactive_sessions[session] = nil;
246                                 session.bosh_max_inactive = nil; -- Stop us marking this session as active during destroy
247                                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
248                         end
249                 else
250                         inactive_sessions[session] = nil;
251                 end
252         end
253 end
254
255 local ports = config.get(module.host, "core", "bosh_ports") or { 5280 };
256 for _, options in ipairs(ports) do
257         local port, base, ssl, interface = 5280, "http-bind", false, nil;
258         if type(options) == "number" then
259                 port = options;
260         elseif type(options) == "table" then
261                 port, base, ssl, interface = options.port or 5280, options.path or "http-bind", options.ssl or false, options.interface;
262         elseif type(options) == "string" then
263                 base = options;
264         end
265         httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
266 end
267
268 server.addtimer(on_timer);