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