2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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,
21 = tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber,
24 local idna_to_ascii = require "util.encodings".idna.to_ascii;
25 local connlisteners_get = require "net.connlisteners".get;
26 local initialize_filters = require "util.filters".initialize;
27 local wrapclient = require "net.server".wrapclient;
28 local modulemanager = require "core.modulemanager";
29 local st = require "stanza";
30 local stanza = st.stanza;
31 local nameprep = require "util.encodings".stringprep.nameprep;
33 local fire_event = require "core.eventmanager".fire_event;
34 local uuid_gen = require "util.uuid".generate;
36 local logger_init = require "util.logger".init;
38 local log = logger_init("s2smanager");
40 local sha256_hash = require "util.hashes".sha256;
42 local adns, dns = require "net.adns", require "net.dns";
43 local config = require "core.configmanager";
44 local connect_timeout = config.get("*", "core", "s2s_timeout") or 60;
45 local dns_timeout = config.get("*", "core", "dns_timeout") or 60;
46 local max_dns_depth = config.get("*", "core", "dns_max_depth") or 3;
49 _G.prosody.incoming_s2s = incoming_s2s;
50 local incoming_s2s = incoming_s2s;
54 function compare_srv_priorities(a,b)
55 return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight);
58 local function bounce_sendq(session, reason)
59 local sendq = session.sendq;
61 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
65 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
69 for i, data in ipairs(sendq) do
70 local reply = data[2];
71 local xmlns = reply.attr.xmlns;
73 reply.attr.type = "error";
74 reply:tag("error", {type = "cancel"})
75 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
77 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):text("Connection failed: "..reason):up();
79 core_process_stanza(dummy, reply);
87 function send_to_host(from_host, to_host, data)
88 if not hosts[from_host] then
89 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
92 local host = hosts[from_host].s2sout[to_host];
94 -- We have a connection to this host already
95 if host.type == "s2sout_unauthed" and (data.name ~= "db:verify" or not host.dialback_key) then
96 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
98 -- Queue stanza until we are able to send it
99 if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
100 else host.sendq = { {tostring(data), st.reply(data)} }; end
101 host.log("debug", "stanza [%s] queued ", data.name);
102 elseif host.type == "local" or host.type == "component" then
103 log("error", "Trying to send a stanza to ourselves??")
104 log("error", "Traceback: %s", get_traceback());
105 log("error", "Stanza: %s", tostring(data));
107 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
109 if host.from_host ~= from_host then
110 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
111 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
114 host.log("debug", "stanza sent over "..host.type);
117 log("debug", "opening a new outgoing connection for this stanza");
118 local host_session = new_outgoing(from_host, to_host);
121 host_session.sendq = { {tostring(data), st.reply(data)} };
122 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
123 if (not host_session.connecting) and (not host_session.conn) then
124 log("warn", "Connection to %s failed already, destroying session...", to_host);
125 destroy_session(host_session);
130 local open_sessions = 0;
132 function new_incoming(conn)
133 local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
135 session.trace = newproxy(true);
136 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
138 open_sessions = open_sessions + 1;
139 local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
141 local filter = initialize_filters(session);
142 session.sends2s = function (t)
144 t = filter("stanzas/out", t);
147 t = filter("bytes/out", tostring(t));
149 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
154 incoming_s2s[session] = true;
155 add_task(connect_timeout, function ()
156 if session.conn ~= conn or
157 session.type == "s2sin" then
158 return; -- Ok, we're connect[ed|ing]
160 -- Not connected, need to close session and clean up
161 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
162 session.from_host or "(unknown)", session.to_host or "(unknown)");
163 session:close("connection-timeout");
168 function new_outgoing(from_host, to_host, connect)
169 local host_session = { to_host = to_host, from_host = from_host, host = from_host,
170 notopen = true, type = "s2sout_unauthed", direction = "outgoing",
171 open_stream = session_open_stream };
173 hosts[from_host].s2sout[to_host] = host_session;
177 local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
178 log = logger_init(conn_name);
179 host_session.log = log;
182 initialize_filters(host_session);
184 if connect ~= false then
185 -- Kick the connection attempting machine into life
186 attempt_connection(host_session);
189 if not host_session.sends2s then
190 -- A sends2s which buffers data (until the stream is opened)
191 -- note that data in this buffer will be sent before the stream is authed
192 -- and will not be ack'd in any way, successful or otherwise
194 function host_session.sends2s(data)
197 host_session.send_buffer = buffer;
199 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
200 buffer[#buffer+1] = data;
201 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
209 function attempt_connection(host_session, err)
210 local from_host, to_host = host_session.from_host, host_session.to_host;
211 local connect_host, connect_port = idna_to_ascii(to_host), 5269;
213 if not connect_host then
217 if not err then -- This is our first attempt
218 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
219 host_session.connecting = true;
221 handle = adns.lookup(function (answer)
223 host_session.connecting = nil;
225 log("debug", to_host.." has SRV records, handling...");
226 local srv_hosts = {};
227 host_session.srv_hosts = srv_hosts;
228 for _, record in ipairs(answer) do
229 t_insert(srv_hosts, record.srv);
231 t_sort(srv_hosts, compare_srv_priorities);
233 local srv_choice = srv_hosts[1];
234 host_session.srv_choice = 1;
236 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
237 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
240 log("debug", to_host.." has no SRV records, falling back to A");
242 -- Try with SRV, or just the plain hostname if no SRV
243 local ok, err = try_connect(host_session, connect_host, connect_port);
245 if not attempt_connection(host_session, err) then
246 -- No more attempts will be made
247 destroy_session(host_session, err);
250 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
252 -- Set handler for DNS timeout
253 add_task(dns_timeout, function ()
255 adns.cancel(handle, true);
259 return true; -- Attempt in progress
260 elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
261 host_session.srv_choice = host_session.srv_choice + 1;
262 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
263 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
264 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
266 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
267 -- We're out of options
271 if not (connect_host and connect_port) then
272 -- Likely we couldn't resolve DNS
273 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));
277 return try_connect(host_session, connect_host, connect_port);
280 function try_connect(host_session, connect_host, connect_port)
281 host_session.connecting = true;
283 handle = adns.lookup(function (reply)
285 host_session.connecting = nil;
287 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
288 if not (reply and reply[#reply] and reply[#reply].a) then
289 local count = max_dns_depth;
290 reply = dns.peek(connect_host, "CNAME", "IN");
291 while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
292 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
293 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
297 -- end of CNAME resolving
299 if reply and reply[#reply] and reply[#reply].a then
300 log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
301 return make_connect(host_session, reply[#reply].a, connect_port);
303 log("debug", "DNS lookup failed to get a response for %s", connect_host);
304 if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
305 log("debug", "No other records to try for %s - destroying", host_session.to_host);
306 destroy_session(host_session, "DNS resolution failed"); -- End of the line, we can't
309 end, connect_host, "A", "IN");
311 -- Set handler for DNS timeout
312 add_task(dns_timeout, function ()
314 adns.cancel(handle, true);
321 function make_connect(host_session, connect_host, connect_port)
322 (host_session.log or log)("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
323 -- Ok, we're going to try to connect
325 local from_host, to_host = host_session.from_host, host_session.to_host;
327 local conn, handler = socket.tcp()
330 log("warn", "Failed to create outgoing connection, system error: %s", handler);
331 return false, handler;
335 local success, err = conn:connect(connect_host, connect_port);
336 if not success and err ~= "timeout" then
337 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
341 local cl = connlisteners_get("xmppserver");
342 conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1 );
343 host_session.conn = conn;
345 -- Register this outgoing connection so that xmppserver_listener knows about it
346 -- otherwise it will assume it is a new incoming connection
347 cl.register_outgoing(conn, host_session);
349 local filter = initialize_filters(host_session);
350 local w, log = conn.write, host_session.log;
351 host_session.sends2s = function (t)
353 t = filter("stanzas/out", t);
356 t = filter("bytes/out", tostring(t));
358 log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?"));
359 return w(conn, tostring(t));
364 host_session:open_stream(from_host, to_host);
366 log("debug", "Connection attempt in progress...");
367 add_task(connect_timeout, function ()
368 if host_session.conn ~= conn or
369 host_session.type == "s2sout" or
370 host_session.connecting then
371 return; -- Ok, we're connect[ed|ing]
373 -- Not connected, need to close session and clean up
374 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
375 host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
376 host_session:close("connection-timeout");
381 function session_open_stream(session, from, to)
382 session.sends2s(st.stanza("stream:stream", {
383 xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
384 ["xmlns:stream"]='http://etherx.jabber.org/streams',
385 from=from, to=to, version='1.0', ["xml:lang"]='en'}):top_tag());
388 function streamopened(session, attr)
389 local send = session.sends2s;
391 -- TODO: #29: SASL/TLS on s2s streams
392 session.version = tonumber(attr.version) or 0;
394 if session.secure == false then
395 session.secure = true;
398 if session.direction == "incoming" then
399 -- Send a reply stream header
400 session.to_host = attr.to and nameprep(attr.to);
401 session.from_host = attr.from and nameprep(attr.from);
403 session.streamid = uuid_gen();
404 (session.log or log)("debug", "incoming s2s received <stream:stream>");
405 if session.to_host and not hosts[session.to_host] then
406 -- Attempting to connect to a host we don't serve
407 session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
410 send("<?xml version='1.0'?>");
411 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
412 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host, to=session.from_host, version=(session.version > 0 and "1.0" or nil) }):top_tag());
413 if session.version >= 1.0 then
414 local features = st.stanza("stream:features");
416 if session.to_host then
417 hosts[session.to_host].events.fire_event("s2s-stream-features", { origin = session, features = features });
419 (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");
422 log("debug", "Sending stream features: %s", tostring(features));
425 elseif session.direction == "outgoing" then
426 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
427 if not attr.id then error("stream response did not give us a streamid!!!"); end
428 session.streamid = attr.id;
430 -- Send unauthed buffer
431 -- (stanzas which are fine to send before dialback)
432 -- Note that this is *not* the stanza queue (which
433 -- we can only send if auth succeeds) :)
434 local send_buffer = session.send_buffer;
435 if send_buffer and #send_buffer > 0 then
436 log("debug", "Sending s2s send_buffer now...");
437 for i, data in ipairs(send_buffer) do
438 session.sends2s(tostring(data));
439 send_buffer[i] = nil;
442 session.send_buffer = nil;
444 -- If server is pre-1.0, don't wait for features, just do dialback
445 if session.version < 1.0 then
446 if not session.dialback_verifying then
447 log("debug", "Initiating dialback...");
448 initiate_dialback(session);
450 mark_connected(session);
454 session.notopen = nil;
457 function streamclosed(session)
458 (session.log or log)("debug", "Received </stream:stream>");
462 function initiate_dialback(session)
463 -- generate dialback key
464 session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
465 session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
466 session.log("info", "sent dialback key on outgoing s2s stream");
469 function generate_dialback(id, to, from)
470 return sha256_hash(id..to..from..hosts[from].dialback_secret, true);
473 function verify_dialback(id, to, from, key)
474 return key == generate_dialback(id, to, from);
477 function make_authenticated(session, host)
478 if not session.secure then
479 local local_host = session.direction == "incoming" and session.to_host or session.from_host;
480 if config.get(local_host, "core", "s2s_require_encryption") then
482 condition = "policy-violation",
483 text = "Encrypted server-to-server communication is required but was not "
484 ..((session.direction == "outgoing" and "offered") or "used")
488 if session.type == "s2sout_unauthed" then
489 session.type = "s2sout";
490 elseif session.type == "s2sin_unauthed" then
491 session.type = "s2sin";
493 session.hosts[host].authed = true;
495 elseif session.type == "s2sin" and host then
496 session.hosts[host].authed = true;
500 session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
502 mark_connected(session);
507 -- Stream is authorised, and ready for normal stanzas
508 function mark_connected(session)
509 local sendq, send = session.sendq, session.sends2s;
511 local from, to = session.from_host, session.to_host;
513 session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
515 local send_to_host = send_to_host;
516 function session.send(data) send_to_host(to, from, data); end
519 if session.direction == "outgoing" then
521 session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
522 for i, data in ipairs(sendq) do
529 session.srv_hosts = nil;
533 local resting_session = { -- Resting, not dead
535 type = "s2s_destroyed";
536 open_stream = function (session)
537 session.log("debug", "Attempt to open stream on resting session");
539 close = function (session)
540 session.log("debug", "Attempt to close already-closed session");
542 }; resting_session.__index = resting_session;
544 function retire_session(session)
545 local log = session.log or log;
546 for k in pairs(session) do
547 if k ~= "trace" and k ~= "log" and k ~= "id" then
552 function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
553 function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
554 return setmetatable(session, resting_session);
557 function destroy_session(session, reason)
558 if session.destroyed then return; end
559 (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
561 if session.direction == "outgoing" then
562 hosts[session.from_host].s2sout[session.to_host] = nil;
563 bounce_sendq(session, reason);
564 elseif session.direction == "incoming" then
565 incoming_s2s[session] = nil;
568 retire_session(session); -- Clean session until it is GC'd