mod_bosh: Use util.timer for timers instead of server.addtimer.
[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 httpserver = require "net.httpserver";
15 local sm = require "core.sessionmanager";
16 local sm_destroy_session = sm.destroy_session;
17 local new_uuid = require "util.uuid".generate;
18 local fire_event = prosody.events.fire_event;
19 local core_process_stanza = core_process_stanza;
20 local st = require "util.stanza";
21 local logger = require "util.logger";
22 local log = logger.init("mod_bosh");
23 local timer = require "util.timer";
24
25 local xmlns_streams = "http://etherx.jabber.org/streams";
26 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
27 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
28
29 local stream_callbacks = {
30         stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
31
32 local BOSH_DEFAULT_HOLD = tonumber(module:get_option("bosh_default_hold")) or 1;
33 local BOSH_DEFAULT_INACTIVITY = tonumber(module:get_option("bosh_max_inactivity")) or 60;
34 local BOSH_DEFAULT_POLLING = tonumber(module:get_option("bosh_max_polling")) or 5;
35 local BOSH_DEFAULT_REQUESTS = tonumber(module:get_option("bosh_max_requests")) or 2;
36 local BOSH_DEFAULT_MAXPAUSE = tonumber(module:get_option("bosh_max_pause")) or 300;
37
38 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
39
40 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
41
42 local cross_domain = module:get_option("cross_domain_bosh");
43 if cross_domain then
44         default_headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
45         default_headers["Access-Control-Allow-Headers"] = "Content-Type";
46         default_headers["Access-Control-Max-Age"] = "7200";
47
48         if cross_domain == true then
49                 default_headers["Access-Control-Allow-Origin"] = "*";
50         elseif type(cross_domain) == "table" then
51                 cross_domain = table.concat(cross_domain, ", ");
52         end
53         if type(cross_domain) == "string" then
54                 default_headers["Access-Control-Allow-Origin"] = cross_domain;
55         end
56 end
57
58 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
59
60 local function get_ip_from_request(request)
61         local ip = request.handler:ip();
62         local forwarded_for = request.headers["x-forwarded-for"];
63         if forwarded_for then
64                 forwarded_for = forwarded_for..", "..ip;
65                 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
66                         if not trusted_proxies[forwarded_ip] then
67                                 ip = forwarded_ip;
68                         end
69                 end
70         end
71         return ip;
72 end
73
74 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
75 local os_time = os.time;
76
77 local sessions = {};
78 local inactive_sessions = {}; -- Sessions which have no open requests
79
80 -- Used to respond to idle sessions (those with waiting requests)
81 local waiting_requests = {};
82 function on_destroy_request(request)
83         waiting_requests[request] = nil;
84         local session = sessions[request.sid];
85         if session then
86                 local requests = session.requests;
87                 for i,r in ipairs(requests) do
88                         if r == request then
89                                 t_remove(requests, i);
90                                 break;
91                         end
92                 end
93                 
94                 -- If this session now has no requests open, mark it as inactive
95                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
96                         inactive_sessions[session] = os_time();
97                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
98                 end
99         end
100 end
101
102 function handle_request(method, body, request)
103         if (not body) or request.method ~= "POST" then
104                 if request.method == "OPTIONS" then
105                         local headers = {};
106                         for k,v in pairs(default_headers) do headers[k] = v; end
107                         headers["Content-Type"] = nil;
108                         return { headers = headers, body = "" };
109                 else
110                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
111                 end
112         end
113         if not method then
114                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
115                 return;
116         end
117         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
118         request.notopen = true;
119         request.log = log;
120         request.on_destroy = on_destroy_request;
121         
122         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "\1");
123         
124         parser:parse(body);
125         
126         local session = sessions[request.sid];
127         if session then
128                 local r = session.requests;
129                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
130                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
131                 if #r > session.bosh_hold then
132                         -- We are holding too many requests, send what's in the buffer,
133                         log("debug", "We are holding too many requests, so...");
134                         if #session.send_buffer > 0 then
135                                 log("debug", "...sending what is in the buffer")
136                                 session.send(t_concat(session.send_buffer));
137                                 session.send_buffer = {};
138                         else
139                                 -- or an empty response
140                                 log("debug", "...sending an empty response");
141                                 session.send("");
142                         end
143                 elseif #session.send_buffer > 0 then
144                         log("debug", "Session has data in the send buffer, will send now..");
145                         local resp = t_concat(session.send_buffer);
146                         session.send_buffer = {};
147                         session.send(resp);
148                 end
149                 
150                 if not request.destroyed then
151                         -- We're keeping this request open, to respond later
152                         log("debug", "Have nothing to say, so leaving request unanswered for now");
153                         if session.bosh_wait then
154                                 request.reply_before = os_time() + session.bosh_wait;
155                                 waiting_requests[request] = true;
156                         end
157                         if inactive_sessions[session] then
158                                 -- Session was marked as inactive, since we have
159                                 -- a request open now, unmark it
160                                 inactive_sessions[session] = nil;
161                         end
162                 end
163                 
164                 return true; -- Inform httpserver we shall reply later
165         end
166 end
167
168
169 local function bosh_reset_stream(session) session.notopen = true; end
170
171 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
172
173 local function bosh_close_stream(session, reason)
174         (session.log or log)("info", "BOSH client disconnected");
175         
176         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
177                 ["xmlns:streams"] = xmlns_streams });
178         
179
180         if reason then
181                 close_reply.attr.condition = "remote-stream-error";
182                 if type(reason) == "string" then -- assume stream error
183                         close_reply:tag("stream:error")
184                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
185                 elseif type(reason) == "table" then
186                         if reason.condition then
187                                 close_reply:tag("stream:error")
188                                         :tag(reason.condition, stream_xmlns_attr):up();
189                                 if reason.text then
190                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
191                                 end
192                                 if reason.extra then
193                                         close_reply:add_child(reason.extra);
194                                 end
195                         elseif reason.name then -- a stanza
196                                 close_reply = reason;
197                         end
198                 end
199                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
200         end
201
202         local session_close_response = { headers = default_headers, body = tostring(close_reply) };
203
204         --FIXME: Quite sure we shouldn't reply to all requests with the error
205         for _, held_request in ipairs(session.requests) do
206                 held_request:send(session_close_response);
207                 held_request:destroy();
208         end
209         sessions[session.sid]  = nil;
210         sm_destroy_session(session);
211 end
212
213 function stream_callbacks.streamopened(request, attr)
214         log("debug", "BOSH body open (sid: %s)", attr.sid);
215         local sid = attr.sid
216         if not sid then
217                 -- New session request
218                 request.notopen = nil; -- Signals that we accept this opening tag
219                 
220                 -- TODO: Sanity checks here (rid, to, known host, etc.)
221                 if not hosts[attr.to] then
222                         -- Unknown host
223                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
224                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
225                                 ["xmlns:streams"] = xmlns_streams, condition = "host-unknown" });
226                         request:send(tostring(close_reply));
227                         return;
228                 end
229                 
230                 -- New session
231                 sid = new_uuid();
232                 local session = {
233                         type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to,
234                         bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid,
235                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
236                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
237                         close = bosh_close_stream, dispatch_stanza = core_process_stanza,
238                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
239                         ip = get_ip_from_request(request);
240                 };
241                 sessions[sid] = session;
242                 
243                 session.log("debug", "BOSH session created for request from %s", session.ip);
244                 log("info", "New BOSH session, assigned it sid '%s'", sid);
245                 local r, send_buffer = session.requests, session.send_buffer;
246                 local response = { headers = default_headers }
247                 function session.send(s)
248                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
249                         if s.attr and not s.attr.xmlns then
250                                 s = st.clone(s);
251                                 s.attr.xmlns = "jabber:client";
252                         end
253                         --log("debug", "Sending BOSH data: %s", tostring(s));
254                         local oldest_request = r[1];
255                         if oldest_request then
256                                 log("debug", "We have an open request, so sending on that");
257                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
258                                 oldest_request:send(response);
259                                 --log("debug", "Sent");
260                                 if oldest_request.stayopen then
261                                         if #r>1 then
262                                                 -- Move front request to back
263                                                 t_insert(r, oldest_request);
264                                                 t_remove(r, 1);
265                                         end
266                                 else
267                                         log("debug", "Destroying the request now...");
268                                         oldest_request:destroy();
269                                 end
270                         elseif s ~= "" then
271                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
272                                 -- Hmm, no requests are open :(
273                                 t_insert(session.send_buffer, tostring(s));
274                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
275                         end
276                 end
277                 
278                 -- Send creation response
279                 
280                 local features = st.stanza("stream:features");
281                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
282                 fire_event("stream-features", session, features);
283                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
284                 local response = st.stanza("body", { xmlns = xmlns_bosh,
285                                                                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY), polling = tostring(BOSH_DEFAULT_POLLING), requests = tostring(BOSH_DEFAULT_REQUESTS), hold = tostring(session.bosh_hold), maxpause = "120",
286                                                                         sid = sid, authid = sid, ver  = '1.6', from = session.host, secure = 'true', ["xmpp:version"] = "1.0",
287                                                                         ["xmlns:xmpp"] = "urn:xmpp:xbosh", ["xmlns:stream"] = "http://etherx.jabber.org/streams" }):add_child(features);
288                 request:send{ headers = default_headers, body = tostring(response) };
289                 
290                 request.sid = sid;
291                 return;
292         end
293         
294         local session = sessions[sid];
295         if not session then
296                 -- Unknown sid
297                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
298                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
299                 request.notopen = nil;
300                 return;
301         end
302         
303         if session.rid then
304                 local rid = tonumber(attr.rid);
305                 local diff = rid - session.rid;
306                 if diff > 1 then
307                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
308                 elseif diff <= 0 then
309                         -- Repeated, ignore
310                         session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
311                         request.notopen = nil;
312                         request.ignore = true;
313                         request.sid = sid;
314                         t_insert(session.requests, request);
315                         return;
316                 end
317                 session.rid = rid;
318         end
319         
320         if attr.type == "terminate" then
321                 -- Client wants to end this session
322                 session:close();
323                 request.notopen = nil;
324                 return;
325         end
326         
327         if session.notopen then
328                 local features = st.stanza("stream:features");
329                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
330                 fire_event("stream-features", session, features);
331                 session.send(features);
332                 session.notopen = nil;
333         end
334         
335         request.notopen = nil; -- Signals that we accept this opening tag
336         t_insert(session.requests, request);
337         request.sid = sid;
338 end
339
340 function stream_callbacks.handlestanza(request, stanza)
341         if request.ignore then return; end
342         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
343         local session = sessions[request.sid];
344         if session then
345                 if stanza.attr.xmlns == xmlns_bosh then
346                         stanza.attr.xmlns = nil;
347                 end
348                 core_process_stanza(session, stanza);
349         end
350 end
351
352 function stream_callbacks.error(request, error)
353         log("debug", "Error parsing BOSH request payload; %s", error);
354         if not request.sid then
355                 request:send({ headers = default_headers, status = "400 Bad Request" });
356                 return;
357         end
358         
359         local session = sessions[request.sid];
360         if error == "stream-error" then -- Remote stream error, we close normally
361                 session:close();
362         else
363                 session:close({ condition = "bad-format", text = "Error processing stream" });
364         end
365 end
366
367 local dead_sessions = {};
368 function on_timer()
369         -- log("debug", "Checking for requests soon to timeout...");
370         -- Identify requests timing out within the next few seconds
371         local now = os_time() + 3;
372         for request in pairs(waiting_requests) do
373                 if request.reply_before <= now then
374                         log("debug", "%s was soon to timeout, sending empty response", request.id);
375                         -- Send empty response to let the
376                         -- client know we're still here
377                         if request.conn then
378                                 sessions[request.sid].send("");
379                         end
380                 end
381         end
382         
383         now = now - 3;
384         local n_dead_sessions = 0;
385         for session, inactive_since in pairs(inactive_sessions) do
386                 if session.bosh_max_inactive then
387                         if now - inactive_since > session.bosh_max_inactive then
388                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
389                                 sessions[session.sid]  = nil;
390                                 inactive_sessions[session] = nil;
391                                 n_dead_sessions = n_dead_sessions + 1;
392                                 dead_sessions[n_dead_sessions] = session;
393                         end
394                 else
395                         inactive_sessions[session] = nil;
396                 end
397         end
398
399         for i=1,n_dead_sessions do
400                 local session = dead_sessions[i];
401                 dead_sessions[i] = nil;
402                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
403         end
404         return 1;
405 end
406
407
408 local function setup()
409         local ports = module:get_option("bosh_ports") or { 5280 };
410         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
411         timer.add_task(1, on_timer);
412 end
413 if prosody.start_time then -- already started
414         setup();
415 else
416         prosody.events.add_handler("server-started", setup);
417 end