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