2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 module:set_global(); -- Global module
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;
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)
29 local stream_callbacks = {
30 stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
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);
38 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
39 local cross_domain = module:get_option("cross_domain_bosh", false);
41 if cross_domain == true then cross_domain = "*"; end
42 if type(cross_domain) == "table" then cross_domain = table.concat(cross_domain, ", "); end
44 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
46 local function get_ip_from_request(request)
47 local ip = request.conn:ip();
48 local forwarded_for = request.headers.x_forwarded_for;
50 forwarded_for = forwarded_for..", "..ip;
51 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
52 if not trusted_proxies[forwarded_ip] then
60 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
61 local os_time = os.time;
63 -- All sessions, and sessions that have no requests open
64 local sessions, inactive_sessions = module:shared("sessions", "inactive_sessions");
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];
73 local requests = session.requests;
74 for i, r in ipairs(requests) do
76 t_remove(requests, i);
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);
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;
99 function handle_OPTIONS(event)
100 if cross_domain and event.request.headers.origin then
101 set_cross_domain_headers(event.response);
106 function handle_POST(event)
107 log("debug", "Handling new request %s: %s\n----------", tostring(event.request), tostring(event.request.body));
109 local request, response = event.request, event.response;
110 response.on_destroy = on_destroy_request;
111 local body = request.body;
113 local context = { request = request, response = response, notopen = true };
114 local stream = new_xmpp_stream(context, stream_callbacks);
115 response.context = context;
117 local headers = response.headers;
118 headers.content_type = "text/xml; charset=utf-8";
120 if cross_domain and event.request.headers.origin then
121 set_cross_domain_headers(response);
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 if not stream:feed(body) then
130 module:log("warn", "Error parsing BOSH payload")
134 -- Stanzas (if any) in the request have now been processed, and
135 -- we take care of the high-level BOSH logic here, including
136 -- giving a response or putting the request "on hold".
137 local session = sessions[context.sid];
139 -- Session was marked as inactive, since we have
140 -- a request open now, unmark it
141 if inactive_sessions[session] and #session.requests > 0 then
142 inactive_sessions[session] = nil;
145 local r = session.requests;
146 log("debug", "Session %s has %d out of %d requests open", context.sid, #r, session.bosh_hold);
147 log("debug", "and there are %d things in the send_buffer:", #session.send_buffer);
148 if #r > session.bosh_hold then
149 -- We are holding too many requests, send what's in the buffer,
150 log("debug", "We are holding too many requests, so...");
151 if #session.send_buffer > 0 then
152 log("debug", "...sending what is in the buffer")
153 session.send(t_concat(session.send_buffer));
154 session.send_buffer = {};
156 -- or an empty response
157 log("debug", "...sending an empty response");
160 elseif #session.send_buffer > 0 then
161 log("debug", "Session has data in the send buffer, will send now..");
162 local resp = t_concat(session.send_buffer);
163 session.send_buffer = {};
167 if not response.finished then
168 -- We're keeping this request open, to respond later
169 log("debug", "Have nothing to say, so leaving request unanswered for now");
170 if session.bosh_wait then
171 waiting_requests[response] = os_time() + session.bosh_wait;
175 if session.bosh_terminate then
176 session.log("debug", "Closing session with %d requests open", #session.requests);
180 return true; -- Inform http server we shall reply later
182 elseif response.finished then
183 return; -- A response has been sent already
185 module:log("warn", "Unable to associate request with a session (incomplete request?)");
190 local function bosh_reset_stream(session) session.notopen = true; end
192 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
194 local function bosh_close_stream(session, reason)
195 (session.log or log)("info", "BOSH client disconnected");
197 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
198 ["xmlns:stream"] = xmlns_streams });
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();
211 close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
214 close_reply:add_child(reason.extra);
216 elseif reason.name then -- a stanza
217 close_reply = reason;
220 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
223 local response_body = tostring(close_reply);
224 for _, held_request in ipairs(session.requests) do
225 held_request:send(response_body);
227 sessions[session.sid] = nil;
228 inactive_sessions[session] = nil;
229 sm_destroy_session(session);
232 -- Handle the <body> tag in the request payload.
233 function stream_callbacks.streamopened(context, attr)
234 local request, response = context.request, context.response;
235 local sid = attr.sid;
236 log("debug", "BOSH body open (sid: %s)", sid or "<none>");
238 -- New session request
239 context.notopen = nil; -- Signals that we accept this opening tag
241 -- TODO: Sanity checks here (rid, to, known host, etc.)
242 if not hosts[attr.to] then
244 log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
245 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
246 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
247 response:send(tostring(close_reply));
254 type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid)-1, host = attr.to,
255 bosh_version = attr.ver, bosh_wait = math_min(attr.wait, bosh_max_wait), streamid = sid,
256 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
257 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
258 close = bosh_close_stream, dispatch_stanza = core_process_stanza, notopen = true,
259 log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
260 ip = get_ip_from_request(request);
262 sessions[sid] = session;
264 local filter = initialize_filters(session);
266 session.log("debug", "BOSH session created for request from %s", session.ip);
267 log("info", "New BOSH session, assigned it sid '%s'", sid);
269 hosts[session.host].events.fire_event("bosh-session", { session = session, request = request });
271 -- Send creation response
272 local creating_session = true;
274 local r = session.requests;
275 function session.send(s)
276 -- We need to ensure that outgoing stanzas have the jabber:client xmlns
277 if s.attr and not s.attr.xmlns then
279 s.attr.xmlns = "jabber:client";
281 s = filter("stanzas/out", s);
282 --log("debug", "Sending BOSH data: %s", tostring(s));
283 if not s then return true end
284 t_insert(session.send_buffer, tostring(s));
286 local oldest_request = r[1];
287 if oldest_request and not session.bosh_processing then
288 log("debug", "We have an open request, so sending on that");
289 local body_attr = { xmlns = "http://jabber.org/protocol/httpbind",
290 ["xmlns:stream"] = "http://etherx.jabber.org/streams";
291 type = session.bosh_terminate and "terminate" or nil;
294 if creating_session then
295 creating_session = nil;
296 body_attr.inactivity = tostring(BOSH_DEFAULT_INACTIVITY);
297 body_attr.polling = tostring(BOSH_DEFAULT_POLLING);
298 body_attr.requests = tostring(BOSH_DEFAULT_REQUESTS);
299 body_attr.wait = tostring(session.bosh_wait);
300 body_attr.hold = tostring(session.bosh_hold);
301 body_attr.authid = sid;
302 body_attr.secure = "true";
303 body_attr.ver = '1.6';
304 body_attr.from = session.host;
305 body_attr["xmlns:xmpp"] = "urn:xmpp:xbosh";
306 body_attr["xmpp:version"] = "1.0";
308 oldest_request:send(st.stanza("body", body_attr):top_tag()..t_concat(session.send_buffer).."</body>");
309 session.send_buffer = {};
316 local session = sessions[sid];
319 log("info", "Client tried to use sid '%s' which we don't know about", sid);
320 response:send(tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })));
321 context.notopen = nil;
326 local rid = tonumber(attr.rid);
327 local diff = rid - session.rid;
329 session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
330 elseif diff <= 0 then
332 session.log("debug", "rid repeated, ignoring: %s (diff %d)", session.rid, diff);
333 context.notopen = nil;
334 context.ignore = true;
336 t_insert(session.requests, response);
342 if attr.type == "terminate" then
343 -- Client wants to end this session, which we'll do
344 -- after processing any stanzas in this request
345 session.bosh_terminate = true;
348 context.notopen = nil; -- Signals that we accept this opening tag
349 t_insert(session.requests, response);
351 session.bosh_processing = true; -- Used to suppress replies until processing of this request is done
353 if session.notopen then
354 local features = st.stanza("stream:features");
355 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
356 session.send(features);
357 session.notopen = nil;
361 local function handleerr(err) log("error", "Traceback[bosh]: %s", traceback(tostring(err), 2)); end
362 function stream_callbacks.handlestanza(context, stanza)
363 if context.ignore then return; end
364 log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
365 local session = sessions[context.sid];
367 if stanza.attr.xmlns == xmlns_bosh then
368 stanza.attr.xmlns = nil;
370 stanza = session.filter("stanzas/in", stanza);
372 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
377 function stream_callbacks.streamclosed(context)
378 local session = sessions[context.sid];
380 session.bosh_processing = false;
381 if #session.send_buffer > 0 then
387 function stream_callbacks.error(context, error)
388 log("debug", "Error parsing BOSH request payload; %s", error);
389 if not context.sid then
390 local response = context.response;
391 response.status_code = 400;
396 local session = sessions[context.sid];
397 if error == "stream-error" then -- Remote stream error, we close normally
400 session:close({ condition = "bad-format", text = "Error processing stream" });
404 local dead_sessions = module:shared("dead_sessions");
406 -- log("debug", "Checking for requests soon to timeout...");
407 -- Identify requests timing out within the next few seconds
408 local now = os_time() + 3;
409 for request, reply_before in pairs(waiting_requests) do
410 if reply_before <= now then
411 log("debug", "%s was soon to timeout (at %d, now %d), sending empty response", tostring(request), reply_before, now);
412 -- Send empty response to let the
413 -- client know we're still here
415 sessions[request.context.sid].send("");
421 local n_dead_sessions = 0;
422 for session, close_after in pairs(inactive_sessions) do
423 if close_after < now then
424 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
425 sessions[session.sid] = nil;
426 inactive_sessions[session] = nil;
427 n_dead_sessions = n_dead_sessions + 1;
428 dead_sessions[n_dead_sessions] = session;
432 for i=1,n_dead_sessions do
433 local session = dead_sessions[i];
434 dead_sessions[i] = nil;
435 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
439 module:add_timer(1, on_timer);
442 local GET_response = {
444 content_type = "text/html";
446 body = [[<html><body>
447 <p>It works! Now point your BOSH client to this URL to connect to Prosody.</p>
448 <p>For more information see <a href="http://prosody.im/doc/setting_up_bosh">Prosody: Setting up BOSH</a>.</p>
452 function module.add_host(module)
453 module:depends("http");
454 module:provides("http", {
455 default_path = "/http-bind";
457 ["GET"] = GET_response;
458 ["GET /"] = GET_response;
459 ["OPTIONS"] = handle_OPTIONS;
460 ["OPTIONS /"] = handle_OPTIONS;
461 ["POST"] = handle_POST;
462 ["POST /"] = handle_POST;