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