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