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