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 = 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;
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)
27 local stream_callbacks = {
28 stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
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);
36 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
38 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
40 local cross_domain = module:get_option("cross_domain_bosh", false);
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";
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, ", ");
51 if type(cross_domain) == "string" then
52 default_headers["Access-Control-Allow-Origin"] = cross_domain;
56 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
58 local function get_ip_from_request(request)
59 local ip = request.conn:ip();
60 local forwarded_for = request.headers.x_forwarded_for;
62 forwarded_for = forwarded_for..", "..ip;
63 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
64 if not trusted_proxies[forwarded_ip] then
72 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
73 local os_time = os.time;
75 -- All sessions, and sessions that have no requests open
76 local sessions, inactive_sessions = module:shared("sessions", "inactive_sessions");
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];
85 local requests = session.requests;
86 for i, r in ipairs(requests) do
88 t_remove(requests, i);
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);
102 function handle_OPTIONS(request)
104 for k,v in pairs(default_headers) do headers[k] = v; end
105 headers["Content-Type"] = nil;
106 return { headers = headers, body = "" };
109 function handle_POST(event)
110 log("debug", "Handling new request %s: %s\n----------", tostring(event.request), tostring(event.request.body));
112 local request, response = event.request, event.response;
113 response.on_destroy = on_destroy_request;
114 local body = request.body;
116 local context = { request = request, response = response, notopen = true };
117 local stream = new_xmpp_stream(context, stream_callbacks);
118 response.context = context;
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.
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];
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;
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));
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 = {};
152 -- or an empty response
153 log("debug", "...sending an empty response");
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 = {};
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;
171 if session.bosh_terminate then
172 session.log("debug", "Closing session with %d requests open", #session.requests);
176 return true; -- Inform http server we shall reply later
182 local function bosh_reset_stream(session) session.notopen = true; end
184 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
186 local function bosh_close_stream(session, reason)
187 (session.log or log)("info", "BOSH client disconnected");
189 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
190 ["xmlns:stream"] = xmlns_streams });
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();
203 close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
206 close_reply:add_child(reason.extra);
208 elseif reason.name then -- a stanza
209 close_reply = reason;
212 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
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);
220 sessions[session.sid] = nil;
221 inactive_sessions[session] = nil;
222 sm_destroy_session(session);
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>");
231 -- New session request
232 context.notopen = nil; -- Signals that we accept this opening tag
234 -- TODO: Sanity checks here (rid, to, known host, etc.)
235 if not hosts[attr.to] then
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));
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);
255 sessions[sid] = session;
257 session.log("debug", "BOSH session created for request from %s", session.ip);
258 log("info", "New BOSH session, assigned it sid '%s'", sid);
260 -- Send creation response
261 local creating_session = true;
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
268 s.attr.xmlns = "jabber:client";
270 --log("debug", "Sending BOSH data: %s", tostring(s));
271 t_insert(session.send_buffer, tostring(s));
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;
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";
294 oldest_request:send(st.stanza("body", body_attr):top_tag()..t_concat(session.send_buffer).."</body>");
295 session.send_buffer = {};
302 local session = sessions[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;
313 local rid = tonumber(attr.rid);
314 local diff = rid - session.rid;
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
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;
323 t_insert(session.requests, response);
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;
335 context.notopen = nil; -- Signals that we accept this opening tag
336 t_insert(session.requests, response);
338 session.bosh_processing = true; -- Used to suppress replies until processing of this request is done
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;
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];
354 if stanza.attr.xmlns == xmlns_bosh then
355 stanza.attr.xmlns = nil;
357 core_process_stanza(session, stanza);
361 function stream_callbacks.streamclosed(request)
362 local session = sessions[request.sid];
364 session.bosh_processing = false;
365 if #session.send_buffer > 0 then
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;
381 local session = sessions[context.sid];
382 if error == "stream-error" then -- Remote stream error, we close normally
385 session:close({ condition = "bad-format", text = "Error processing stream" });
389 local dead_sessions = {};
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
400 sessions[request.context.sid].send("");
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;
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");
424 module:add_timer(1, on_timer);
427 local GET_response = {
429 content_type = "text/html";
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>
437 function module.add_host(module)
438 module:depends("http");
439 module:provides("http", {
440 default_path = "/http-bind";
442 ["GET"] = GET_response;
443 ["GET /"] = GET_response;
444 ["OPTIONS"] = handle_OPTIONS;
445 ["OPTIONS /"] = handle_OPTIONS;
446 ["POST"] = handle_POST;
447 ["POST /"] = handle_POST;