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