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