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