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