Merge 0.9->0.10
[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         if not stream:feed(body) then
131                 module:log("warn", "Error parsing BOSH payload")
132                 return 400;
133         end
134
135         -- Stanzas (if any) in the request have now been processed, and
136         -- we take care of the high-level BOSH logic here, including
137         -- giving a response or putting the request "on hold".
138         local session = sessions[context.sid];
139         if session then
140                 -- Session was marked as inactive, since we have
141                 -- a request open now, unmark it
142                 if inactive_sessions[session] and #session.requests > 0 then
143                         inactive_sessions[session] = nil;
144                 end
145
146                 local r = session.requests;
147                 log("debug", "Session %s has %d out of %d requests open", context.sid, #r, session.bosh_hold);
148                 log("debug", "and there are %d things in the send_buffer:", #session.send_buffer);
149                 if #r > session.bosh_hold then
150                         -- We are holding too many requests, send what's in the buffer,
151                         log("debug", "We are holding too many requests, so...");
152                         if #session.send_buffer > 0 then
153                                 log("debug", "...sending what is in the buffer")
154                                 session.send(t_concat(session.send_buffer));
155                                 session.send_buffer = {};
156                         else
157                                 -- or an empty response
158                                 log("debug", "...sending an empty response");
159                                 session.send("");
160                         end
161                 elseif #session.send_buffer > 0 then
162                         log("debug", "Session has data in the send buffer, will send now..");
163                         local resp = t_concat(session.send_buffer);
164                         session.send_buffer = {};
165                         session.send(resp);
166                 end
167
168                 if not response.finished then
169                         -- We're keeping this request open, to respond later
170                         log("debug", "Have nothing to say, so leaving request unanswered for now");
171                         if session.bosh_wait then
172                                 waiting_requests[response] = os_time() + session.bosh_wait;
173                         end
174                 end
175
176                 if session.bosh_terminate then
177                         session.log("debug", "Closing session with %d requests open", #session.requests);
178                         session:close();
179                         return nil;
180                 else
181                         return true; -- Inform http server we shall reply later
182                 end
183         end
184         module:log("warn", "Unable to associate request with a session (incomplete request?)");
185         return 400;
186 end
187
188
189 local function bosh_reset_stream(session) session.notopen = true; end
190
191 local stream_xmlns_attr = { xmlns = "urn:ietf:params:xml:ns:xmpp-streams" };
192
193 local function bosh_close_stream(session, reason)
194         (session.log or log)("info", "BOSH client disconnected");
195
196         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
197                 ["xmlns:stream"] = xmlns_streams });
198
199
200         if reason then
201                 close_reply.attr.condition = "remote-stream-error";
202                 if type(reason) == "string" then -- assume stream error
203                         close_reply:tag("stream:error")
204                                 :tag(reason, {xmlns = xmlns_xmpp_streams});
205                 elseif type(reason) == "table" then
206                         if reason.condition then
207                                 close_reply:tag("stream:error")
208                                         :tag(reason.condition, stream_xmlns_attr):up();
209                                 if reason.text then
210                                         close_reply:tag("text", stream_xmlns_attr):text(reason.text):up();
211                                 end
212                                 if reason.extra then
213                                         close_reply:add_child(reason.extra);
214                                 end
215                         elseif reason.name then -- a stanza
216                                 close_reply = reason;
217                         end
218                 end
219                 log("info", "Disconnecting client, <stream:error> is: %s", tostring(close_reply));
220         end
221
222         local response_body = tostring(close_reply);
223         for _, held_request in ipairs(session.requests) do
224                 held_request:send(response_body);
225         end
226         sessions[session.sid] = nil;
227         inactive_sessions[session] = nil;
228         sm_destroy_session(session);
229 end
230
231 -- Handle the <body> tag in the request payload.
232 function stream_callbacks.streamopened(context, attr)
233         local request, response = context.request, context.response;
234         local sid = attr.sid;
235         log("debug", "BOSH body open (sid: %s)", sid or "<none>");
236         if not sid then
237                 -- New session request
238                 context.notopen = nil; -- Signals that we accept this opening tag
239
240                 -- TODO: Sanity checks here (rid, to, known host, etc.)
241                 if not hosts[attr.to] then
242                         -- Unknown host
243                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
244                         local close_reply = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate",
245                                 ["xmlns:stream"] = xmlns_streams, condition = "host-unknown" });
246                         response:send(tostring(close_reply));
247                         return;
248                 end
249
250                 -- New session
251                 sid = new_uuid();
252                 local session = {
253                         type = "c2s_unauthed", conn = {}, sid = sid, rid = tonumber(attr.rid)-1, host = attr.to,
254                         bosh_version = attr.ver, bosh_wait = math_min(attr.wait, bosh_max_wait), streamid = sid,
255                         bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
256                         requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream,
257                         close = bosh_close_stream, dispatch_stanza = core_process_stanza, notopen = true,
258                         log = logger.init("bosh"..sid), secure = consider_bosh_secure or request.secure,
259                         ip = get_ip_from_request(request);
260                 };
261                 sessions[sid] = session;
262
263                 local filter = initialize_filters(session);
264
265                 session.log("debug", "BOSH session created for request from %s", session.ip);
266                 log("info", "New BOSH session, assigned it sid '%s'", sid);
267
268                 hosts[session.host].events.fire_event("bosh-session", { session = session, request = request });
269
270                 -- Send creation response
271                 local creating_session = true;
272
273                 local r = session.requests;
274                 function session.send(s)
275                         -- We need to ensure that outgoing stanzas have the jabber:client xmlns
276                         if s.attr and not s.attr.xmlns then
277                                 s = st.clone(s);
278                                 s.attr.xmlns = "jabber:client";
279                         end
280                         s = filter("stanzas/out", s);
281                         --log("debug", "Sending BOSH data: %s", tostring(s));
282                         if not s then return true end
283                         t_insert(session.send_buffer, tostring(s));
284
285                         local oldest_request = r[1];
286                         if oldest_request and not session.bosh_processing then
287                                 log("debug", "We have an open request, so sending on that");
288                                 local body_attr = { xmlns = "http://jabber.org/protocol/httpbind",
289                                         ["xmlns:stream"] = "http://etherx.jabber.org/streams";
290                                         type = session.bosh_terminate and "terminate" or nil;
291                                         sid = sid;
292                                 };
293                                 if creating_session then
294                                         creating_session = nil;
295                                         body_attr.inactivity = tostring(BOSH_DEFAULT_INACTIVITY);
296                                         body_attr.polling = tostring(BOSH_DEFAULT_POLLING);
297                                         body_attr.requests = tostring(BOSH_DEFAULT_REQUESTS);
298                                         body_attr.wait = tostring(session.bosh_wait);
299                                         body_attr.hold = tostring(session.bosh_hold);
300                                         body_attr.authid = sid;
301                                         body_attr.secure = "true";
302                                         body_attr.ver  = '1.6';
303                                         body_attr.from = session.host;
304                                         body_attr["xmlns:xmpp"] = "urn:xmpp:xbosh";
305                                         body_attr["xmpp:version"] = "1.0";
306                                 end
307                                 oldest_request:send(st.stanza("body", body_attr):top_tag()..t_concat(session.send_buffer).."</body>");
308                                 session.send_buffer = {};
309                         end
310                         return true;
311                 end
312                 request.sid = sid;
313         end
314
315         local session = sessions[sid];
316         if not session then
317                 -- Unknown sid
318                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
319                 response:send(tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })));
320                 context.notopen = nil;
321                 return;
322         end
323
324         if session.rid then
325                 local rid = tonumber(attr.rid);
326                 local diff = rid - session.rid;
327                 if diff > 1 then
328                         session.log("warn", "rid too large (means a request was lost). Last rid: %d New rid: %s", session.rid, attr.rid);
329                 elseif diff <= 0 then
330                         -- Repeated, ignore
331                         session.log("debug", "rid repeated, ignoring: %s (diff %d)", session.rid, diff);
332                         context.notopen = nil;
333                         context.ignore = true;
334                         context.sid = sid;
335                         t_insert(session.requests, response);
336                         return;
337                 end
338                 session.rid = rid;
339         end
340
341         if attr.type == "terminate" then
342                 -- Client wants to end this session, which we'll do
343                 -- after processing any stanzas in this request
344                 session.bosh_terminate = true;
345         end
346
347         context.notopen = nil; -- Signals that we accept this opening tag
348         t_insert(session.requests, response);
349         context.sid = sid;
350         session.bosh_processing = true; -- Used to suppress replies until processing of this request is done
351
352         if session.notopen then
353                 local features = st.stanza("stream:features");
354                 hosts[session.host].events.fire_event("stream-features", { origin = session, features = features });
355                 session.send(features);
356                 session.notopen = nil;
357         end
358 end
359
360 local function handleerr(err) log("error", "Traceback[bosh]: %s", traceback(tostring(err), 2)); end
361 function stream_callbacks.handlestanza(context, stanza)
362         if context.ignore then return; end
363         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
364         local session = sessions[context.sid];
365         if session then
366                 if stanza.attr.xmlns == xmlns_bosh then
367                         stanza.attr.xmlns = nil;
368                 end
369                 stanza = session.filter("stanzas/in", stanza);
370                 if stanza then
371                         return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
372                 end
373         end
374 end
375
376 function stream_callbacks.streamclosed(context)
377         local session = sessions[context.sid];
378         if session then
379                 session.bosh_processing = false;
380                 if #session.send_buffer > 0 then
381                         session.send("");
382                 end
383         end
384 end
385
386 function stream_callbacks.error(context, error)
387         log("debug", "Error parsing BOSH request payload; %s", error);
388         if not context.sid then
389                 local response = context.response;
390                 response.status_code = 400;
391                 response:send();
392                 return;
393         end
394
395         local session = sessions[context.sid];
396         if error == "stream-error" then -- Remote stream error, we close normally
397                 session:close();
398         else
399                 session:close({ condition = "bad-format", text = "Error processing stream" });
400         end
401 end
402
403 local dead_sessions = module:shared("dead_sessions");
404 function on_timer()
405         -- log("debug", "Checking for requests soon to timeout...");
406         -- Identify requests timing out within the next few seconds
407         local now = os_time() + 3;
408         for request, reply_before in pairs(waiting_requests) do
409                 if reply_before <= now then
410                         log("debug", "%s was soon to timeout (at %d, now %d), sending empty response", tostring(request), reply_before, now);
411                         -- Send empty response to let the
412                         -- client know we're still here
413                         if request.conn then
414                                 sessions[request.context.sid].send("");
415                         end
416                 end
417         end
418
419         now = now - 3;
420         local n_dead_sessions = 0;
421         for session, close_after in pairs(inactive_sessions) do
422                 if close_after < now then
423                         (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
424                         sessions[session.sid]  = nil;
425                         inactive_sessions[session] = nil;
426                         n_dead_sessions = n_dead_sessions + 1;
427                         dead_sessions[n_dead_sessions] = session;
428                 end
429         end
430
431         for i=1,n_dead_sessions do
432                 local session = dead_sessions[i];
433                 dead_sessions[i] = nil;
434                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
435         end
436         return 1;
437 end
438 module:add_timer(1, on_timer);
439
440
441 local GET_response = {
442         headers = {
443                 content_type = "text/html";
444         };
445         body = [[<html><body>
446         <p>It works! Now point your BOSH client to this URL to connect to Prosody.</p>
447         <p>For more information see <a href="http://prosody.im/doc/setting_up_bosh">Prosody: Setting up BOSH</a>.</p>
448         </body></html>]];
449 };
450
451 function module.add_host(module)
452         module:depends("http");
453         module:provides("http", {
454                 default_path = "/http-bind";
455                 route = {
456                         ["GET"] = GET_response;
457                         ["GET /"] = GET_response;
458                         ["OPTIONS"] = handle_OPTIONS;
459                         ["OPTIONS /"] = handle_OPTIONS;
460                         ["POST"] = handle_POST;
461                         ["POST /"] = handle_POST;
462                 };
463         });
464 end