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