mod_bosh: Delay setup until after server is started.
[prosody.git] / core / s2smanager.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
11 local hosts = hosts;
12 local sessions = sessions;
13 local core_process_stanza = function(a, b) core_process_stanza(a, b); end
14 local add_task = require "util.timer".add_task;
15 local socket = require "socket";
16 local format = string.format;
17 local t_insert, t_sort = table.insert, table.sort;
18 local get_traceback = debug.traceback;
19 local tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber
20     = tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber;
21
22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local connlisteners_get = require "net.connlisteners".get;
24 local wrapclient = require "net.server".wrapclient;
25 local modulemanager = require "core.modulemanager";
26 local st = require "stanza";
27 local stanza = st.stanza;
28 local nameprep = require "util.encodings".stringprep.nameprep;
29
30 local fire_event = require "core.eventmanager".fire_event;
31 local uuid_gen = require "util.uuid".generate;
32
33 local logger_init = require "util.logger".init;
34
35 local log = logger_init("s2smanager");
36
37 local sha256_hash = require "util.hashes".sha256;
38
39 local adns, dns = require "net.adns", require "net.dns";
40 local config = require "core.configmanager";
41 local connect_timeout = config.get("*", "core", "s2s_timeout") or 60;
42 local dns_timeout = config.get("*", "core", "dns_timeout") or 60;
43 local max_dns_depth = config.get("*", "core", "dns_max_depth") or 3;
44 local dialback_secret = config.get("*", "core", "dialback_secret") or uuid_gen();
45
46 incoming_s2s = {};
47 _G.prosody.incoming_s2s = incoming_s2s;
48 local incoming_s2s = incoming_s2s;
49
50 module "s2smanager"
51
52 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
53
54 local function bounce_sendq(session)
55         local sendq = session.sendq;
56         if sendq then
57                 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
58                 local dummy = {
59                         type = "s2sin";
60                         send = function(s)
61                                 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
62                         end;
63                         dummy = true;
64                 };
65                 for i, data in ipairs(sendq) do
66                         local reply = data[2];
67                         local xmlns = reply.attr.xmlns;
68                         if not xmlns or xmlns == "jabber:client" or xmlns == "jabber:server" then
69                                 reply.attr.type = "error";
70                                 reply:tag("error", {type = "cancel"})
71                                         :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
72                                 core_process_stanza(dummy, reply);
73                         end
74                         sendq[i] = nil;
75                 end
76                 session.sendq = nil;
77         end
78 end
79
80 function send_to_host(from_host, to_host, data)
81         if not hosts[from_host] then
82                 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
83                 return false;
84         end
85         local host = hosts[from_host].s2sout[to_host];
86         if host then
87                 -- We have a connection to this host already
88                 if host.type == "s2sout_unauthed" and (data.name ~= "db:verify" or not host.dialback_key) and ((not data.xmlns) or data.xmlns == "jabber:client" or data.xmlns == "jabber:server") then
89                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
90                         
91                         -- Queue stanza until we are able to send it
92                         if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
93                         else host.sendq = { {tostring(data), st.reply(data)} }; end
94                         host.log("debug", "stanza [%s] queued ", data.name);
95                 elseif host.type == "local" or host.type == "component" then
96                         log("error", "Trying to send a stanza to ourselves??")
97                         log("error", "Traceback: %s", get_traceback());
98                         log("error", "Stanza: %s", tostring(data));
99                 else
100                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
101                         -- FIXME
102                         if host.from_host ~= from_host then
103                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
104                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
105                         end
106                         host.sends2s(data);
107                         host.log("debug", "stanza sent over "..host.type);
108                 end
109         else
110                 log("debug", "opening a new outgoing connection for this stanza");
111                 local host_session = new_outgoing(from_host, to_host);
112
113                 -- Store in buffer
114                 host_session.sendq = { {tostring(data), st.reply(data)} };
115                 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
116                 if (not host_session.connecting) and (not host_session.conn) then
117                         log("warn", "Connection to %s failed already, destroying session...", to_host);
118                         destroy_session(host_session);
119                 end
120         end
121 end
122
123 local open_sessions = 0;
124
125 function new_incoming(conn)
126         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
127         if true then
128                 session.trace = newproxy(true);
129                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
130         end
131         open_sessions = open_sessions + 1;
132         local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
133         session.log = log;
134         session.sends2s = function (t) log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)")); w(conn, tostring(t)); end
135         incoming_s2s[session] = true;
136         add_task(connect_timeout, function ()
137                 if session.conn ~= conn or
138                    session.type == "s2sin" then
139                         return; -- Ok, we're connect[ed|ing]
140                 end
141                 -- Not connected, need to close session and clean up
142                 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity", 
143                     session.from_host or "(unknown)", session.to_host or "(unknown)");
144                 session:close("connection-timeout");
145         end);
146         return session;
147 end
148
149 function new_outgoing(from_host, to_host)
150                 local host_session = { to_host = to_host, from_host = from_host, host = from_host, 
151                                        notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
152                 
153                 hosts[from_host].s2sout[to_host] = host_session;
154                 
155                 local log;
156                 do
157                         local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
158                         log = logger_init(conn_name);
159                         host_session.log = log;
160                 end
161                 
162                 -- Kick the connection attempting machine
163                 attempt_connection(host_session);
164                 
165                 if not host_session.sends2s then                
166                         -- A sends2s which buffers data (until the stream is opened)
167                         -- note that data in this buffer will be sent before the stream is authed
168                         -- and will not be ack'd in any way, successful or otherwise
169                         local buffer;
170                         function host_session.sends2s(data)
171                                 if not buffer then
172                                         buffer = {};
173                                         host_session.send_buffer = buffer;
174                                 end
175                                 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
176                                 buffer[#buffer+1] = data;
177                                 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
178                         end
179                         
180                 end
181
182                 return host_session;
183 end
184
185
186 function attempt_connection(host_session, err)
187         local from_host, to_host = host_session.from_host, host_session.to_host;
188         local connect_host, connect_port = idna_to_ascii(to_host), 5269;
189         
190         if not connect_host then
191                 return false;
192         end
193         
194         if not err then -- This is our first attempt
195                 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
196                 host_session.connecting = true;
197                 local handle;
198                 handle = adns.lookup(function (answer)
199                         handle = nil;
200                         host_session.connecting = nil;
201                         if answer then
202                                 log("debug", to_host.." has SRV records, handling...");
203                                 local srv_hosts = {};
204                                 host_session.srv_hosts = srv_hosts;
205                                 for _, record in ipairs(answer) do
206                                         t_insert(srv_hosts, record.srv);
207                                 end
208                                 t_sort(srv_hosts, compare_srv_priorities);
209                                 
210                                 local srv_choice = srv_hosts[1];
211                                 host_session.srv_choice = 1;
212                                 if srv_choice then
213                                         connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
214                                         log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
215                                 end
216                         else
217                                 log("debug", to_host.." has no SRV records, falling back to A");
218                         end
219                         -- Try with SRV, or just the plain hostname if no SRV
220                         local ok, err = try_connect(host_session, connect_host, connect_port);
221                         if not ok then
222                                 if not attempt_connection(host_session, err) then
223                                         -- No more attempts will be made
224                                         destroy_session(host_session);
225                                 end
226                         end
227                 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
228                 
229                 -- Set handler for DNS timeout
230                 add_task(dns_timeout, function ()
231                         if handle then
232                                 adns.cancel(handle, true);
233                         end
234                 end);
235                 
236                 log("debug", "DNS lookup for %s sent, waiting for response before we can connect", to_host);
237                 return true; -- Attempt in progress
238         elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
239                 host_session.srv_choice = host_session.srv_choice + 1;
240                 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
241                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
242                 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
243         else
244                 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
245                 -- We're out of options
246                 return false;
247         end
248         
249         if not (connect_host and connect_port) then
250                 -- Likely we couldn't resolve DNS
251                 log("warn", "Hmm, we're without a host (%s) and port (%s) to connect to for %s, giving up :(", tostring(connect_host), tostring(connect_port), tostring(to_host));
252                 return false;
253         end
254         
255         return try_connect(host_session, connect_host, connect_port);
256 end
257
258 function try_connect(host_session, connect_host, connect_port)
259         host_session.connecting = true;
260         local handle;
261         handle = adns.lookup(function (reply)
262                 handle = nil;
263                 host_session.connecting = nil;
264                 
265                 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
266                 if not (reply and reply[#reply] and reply[#reply].a) then
267                         local count = max_dns_depth;
268                         reply = dns.peek(connect_host, "CNAME", "IN");
269                         while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
270                                 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
271                                 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
272                                 count = count - 1;
273                         end
274                 end
275                 -- end of CNAME resolving
276                 
277                 if reply and reply[#reply] and reply[#reply].a then
278                         log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
279                         return make_connect(host_session, reply[#reply].a, connect_port);
280                 else
281                         log("debug", "DNS lookup failed to get a response for %s", connect_host);
282                         if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
283                                 log("debug", "No other records to try for %s - destroying", host_session.to_host);
284                                 destroy_session(host_session); -- End of the line, we can't
285                         end
286                 end
287         end, connect_host, "A", "IN");
288
289         -- Set handler for DNS timeout
290         add_task(dns_timeout, function ()
291                 if handle then
292                         adns.cancel(handle, true);
293                 end
294         end);
295                 
296         return true;
297 end
298
299 function make_connect(host_session, connect_host, connect_port)
300         host_session.log("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
301         -- Ok, we're going to try to connect
302         
303         local from_host, to_host = host_session.from_host, host_session.to_host;
304         
305         local conn, handler = socket.tcp()
306
307         conn:settimeout(0);
308         local success, err = conn:connect(connect_host, connect_port);
309         if not success and err ~= "timeout" then
310                 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
311                 return false, err;
312         end
313         
314         local cl = connlisteners_get("xmppserver");
315         conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1, hosts[from_host].ssl_ctx, false );
316         host_session.conn = conn;
317         
318         -- Register this outgoing connection so that xmppserver_listener knows about it
319         -- otherwise it will assume it is a new incoming connection
320         cl.register_outgoing(conn, host_session);
321         
322         local w, log = conn.write, host_session.log;
323         host_session.sends2s = function (t) log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?")); w(conn, tostring(t)); end
324         
325         conn:write(format([[<stream:stream xmlns='jabber:server' xmlns:db='jabber:server:dialback' xmlns:stream='http://etherx.jabber.org/streams' from='%s' to='%s' version='1.0' xml:lang='en'>]], from_host, to_host));
326         log("debug", "Connection attempt in progress...");
327         add_task(connect_timeout, function ()
328                 if host_session.conn ~= conn or
329                    host_session.type == "s2sout" or
330                    host_session.connecting then
331                         return; -- Ok, we're connect[ed|ing]
332                 end
333                 -- Not connected, need to close session and clean up
334                 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity", 
335                     host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
336                 host_session:close("connection-timeout");
337         end);
338         return true;
339 end
340
341 function streamopened(session, attr)
342         local send = session.sends2s;
343         
344         -- TODO: #29: SASL/TLS on s2s streams
345         session.version = tonumber(attr.version) or 0;
346         
347         if session.secure == false then
348                 session.secure = true;
349         end
350         
351         if session.version >= 1.0 and not (attr.to and attr.from) then
352                 
353                 (session.log or log)("warn", "Remote of stream "..(session.from_host or "(unknown)").."->"..(session.to_host or "(unknown)")
354                         .." failed to specify to (%s) and/or from (%s) hostname as per RFC", tostring(attr.to), tostring(attr.from));
355         end
356         
357         if session.direction == "incoming" then
358                 -- Send a reply stream header
359                 session.to_host = attr.to and nameprep(attr.to);
360                 session.from_host = attr.from and nameprep(attr.from);
361         
362                 session.streamid = uuid_gen();
363                 (session.log or log)("debug", "incoming s2s received <stream:stream>");
364                 send("<?xml version='1.0'?>");
365                 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', 
366                                 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host, version=(session.version > 0 and "1.0" or nil) }):top_tag());
367                 if session.to_host and not hosts[session.to_host] then
368                         -- Attempting to connect to a host we don't serve
369                         session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
370                         return;
371                 end
372                 if session.version >= 1.0 then
373                         local features = st.stanza("stream:features");
374                                                         
375                         if session.to_host then
376                                 hosts[session.to_host].events.fire_event("s2s-stream-features", { session = session, features = features });
377                         else
378                                 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", session.from_host or "unknown host");
379                         end
380                         
381                         log("debug", "Sending stream features: %s", tostring(features));
382                         send(features);
383                 end
384         elseif session.direction == "outgoing" then
385                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
386                 if not attr.id then error("stream response did not give us a streamid!!!"); end
387                 session.streamid = attr.id;
388         
389                 -- Send unauthed buffer
390                 -- (stanzas which are fine to send before dialback)
391                 -- Note that this is *not* the stanza queue (which 
392                 -- we can only send if auth succeeds) :)
393                 local send_buffer = session.send_buffer;
394                 if send_buffer and #send_buffer > 0 then
395                         log("debug", "Sending s2s send_buffer now...");
396                         for i, data in ipairs(send_buffer) do
397                                 session.sends2s(tostring(data));
398                                 send_buffer[i] = nil;
399                         end
400                 end
401                 session.send_buffer = nil;
402         
403                 -- If server is pre-1.0, don't wait for features, just do dialback
404                 if session.version < 1.0 then
405                         if not session.dialback_verifying then
406                                 log("debug", "Initiating dialback...");
407                                 initiate_dialback(session);
408                         else
409                                 mark_connected(session);
410                         end
411                 end
412         end
413
414         session.notopen = nil;
415 end
416
417 function streamclosed(session)
418         (session.log or log)("debug", "</stream:stream>");
419         if session.sends2s then
420                 session.sends2s("</stream:stream>");
421         end
422         session.notopen = true;
423 end
424
425 function initiate_dialback(session)
426         -- generate dialback key
427         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
428         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
429         session.log("info", "sent dialback key on outgoing s2s stream");
430 end
431
432 function generate_dialback(id, to, from)
433         return sha256_hash(id..to..from..dialback_secret, true);
434 end
435
436 function verify_dialback(id, to, from, key)
437         return key == generate_dialback(id, to, from);
438 end
439
440 function make_authenticated(session, host)
441         if session.type == "s2sout_unauthed" then
442                 session.type = "s2sout";
443         elseif session.type == "s2sin_unauthed" then
444                 session.type = "s2sin";
445                 if host then
446                         session.hosts[host].authed = true;
447                 end
448         elseif session.type == "s2sin" and host then
449                 session.hosts[host].authed = true;
450         else
451                 return false;
452         end
453         session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
454         
455         mark_connected(session);
456         
457         return true;
458 end
459
460 -- Stream is authorised, and ready for normal stanzas
461 function mark_connected(session)
462         local sendq, send = session.sendq, session.sends2s;
463         
464         local from, to = session.from_host, session.to_host;
465         
466         session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
467         
468         local send_to_host = send_to_host;
469         function session.send(data) send_to_host(to, from, data); end
470         
471         
472         if session.direction == "outgoing" then
473                 if sendq then
474                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
475                         for i, data in ipairs(sendq) do
476                                 send(data[1]);
477                                 sendq[i] = nil;
478                         end
479                         session.sendq = nil;
480                 end
481                 
482                 session.srv_hosts = nil;
483         end
484 end
485
486 function destroy_session(session)
487         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
488         
489         if session.direction == "outgoing" then
490                 hosts[session.from_host].s2sout[session.to_host] = nil;
491                 bounce_sendq(session);
492         elseif session.direction == "incoming" then
493                 incoming_s2s[session] = nil;
494         end
495         
496         for k in pairs(session) do
497                 if k ~= "trace" then
498                         session[k] = nil;
499                 end
500         end
501 end
502
503 return _M;