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, setmetatable
20 = tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber, setmetatable;
22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local connlisteners_get = require "net.connlisteners".get;
24 local initialize_filters = require "util.filters".initialize;
25 local wrapclient = require "net.server".wrapclient;
26 local modulemanager = require "core.modulemanager";
27 local st = require "stanza";
28 local stanza = st.stanza;
29 local nameprep = require "util.encodings".stringprep.nameprep;
31 local fire_event = prosody.events.fire_event;
32 local uuid_gen = require "util.uuid".generate;
34 local logger_init = require "util.logger".init;
36 local log = logger_init("s2smanager");
38 local sha256_hash = require "util.hashes".sha256;
40 local adns, dns = require "net.adns", require "net.dns";
41 local config = require "core.configmanager";
42 local connect_timeout = config.get("*", "core", "s2s_timeout") or 60;
43 local dns_timeout = config.get("*", "core", "dns_timeout") or 15;
44 local max_dns_depth = config.get("*", "core", "dns_max_depth") or 3;
46 dns.settimeout(dns_timeout);
48 local prosody = _G.prosody;
50 prosody.incoming_s2s = incoming_s2s;
51 local incoming_s2s = incoming_s2s;
55 function compare_srv_priorities(a,b)
56 return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight);
59 local bouncy_stanzas = { message = true, presence = true, iq = true };
60 local function bounce_sendq(session, reason)
61 local sendq = session.sendq;
63 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
67 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
71 for i, data in ipairs(sendq) do
72 local reply = data[2];
73 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
74 reply.attr.type = "error";
75 reply:tag("error", {type = "cancel"})
76 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
78 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):text("Connection failed: "..reason):up();
80 core_process_stanza(dummy, reply);
88 function send_to_host(from_host, to_host, data)
89 if not hosts[from_host] then
90 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
93 local host = hosts[from_host].s2sout[to_host];
95 -- We have a connection to this host already
96 if host.type == "s2sout_unauthed" and (data.name ~= "db:verify" or not host.dialback_key) then
97 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
99 -- Queue stanza until we are able to send it
100 if host.sendq then t_insert(host.sendq, {tostring(data), data.attr.type ~= "error" and data.attr.type ~= "result" and st.reply(data)});
101 else host.sendq = { {tostring(data), data.attr.type ~= "error" and data.attr.type ~= "result" and st.reply(data)} }; end
102 host.log("debug", "stanza [%s] queued ", data.name);
103 elseif host.type == "local" or host.type == "component" then
104 log("error", "Trying to send a stanza to ourselves??")
105 log("error", "Traceback: %s", get_traceback());
106 log("error", "Stanza: %s", tostring(data));
109 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
111 if host.from_host ~= from_host then
112 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
113 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
116 host.log("debug", "stanza sent over "..host.type);
119 log("debug", "opening a new outgoing connection for this stanza");
120 local host_session = new_outgoing(from_host, to_host);
123 host_session.sendq = { {tostring(data), data.attr.type ~= "error" and data.attr.type ~= "result" and st.reply(data)} };
124 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
125 if (not host_session.connecting) and (not host_session.conn) then
126 log("warn", "Connection to %s failed already, destroying session...", to_host);
127 if not destroy_session(host_session, "Connection failed") then
128 -- Already destroyed, we need to bounce our stanza
129 bounce_sendq(host_session, host_session.destruction_reason);
137 local open_sessions = 0;
139 function new_incoming(conn)
140 local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
142 session.trace = newproxy(true);
143 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
145 open_sessions = open_sessions + 1;
146 local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
148 local filter = initialize_filters(session);
149 session.sends2s = function (t)
150 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
152 t = filter("stanzas/out", t);
155 t = filter("bytes/out", tostring(t));
161 incoming_s2s[session] = true;
162 add_task(connect_timeout, function ()
163 if session.conn ~= conn or
164 session.type == "s2sin" then
165 return; -- Ok, we're connect[ed|ing]
167 -- Not connected, need to close session and clean up
168 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
169 session.from_host or "(unknown)", session.to_host or "(unknown)");
170 session:close("connection-timeout");
175 function new_outgoing(from_host, to_host, connect)
176 local host_session = { to_host = to_host, from_host = from_host, host = from_host,
177 notopen = true, type = "s2sout_unauthed", direction = "outgoing",
178 open_stream = session_open_stream };
180 hosts[from_host].s2sout[to_host] = host_session;
182 host_session.close = destroy_session; -- This gets replaced by xmppserver_listener later
186 local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
187 log = logger_init(conn_name);
188 host_session.log = log;
191 initialize_filters(host_session);
193 if connect ~= false then
194 -- Kick the connection attempting machine into life
195 if not attempt_connection(host_session) then
196 -- Intentionally not returning here, the
197 -- session is needed, connected or not
198 destroy_session(host_session);
202 if not host_session.sends2s then
203 -- A sends2s which buffers data (until the stream is opened)
204 -- note that data in this buffer will be sent before the stream is authed
205 -- and will not be ack'd in any way, successful or otherwise
207 function host_session.sends2s(data)
210 host_session.send_buffer = buffer;
212 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
213 buffer[#buffer+1] = data;
214 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
222 function attempt_connection(host_session, err)
223 local from_host, to_host = host_session.from_host, host_session.to_host;
224 local connect_host, connect_port = to_host and idna_to_ascii(to_host), 5269;
226 if not connect_host then
230 if not err then -- This is our first attempt
231 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
232 host_session.connecting = true;
234 handle = adns.lookup(function (answer)
236 host_session.connecting = nil;
238 log("debug", to_host.." has SRV records, handling...");
239 local srv_hosts = {};
240 host_session.srv_hosts = srv_hosts;
241 for _, record in ipairs(answer) do
242 t_insert(srv_hosts, record.srv);
244 t_sort(srv_hosts, compare_srv_priorities);
246 local srv_choice = srv_hosts[1];
247 host_session.srv_choice = 1;
249 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
250 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
253 log("debug", to_host.." has no SRV records, falling back to A");
255 -- Try with SRV, or just the plain hostname if no SRV
256 local ok, err = try_connect(host_session, connect_host, connect_port);
258 if not attempt_connection(host_session, err) then
259 -- No more attempts will be made
260 destroy_session(host_session, err);
263 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
265 return true; -- Attempt in progress
266 elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
267 host_session.srv_choice = host_session.srv_choice + 1;
268 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
269 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
270 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
272 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
273 -- We're out of options
277 if not (connect_host and connect_port) then
278 -- Likely we couldn't resolve DNS
279 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));
283 return try_connect(host_session, connect_host, connect_port);
286 function try_connect(host_session, connect_host, connect_port)
287 host_session.connecting = true;
289 handle = adns.lookup(function (reply, err)
291 host_session.connecting = nil;
293 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
294 if not (reply and reply[#reply] and reply[#reply].a) then
295 local count = max_dns_depth;
296 reply = dns.peek(connect_host, "CNAME", "IN");
297 while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
298 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
299 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
303 -- end of CNAME resolving
305 if reply and reply[#reply] and reply[#reply].a then
306 log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
307 local ok, err = make_connect(host_session, reply[#reply].a, connect_port);
309 if not attempt_connection(host_session, err or "closed") then
310 err = err and (": "..err) or "";
311 destroy_session(host_session, "Connection failed"..err);
315 log("debug", "DNS lookup failed to get a response for %s", connect_host);
316 if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
317 log("debug", "No other records to try for %s - destroying", host_session.to_host);
318 err = err and (": "..err) or "";
319 destroy_session(host_session, "DNS resolution failed"..err); -- End of the line, we can't
322 end, connect_host, "A", "IN");
327 function make_connect(host_session, connect_host, connect_port)
328 (host_session.log or log)("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
329 -- Ok, we're going to try to connect
331 local from_host, to_host = host_session.from_host, host_session.to_host;
333 local conn, handler = socket.tcp();
336 log("warn", "Failed to create outgoing connection, system error: %s", handler);
337 return false, handler;
341 local success, err = conn:connect(connect_host, connect_port);
342 if not success and err ~= "timeout" then
343 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
347 local cl = connlisteners_get("xmppserver");
348 conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1 );
349 host_session.conn = conn;
351 local filter = initialize_filters(host_session);
352 local w, log = conn.write, host_session.log;
353 host_session.sends2s = function (t)
354 log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?"));
356 t = filter("stanzas/out", t);
359 t = filter("bytes/out", tostring(t));
361 return w(conn, tostring(t));
366 -- Register this outgoing connection so that xmppserver_listener knows about it
367 -- otherwise it will assume it is a new incoming connection
368 cl.register_outgoing(conn, host_session);
370 host_session:open_stream(from_host, to_host);
372 log("debug", "Connection attempt in progress...");
373 add_task(connect_timeout, function ()
374 if host_session.conn ~= conn or
375 host_session.type == "s2sout" or
376 host_session.connecting then
377 return; -- Ok, we're connect[ed|ing]
379 -- Not connected, need to close session and clean up
380 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
381 host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
382 host_session:close("connection-timeout");
387 function session_open_stream(session, from, to)
388 session.sends2s(st.stanza("stream:stream", {
389 xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
390 ["xmlns:stream"]='http://etherx.jabber.org/streams',
391 from=from, to=to, version='1.0', ["xml:lang"]='en'}):top_tag());
394 function streamopened(session, attr)
395 local send = session.sends2s;
397 -- TODO: #29: SASL/TLS on s2s streams
398 session.version = tonumber(attr.version) or 0;
400 if session.secure == false then
401 session.secure = true;
404 if session.direction == "incoming" then
405 -- Send a reply stream header
406 session.to_host = attr.to and nameprep(attr.to);
407 session.from_host = attr.from and nameprep(attr.from);
409 session.streamid = uuid_gen();
410 (session.log or log)("debug", "incoming s2s received <stream:stream>");
411 if session.to_host then
412 if not hosts[session.to_host] then
413 -- Attempting to connect to a host we don't serve
415 condition = "host-unknown";
416 text = "This host does not serve "..session.to_host
419 elseif hosts[session.to_host].disallow_s2s then
420 -- Attempting to connect to a host that disallows s2s
422 condition = "policy-violation";
423 text = "Server-to-server communication is not allowed to this host";
428 send("<?xml version='1.0'?>");
429 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
430 ["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());
431 if session.version >= 1.0 then
432 local features = st.stanza("stream:features");
434 if session.to_host then
435 hosts[session.to_host].events.fire_event("s2s-stream-features", { origin = session, features = features });
437 (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");
440 log("debug", "Sending stream features: %s", tostring(features));
443 elseif session.direction == "outgoing" then
444 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
445 if not attr.id then error("stream response did not give us a streamid!!!"); end
446 session.streamid = attr.id;
448 -- Send unauthed buffer
449 -- (stanzas which are fine to send before dialback)
450 -- Note that this is *not* the stanza queue (which
451 -- we can only send if auth succeeds) :)
452 local send_buffer = session.send_buffer;
453 if send_buffer and #send_buffer > 0 then
454 log("debug", "Sending s2s send_buffer now...");
455 for i, data in ipairs(send_buffer) do
456 session.sends2s(tostring(data));
457 send_buffer[i] = nil;
460 session.send_buffer = nil;
462 -- If server is pre-1.0, don't wait for features, just do dialback
463 if session.version < 1.0 then
464 if not session.dialback_verifying then
465 log("debug", "Initiating dialback...");
466 initiate_dialback(session);
468 mark_connected(session);
472 session.notopen = nil;
475 function streamclosed(session)
476 (session.log or log)("debug", "Received </stream:stream>");
480 function initiate_dialback(session)
481 -- generate dialback key
482 session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
483 session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
484 session.log("info", "sent dialback key on outgoing s2s stream");
487 function generate_dialback(id, to, from)
488 return sha256_hash(id..to..from..hosts[from].dialback_secret, true);
491 function verify_dialback(id, to, from, key)
492 return key == generate_dialback(id, to, from);
495 function make_authenticated(session, host)
496 if not session.secure then
497 local local_host = session.direction == "incoming" and session.to_host or session.from_host;
498 if config.get(local_host, "core", "s2s_require_encryption") then
500 condition = "policy-violation",
501 text = "Encrypted server-to-server communication is required but was not "
502 ..((session.direction == "outgoing" and "offered") or "used")
506 if session.type == "s2sout_unauthed" then
507 session.type = "s2sout";
508 elseif session.type == "s2sin_unauthed" then
509 session.type = "s2sin";
511 if not session.hosts[host] then session.hosts[host] = {}; end
512 session.hosts[host].authed = true;
514 elseif session.type == "s2sin" and host then
515 if not session.hosts[host] then session.hosts[host] = {}; end
516 session.hosts[host].authed = true;
520 session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
522 mark_connected(session);
527 -- Stream is authorised, and ready for normal stanzas
528 function mark_connected(session)
529 local sendq, send = session.sendq, session.sends2s;
531 local from, to = session.from_host, session.to_host;
533 session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
535 local send_to_host = send_to_host;
536 function session.send(data) return send_to_host(to, from, data); end
538 local event_data = { session = session };
539 if session.type == "s2sout" then
540 prosody.events.fire_event("s2sout-established", event_data);
541 hosts[session.from_host].events.fire_event("s2sout-established", event_data);
543 prosody.events.fire_event("s2sin-established", event_data);
544 hosts[session.to_host].events.fire_event("s2sin-established", event_data);
547 if session.direction == "outgoing" then
549 session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
550 for i, data in ipairs(sendq) do
557 session.srv_hosts = nil;
561 local resting_session = { -- Resting, not dead
563 type = "s2s_destroyed";
564 open_stream = function (session)
565 session.log("debug", "Attempt to open stream on resting session");
567 close = function (session)
568 session.log("debug", "Attempt to close already-closed session");
570 filter = function (type, data) return data; end;
571 }; resting_session.__index = resting_session;
573 function retire_session(session, reason)
574 local log = session.log or log;
575 for k in pairs(session) do
576 if k ~= "trace" and k ~= "log" and k ~= "id" then
581 session.destruction_reason = reason;
583 function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
584 function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
585 return setmetatable(session, resting_session);
588 function destroy_session(session, reason)
589 if session.destroyed then return; end
590 (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
592 if session.direction == "outgoing" then
593 hosts[session.from_host].s2sout[session.to_host] = nil;
594 bounce_sendq(session, reason);
595 elseif session.direction == "incoming" then
596 incoming_s2s[session] = nil;
599 local event_data = { session = session, reason = reason };
600 if session.type == "s2sout" then
601 prosody.events.fire_event("s2sout-destroyed", event_data);
602 if hosts[session.from_host] then
603 hosts[session.from_host].events.fire_event("s2sout-destroyed", event_data);
605 elseif session.type == "s2sin" then
606 prosody.events.fire_event("s2sin-destroyed", event_data);
607 if hosts[session.to_host] then
608 hosts[session.to_host].events.fire_event("s2sin-destroyed", event_data);
612 retire_session(session, reason); -- Clean session until it is GC'd