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