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