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