Merge 0.10->trunk
[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:set_global(); -- Global module
10
11 local hosts = _G.hosts;
12 local new_xmpp_stream = require "util.xmppstream".new;
13 local sm = require "core.sessionmanager";
14 local sm_destroy_session = sm.destroy_session;
15 local new_uuid = require "util.uuid".generate;
16 local fire_event = prosody.events.fire_event;
17 local core_process_stanza = prosody.core_process_stanza;
18 local st = require "util.stanza";
19 local logger = require "util.logger";
20 local log = logger.init("mod_bosh");
21 local initialize_filters = require "util.filters".initialize;
22 local math_min = math.min;
23 local xpcall, tostring, type = xpcall, tostring, type;
24 local traceback = debug.traceback;
25
26 local xmlns_streams = "http://etherx.jabber.org/streams";
27 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
28 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
29
30 local stream_callbacks = {
31         stream_ns = xmlns_bosh, stream_tag = "body", default_ns = "jabber:client" };
32
33 local BOSH_DEFAULT_HOLD = module:get_option_number("bosh_default_hold", 1);
34 local BOSH_DEFAULT_INACTIVITY = module:get_option_number("bosh_max_inactivity", 60);
35 local BOSH_DEFAULT_POLLING = module:get_option_number("bosh_max_polling", 5);
36 local BOSH_DEFAULT_REQUESTS = module:get_option_number("bosh_max_requests", 2);
37 local bosh_max_wait = module:get_option_number("bosh_max_wait", 120);
38
39 local consider_bosh_secure = module:get_option_boolean("consider_bosh_secure");
40 local cross_domain = module:get_option("cross_domain_bosh", false);
41
42 if cross_domain == true then cross_domain = "*"; end
43 if type(cross_domain) == "table" then cross_domain = table.concat(cross_domain, ", "); end
44
45 local trusted_proxies = module:get_option_set("trusted_proxies", {"127.0.0.1"})._items;
46
47 local function get_ip_from_request(request)
48         local ip = request.conn:ip();
49         local forwarded_for = request.headers.x_forwarded_for;
50         if forwarded_for then
51                 forwarded_for = forwarded_for..", "..ip;
52                 for forwarded_ip in forwarded_for:gmatch("[^%s,]+") do
53                         if not trusted_proxies[forwarded_ip] then
54                                 ip = forwarded_ip;
55                         end
56                 end
57         end
58         return ip;
59 end
60
61 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
62 local os_time = os.time;
63
64 -- All sessions, and sessions that have no requests open
65 local sessions, inactive_sessions = module:shared("sessions", "inactive_sessions");
66
67 -- Used to respond to idle sessions (those with waiting requests)
68 local waiting_requests = module:shared("waiting_requests");
69 function on_destroy_request(request)
70         log("debug", "Request destroyed: %s", tostring(request));
71         waiting_requests[request] = nil;
72         local session = sessions[request.context.sid];
73         if session then
74                 local requests = session.requests;
75                 for i, r in ipairs(requests) do
76                         if r == request then
77                                 t_remove(requests, i);
78                                 break;
79                         end
80                 end
81
82                 -- If this session now has no requests open, mark it as inactive
83                 local max_inactive = session.bosh_max_inactive;
84                 if max_inactive and #requests == 0 then
85                         inactive_sessions[session] = os_time() + max_inactive;
86                         (session.log or log)("debug", "BOSH session marked as inactive (for %ds)", max_inactive);
87                 end
88         end
89 end
90
91 local function set_cross_domain_headers(response)
92         local headers = response.headers;
93         headers.access_control_allow_methods = "GET, POST, OPTIONS";
94         headers.access_control_allow_headers = "Content-Type";
95         headers.access_control_max_age = "7200";
96         headers.access_control_allow_origin = cross_domain;
97         return response;
98 end
99
100 function handle_OPTIONS(event)
101         if cross_domain and event.request.headers.origin then
102                 set_cross_domain_headers(event.response);
103         end
104         return "";
105 end
106
107 function handle_POST(event)
108         log("debug", "Handling new request %s: %s\n----------", tostring(event.request), tostring(event.request.body));
109
110         local request, response = event.request, event.response;
111         response.on_destroy = on_destroy_request;
112         local body = request.body;
113
114         local context = { request = request, response = response, notopen = true };
115         local stream = new_xmpp_stream(context, stream_callbacks);
116         response.context = context;
117
118         local headers = response.headers;
119         headers.content_type = "text/xml; charset=utf-8";
120
121         if cross_domain and event.request.headers.origin then
122                 set_cross_domain_headers(response);
123         end
124
125         -- stream:feed() calls the stream_callbacks, so all stanzas in
126         -- the body are processed in this next line before it returns.
127         -- In particular, the streamopened() stream callback is where
128         -- much of the session logic happens, because it's where we first
129         -- get to see the 'sid' of this request.
130         local ok, err = stream:feed(body);
131         if not ok then
132                 module:log("warn", "Error parsing BOSH payload; %s", err)
133                 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
134                         ["xmlns:stream"] = xmlns_streams, condition = "bad-request" });
135                 return tostring(close_reply);
136         end
137
138         -- Stanzas (if any) in the request have now been processed, and
139         -- we take care of the high-level BOSH logic here, including
140         -- giving a response or putting the request "on hold".
141         local session = sessions[context.sid];
142         if session then
143                 -- Session was marked as inactive, since we have
144                 -- a request open now, unmark it
145                 if session.inactive_timer and #session.requests > 0 then
146                         session.inactive_timer:stop();
147                         session.inactive_timer = nil;
148                 end
149
150                 if session.bosh_wait_timer then
151                         session.bosh_wait_timer:stop();
152                         session.bosh_wait_timer = nil;
153                 end
154
155                 local r = session.requests;
156                 log("debug", "Session %s has %d out of %d requests open", context.sid, #r, session.bosh_hold);
157                 log("debug", "and there are %d things in the send_buffer:", #session.send_buffer);
158                 if #r > session.bosh_hold then
159                         -- We are holding too many requests, send what's in the buffer,
160                         log("debug", "We are holding too many requests, so...");
161                         if #session.send_buffer > 0 then
162                                 log("debug", "...sending what is in the buffer")
163                                 session.send(t_concat(session.send_buffer));
164                                 session.send_buffer = {};
165                         else
166                                 -- or an empty response
167                                 log("debug", "...sending an empty response");
168                                 session.send("");
169                         end
170                 elseif #session.send_buffer > 0 then
171                         log("debug", "Session has data in the send buffer, will send now..");
172                         local resp = t_concat(session.send_buffer);
173                         session.send_buffer = {};
174                         session.send(resp);
175                 end
176
177                 if not response.finished then
178                         -- We're keeping this request open, to respond later
179                         log("debug", "Have nothing to say, so leaving request unanswered for now");
180                         if session.bosh_wait then
181                                 session.bosh_wait_timer = module:add_timer(session.bosh_wait, after_bosh_wait, request, session)
182                         end
183                 end
184
185                 if session.bosh_terminate then
186                         session.log("debug", "Closing session with %d requests open", #session.requests);
187                         session:close();
188                         return nil;
189                 else
190                         return true; -- Inform http server we shall reply later
191                 end
192         elseif response.finished then
193                 return; -- A response has been sent already
194         end
195         module:log("warn", "Unable to associate request with a session (incomplete request?)");
196         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
197                 ["xmlns:stream"] = xmlns_streams, condition = "item-not-found" });
198         return tostring(close_reply) .. "\n";
199 end
200
201 function after_bosh_wait(now, request, session)
202         if request.conn then
203                 session.send("");
204         end
205 end
206
207 local function bosh_reset_stream(session) session.notopen = true; end
208
209 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
210
211 local function bosh_close_stream(session, reason)
212         (session.log or log)("info", "BOSH client disconnected");
213
214         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
215                 ["xmlns:stream"] = xmlns_streams });
216
217
218         if reason then
219                 close_reply.attr.condition = "remote-stream-error";
220                 if type(reason) == "string" then -- assume stream error
221                         close_reply:tag("stream:error")
222                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
223                 elseif type(reason) == "table" then
224                         if reason.condition then
225                                 close_reply:tag("stream:error")
226                                         :tag(reason.condition, stream_xmlns_attr):up();
227                                 if reason.text then
228                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
229                                 end
230                                 if reason.extra then
231                                         close_reply:add_child(reason.extra);
232                                 end
233                         elseif reason.name then -- a stanza
234                                 close_reply = reason;
235                         end
236                 end
237                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
238         end
239
240         local response_body = tostring(close_reply);
241         for _, held_request in ipairs(session.requests) do
242                 held_request:send(response_body);
243         end
244         sessions[session.sid] = nil;
245         sm_destroy_session(session);
246 end
247
248 local runner_callbacks = { };
249
250 -- Handle the <body> tag in the request payload.
251 function stream_callbacks.streamopened(context, attr)
252         local request, response = context.request, context.response;
253         local sid = attr.sid;
254         log("debug", "BOSH body open (sid: %s)", sid or "<none>");
255         if not sid then
256                 -- New session request
257                 context.notopen = nil; -- Signals that we accept this opening tag
258
259                 local to_host = nameprep(attr.to);
260                 local rid = tonumber(attr.rid);
261                 local wait = tonumber(attr.wait);
262                 if not to_host then
263                         log("debug", "BOSH client tried to connect to invalid host: %s", tostring(attr.to));
264                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
265                                 ["xmlns:stream"] = xmlns_streams, condition = "improper-addressing" });
266                         response:send(tostring(close_reply));
267                         return;
268                 elseif not hosts[to_host] then
269                         -- Unknown host
270                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
271                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
272                                 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
273                         response:send(tostring(close_reply));
274                         return;
275                 end
276                 if not rid or (not wait and attr.wait or wait < 0 or wait % 1 ~= 0) then
277                         log("debug", "BOSH client sent invalid rid or wait attributes: rid=%s, wait=%s", tostring(attr.rid), tostring(attr.wait));
278                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
279                                 ["xmlns:stream"] = xmlns_streams, condition = "bad-request" });
280                         response:send(tostring(close_reply));
281                         return;
282                 end
283
284                 rid = rid - 1;
285                 wait = math_min(wait, bosh_max_wait);
286
287                 -- New session
288                 sid = new_uuid();
289                 local session = {
290                         type = "c2s_unauthed", conn = {}, sid = sid, rid = rid, host = attr.to,
291                         bosh_version = attr.ver, bosh_wait = wait, streamid = sid,
292                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
293                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
294                         close = bosh_close_stream, dispatch_stanza = core_process_stanza, notopen = true,
295                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
296                         ip = get_ip_from_request(request);
297                 };
298                 sessions[sid] = session;
299
300                 session.thread = runner(function (stanza)
301                         session:dispatch_stanza(stanza);
302                 end, runner_callbacks, session);
303
304                 local filter = initialize_filters(session);
305
306                 session.log("debug", "BOSH session created for request from %s", session.ip);
307                 log("info", "New BOSH session, assigned it sid '%s'", sid);
308
309                 hosts[session.host].events.fire_event("bosh-session", { session = session, request = request });
310
311                 -- Send creation response
312                 local creating_session = true;
313
314                 local r = session.requests;
315                 function session.send(s)
316                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
317                         if s.attr and not s.attr.xmlns then
318                                 s = st.clone(s);
319                                 s.attr.xmlns = "jabber:client";
320                         end
321                         s = filter("stanzas/out", s);
322                         --log("debug", "Sending BOSH data: %s", tostring(s));
323                         if not s then return true end
324                         t_insert(session.send_buffer, tostring(s));
325
326                         local oldest_request = r[1];
327                         if oldest_request and not session.bosh_processing then
328                                 log("debug", "We have an open request, so sending on that");
329                                 local body_attr = { xmlns = "http://jabber.org/protocol/httpbind",
330                                         ["xmlns:stream"] = "http://etherx.jabber.org/streams";
331                                         type = session.bosh_terminate and "terminate" or nil;
332                                         sid = sid;
333                                 };
334                                 if creating_session then
335                                         creating_session = nil;
336                                         body_attr.inactivity = tostring(BOSH_DEFAULT_INACTIVITY);
337                                         body_attr.polling = tostring(BOSH_DEFAULT_POLLING);
338                                         body_attr.requests = tostring(BOSH_DEFAULT_REQUESTS);
339                                         body_attr.wait = tostring(session.bosh_wait);
340                                         body_attr.hold = tostring(session.bosh_hold);
341                                         body_attr.authid = sid;
342                                         body_attr.secure = "true";
343                                         body_attr.ver  = '1.6';
344                                         body_attr.from = session.host;
345                                         body_attr["xmlns:xmpp"] = "urn:xmpp:xbosh";
346                                         body_attr["xmpp:version"] = "1.0";
347                                 end
348                                 oldest_request:send(st.stanza("body", body_attr):top_tag()..t_concat(session.send_buffer).."</body>");
349                                 session.send_buffer = {};
350                         end
351                         return true;
352                 end
353                 request.sid = sid;
354         end
355
356         local session = sessions[sid];
357         if not session then
358                 -- Unknown sid
359                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
360                 response:send(tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })));
361                 context.notopen = nil;
362                 return;
363         end
364
365         if session.rid then
366                 local rid = tonumber(attr.rid);
367                 local diff = rid - session.rid;
368                 if diff > 1 then
369                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
370                 elseif diff <= 0 then
371                         -- Repeated, ignore
372                         session.log("debug", "rid repeated, ignoring: %s (diff %d)", session.rid, diff);
373                         context.notopen = nil;
374                         context.ignore = true;
375                         context.sid = sid;
376                         t_insert(session.requests, response);
377                         return;
378                 end
379                 session.rid = rid;
380         end
381
382         if attr.type == "terminate" then
383                 -- Client wants to end this session, which we'll do
384                 -- after processing any stanzas in this request
385                 session.bosh_terminate = true;
386         end
387
388         context.notopen = nil; -- Signals that we accept this opening tag
389         t_insert(session.requests, response);
390         context.sid = sid;
391         session.bosh_processing = true; -- Used to suppress replies until processing of this request is done
392
393         if session.notopen then
394                 local features = st.stanza("stream:features");
395                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
396                 session.send(features);
397                 session.notopen = nil;
398         end
399 end
400
401 local function handleerr(err) log("error", "Traceback[bosh]: %s", traceback(tostring(err), 2)); end
402
403 function runner_callbacks:error(err)
404         return handleerr(err);
405 end
406
407 function stream_callbacks.handlestanza(context, stanza)
408         if context.ignore then return; end
409         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
410         local session = sessions[context.sid];
411         if session then
412                 if stanza.attr.xmlns == xmlns_bosh then
413                         stanza.attr.xmlns = nil;
414                 end
415                 stanza = session.filter("stanzas/in", stanza);
416                 session.thread:run(stanza);
417         end
418 end
419
420 function stream_callbacks.streamclosed(context)
421         local session = sessions[context.sid];
422         if session then
423                 session.bosh_processing = false;
424                 if #session.send_buffer > 0 then
425                         session.send("");
426                 end
427         end
428 end
429
430 function stream_callbacks.error(context, error)
431         log("debug", "Error parsing BOSH request payload; %s", error);
432         if not context.sid then
433                 local response = context.response;
434                 local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
435                         ["xmlns:stream"] = xmlns_streams, condition = "bad-request" });
436                 response:send(tostring(close_reply));
437                 return;
438         end
439
440         local session = sessions[context.sid];
441         if error == "stream-error" then -- Remote stream error, we close normally
442                 session:close();
443         else
444                 session:close({ condition = "bad-format", text = "Error processing stream" });
445         end
446 end
447
448 local GET_response = {
449         headers = {
450                 content_type = "text/html";
451         };
452         body = [[<html><body>
453         <p>It works! Now point your BOSH client to this URL to connect to Prosody.</p>
454         <p>For more information see <a href="https://prosody.im/doc/setting_up_bosh">Prosody: Setting up BOSH</a>.</p>
455         </body></html>]];
456 };
457
458 function module.add_host(module)
459         module:depends("http");
460         module:provides("http", {
461                 default_path = "/http-bind";
462                 route = {
463                         ["GET"] = GET_response;
464                         ["GET /"] = GET_response;
465                         ["OPTIONS"] = handle_OPTIONS;
466                         ["OPTIONS /"] = handle_OPTIONS;
467                         ["POST"] = handle_POST;
468                         ["POST /"] = handle_POST;
469                 };
470         });
471 end