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 fire_event = prosody.events.fire_event;
17 local core_process_stanza = core_process_stanza;
18 local st = require "util.stanza";
19 local logger = require "util.logger";
20 local log = logger.init("mod_bosh");
22 local xmlns_streams = "http://etherx.jabber.org/streams";
23 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
24 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
26 local stream_callbacks = {
27 stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
29 local BOSH_DEFAULT_HOLD = module:get_option_number("bosh_default_hold", 1);
30 local BOSH_DEFAULT_INACTIVITY = module:get_option_number("bosh_max_inactivity", 60);
31 local BOSH_DEFAULT_POLLING = module:get_option_number("bosh_max_polling", 5);
32 local BOSH_DEFAULT_REQUESTS = module:get_option_number("bosh_max_requests", 2);
34 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
35 local auto_cork = module:get_option_boolean("bosh_auto_cork", false);
37 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
39 local cross_domain = module:get_option("cross_domain_bosh", false);
41 default_headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
42 default_headers["Access-Control-Allow-Headers"] = "Content-Type";
43 default_headers["Access-Control-Max-Age"] = "7200";
45 if cross_domain == true then
46 default_headers["Access-Control-Allow-Origin"] = "*";
47 elseif type(cross_domain) == "table" then
48 cross_domain = table.concat(cross_domain, ", ");
50 if type(cross_domain) == "string" then
51 default_headers["Access-Control-Allow-Origin"] = cross_domain;
55 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
57 local function get_ip_from_request(request)
58 local ip = request.conn:ip();
59 local forwarded_for = request.headers["x-forwarded-for"];
61 forwarded_for = forwarded_for..", "..ip;
62 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
63 if not trusted_proxies[forwarded_ip] then
71 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
72 local os_time = os.time;
75 local inactive_sessions = {}; -- Sessions which have no open requests
77 -- Used to respond to idle sessions (those with waiting requests)
78 local waiting_requests = {};
79 function on_destroy_request(request)
80 log("debug", "Request destroyed: %s", tostring(request));
81 waiting_requests[request] = nil;
82 local session = sessions[request.context.sid];
84 local requests = session.requests;
85 for i, r in ipairs(requests) do
87 t_remove(requests, i);
92 -- If this session now has no requests open, mark it as inactive
93 local max_inactive = session.bosh_max_inactive;
94 if max_inactive and #requests == 0 then
95 inactive_sessions[session] = os_time() + max_inactive;
96 (session.log or log)("debug", "BOSH session marked as inactive (for %ds)", max_inactive);
101 local function handle_GET(request)
102 return [[<html><body>
103 <p>It works! Now point your BOSH client to this URL to connect to Prosody.</p>
104 <p>For more information see <a href="http://prosody.im/doc/setting_up_bosh">Prosody: Setting up BOSH</a>.</p>
108 function handle_OPTIONS(request)
110 for k,v in pairs(default_headers) do headers[k] = v; end
111 headers["Content-Type"] = nil;
112 return { headers = headers, body = "" };
115 function handle_POST(event)
116 log("debug", "Handling new request %s: %s\n----------", tostring(event.request), tostring(event.request.body));
118 local request, response = event.request, event.response;
119 response.on_destroy = on_destroy_request;
120 local body = request.body;
122 local context = { request = request, response = response, notopen = true };
123 local stream = new_xmpp_stream(context, stream_callbacks);
124 response.context = context;
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.
133 -- Stanzas (if any) in the request have now been processed, and
134 -- we take care of the high-level BOSH logic here, including
135 -- giving a response or putting the request "on hold".
136 local session = sessions[context.sid];
138 -- Session was marked as inactive, since we have
139 -- a request open now, unmark it
140 if inactive_sessions[session] and #session.requests > 0 then
141 inactive_sessions[session] = nil;
144 local r = session.requests;
145 log("debug", "Session %s has %d out of %d requests open", context.sid, #r, session.bosh_hold);
146 log("debug", "and there are %d things in the send_buffer:", #session.send_buffer);
147 for i, thing in ipairs(session.send_buffer) do
148 log("debug", " %s", tostring(thing));
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 = {};
158 -- or an empty response
159 log("debug", "...sending an empty response");
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 = {};
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;
177 if session.bosh_terminate then
178 session.log("debug", "Closing session with %d requests open", #session.requests);
182 return true; -- Inform http server we shall reply later
188 local function bosh_reset_stream(session) session.notopen = true; end
190 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
192 local function bosh_close_stream(session, reason)
193 (session.log or log)("info", "BOSH client disconnected");
195 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
196 ["xmlns:stream"] = xmlns_streams });
200 close_reply.attr.condition = "remote-stream-error";
201 if type(reason) == "string" then -- assume stream error
202 close_reply:tag("stream:error")
203 :tag(reason, {xmlns = xmlns_xmpp_streams});
204 elseif type(reason) == "table" then
205 if reason.condition then
206 close_reply:tag("stream:error")
207 :tag(reason.condition, stream_xmlns_attr):up();
209 close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
212 close_reply:add_child(reason.extra);
214 elseif reason.name then -- a stanza
215 close_reply = reason;
218 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
221 local response_body = tostring(close_reply);
222 for _, held_request in ipairs(session.requests) do
223 held_request.headers = default_headers;
224 held_request:send(response_body);
226 sessions[session.sid] = nil;
227 inactive_sessions[session] = nil;
228 sm_destroy_session(session);
231 -- Handle the <body> tag in the request payload.
232 function stream_callbacks.streamopened(context, attr)
233 local request, response = context.request, context.response;
234 local sid = attr.sid;
235 log("debug", "BOSH body open (sid: %s)", sid or "<none>");
237 -- New session request
238 context.notopen = nil; -- Signals that we accept this opening tag
240 -- TODO: Sanity checks here (rid, to, known host, etc.)
241 if not hosts[attr.to] then
243 log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
244 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
245 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
246 response:send(tostring(close_reply));
253 type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to,
254 bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid,
255 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
256 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
257 close = bosh_close_stream, dispatch_stanza = core_process_stanza,
258 log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
259 ip = get_ip_from_request(request);
261 sessions[sid] = session;
263 session.log("debug", "BOSH session created for request from %s", session.ip);
264 log("info", "New BOSH session, assigned it sid '%s'", sid);
265 local r = session.requests;
266 function session.send(s)
267 -- We need to ensure that outgoing stanzas have the jabber:client xmlns
268 if s.attr and not s.attr.xmlns then
270 s.attr.xmlns = "jabber:client";
272 --log("debug", "Sending BOSH data: %s", tostring(s));
273 local oldest_request = r[1];
274 if oldest_request and (not(auto_cork) or waiting_requests[oldest_request]) then
275 log("debug", "We have an open request, so sending on that");
276 oldest_request.headers = default_headers;
277 oldest_request:send(t_concat({
278 "<body xmlns='http://jabber.org/protocol/httpbind' ",
279 session.bosh_terminate and "type='terminate' " or "",
280 "sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>",
285 log("debug", "Saved to send buffer because there are %d open requests", #r);
286 -- Hmm, no requests are open :(
287 t_insert(session.send_buffer, tostring(s));
288 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
293 -- Send creation response
295 local features = st.stanza("stream:features");
296 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
297 fire_event("stream-features", session, features);
298 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
299 local body = st.stanza("body", { xmlns = xmlns_bosh,
301 inactivity = tostring(BOSH_DEFAULT_INACTIVITY),
302 polling = tostring(BOSH_DEFAULT_POLLING),
303 requests = tostring(BOSH_DEFAULT_REQUESTS),
304 hold = tostring(session.bosh_hold),
305 sid = sid, authid = sid,
306 ver = '1.6', from = session.host,
307 secure = 'true', ["xmpp:version"] = "1.0",
308 ["xmlns:xmpp"] = "urn:xmpp:xbosh",
309 ["xmlns:stream"] = "http://etherx.jabber.org/streams"
310 }):add_child(features);
311 response.headers = default_headers;
312 response:send(tostring(body));
318 local session = sessions[sid];
321 log("info", "Client tried to use sid '%s' which we don't know about", sid);
322 response.headers = default_headers;
323 response:send(tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })));
324 context.notopen = nil;
329 local rid = tonumber(attr.rid);
330 local diff = rid - session.rid;
332 session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
333 elseif diff <= 0 then
335 session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
336 context.notopen = nil;
337 context.ignore = true;
339 t_insert(session.requests, response);
345 if attr.type == "terminate" then
346 -- Client wants to end this session, which we'll do
347 -- after processing any stanzas in this request
348 session.bosh_terminate = true;
351 context.notopen = nil; -- Signals that we accept this opening tag
352 t_insert(session.requests, response);
355 if session.notopen then
356 local features = st.stanza("stream:features");
357 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
358 fire_event("stream-features", session, features);
359 session.send(features);
360 session.notopen = nil;
364 function stream_callbacks.handlestanza(context, stanza)
365 if context.ignore then return; end
366 log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
367 local session = sessions[context.sid];
369 if stanza.attr.xmlns == xmlns_bosh then
370 stanza.attr.xmlns = nil;
372 core_process_stanza(session, stanza);
376 function stream_callbacks.error(context, error)
377 log("debug", "Error parsing BOSH request payload; %s", error);
378 if not context.sid then
379 local response = context.response;
380 response.headers = default_headers;
381 response.status_code = 400;
386 local session = sessions[context.sid];
387 if error == "stream-error" then -- Remote stream error, we close normally
390 session:close({ condition = "bad-format", text = "Error processing stream" });
394 local dead_sessions = {};
396 -- log("debug", "Checking for requests soon to timeout...");
397 -- Identify requests timing out within the next few seconds
398 local now = os_time() + 3;
399 for request, reply_before in pairs(waiting_requests) do
400 if reply_before <= now then
401 log("debug", "%s was soon to timeout (at %d, now %d), sending empty response", tostring(request), reply_before, now);
402 -- Send empty response to let the
403 -- client know we're still here
405 sessions[request.context.sid].send("");
411 local n_dead_sessions = 0;
412 for session, close_after in pairs(inactive_sessions) do
413 if close_after < now then
414 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
415 sessions[session.sid] = nil;
416 inactive_sessions[session] = nil;
417 n_dead_sessions = n_dead_sessions + 1;
418 dead_sessions[n_dead_sessions] = session;
422 for i=1,n_dead_sessions do
423 local session = dead_sessions[i];
424 dead_sessions[i] = nil;
425 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
429 module:add_timer(1, on_timer);
431 function module.add_host(module)
432 module:depends("http");
433 module:provides("http", {
434 default_path = "/http-bind";
436 ["GET"] = handle_GET;
437 ["GET /"] = handle_GET;
438 ["OPTIONS"] = handle_OPTIONS;
439 ["OPTIONS /"] = handle_OPTIONS;
440 ["POST"] = handle_POST;
441 ["POST /"] = handle_POST;