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 fire_event = require "core.eventmanager".fire_event;
31 local uuid_gen = require "util.uuid".generate;
33 local logger_init = require "util.logger".init;
35 local log = logger_init("s2smanager");
37 local sha256_hash = require "util.hashes".sha256;
39 local dialback_secret = uuid_gen();
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;
48 _G.prosody.incoming_s2s = incoming_s2s;
49 local incoming_s2s = incoming_s2s;
53 function compare_srv_priorities(a,b)
54 return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight);
57 local function bounce_sendq(session, reason)
58 local sendq = session.sendq;
60 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
64 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
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();
76 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):text("Connection failed: "..reason):up();
78 core_process_stanza(dummy, reply);
86 function send_to_host(from_host, to_host, data)
87 if not hosts[from_host] then
88 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
91 local host = hosts[from_host].s2sout[to_host];
93 -- We have a connection to this host already
94 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
95 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
97 -- Queue stanza until we are able to send it
98 if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
99 else host.sendq = { {tostring(data), st.reply(data)} }; end
100 host.log("debug", "stanza [%s] queued ", data.name);
101 elseif host.type == "local" or host.type == "component" then
102 log("error", "Trying to send a stanza to ourselves??")
103 log("error", "Traceback: %s", get_traceback());
104 log("error", "Stanza: %s", tostring(data));
106 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
108 if host.from_host ~= from_host then
109 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
110 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
113 host.log("debug", "stanza sent over "..host.type);
116 log("debug", "opening a new outgoing connection for this stanza");
117 local host_session = new_outgoing(from_host, to_host);
120 host_session.sendq = { {tostring(data), st.reply(data)} };
121 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
122 if (not host_session.connecting) and (not host_session.conn) then
123 log("warn", "Connection to %s failed already, destroying session...", to_host);
124 destroy_session(host_session);
129 local open_sessions = 0;
131 function new_incoming(conn)
132 local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
134 session.trace = newproxy(true);
135 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
137 open_sessions = open_sessions + 1;
138 local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
140 session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
141 incoming_s2s[session] = true;
142 add_task(connect_timeout, function ()
143 if session.conn ~= conn or
144 session.type == "s2sin" then
145 return; -- Ok, we're connect[ed|ing]
147 -- Not connected, need to close session and clean up
148 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
149 session.from_host or "(unknown)", session.to_host or "(unknown)");
150 session:close("connection-timeout");
155 function new_outgoing(from_host, to_host)
156 local host_session = { to_host = to_host, from_host = from_host, host = from_host,
157 notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
159 hosts[from_host].s2sout[to_host] = host_session;
163 local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
164 log = logger_init(conn_name);
165 host_session.log = log;
168 -- Kick the connection attempting machine
169 attempt_connection(host_session);
171 if not host_session.sends2s then
172 -- A sends2s which buffers data (until the stream is opened)
173 -- note that data in this buffer will be sent before the stream is authed
174 -- and will not be ack'd in any way, successful or otherwise
176 function host_session.sends2s(data)
179 host_session.send_buffer = buffer;
181 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
182 buffer[#buffer+1] = data;
183 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
192 function attempt_connection(host_session, err)
193 local from_host, to_host = host_session.from_host, host_session.to_host;
194 local connect_host, connect_port = idna_to_ascii(to_host), 5269;
196 if not connect_host then
200 if not err then -- This is our first attempt
201 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
202 host_session.connecting = true;
204 handle = adns.lookup(function (answer)
206 host_session.connecting = nil;
208 log("debug", to_host.." has SRV records, handling...");
209 local srv_hosts = {};
210 host_session.srv_hosts = srv_hosts;
211 for _, record in ipairs(answer) do
212 t_insert(srv_hosts, record.srv);
214 t_sort(srv_hosts, compare_srv_priorities);
216 local srv_choice = srv_hosts[1];
217 host_session.srv_choice = 1;
219 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
220 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
223 log("debug", to_host.." has no SRV records, falling back to A");
225 -- Try with SRV, or just the plain hostname if no SRV
226 local ok, err = try_connect(host_session, connect_host, connect_port);
228 if not attempt_connection(host_session, err) then
229 -- No more attempts will be made
230 destroy_session(host_session, err);
233 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
235 -- Set handler for DNS timeout
236 add_task(dns_timeout, function ()
238 adns.cancel(handle, true);
242 log("debug", "DNS lookup for %s sent, waiting for response before we can connect", to_host);
243 return true; -- Attempt in progress
244 elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
245 host_session.srv_choice = host_session.srv_choice + 1;
246 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
247 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
248 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
250 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
251 -- We're out of options
255 if not (connect_host and connect_port) then
256 -- Likely we couldn't resolve DNS
257 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));
261 return try_connect(host_session, connect_host, connect_port);
264 function try_connect(host_session, connect_host, connect_port)
265 host_session.connecting = true;
267 handle = adns.lookup(function (reply)
269 host_session.connecting = nil;
271 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
272 if not (reply and reply[#reply] and reply[#reply].a) then
273 local count = max_dns_depth;
274 reply = dns.peek(connect_host, "CNAME", "IN");
275 while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
276 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
277 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
281 -- end of CNAME resolving
283 if reply and reply[#reply] and reply[#reply].a then
284 log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
285 return make_connect(host_session, reply[#reply].a, connect_port);
287 log("debug", "DNS lookup failed to get a response for %s", connect_host);
288 if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
289 log("debug", "No other records to try for %s - destroying", host_session.to_host);
290 destroy_session(host_session, "DNS resolution failed"); -- End of the line, we can't
293 end, connect_host, "A", "IN");
295 -- Set handler for DNS timeout
296 add_task(dns_timeout, function ()
298 adns.cancel(handle, true);
305 function make_connect(host_session, connect_host, connect_port)
306 host_session.log("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
307 -- Ok, we're going to try to connect
309 local from_host, to_host = host_session.from_host, host_session.to_host;
311 local conn, handler = socket.tcp()
314 log("warn", "Failed to create outgoing connection, system error: %s", handler);
315 return false, handler;
319 local success, err = conn:connect(connect_host, connect_port);
320 if not success and err ~= "timeout" then
321 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
325 local cl = connlisteners_get("xmppserver");
326 conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1, hosts[from_host].ssl_ctx, false );
327 host_session.conn = conn;
329 -- Register this outgoing connection so that xmppserver_listener knows about it
330 -- otherwise it will assume it is a new incoming connection
331 cl.register_outgoing(conn, host_session);
333 local w, log = conn.write, host_session.log;
334 host_session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
336 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));
337 log("debug", "Connection attempt in progress...");
338 add_task(connect_timeout, function ()
339 if host_session.conn ~= conn or
340 host_session.type == "s2sout" or
341 host_session.connecting then
342 return; -- Ok, we're connect[ed|ing]
344 -- Not connected, need to close session and clean up
345 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
346 host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
347 host_session:close("connection-timeout");
352 function streamopened(session, attr)
353 local send = session.sends2s;
355 -- TODO: #29: SASL/TLS on s2s streams
356 session.version = tonumber(attr.version) or 0;
358 if session.secure == false then
359 session.secure = true;
362 if session.version >= 1.0 and not (attr.to and attr.from) then
364 (session.log or log)("warn", "Remote of stream "..(session.from_host or "(unknown)").."->"..(session.to_host or "(unknown)")
365 .." failed to specify to (%s) and/or from (%s) hostname as per RFC", tostring(attr.to), tostring(attr.from));
368 if session.direction == "incoming" then
369 -- Send a reply stream header
370 session.to_host = attr.to and nameprep(attr.to);
371 session.from_host = attr.from and nameprep(attr.from);
373 session.streamid = uuid_gen();
374 (session.log or log)("debug", "incoming s2s received <stream:stream>");
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 });
380 send("<?xml version='1.0'?>");
381 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
382 ["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());
383 if session.version >= 1.0 then
384 local features = st.stanza("stream:features");
386 if session.to_host then
387 hosts[session.to_host].events.fire_event("s2s-stream-features", { session = session, features = features });
389 (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");
392 log("debug", "Sending stream features: %s", tostring(features));
395 elseif session.direction == "outgoing" then
396 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
397 if not attr.id then error("stream response did not give us a streamid!!!"); end
398 session.streamid = attr.id;
400 -- Send unauthed buffer
401 -- (stanzas which are fine to send before dialback)
402 -- Note that this is *not* the stanza queue (which
403 -- we can only send if auth succeeds) :)
404 local send_buffer = session.send_buffer;
405 if send_buffer and #send_buffer > 0 then
406 log("debug", "Sending s2s send_buffer now...");
407 for i, data in ipairs(send_buffer) do
408 session.sends2s(data);
409 send_buffer[i] = nil;
412 session.send_buffer = nil;
414 -- If server is pre-1.0, don't wait for features, just do dialback
415 if session.version < 1.0 then
416 if not session.dialback_verifying then
417 log("debug", "Initiating dialback...");
418 initiate_dialback(session);
420 mark_connected(session);
425 session.notopen = nil;
428 function streamclosed(session)
429 (session.log or log)("debug", "</stream:stream>");
430 if session.sends2s then
431 session.sends2s("</stream:stream>");
433 session.notopen = true;
436 function initiate_dialback(session)
437 -- generate dialback key
438 session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
439 session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
440 session.log("info", "sent dialback key on outgoing s2s stream");
443 function generate_dialback(id, to, from)
444 return sha256_hash(id..to..from..dialback_secret, true);
447 function verify_dialback(id, to, from, key)
448 return key == generate_dialback(id, to, from);
451 function make_authenticated(session, host)
452 if session.type == "s2sout_unauthed" then
453 session.type = "s2sout";
454 elseif session.type == "s2sin_unauthed" then
455 session.type = "s2sin";
457 session.hosts[host].authed = true;
459 elseif session.type == "s2sin" and host then
460 session.hosts[host].authed = true;
464 session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
466 mark_connected(session);
471 -- Stream is authorised, and ready for normal stanzas
472 function mark_connected(session)
473 local sendq, send = session.sendq, session.sends2s;
475 local from, to = session.from_host, session.to_host;
477 session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
479 local send_to_host = send_to_host;
480 function session.send(data) send_to_host(to, from, data); end
483 if session.direction == "outgoing" then
485 session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
486 for i, data in ipairs(sendq) do
493 session.srv_hosts = nil;
497 function destroy_session(session, reason)
498 (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
500 if session.direction == "outgoing" then
501 hosts[session.from_host].s2sout[session.to_host] = nil;
502 bounce_sendq(session, reason);
503 elseif session.direction == "incoming" then
504 incoming_s2s[session] = nil;
507 for k in pairs(session) do