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