2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
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;
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;
30 local uuid_gen = require "util.uuid".generate;
32 local logger_init = require "util.logger".init;
34 local log = logger_init("s2smanager");
36 local sha256_hash = require "util.hashes".sha256;
38 local dialback_secret = uuid_gen();
40 local adns = require "net.adns";
42 local dns_timeout = config.get("*", "core", "dns_timeout") or 60;
45 local incoming_s2s = incoming_s2s;
49 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
51 local function bounce_sendq(session)
52 local sendq = session.sendq;
54 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
58 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
62 for i, data in ipairs(sendq) do
63 local reply = data[2];
64 local xmlns = reply.attr.xmlns;
65 if not xmlns or xmlns == "jabber:client" or xmlns == "jabber:server" then
66 reply.attr.type = "error";
67 reply:tag("error", {type = "cancel"})
68 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
69 core_process_stanza(dummy, reply);
77 function send_to_host(from_host, to_host, data)
78 local host = hosts[from_host].s2sout[to_host];
80 -- We have a connection to this host already
81 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
82 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
83 if not host.notopen and not host.dialback_key and host.sends2s then
84 host.log("debug", "dialback had not been initiated");
85 initiate_dialback(host);
88 -- Queue stanza until we are able to send it
89 if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
90 else host.sendq = { {tostring(data), st.reply(data)} }; end
91 host.log("debug", "stanza [%s] queued ", data.name);
92 elseif host.type == "local" or host.type == "component" then
93 log("error", "Trying to send a stanza to ourselves??")
94 log("error", "Traceback: %s", get_traceback());
95 log("error", "Stanza: %s", tostring(data));
97 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
99 if host.from_host ~= from_host then
100 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
101 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
104 host.log("debug", "stanza sent over "..host.type);
107 log("debug", "opening a new outgoing connection for this stanza");
108 local host_session = new_outgoing(from_host, to_host);
110 host_session.sendq = { {tostring(data), st.reply(data)} };
111 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
112 if (not host_session.connecting) and (not host_session.conn) then
113 log("warn", "Connection to %s failed already, destroying session...", to_host);
114 destroy_session(host_session);
119 local open_sessions = 0;
121 function new_incoming(conn)
122 local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
124 session.trace = newproxy(true);
125 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
127 open_sessions = open_sessions + 1;
128 local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
129 session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
130 incoming_s2s[session] = true;
134 function new_outgoing(from_host, to_host)
135 local host_session = { to_host = to_host, from_host = from_host, notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
136 hosts[from_host].s2sout[to_host] = host_session;
140 local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
141 log = logger_init(conn_name);
142 host_session.log = log;
145 attempt_connection(host_session);
147 if not host_session.sends2s then
148 -- A sends2s which buffers data (until the stream is opened)
149 -- note that data in this buffer will be sent before the stream is authed
150 -- and will not be ack'd in any way, successful or otherwise
152 function host_session.sends2s(data)
155 host_session.send_buffer = buffer;
157 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
158 buffer[#buffer+1] = data;
159 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
168 function attempt_connection(host_session, err)
169 local from_host, to_host = host_session.from_host, host_session.to_host;
170 local connect_host, connect_port = idna_to_ascii(to_host), 5269;
172 if not err then -- This is our first attempt
173 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
174 host_session.connecting = true;
175 local answer, handle;
176 handle = adns.lookup(function (answer)
178 host_session.connecting = nil;
180 log("debug", to_host.." has SRV records, handling...");
181 local srv_hosts = {};
182 host_session.srv_hosts = srv_hosts;
183 for _, record in ipairs(answer) do
184 t_insert(srv_hosts, record.srv);
186 t_sort(srv_hosts, compare_srv_priorities);
188 local srv_choice = srv_hosts[1];
189 host_session.srv_choice = 1;
191 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
192 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
195 log("debug", to_host.." has no SRV records, falling back to A");
197 -- Try with SRV, or just the plain hostname if no SRV
198 return try_connect(host_session, connect_host, connect_port);
199 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
201 -- Set handler for DNS timeout
202 add_task(dns_timeout, function ()
204 adns.cancel(handle, true);
208 log("debug", "DNS lookup for %s sent, waiting for response before we can connect", to_host);
209 return true; -- Attempt in progress
210 elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
211 host_session.srv_choice = host_session.srv_choice + 1;
212 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
213 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
214 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
216 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
217 -- We're out of options
221 if not (connect_host and connect_port) then
222 -- Likely we couldn't resolve DNS
223 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));
227 return try_connect(host_session, connect_host, connect_port);
230 function try_connect(host_session, connect_host, connect_port)
231 host_session.log("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
232 -- Ok, we're going to try to connect
234 local from_host, to_host = host_session.from_host, host_session.to_host;
236 local conn, handler = socket.tcp()
239 local success, err = conn:connect(connect_host, connect_port);
240 if not success and err ~= "timeout" then
241 log("warn", "s2s connect() failed: %s", err);
245 local cl = connlisteners_get("xmppserver");
246 conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1, hosts[from_host].ssl_ctx, false );
247 host_session.conn = conn;
249 -- Register this outgoing connection so that xmppserver_listener knows about it
250 -- otherwise it will assume it is a new incoming connection
251 cl.register_outgoing(conn, host_session);
253 local w = conn.write;
254 host_session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
256 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'>]], from_host, to_host));
257 log("debug", "Connection attempt in progress...");
261 function streamopened(session, attr)
262 local send = session.sends2s;
264 -- TODO: #29: SASL/TLS on s2s streams
265 session.version = 0; --tonumber(attr.version) or 0;
267 if session.version >= 1.0 and not (attr.to and attr.from) then
268 log("warn", (session.to_host or "(unknown)").." failed to specify 'to' or 'from' hostname as per RFC");
271 if session.direction == "incoming" then
272 -- Send a reply stream header
273 session.to_host = attr.to and nameprep(attr.to);
274 session.from_host = attr.from and nameprep(attr.from);
276 session.streamid = uuid_gen();
277 (session.log or log)("debug", "incoming s2s received <stream:stream>");
278 send("<?xml version='1.0'?>");
279 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
280 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host }):top_tag());
281 if session.to_host and not hosts[session.to_host] then
282 -- Attempting to connect to a host we don't serve
283 session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
286 if session.version >= 1.0 then
287 send(st.stanza("stream:features")
288 :tag("dialback", { xmlns='urn:xmpp:features:dialback' }):tag("optional"):up():up());
290 elseif session.direction == "outgoing" then
291 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
292 if not attr.id then error("stream response did not give us a streamid!!!"); end
293 session.streamid = attr.id;
295 -- Send unauthed buffer
296 -- (stanzas which are fine to send before dialback)
297 -- Note that this is *not* the stanza queue (which
298 -- we can only send if auth succeeds) :)
299 local send_buffer = session.send_buffer;
300 if send_buffer and #send_buffer > 0 then
301 log("debug", "Sending s2s send_buffer now...");
302 for i, data in ipairs(send_buffer) do
303 session.sends2s(tostring(data));
304 send_buffer[i] = nil;
307 session.send_buffer = nil;
309 if not session.dialback_verifying then
310 initiate_dialback(session);
312 mark_connected(session);
316 session.notopen = nil;
319 function streamclosed(session)
320 (session.log or log)("debug", "</stream:stream>");
321 if session.sends2s then
322 session.sends2s("</stream:stream>");
324 session.notopen = true;
327 function initiate_dialback(session)
328 -- generate dialback key
329 session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
330 session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
331 session.log("info", "sent dialback key on outgoing s2s stream");
334 function generate_dialback(id, to, from)
335 return sha256_hash(id..to..from..dialback_secret, true);
338 function verify_dialback(id, to, from, key)
339 return key == generate_dialback(id, to, from);
342 function make_authenticated(session, host)
343 if session.type == "s2sout_unauthed" then
344 session.type = "s2sout";
345 elseif session.type == "s2sin_unauthed" then
346 session.type = "s2sin";
348 session.hosts[host].authed = true;
350 elseif session.type == "s2sin" and host then
351 session.hosts[host].authed = true;
355 session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
357 mark_connected(session);
362 function mark_connected(session)
363 local sendq, send = session.sendq, session.sends2s;
365 local from, to = session.from_host, session.to_host;
367 session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
369 local send_to_host = send_to_host;
370 function session.send(data) send_to_host(to, from, data); end
373 if session.direction == "outgoing" then
375 session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
376 for i, data in ipairs(sendq) do
385 function destroy_session(session)
386 (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
388 if session.direction == "outgoing" then
389 hosts[session.from_host].s2sout[session.to_host] = nil;
390 bounce_sendq(session);
391 elseif session.direction == "incoming" then
392 incoming_s2s[session] = nil;
395 for k in pairs(session) do