mod_bosh: Give BOSH sessions a logger (thanks Florob)
[prosody.git] / plugins / mod_bosh.lua
1
2 module.host = "*" -- Global module
3
4 local lxp = require "lxp";
5 local init_xmlhandlers = require "core.xmlhandlers"
6 local server = require "net.server";
7 local httpserver = require "net.httpserver";
8 local sm = require "core.sessionmanager";
9 local sm_destroy_session = sm.destroy_session;
10 local new_uuid = require "util.uuid".generate;
11 local fire_event = require "core.eventmanager".fire_event;
12 local core_process_stanza = core_process_stanza;
13 local st = require "util.stanza";
14 local logger = require "util.logger";
15 local log = logger.init("mod_bosh");
16 local stream_callbacks = { stream_tag = "http://jabber.org/protocol/httpbind|body" };
17 local config = require "core.configmanager";
18 local xmlns_bosh = "http://jabber.org/protocol/httpbind"; -- (hard-coded into a literal in session.send)
19
20 local BOSH_DEFAULT_HOLD = tonumber(config.get("*", "core", "bosh_default_hold")) or 1;
21 local BOSH_DEFAULT_INACTIVITY = tonumber(config.get("*", "core", "bosh_max_inactivity")) or 60;
22 local BOSH_DEFAULT_POLLING = tonumber(config.get("*", "core", "bosh_max_polling")) or 5;
23 local BOSH_DEFAULT_REQUESTS = tonumber(config.get("*", "core", "bosh_max_requests")) or 2;
24 local BOSH_DEFAULT_MAXPAUSE = tonumber(config.get("*", "core", "bosh_max_pause")) or 300;
25
26 local default_headers = { ["Content-Type"] = "text/xml; charset=utf-8" };
27
28 local t_insert, t_remove, t_concat = table.insert, table.remove, table.concat;
29 local os_time = os.time;
30
31 local sessions = {};
32 local inactive_sessions = {}; -- Sessions which have no open requests
33
34 -- Used to respond to idle sessions (those with waiting requests)
35 local waiting_requests = {};
36 function on_destroy_request(request)
37         waiting_requests[request] = nil;
38         local session = sessions[request.sid];
39         if session then
40                 local requests = session.requests;
41                 for i,r in pairs(requests) do
42                         if r == request then requests[i] = nil; break; end
43                 end
44                 
45                 -- If this session now has no requests open, mark it as inactive
46                 if #requests == 0 and session.bosh_max_inactive and not inactive_sessions[session] then
47                         inactive_sessions[session] = os_time();
48                         (session.log or log)("debug", "BOSH session marked as inactive at %d", inactive_sessions[session]);
49                 end
50         end
51 end
52
53 function handle_request(method, body, request)
54         if (not body) or request.method ~= "POST" then
55                 return "<html><body>You really don't look like a BOSH client to me... what do you want?</body></html>";
56         end
57         if not method then 
58                 log("debug", "Request %s suffered error %s", tostring(request.id), body);
59                 return;
60         end
61         --log("debug", "Handling new request %s: %s\n----------", request.id, tostring(body));
62         request.notopen = true;
63         request.log = log;
64         local parser = lxp.new(init_xmlhandlers(request, stream_callbacks), "|");
65         
66         parser:parse(body);
67         
68         local session = sessions[request.sid];
69         if session then
70                 local r = session.requests;
71                 log("debug", "Session %s has %d out of %d requests open", request.sid, #r, session.bosh_hold);
72                 log("debug", "and there are %d things in the send_buffer", #session.send_buffer);
73                 if #r > session.bosh_hold then
74                         -- We are holding too many requests, send what's in the buffer,
75                         log("debug", "We are holding too many requests, so...");
76                         if #session.send_buffer > 0 then
77                                 log("debug", "...sending what is in the buffer")
78                                 session.send(t_concat(session.send_buffer));
79                                 session.send_buffer = {};
80                         else
81                                 -- or an empty response
82                                 log("debug", "...sending an empty response");
83                                 session.send("");
84                         end
85                 elseif #session.send_buffer > 0 then
86                         log("debug", "Session has data in the send buffer, will send now..");
87                         local resp = t_concat(session.send_buffer);
88                         session.send_buffer = {};
89                         session.send(resp);
90                 end
91                 
92                 if not request.destroyed and session.bosh_wait then
93                         request.reply_before = os_time() + session.bosh_wait;
94                         request.on_destroy = on_destroy_request;
95                         waiting_requests[request] = true;
96                 end
97                 
98                 log("debug", "Have nothing to say, so leaving request unanswered for now");
99                 return true;
100         end
101 end
102
103
104 local function bosh_reset_stream(session) session.notopen = true; end
105
106 local session_close_reply = { headers = default_headers, body = st.stanza("body", { xmlns = xmlns_bosh, type = "terminate" }), attr = {} };
107 local function bosh_close_stream(session, reason)
108         (session.log or log)("info", "BOSH client disconnected");
109         session_close_reply.attr.condition = reason;
110         local session_close_reply = tostring(session_close_reply);
111         for _, held_request in ipairs(session.requests) do
112                 held_request:send(session_close_reply);
113                 held_request:destroy();
114         end
115         sessions[session.sid]  = nil;
116         sm_destroy_session(session);
117 end
118
119 function stream_callbacks.streamopened(request, attr)
120         log("debug", "BOSH body open (sid: %s)", attr.sid);
121         local sid = attr.sid
122         if not sid then
123                 -- New session request
124                 request.notopen = nil; -- Signals that we accept this opening tag
125                 
126                 -- TODO: Sanity checks here (rid, to, known host, etc.)
127                 if not hosts[attr.to] then
128                         -- Unknown host
129                         log("debug", "BOSH client tried to connect to unknown host: %s", tostring(attr.to));
130                         session_close_reply.attr.condition = "host-unknown";
131                         request:send{ headers = default_headers, body = tostring(session_close_reply) };
132                         request.notopen = nil
133                         return;
134                 end
135                 
136                 -- New session
137                 sid = new_uuid();
138                 local session = { type = "c2s_unauthed", conn = {}, sid = sid, rid = attr.rid, host = attr.to, bosh_version = attr.ver, bosh_wait = attr.wait, streamid = sid, 
139                                                 bosh_hold = BOSH_DEFAULT_HOLD, bosh_max_inactive = BOSH_DEFAULT_INACTIVITY,
140                                                 requests = { }, send_buffer = {}, reset_stream = bosh_reset_stream, close = bosh_close_stream, 
141                                                 dispatch_stanza = core_process_stanza, log = logger.init("bosh"..sid) };
142                 sessions[sid] = session;
143                 
144                 log("info", "New BOSH session, assigned it sid '%s'", sid);
145                 local r, send_buffer = session.requests, session.send_buffer;
146                 local response = { headers = default_headers }
147                 function session.send(s)
148                         log("debug", "Sending BOSH data: %s", tostring(s));
149                         local oldest_request = r[1];
150                         while oldest_request and oldest_request.destroyed do
151                                 t_remove(r, 1);
152                                 waiting_requests[oldest_request] = nil;
153                                 oldest_request = r[1];
154                         end
155                         if oldest_request then
156                                 log("debug", "We have an open request, so using that to send with");
157                                 response.body = t_concat{"<body xmlns='http://jabber.org/protocol/httpbind' sid='", sid, "' xmlns:stream = 'http://etherx.jabber.org/streams'>", tostring(s), "</body>" };
158                                 oldest_request:send(response);
159                                 --log("debug", "Sent");
160                                 if oldest_request.stayopen then
161                                         if #r>1 then
162                                                 -- Move front request to back
163                                                 t_insert(r, oldest_request);
164                                                 t_remove(r, 1);
165                                         end
166                                 else
167                                         log("debug", "Destroying the request now...");
168                                         oldest_request:destroy();
169                                         t_remove(r, 1);
170                                 end
171                         elseif s ~= "" then
172                                 log("debug", "Saved to send buffer because there are %d open requests", #r);
173                                 -- Hmm, no requests are open :(
174                                 t_insert(session.send_buffer, tostring(s));
175                                 log("debug", "There are now %d things in the send_buffer", #session.send_buffer);
176                         end
177                 end
178                 
179                 -- Send creation response
180                 
181                 local features = st.stanza("stream:features");
182                 fire_event("stream-features", session, features);
183                 --xmpp:version='1.0' xmlns:xmpp='urn:xmpp:xbosh'
184                 local response = st.stanza("body", { xmlns = xmlns_bosh, 
185                                                                         inactivity = tostring(BOSH_DEFAULT_INACTIVITY), polling = tostring(BOSH_DEFAULT_POLLING), requests = tostring(BOSH_DEFAULT_REQUESTS), hold = tostring(session.bosh_hold), maxpause = "120", 
186                                                                         sid = sid, authid = sid, ver  = '1.6', from = session.host, secure = 'true', ["xmpp:version"] = "1.0", 
187                                                                         ["xmlns:xmpp"] = "urn:xmpp:xbosh", ["xmlns:stream"] = "http://etherx.jabber.org/streams" }):add_child(features);
188                 request:send{ headers = default_headers, body = tostring(response) };
189                                 
190                 request.sid = sid;
191                 return;
192         end
193         
194         local session = sessions[sid];
195         if not session then
196                 -- Unknown sid
197                 log("info", "Client tried to use sid '%s' which we don't know about", sid);
198                 request:send{ headers = default_headers, body = tostring(st.stanza("body", { xmlns = xmlns_bosh, type = "terminate", condition = "item-not-found" })) };
199                 request.notopen = nil;
200                 return;
201         end
202         
203         if attr.type == "terminate" then
204                 -- Client wants to end this session
205                 session:close();
206                 request.notopen = nil;
207                 return;
208         end
209         
210         -- If session was inactive, make sure it is now marked as not
211         if #session.requests == 0 then
212                 (session.log or log)("debug", "BOSH client now active again at %d", os_time());
213                 inactive_sessions[session] = nil;
214         end
215         
216         if session.notopen then
217                 local features = st.stanza("stream:features");
218                 fire_event("stream-features", session, features);
219                 session.send(features);
220                 session.notopen = nil;
221         end
222         
223         request.notopen = nil; -- Signals that we accept this opening tag
224         t_insert(session.requests, request);
225         request.sid = sid;
226 end
227
228 function stream_callbacks.handlestanza(request, stanza)
229         log("debug", "BOSH stanza received: %s\n", stanza:top_tag());
230         local session = sessions[request.sid];
231         if session then
232                 if stanza.attr.xmlns == xmlns_bosh then
233                         stanza.attr.xmlns = "jabber:client";
234                 end
235                 core_process_stanza(session, stanza);
236         end
237 end
238
239 function on_timer()
240         -- log("debug", "Checking for requests soon to timeout...");
241         -- Identify requests timing out within the next few seconds
242         local now = os_time() + 3;
243         for request in pairs(waiting_requests) do
244                 if request.reply_before <= now then
245                         log("debug", "%s was soon to timeout, sending empty response", request.id);
246                         -- Send empty response to let the
247                         -- client know we're still here
248                         if request.conn then
249                                 sessions[request.sid].send("");
250                         end
251                 end
252         end
253         
254         now = now - 3;
255         for session, inactive_since in pairs(inactive_sessions) do
256                 if session.bosh_max_inactive then
257                         if now - inactive_since > session.bosh_max_inactive then
258                                 (session.log or log)("debug", "BOSH client inactive too long, destroying session at %d", now);
259                                 sessions[session.sid]  = nil;
260                                 inactive_sessions[session] = nil;
261                                 sm_destroy_session(session, "BOSH client silent for over "..session.bosh_max_inactive.." seconds");
262                         end
263                 else
264                         inactive_sessions[session] = nil;
265                 end
266         end
267 end
268
269 local ports = config.get(module.host, "core", "bosh_ports") or { 5280 };
270 for _, options in ipairs(ports) do
271         local port, base, ssl, interface = 5280, "http-bind", false, nil;
272         if type(options) == "number" then
273                 port = options;
274         elseif type(options) == "table" then
275                 port, base, ssl, interface = options.port or 5280, options.path or "http-bind", options.ssl or false, options.interface;
276         elseif type(options) == "string" then
277                 base = options;
278         end
279         httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl }
280 end
281
282 server.addtimer(on_timer);