8e87e140042dc4dea64e5ca83386e24eba63778b
[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 new_xmpp_stream = require "util.xmppstream".new;
13 local httpserver = require "net.httpserver";
14 local sm = require "core.sessionmanager";
15 local sm_destroy_session = sm.destroy_session;
16 local new_uuid = require "util.uuid".generate;
17 local fire_event = prosody.events.fire_event;
18 local core_process_stanza = core_process_stanza;
19 local st = require "util.stanza";
20 local logger = require "util.logger";
21 local log = logger.init("mod_bosh");
22 local timer = require "util.timer";
23
24 local xmlns_streams = "http://etherx.jabber.org/streams";
25 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
26 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
27
28 local stream_callbacks = {
29         stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
30
31 local BOSH_DEFAULT_HOLD = module:get_option_number("bosh_default_hold", 1);
32 local BOSH_DEFAULT_INACTIVITY = module:get_option_number("bosh_max_inactivity", 60);
33 local BOSH_DEFAULT_POLLING = module:get_option_number("bosh_max_polling", 5);
34 local BOSH_DEFAULT_REQUESTS = module:get_option_number("bosh_max_requests", 2);
35
36 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
37 local auto_cork = module:get_option_boolean("bosh_auto_cork", false);
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.conn: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         
124         -- stream:feed() calls the stream_callbacks, so all stanzas in
125         -- the body are processed in this next line before it returns.
126         local ok, err = stream:feed(body);
127         if not ok then
128                 log("error", "Failed to parse BOSH payload: %s", err);
129         end
130         
131         -- Stanzas (if any) in the request have now been processed, and
132         -- we take care of the high-level BOSH logic here, including
133         -- giving a response or putting the request "on hold".
134         local session = sessions[request.sid];
135         if session then
136                 -- Session was marked as inactive, since we have
137                 -- a request open now, unmark it
138                 if inactive_sessions[session] and #session.requests > 0 then
139                         inactive_sessions[session] = nil;
140                 end
141
142                 local r = session.requests;
143                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
144                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
145                 if #r > session.bosh_hold then
146                         -- We are holding too many requests, send what's in the buffer,
147                         log("debug", "We are holding too many requests, so...");
148                         if #session.send_buffer > 0 then
149                                 log("debug", "...sending what is in the buffer")
150                                 session.send(t_concat(session.send_buffer));
151                                 session.send_buffer = {};
152                         else
153                                 -- or an empty response
154                                 log("debug", "...sending an empty response");
155                                 session.send("");
156                         end
157                 elseif #session.send_buffer > 0 then
158                         log("debug", "Session has data in the send buffer, will send now..");
159                         local resp = t_concat(session.send_buffer);
160                         session.send_buffer = {};
161                         session.send(resp);
162                 end
163                 
164                 if not request.destroyed then
165                         -- We're keeping this request open, to respond later
166                         log("debug", "Have nothing to say, so leaving request unanswered for now");
167                         if session.bosh_wait then
168                                 request.reply_before = os_time() + session.bosh_wait;
169                                 waiting_requests[request] = true;
170                         end
171                 end
172                 
173                 if session.bosh_terminate then
174                         session.log("debug", "Closing session with %d requests open", #session.requests);
175                         session:close();
176                         return nil;
177                 else
178                         return true; -- Inform httpserver we shall reply later
179                 end
180         end
181 end
182
183
184 local function bosh_reset_stream(session) session.notopen = true; end
185
186 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
187
188 local function bosh_close_stream(session, reason)
189         (session.log or log)("info", "BOSH client disconnected");
190         
191         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
192                 ["xmlns:stream"] = xmlns_streams });
193         
194
195         if reason then
196                 close_reply.attr.condition = "remote-stream-error";
197                 if type(reason) == "string" then -- assume stream error
198                         close_reply:tag("stream:error")
199                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
200                 elseif type(reason) == "table" then
201                         if reason.condition then
202                                 close_reply:tag("stream:error")
203                                         :tag(reason.condition, stream_xmlns_attr):up();
204                                 if reason.text then
205                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
206                                 end
207                                 if reason.extra then
208                                         close_reply:add_child(reason.extra);
209                                 end
210                         elseif reason.name then -- a stanza
211                                 close_reply = reason;
212                         end
213                 end
214                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
215         end
216
217         local session_close_response = { headers = default_headers, body = tostring(close_reply) };
218
219         for _, held_request in ipairs(session.requests) do
220                 held_request:send(session_close_response);
221                 held_request:destroy();
222         end
223         sessions[session.sid]  = nil;
224         inactive_sessions[session] = nil;
225         sm_destroy_session(session);
226 end
227
228 -- Handle the <body> tag in the request payload.
229 function stream_callbacks.streamopened(request, attr)
230         local sid = attr.sid;
231         log("debug", "BOSH body open (sid: %s)", sid or "<none>");
232         if not sid then
233                 -- New session request
234                 request.notopen = nil; -- Signals that we accept this opening tag
235                 
236                 -- TODO: Sanity checks here (rid, to, known host, etc.)
237                 if not hosts[attr.to] then
238                         -- Unknown host
239                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
240                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
241                                 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
242                         request:send(tostring(close_reply));
243                         return;
244                 end
245                 
246                 -- New session
247                 sid = new_uuid();
248                 local session = {
249                         type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to,
250                         bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid,
251                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
252                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
253                         close = bosh_close_stream, dispatch_stanza = core_process_stanza,
254                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
255                         ip = get_ip_from_request(request);
256                 };
257                 sessions[sid] = session;
258                 
259                 session.log("debug", "BOSH session created for request from %s", session.ip);
260                 log("info", "New BOSH session, assigned it sid '%s'", sid);
261                 local r, send_buffer = session.requests, session.send_buffer;
262                 local response = { headers = default_headers }
263                 function session.send(s)
264                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
265                         if s.attr and not s.attr.xmlns then
266                                 s = st.clone(s);
267                                 s.attr.xmlns = "jabber:client";
268                         end
269                         --log("debug", "Sending BOSH data: %s", tostring(s));
270                         local oldest_request = r[1];
271                         if oldest_request and (not(auto_cork) or waiting_requests[oldest_request]) then
272                                 log("debug", "We have an open request, so sending on that");
273                                 response.body = t_concat({
274                                         "<body xmlns='http://jabber.org/protocol/httpbind' ",
275                                         session.bosh_terminate and "type='terminate' " or "",
276                                         "sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>",
277                                         tostring(s),
278                                         "</body>"
279                                 });
280                                 oldest_request:send(response);
281                                 --log("debug", "Sent");
282                                 if oldest_request.stayopen then
283                                         if #r>1 then
284                                                 -- Move front request to back
285                                                 t_insert(r, oldest_request);
286                                                 t_remove(r, 1);
287                                         end
288                                 else
289                                         log("debug", "Destroying the request now...");
290                                         oldest_request:destroy();
291                                 end
292                         elseif s ~= "" then
293                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
294                                 -- Hmm, no requests are open :(
295                                 t_insert(session.send_buffer, tostring(s));
296                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
297                         end
298                         return true;
299                 end
300                 
301                 -- Send creation response
302                 
303                 local features = st.stanza("stream:features");
304                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
305                 fire_event("stream-features", session, features);
306                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
307                 local response = st.stanza("body", { xmlns = xmlns_bosh,
308                         wait = attr.wait,
309                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY),
310                         polling = tostring(BOSH_DEFAULT_POLLING),
311                         requests = tostring(BOSH_DEFAULT_REQUESTS),
312                         hold = tostring(session.bosh_hold),
313                         sid = sid, authid = sid,
314                         ver  = '1.6', from = session.host,
315                         secure = 'true', ["xmpp:version"] = "1.0",
316                         ["xmlns:xmpp"] = "urn:xmpp:xbosh",
317                         ["xmlns:stream"] = "http://etherx.jabber.org/streams"
318                 }):add_child(features);
319                 request:send{ headers = default_headers, body = tostring(response) };
320                 
321                 request.sid = sid;
322                 return;
323         end
324         
325         local session = sessions[sid];
326         if not session then
327                 -- Unknown sid
328                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
329                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
330                 request.notopen = nil;
331                 return;
332         end
333         
334         if session.rid then
335                 local rid = tonumber(attr.rid);
336                 local diff = rid - session.rid;
337                 if diff > 1 then
338                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
339                 elseif diff <= 0 then
340                         -- Repeated, ignore
341                         session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
342                         request.notopen = nil;
343                         request.ignore = true;
344                         request.sid = sid;
345                         t_insert(session.requests, request);
346                         return;
347                 end
348                 session.rid = rid;
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
361         if session.notopen then
362                 local features = st.stanza("stream:features");
363                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
364                 fire_event("stream-features", session, features);
365                 session.send(features);
366                 session.notopen = nil;
367         end
368 end
369
370 function stream_callbacks.handlestanza(request, stanza)
371         if request.ignore then return; end
372         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
373         local session = sessions[request.sid];
374         if session then
375                 if stanza.attr.xmlns == xmlns_bosh then
376                         stanza.attr.xmlns = nil;
377                 end
378                 core_process_stanza(session, stanza);
379         end
380 end
381
382 function stream_callbacks.error(request, error)
383         log("debug", "Error parsing BOSH request payload; %s", error);
384         if not request.sid then
385                 request:send({ headers = default_headers, status = "400 Bad Request" });
386                 return;
387         end
388         
389         local session = sessions[request.sid];
390         if error == "stream-error" then -- Remote stream error, we close normally
391                 session:close();
392         else
393                 session:close({ condition = "bad-format", text = "Error processing stream" });
394         end
395 end
396
397 local dead_sessions = {};
398 function on_timer()
399         -- log("debug", "Checking for requests soon to timeout...");
400         -- Identify requests timing out within the next few seconds
401         local now = os_time() + 3;
402         for request in pairs(waiting_requests) do
403                 if request.reply_before <= now then
404                         log("debug", "%s was soon to timeout, sending empty response", request.id);
405                         -- Send empty response to let the
406                         -- client know we're still here
407                         if request.conn then
408                                 sessions[request.sid].send("");
409                         end
410                 end
411         end
412         
413         now = now - 3;
414         local n_dead_sessions = 0;
415         for session, close_after in pairs(inactive_sessions) do
416                 if close_after < now then
417                         (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
418                         sessions[session.sid]  = nil;
419                         inactive_sessions[session] = nil;
420                         n_dead_sessions = n_dead_sessions + 1;
421                         dead_sessions[n_dead_sessions] = session;
422                 end
423         end
424
425         for i=1,n_dead_sessions do
426                 local session = dead_sessions[i];
427                 dead_sessions[i] = nil;
428                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
429         end
430         return 1;
431 end
432
433
434 local function setup()
435         local ports = module:get_option_array("bosh_ports") or { 5280 };
436         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
437         timer.add_task(1, on_timer);
438 end
439 if prosody.start_time then -- already started
440         setup();
441 else
442         prosody.events.add_handler("server-started", setup);
443 end