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