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