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