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