Backout commit d6366294f618 which I was testing and didn't mean to push to 0.8
[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 = tonumber(module:get_option("bosh_default_hold")) or 1;
33 local BOSH_DEFAULT_INACTIVITY = tonumber(module:get_option("bosh_max_inactivity")) or 60;
34 local BOSH_DEFAULT_POLLING = tonumber(module:get_option("bosh_max_polling")) or 5;
35 local BOSH_DEFAULT_REQUESTS = tonumber(module:get_option("bosh_max_requests")) or 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");
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                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
95                         inactive_sessions[session] = os_time();
96                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
97                 end
98         end
99 end
100
101 function handle_request(method, body, request)
102         if (not body) or request.method ~= "POST" then
103                 if request.method == "OPTIONS" then
104                         local headers = {};
105                         for k,v in pairs(default_headers) do headers[k] = v; end
106                         headers["Content-Type"] = nil;
107                         return { headers = headers, body = "" };
108                 else
109                         return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
110                 end
111         end
112         if not method then
113                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
114                 return;
115         end
116         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
117         request.notopen = true;
118         request.log = log;
119         request.on_destroy = on_destroy_request;
120         
121         local stream = new_xmpp_stream(request, stream_callbacks);
122         -- stream:feed() calls the stream_callbacks, so all stanzas in
123         -- the body are processed in this next line before it returns.
124         stream:feed(body);
125         
126         local session = sessions[request.sid];
127         if session then
128                 -- Session was marked as inactive, since we have
129                 -- a request open now, unmark it
130                 if inactive_sessions[session] and #session.requests > 0 then
131                         inactive_sessions[session] = nil;
132                 end
133
134                 local r = session.requests;
135                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
136                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
137                 if #r > session.bosh_hold then
138                         -- We are holding too many requests, send what's in the buffer,
139                         log("debug", "We are holding too many requests, so...");
140                         if #session.send_buffer > 0 then
141                                 log("debug", "...sending what is in the buffer")
142                                 session.send(t_concat(session.send_buffer));
143                                 session.send_buffer = {};
144                         else
145                                 -- or an empty response
146                                 log("debug", "...sending an empty response");
147                                 session.send("");
148                         end
149                 elseif #session.send_buffer > 0 then
150                         log("debug", "Session has data in the send buffer, will send now..");
151                         local resp = t_concat(session.send_buffer);
152                         session.send_buffer = {};
153                         session.send(resp);
154                 end
155                 
156                 if not request.destroyed then
157                         -- We're keeping this request open, to respond later
158                         log("debug", "Have nothing to say, so leaving request unanswered for now");
159                         if session.bosh_wait then
160                                 request.reply_before = os_time() + session.bosh_wait;
161                                 waiting_requests[request] = true;
162                         end
163                 end
164                 
165                 return true; -- Inform httpserver we shall reply later
166         end
167 end
168
169
170 local function bosh_reset_stream(session) session.notopen = true; end
171
172 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
173
174 local function bosh_close_stream(session, reason)
175         (session.log or log)("info", "BOSH client disconnected");
176         
177         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
178                 ["xmlns:streams"] = xmlns_streams });
179         
180
181         if reason then
182                 close_reply.attr.condition = "remote-stream-error";
183                 if type(reason) == "string" then -- assume stream error
184                         close_reply:tag("stream:error")
185                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
186                 elseif type(reason) == "table" then
187                         if reason.condition then
188                                 close_reply:tag("stream:error")
189                                         :tag(reason.condition, stream_xmlns_attr):up();
190                                 if reason.text then
191                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
192                                 end
193                                 if reason.extra then
194                                         close_reply:add_child(reason.extra);
195                                 end
196                         elseif reason.name then -- a stanza
197                                 close_reply = reason;
198                         end
199                 end
200                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
201         end
202
203         local session_close_response = { headers = default_headers, body = tostring(close_reply) };
204
205         --FIXME: Quite sure we shouldn't reply to all requests with the error
206         for _, held_request in ipairs(session.requests) do
207                 held_request:send(session_close_response);
208                 held_request:destroy();
209         end
210         sessions[session.sid]  = nil;
211         sm_destroy_session(session);
212 end
213
214 function stream_callbacks.streamopened(request, attr)
215         log("debug", "BOSH body open (sid: %s)", attr.sid);
216         local sid = attr.sid
217         if not sid then
218                 -- New session request
219                 request.notopen = nil; -- Signals that we accept this opening tag
220                 
221                 -- TODO: Sanity checks here (rid, to, known host, etc.)
222                 if not hosts[attr.to] then
223                         -- Unknown host
224                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
225                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
226                                 ["xmlns:streams"] = xmlns_streams, condition = "host-unknown" });
227                         request:send(tostring(close_reply));
228                         return;
229                 end
230                 
231                 -- New session
232                 sid = new_uuid();
233                 local session = {
234                         type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid), host = attr.to,
235                         bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid,
236                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
237                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
238                         close = bosh_close_stream, dispatch_stanza = core_process_stanza,
239                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
240                         ip = get_ip_from_request(request);
241                 };
242                 sessions[sid] = session;
243                 
244                 session.log("debug", "BOSH session created for request from %s", session.ip);
245                 log("info", "New BOSH session, assigned it sid '%s'", sid);
246                 local r, send_buffer = session.requests, session.send_buffer;
247                 local response = { headers = default_headers }
248                 function session.send(s)
249                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
250                         if s.attr and not s.attr.xmlns then
251                                 s = st.clone(s);
252                                 s.attr.xmlns = "jabber:client";
253                         end
254                         --log("debug", "Sending BOSH data: %s", tostring(s));
255                         local oldest_request = r[1];
256                         if oldest_request then
257                                 log("debug", "We have an open request, so sending on that");
258                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
259                                 oldest_request:send(response);
260                                 --log("debug", "Sent");
261                                 if oldest_request.stayopen then
262                                         if #r>1 then
263                                                 -- Move front request to back
264                                                 t_insert(r, oldest_request);
265                                                 t_remove(r, 1);
266                                         end
267                                 else
268                                         log("debug", "Destroying the request now...");
269                                         oldest_request:destroy();
270                                 end
271                         elseif s ~= "" then
272                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
273                                 -- Hmm, no requests are open :(
274                                 t_insert(session.send_buffer, tostring(s));
275                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
276                         end
277                         return true;
278                 end
279                 
280                 -- Send creation response
281                 
282                 local features = st.stanza("stream:features");
283                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
284                 fire_event("stream-features", session, features);
285                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
286                 local response = st.stanza("body", { xmlns = xmlns_bosh,
287                         wait = attr.wait,
288                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY),
289                         polling = tostring(BOSH_DEFAULT_POLLING),
290                         requests = tostring(BOSH_DEFAULT_REQUESTS),
291                         hold = tostring(session.bosh_hold),
292                         sid = sid, authid = sid,
293                         ver  = '1.6', from = session.host,
294                         secure = 'true', ["xmpp:version"] = "1.0",
295                         ["xmlns:xmpp"] = "urn:xmpp:xbosh",
296                         ["xmlns:stream"] = "http://etherx.jabber.org/streams"
297                 }):add_child(features);
298                 request:send{ headers = default_headers, body = tostring(response) };
299                 
300                 request.sid = sid;
301                 return;
302         end
303         
304         local session = sessions[sid];
305         if not session then
306                 -- Unknown sid
307                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
308                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
309                 request.notopen = nil;
310                 return;
311         end
312         
313         if session.rid then
314                 local rid = tonumber(attr.rid);
315                 local diff = rid - session.rid;
316                 if diff > 1 then
317                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
318                 elseif diff <= 0 then
319                         -- Repeated, ignore
320                         session.log("debug", "rid repeated (on request %s), ignoring: %s (diff %d)", request.id, session.rid, diff);
321                         request.notopen = nil;
322                         request.ignore = true;
323                         request.sid = sid;
324                         t_insert(session.requests, request);
325                         return;
326                 end
327                 session.rid = rid;
328         end
329         
330         if attr.type == "terminate" then
331                 -- Client wants to end this session
332                 session:close();
333                 request.notopen = nil;
334                 return;
335         end
336         
337         if session.notopen then
338                 local features = st.stanza("stream:features");
339                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
340                 fire_event("stream-features", session, features);
341                 session.send(features);
342                 session.notopen = nil;
343         end
344         
345         request.notopen = nil; -- Signals that we accept this opening tag
346         t_insert(session.requests, request);
347         request.sid = sid;
348 end
349
350 function stream_callbacks.handlestanza(request, stanza)
351         if request.ignore then return; end
352         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
353         local session = sessions[request.sid];
354         if session then
355                 if stanza.attr.xmlns == xmlns_bosh then
356                         stanza.attr.xmlns = nil;
357                 end
358                 core_process_stanza(session, stanza);
359         end
360 end
361
362 function stream_callbacks.error(request, error)
363         log("debug", "Error parsing BOSH request payload; %s", error);
364         if not request.sid then
365                 request:send({ headers = default_headers, status = "400 Bad Request" });
366                 return;
367         end
368         
369         local session = sessions[request.sid];
370         if error == "stream-error" then -- Remote stream error, we close normally
371                 session:close();
372         else
373                 session:close({ condition = "bad-format", text = "Error processing stream" });
374         end
375 end
376
377 local dead_sessions = {};
378 function on_timer()
379         -- log("debug", "Checking for requests soon to timeout...");
380         -- Identify requests timing out within the next few seconds
381         local now = os_time() + 3;
382         for request in pairs(waiting_requests) do
383                 if request.reply_before <= now then
384                         log("debug", "%s was soon to timeout, sending empty response", request.id);
385                         -- Send empty response to let the
386                         -- client know we're still here
387                         if request.conn then
388                                 sessions[request.sid].send("");
389                         end
390                 end
391         end
392         
393         now = now - 3;
394         local n_dead_sessions = 0;
395         for session, inactive_since in pairs(inactive_sessions) do
396                 if session.bosh_max_inactive then
397                         if now - inactive_since > session.bosh_max_inactive then
398                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
399                                 sessions[session.sid]  = nil;
400                                 inactive_sessions[session] = nil;
401                                 n_dead_sessions = n_dead_sessions + 1;
402                                 dead_sessions[n_dead_sessions] = session;
403                         end
404                 else
405                         inactive_sessions[session] = nil;
406                 end
407         end
408
409         for i=1,n_dead_sessions do
410                 local session = dead_sessions[i];
411                 dead_sessions[i] = nil;
412                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
413         end
414         return 1;
415 end
416
417
418 local function setup()
419         local ports = module:get_option("bosh_ports") or { 5280 };
420         httpserver.new_from_config(ports, handle_request, { base = "http-bind" });
421         timer.add_task(1, on_timer);
422 end
423 if prosody.start_time then -- already started
424         setup();
425 else
426         prosody.events.add_handler("server-started", setup);
427 end