mod_bosh: Add option consider_bosh_secure to treat BOSH sessions as encrypted even...
[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.host = "*" -- Global module
10
11 local hosts = _G.hosts;
12 local lxp = require "lxp";
13 local init_xmlhandlers = require "core.xmlhandlers"
14 local server = require "net.server";
15 local httpserver = require "net.httpserver";
16 local sm = require "core.sessionmanager";
17 local sm_destroy_session = sm.destroy_session;
18 local new_uuid = require "util.uuid".generate;
19 local fire_event = require "core.eventmanager".fire_event;
20 local core_process_stanza = core_process_stanza;
21 local st = require "util.stanza";
22 local logger = require "util.logger";
23 local log = logger.init("mod_bosh");
24
25 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
26 local stream_callbacks = { stream_ns = "http://jabber.org/protocol/httpbind", stream_tag = "body", default_ns = "jabber:client" };
27
28 local BOSH_DEFAULT_HOLD = tonumber(module:get_option("bosh_default_hold")) or 1;
29 local BOSH_DEFAULT_INACTIVITY = tonumber(module:get_option("bosh_max_inactivity")) or 60;
30 local BOSH_DEFAULT_POLLING = tonumber(module:get_option("bosh_max_polling")) or 5;
31 local BOSH_DEFAULT_REQUESTS = tonumber(module:get_option("bosh_max_requests")) or 2;
32 local BOSH_DEFAULT_MAXPAUSE = tonumber(module:get_option("bosh_max_pause")) or 300;
33
34 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
35
36 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
37 local session_close_reply = { headers = default_headers, body = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate" }), attr = {} };
38
39 local cross_domain = module:get_option("cross_domain_bosh");
40 if cross_domain then
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";
44
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, ", ");
49         end
50         if type(cross_domain) == "string" then
51                 default_headers["Access-Control-Allow-Origin"] = cross_domain;
52         end
53 end
54
55 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
56 local os_time = os.time;
57
58 local sessions = {};
59 local inactive_sessions = {}; -- Sessions which have no open requests
60
61 -- Used to respond to idle sessions (those with waiting requests)
62 local waiting_requests = {};
63 function on_destroy_request(request)
64         waiting_requests[request] = nil;
65         local session = sessions[request.sid];
66         if session then
67                 local requests = session.requests;
68                 for i,r in ipairs(requests) do
69                         if r == request then
70                                 t_remove(requests, i);
71                                 break;
72                         end
73                 end
74                 
75                 -- If this session now has no requests open, mark it as inactive
76                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
77                         inactive_sessions[session] = os_time();
78                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
79                 end
80         end
81 end
82
83 function handle_request(method, body, request)
84         if (not body) or request.method ~= "POST" then
85                 if request.method == "OPTIONS" then
86                         return { headers = default_headers, body = "" };
87                 else
88                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
89                 end
90         end
91         if not method then
92                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
93                 return;
94         end
95         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
96         request.notopen = true;
97         request.log = log;
98         request.on_destroy = on_destroy_request;
99         
100         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "\1");
101         
102         parser:parse(body);
103         
104         local session = sessions[request.sid];
105         if session then
106                 local r = session.requests;
107                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
108                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
109                 if #r > session.bosh_hold then
110                         -- We are holding too many requests, send what's in the buffer,
111                         log("debug", "We are holding too many requests, so...");
112                         if #session.send_buffer > 0 then
113                                 log("debug", "...sending what is in the buffer")
114                                 session.send(t_concat(session.send_buffer));
115                                 session.send_buffer = {};
116                         else
117                                 -- or an empty response
118                                 log("debug", "...sending an empty response");
119                                 session.send("");
120                         end
121                 elseif #session.send_buffer > 0 then
122                         log("debug", "Session has data in the send buffer, will send now..");
123                         local resp = t_concat(session.send_buffer);
124                         session.send_buffer = {};
125                         session.send(resp);
126                 end
127                 
128                 if not request.destroyed then
129                         -- We're keeping this request open, to respond later
130                         log("debug", "Have nothing to say, so leaving request unanswered for now");
131                         if session.bosh_wait then
132                                 request.reply_before = os_time() + session.bosh_wait;
133                                 waiting_requests[request] = true;
134                         end
135                         if inactive_sessions[session] then
136                                 -- Session was marked as inactive, since we have
137                                 -- a request open now, unmark it
138                                 inactive_sessions[session] = nil;
139                         end
140                 end
141                 
142                 return true; -- Inform httpserver we shall reply later
143         end
144 end
145
146
147 local function bosh_reset_stream(session) session.notopen = true; end
148
149 local function bosh_close_stream(session, reason)
150         (session.log or log)("info", "BOSH client disconnected");
151         session_close_reply.attr.condition = reason;
152         for _, held_request in ipairs(session.requests) do
153                 held_request:send(session_close_reply);
154                 held_request:destroy();
155         end
156         sessions[session.sid]  = nil;
157         sm_destroy_session(session);
158 end
159
160 function stream_callbacks.streamopened(request, attr)
161         log("debug", "BOSH body open (sid: %s)", attr.sid);
162         local sid = attr.sid
163         if not sid then
164                 -- New session request
165                 request.notopen = nil; -- Signals that we accept this opening tag
166                 
167                 -- TODO: Sanity checks here (rid, to, known host, etc.)
168                 if not hosts[attr.to] then
169                         -- Unknown host
170                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
171                         session_close_reply.body.attr.condition = "host-unknown";
172                         request:send(session_close_reply);
173                         request.notopen = nil
174                         return;
175                 end
176                 
177                 -- New session
178                 sid = new_uuid();
179                 local session = { type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid)-1, host = attr.to, bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid, 
180                                                 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
181                                                 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream, close = bosh_close_stream, 
182                                                 dispatch_stanza = core_process_stanza, log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure };
183                 sessions[sid] = session;
184                 
185                 log("info", "New BOSH session, assigned it sid '%s'", sid);
186                 local r, send_buffer = session.requests, session.send_buffer;
187                 local response = { headers = default_headers }
188                 function session.send(s)
189                         --log("debug", "Sending BOSH data: %s", tostring(s));
190                         local oldest_request = r[1];
191                         if oldest_request then
192                                 log("debug", "We have an open request, so sending on that");
193                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
194                                 oldest_request:send(response);
195                                 --log("debug", "Sent");
196                                 if oldest_request.stayopen then
197                                         if #r>1 then
198                                                 -- Move front request to back
199                                                 t_insert(r, oldest_request);
200                                                 t_remove(r, 1);
201                                         end
202                                 else
203                                         log("debug", "Destroying the request now...");
204                                         oldest_request:destroy();
205                                 end
206                         elseif s ~= "" then
207                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
208                                 -- Hmm, no requests are open :(
209                                 t_insert(session.send_buffer, tostring(s));
210                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
211                         end
212                 end
213                 
214                 -- Send creation response
215                 
216                 local features = st.stanza("stream:features");
217                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
218                 fire_event("stream-features", session, features);
219                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
220                 local response = st.stanza("body", { xmlns = xmlns_bosh,
221                                                                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY), polling = tostring(BOSH_DEFAULT_POLLING), requests = tostring(BOSH_DEFAULT_REQUESTS), hold = tostring(session.bosh_hold), maxpause = "120",
222                                                                         sid = sid, authid = sid, ver  = '1.6', from = session.host, secure = 'true', ["xmpp:version"] = "1.0",
223                                                                         ["xmlns:xmpp"] = "urn:xmpp:xbosh", ["xmlns:stream"] = "http://etherx.jabber.org/streams" }):add_child(features);
224                 request:send{ headers = default_headers, body = tostring(response) };
225                 
226                 request.sid = sid;
227                 return;
228         end
229         
230         local session = sessions[sid];
231         if not session then
232                 -- Unknown sid
233                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
234                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
235                 request.notopen = nil;
236                 return;
237         end
238         
239         if session.rid then
240                 local rid = tonumber(attr.rid);
241                 local diff = rid - session.rid;
242                 if diff > 1 then
243                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
244                 elseif diff <= 0 then
245                         -- Repeated, ignore
246                         session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
247                         request.notopen = nil;
248                         request.sid = sid;
249                         t_insert(session.requests, request);
250                         return;
251                 end
252                 session.rid = rid;
253         end
254         
255         if attr.type == "terminate" then
256                 -- Client wants to end this session
257                 session:close();
258                 request.notopen = nil;
259                 return;
260         end
261         
262         if session.notopen then
263                 local features = st.stanza("stream:features");
264                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
265                 fire_event("stream-features", session, features);
266                 session.send(features);
267                 session.notopen = nil;
268         end
269         
270         request.notopen = nil; -- Signals that we accept this opening tag
271         t_insert(session.requests, request);
272         request.sid = sid;
273 end
274
275 function stream_callbacks.handlestanza(request, stanza)
276         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
277         local session = sessions[request.sid];
278         if session then
279                 if stanza.attr.xmlns == xmlns_bosh then
280                         stanza.attr.xmlns = nil;
281                 end
282                 session.ip = request.handler:ip();
283                 core_process_stanza(session, stanza);
284         end
285 end
286
287 local dead_sessions = {};
288 function on_timer()
289         -- log("debug", "Checking for requests soon to timeout...");
290         -- Identify requests timing out within the next few seconds
291         local now = os_time() + 3;
292         for request in pairs(waiting_requests) do
293                 if request.reply_before <= now then
294                         log("debug", "%s was soon to timeout, sending empty response", request.id);
295                         -- Send empty response to let the
296                         -- client know we're still here
297                         if request.conn then
298                                 sessions[request.sid].send("");
299                         end
300                 end
301         end
302         
303         now = now - 3;
304         local n_dead_sessions = 0;
305         for session, inactive_since in pairs(inactive_sessions) do
306                 if session.bosh_max_inactive then
307                         if now - inactive_since > session.bosh_max_inactive then
308                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
309                                 sessions[session.sid]  = nil;
310                                 inactive_sessions[session] = nil;
311                                 n_dead_sessions = n_dead_sessions + 1;
312                                 dead_sessions[n_dead_sessions] = session;
313                         end
314                 else
315                         inactive_sessions[session] = nil;
316                 end
317         end
318
319         for i=1,n_dead_sessions do
320                 local session = dead_sessions[i];
321                 dead_sessions[i] = nil;
322                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
323         end
324 end
325
326
327 local function setup()
328         local ports = module:get_option("bosh_ports") or { 5280 };
329         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
330         server.addtimer(on_timer);
331 end
332 if prosody.start_time then -- already started
333         setup();
334 else
335         prosody.events.add_handler("server-started", setup);
336 end