3541f6145cf24e5ba37fa2537e1658c6f3501899
[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 new_xmpp_stream = require "util.xmppstream".new;
14 local httpserver = require "net.httpserver";
15 local sm = require "core.sessionmanager";
16 local sm_destroy_session = sm.destroy_session;
17 local new_uuid = require "util.uuid".generate;
18 local fire_event = prosody.events.fire_event;
19 local core_process_stanza = core_process_stanza;
20 local st = require "util.stanza";
21 local logger = require "util.logger";
22 local log = logger.init("mod_bosh");
23 local timer = require "util.timer";
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
37 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
38
39 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
40
41 local cross_domain = module:get_option("cross_domain_bosh", false);
42 if cross_domain then
43         default_headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS";
44         default_headers["Access-Control-Allow-Headers"] = "Content-Type";
45         default_headers["Access-Control-Max-Age"] = "7200";
46
47         if cross_domain == true then
48                 default_headers["Access-Control-Allow-Origin"] = "*";
49         elseif type(cross_domain) == "table" then
50                 cross_domain = table.concat(cross_domain, ", ");
51         end
52         if type(cross_domain) == "string" then
53                 default_headers["Access-Control-Allow-Origin"] = cross_domain;
54         end
55 end
56
57 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
58
59 local function get_ip_from_request(request)
60         local ip = request.handler:ip();
61         local forwarded_for = request.headers["x-forwarded-for"];
62         if forwarded_for then
63                 forwarded_for = forwarded_for..", "..ip;
64                 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
65                         if not trusted_proxies[forwarded_ip] then
66                                 ip = forwarded_ip;
67                         end
68                 end
69         end
70         return ip;
71 end
72
73 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
74 local os_time = os.time;
75
76 local sessions = {};
77 local inactive_sessions = {}; -- Sessions which have no open requests
78
79 -- Used to respond to idle sessions (those with waiting requests)
80 local waiting_requests = {};
81 function on_destroy_request(request)
82         waiting_requests[request] = nil;
83         local session = sessions[request.sid];
84         if session then
85                 local requests = session.requests;
86                 for i,r in ipairs(requests) do
87                         if r == request then
88                                 t_remove(requests, i);
89                                 break;
90                         end
91                 end
92                 
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);
98                 end
99         end
100 end
101
102 function handle_request(method, body, request)
103         if (not body) or request.method ~= "POST" then
104                 if request.method == "OPTIONS" then
105                         local headers = {};
106                         for k,v in pairs(default_headers) do headers[k] = v; end
107                         headers["Content-Type"] = nil;
108                         return { headers = headers, body = "" };
109                 else
110                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
111                 end
112         end
113         if not method then
114                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
115                 return;
116         end
117         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
118         request.notopen = true;
119         request.log = log;
120         request.on_destroy = on_destroy_request;
121         
122         local stream = new_xmpp_stream(request, stream_callbacks);
123         -- stream:feed() calls the stream_callbacks, so all stanzas in
124         -- the body are processed in this next line before it returns.
125         stream:feed(body);
126         
127         local session = sessions[request.sid];
128         if session then
129                 -- Session was marked as inactive, since we have
130                 -- a request open now, unmark it
131                 if inactive_sessions[session] and #session.requests > 0 then
132                         inactive_sessions[session] = nil;
133                 end
134
135                 local r = session.requests;
136                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
137                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
138                 if #r > session.bosh_hold then
139                         -- We are holding too many requests, send what's in the buffer,
140                         log("debug", "We are holding too many requests, so...");
141                         if #session.send_buffer > 0 then
142                                 log("debug", "...sending what is in the buffer")
143                                 session.send(t_concat(session.send_buffer));
144                                 session.send_buffer = {};
145                         else
146                                 -- or an empty response
147                                 log("debug", "...sending an empty response");
148                                 session.send("");
149                         end
150                 elseif #session.send_buffer > 0 then
151                         log("debug", "Session has data in the send buffer, will send now..");
152                         local resp = t_concat(session.send_buffer);
153                         session.send_buffer = {};
154                         session.send(resp);
155                 end
156                 
157                 if not request.destroyed then
158                         -- We're keeping this request open, to respond later
159                         log("debug", "Have nothing to say, so leaving request unanswered for now");
160                         if session.bosh_wait then
161                                 request.reply_before = os_time() + session.bosh_wait;
162                                 waiting_requests[request] = true;
163                         end
164                 end
165                 
166                 if session.bosh_terminate then
167                         session.log("debug", "Closing session with %d requests open", #session.requests);
168                         session:close();
169                         return nil;
170                 else
171                         return true; -- Inform httpserver we shall reply later
172                 end
173         end
174 end
175
176
177 local function bosh_reset_stream(session) session.notopen = true; end
178
179 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
180
181 local function bosh_close_stream(session, reason)
182         (session.log or log)("info", "BOSH client disconnected");
183         
184         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
185                 ["xmlns:stream"] = xmlns_streams });
186         
187
188         if reason then
189                 close_reply.attr.condition = "remote-stream-error";
190                 if type(reason) == "string" then -- assume stream error
191                         close_reply:tag("stream:error")
192                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
193                 elseif type(reason) == "table" then
194                         if reason.condition then
195                                 close_reply:tag("stream:error")
196                                         :tag(reason.condition, stream_xmlns_attr):up();
197                                 if reason.text then
198                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
199                                 end
200                                 if reason.extra then
201                                         close_reply:add_child(reason.extra);
202                                 end
203                         elseif reason.name then -- a stanza
204                                 close_reply = reason;
205                         end
206                 end
207                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
208         end
209
210         local session_close_response = { headers = default_headers, body = tostring(close_reply) };
211
212         for _, held_request in ipairs(session.requests) do
213                 held_request:send(session_close_response);
214                 held_request:destroy();
215         end
216         sessions[session.sid]  = nil;
217         inactive_sessions[session] = nil;
218         sm_destroy_session(session);
219 end
220
221 function stream_callbacks.streamopened(request, attr)
222         local sid = attr.sid;
223         log("debug", "BOSH body open (sid: %s)", sid or "<none>");
224         if not sid then
225                 -- New session request
226                 request.notopen = nil; -- Signals that we accept this opening tag
227                 
228                 -- TODO: Sanity checks here (rid, to, known host, etc.)
229                 if not hosts[attr.to] then
230                         -- Unknown host
231                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
232                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
233                                 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
234                         request:send(tostring(close_reply));
235                         return;
236                 end
237                 
238                 -- New session
239                 sid = new_uuid();
240                 local session = {
241                         type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to,
242                         bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid,
243                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
244                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
245                         close = bosh_close_stream, dispatch_stanza = core_process_stanza,
246                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
247                         ip = get_ip_from_request(request);
248                 };
249                 sessions[sid] = session;
250                 
251                 session.log("debug", "BOSH session created for request from %s", session.ip);
252                 log("info", "New BOSH session, assigned it sid '%s'", sid);
253                 local r, send_buffer = session.requests, session.send_buffer;
254                 local response = { headers = default_headers }
255                 function session.send(s)
256                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
257                         if s.attr and not s.attr.xmlns then
258                                 s = st.clone(s);
259                                 s.attr.xmlns = "jabber:client";
260                         end
261                         --log("debug", "Sending BOSH data: %s", tostring(s));
262                         local oldest_request = r[1];
263                         if oldest_request then
264                                 log("debug", "We have an open request, so sending on that");
265                                 response.body = t_concat({
266                                         "<body xmlns='http://jabber.org/protocol/httpbind' ",
267                                         session.bosh_terminate and "type='terminate' " or "",
268                                         "sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>",
269                                         tostring(s),
270                                         "</body>"
271                                 });
272                                 oldest_request:send(response);
273                                 --log("debug", "Sent");
274                                 if oldest_request.stayopen then
275                                         if #r>1 then
276                                                 -- Move front request to back
277                                                 t_insert(r, oldest_request);
278                                                 t_remove(r, 1);
279                                         end
280                                 else
281                                         log("debug", "Destroying the request now...");
282                                         oldest_request:destroy();
283                                 end
284                         elseif s ~= "" then
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);
289                         end
290                         return true;
291                 end
292                 
293                 -- Send creation response
294                 
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 response = st.stanza("body", { xmlns = xmlns_bosh,
300                         wait = attr.wait,
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                 request:send{ headers = default_headers, body = tostring(response) };
312                 
313                 request.sid = sid;
314                 return;
315         end
316         
317         local session = sessions[sid];
318         if not session then
319                 -- Unknown sid
320                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
321                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
322                 request.notopen = nil;
323                 return;
324         end
325         
326         if session.rid then
327                 local rid = tonumber(attr.rid);
328                 local diff = rid - session.rid;
329                 if diff > 1 then
330                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
331                 elseif diff <= 0 then
332                         -- Repeated, ignore
333                         session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
334                         request.notopen = nil;
335                         request.ignore = true;
336                         request.sid = sid;
337                         t_insert(session.requests, request);
338                         return;
339                 end
340                 session.rid = rid;
341         end
342         
343         if session.notopen then
344                 local features = st.stanza("stream:features");
345                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
346                 fire_event("stream-features", session, features);
347                 session.send(features);
348                 session.notopen = nil;
349         end
350         
351         if attr.type == "terminate" then
352                 -- Client wants to end this session, which we'll do
353                 -- after processing any stanzas in this request
354                 session.bosh_terminate = true;
355         end
356
357         request.notopen = nil; -- Signals that we accept this opening tag
358         t_insert(session.requests, request);
359         request.sid = sid;
360 end
361
362 function stream_callbacks.handlestanza(request, stanza)
363         if request.ignore then return; end
364         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
365         local session = sessions[request.sid];
366         if session then
367                 if stanza.attr.xmlns == xmlns_bosh then
368                         stanza.attr.xmlns = nil;
369                 end
370                 core_process_stanza(session, stanza);
371         end
372 end
373
374 function stream_callbacks.error(request, error)
375         log("debug", "Error parsing BOSH request payload; %s", error);
376         if not request.sid then
377                 request:send({ headers = default_headers, status = "400 Bad Request" });
378                 return;
379         end
380         
381         local session = sessions[request.sid];
382         if error == "stream-error" then -- Remote stream error, we close normally
383                 session:close();
384         else
385                 session:close({ condition = "bad-format", text = "Error processing stream" });
386         end
387 end
388
389 local dead_sessions = {};
390 function on_timer()
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 in pairs(waiting_requests) do
395                 if request.reply_before <= now then
396                         log("debug", "%s was soon to timeout, sending empty response", request.id);
397                         -- Send empty response to let the
398                         -- client know we're still here
399                         if request.conn then
400                                 sessions[request.sid].send("");
401                         end
402                 end
403         end
404         
405         now = now - 3;
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;
414                 end
415         end
416
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");
421         end
422         return 1;
423 end
424
425
426 local function setup()
427         local ports = module:get_option_array("bosh_ports") or { 5280 };
428         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
429         timer.add_task(1, on_timer);
430 end
431 if prosody.start_time then -- already started
432         setup();
433 else
434         prosody.events.add_handler("server-started", setup);
435 end