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