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