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 = prosody.events.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 15;
46 local max_dns_depth = config.get("*", "core", "dns_max_depth") or 3;
48 dns.settimeout(dns_timeout);
50 local prosody = _G.prosody;
52 prosody.incoming_s2s = incoming_s2s;
53 local incoming_s2s = incoming_s2s;
57 function compare_srv_priorities(a,b)
58 return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight);
61 local bouncy_stanzas = { message = true, presence = true, iq = true };
62 local function bounce_sendq(session, reason)
63 local sendq = session.sendq;
65 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
69 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
73 for i, data in ipairs(sendq) do
74 local reply = data[2];
75 local xmlns = reply.attr.xmlns;
76 if not(xmlns) and bouncy_stanzas[reply.name] then
77 reply.attr.type = "error";
78 reply:tag("error", {type = "cancel"})
79 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
81 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):text("Connection failed: "..reason):up();
83 core_process_stanza(dummy, reply);
91 function send_to_host(from_host, to_host, data)
92 if not hosts[from_host] then
93 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
96 local host = hosts[from_host].s2sout[to_host];
98 -- We have a connection to this host already
99 if host.type == "s2sout_unauthed" and (data.name ~= "db:verify" or not host.dialback_key) then
100 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
102 -- Queue stanza until we are able to send it
103 if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
104 else host.sendq = { {tostring(data), st.reply(data)} }; end
105 host.log("debug", "stanza [%s] queued ", data.name);
106 elseif host.type == "local" or host.type == "component" then
107 log("error", "Trying to send a stanza to ourselves??")
108 log("error", "Traceback: %s", get_traceback());
109 log("error", "Stanza: %s", tostring(data));
111 (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
113 if host.from_host ~= from_host then
114 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
115 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
118 host.log("debug", "stanza sent over "..host.type);
121 log("debug", "opening a new outgoing connection for this stanza");
122 local host_session = new_outgoing(from_host, to_host);
125 host_session.sendq = { {tostring(data), st.reply(data)} };
126 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
127 if (not host_session.connecting) and (not host_session.conn) then
128 log("warn", "Connection to %s failed already, destroying session...", to_host);
129 destroy_session(host_session);
134 local open_sessions = 0;
136 function new_incoming(conn)
137 local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
139 session.trace = newproxy(true);
140 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
142 open_sessions = open_sessions + 1;
143 local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
145 local filter = initialize_filters(session);
146 session.sends2s = function (t)
147 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
149 t = filter("stanzas/out", t);
152 t = filter("bytes/out", tostring(t));
158 incoming_s2s[session] = true;
159 add_task(connect_timeout, function ()
160 if session.conn ~= conn or
161 session.type == "s2sin" then
162 return; -- Ok, we're connect[ed|ing]
164 -- Not connected, need to close session and clean up
165 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
166 session.from_host or "(unknown)", session.to_host or "(unknown)");
167 session:close("connection-timeout");
172 function new_outgoing(from_host, to_host, connect)
173 local host_session = { to_host = to_host, from_host = from_host, host = from_host,
174 notopen = true, type = "s2sout_unauthed", direction = "outgoing",
175 open_stream = session_open_stream };
177 hosts[from_host].s2sout[to_host] = host_session;
181 local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
182 log = logger_init(conn_name);
183 host_session.log = log;
186 initialize_filters(host_session);
188 if connect ~= false then
189 -- Kick the connection attempting machine into life
190 attempt_connection(host_session);
193 if not host_session.sends2s then
194 -- A sends2s which buffers data (until the stream is opened)
195 -- note that data in this buffer will be sent before the stream is authed
196 -- and will not be ack'd in any way, successful or otherwise
198 function host_session.sends2s(data)
201 host_session.send_buffer = buffer;
203 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
204 buffer[#buffer+1] = data;
205 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
213 function attempt_connection(host_session, err)
214 local from_host, to_host = host_session.from_host, host_session.to_host;
215 local connect_host, connect_port = to_host and idna_to_ascii(to_host), 5269;
217 if not connect_host then
221 if not err then -- This is our first attempt
222 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
223 host_session.connecting = true;
225 handle = adns.lookup(function (answer)
227 host_session.connecting = nil;
229 log("debug", to_host.." has SRV records, handling...");
230 local srv_hosts = {};
231 host_session.srv_hosts = srv_hosts;
232 for _, record in ipairs(answer) do
233 t_insert(srv_hosts, record.srv);
235 t_sort(srv_hosts, compare_srv_priorities);
237 local srv_choice = srv_hosts[1];
238 host_session.srv_choice = 1;
240 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
241 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
244 log("debug", to_host.." has no SRV records, falling back to A");
246 -- Try with SRV, or just the plain hostname if no SRV
247 local ok, err = try_connect(host_session, connect_host, connect_port);
249 if not attempt_connection(host_session, err) then
250 -- No more attempts will be made
251 destroy_session(host_session, err);
254 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
256 return true; -- Attempt in progress
257 elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
258 host_session.srv_choice = host_session.srv_choice + 1;
259 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
260 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
261 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
263 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
264 -- We're out of options
268 if not (connect_host and connect_port) then
269 -- Likely we couldn't resolve DNS
270 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));
274 return try_connect(host_session, connect_host, connect_port);
277 function try_connect(host_session, connect_host, connect_port)
278 host_session.connecting = true;
280 handle = adns.lookup(function (reply)
282 host_session.connecting = nil;
284 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
285 if not (reply and reply[#reply] and reply[#reply].a) then
286 local count = max_dns_depth;
287 reply = dns.peek(connect_host, "CNAME", "IN");
288 while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
289 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
290 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
294 -- end of CNAME resolving
296 if reply and reply[#reply] and reply[#reply].a then
297 log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
298 return make_connect(host_session, reply[#reply].a, connect_port);
300 log("debug", "DNS lookup failed to get a response for %s", connect_host);
301 if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
302 log("debug", "No other records to try for %s - destroying", host_session.to_host);
303 destroy_session(host_session, "DNS resolution failed"); -- End of the line, we can't
306 end, connect_host, "A", "IN");
311 function make_connect(host_session, connect_host, connect_port)
312 (host_session.log or log)("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
313 -- Ok, we're going to try to connect
315 local from_host, to_host = host_session.from_host, host_session.to_host;
317 local conn, handler = socket.tcp()
320 log("warn", "Failed to create outgoing connection, system error: %s", handler);
321 return false, handler;
325 local success, err = conn:connect(connect_host, connect_port);
326 if not success and err ~= "timeout" then
327 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
331 local cl = connlisteners_get("xmppserver");
332 conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1 );
333 host_session.conn = conn;
335 local filter = initialize_filters(host_session);
336 local w, log = conn.write, host_session.log;
337 host_session.sends2s = function (t)
338 log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?"));
340 t = filter("stanzas/out", t);
343 t = filter("bytes/out", tostring(t));
345 return w(conn, tostring(t));
350 -- Register this outgoing connection so that xmppserver_listener knows about it
351 -- otherwise it will assume it is a new incoming connection
352 cl.register_outgoing(conn, host_session);
354 host_session:open_stream(from_host, to_host);
356 log("debug", "Connection attempt in progress...");
357 add_task(connect_timeout, function ()
358 if host_session.conn ~= conn or
359 host_session.type == "s2sout" or
360 host_session.connecting then
361 return; -- Ok, we're connect[ed|ing]
363 -- Not connected, need to close session and clean up
364 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity",
365 host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
366 host_session:close("connection-timeout");
371 function session_open_stream(session, from, to)
372 session.sends2s(st.stanza("stream:stream", {
373 xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
374 ["xmlns:stream"]='http://etherx.jabber.org/streams',
375 from=from, to=to, version='1.0', ["xml:lang"]='en'}):top_tag());
378 function streamopened(session, attr)
379 local send = session.sends2s;
381 -- TODO: #29: SASL/TLS on s2s streams
382 session.version = tonumber(attr.version) or 0;
384 if session.secure == false then
385 session.secure = true;
388 if session.direction == "incoming" then
389 -- Send a reply stream header
390 session.to_host = attr.to and nameprep(attr.to);
391 session.from_host = attr.from and nameprep(attr.from);
393 session.streamid = uuid_gen();
394 (session.log or log)("debug", "incoming s2s received <stream:stream>");
395 if session.to_host then
396 if not hosts[session.to_host] then
397 -- Attempting to connect to a host we don't serve
399 condition = "host-unknown";
400 text = "This host does not serve "..session.to_host
403 elseif hosts[session.to_host].disallow_s2s then
404 -- Attempting to connect to a host that disallows s2s
406 condition = "policy-violation";
407 text = "Server-to-server communication is not allowed to this host";
412 send("<?xml version='1.0'?>");
413 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback',
414 ["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());
415 if session.version >= 1.0 then
416 local features = st.stanza("stream:features");
418 if session.to_host then
419 hosts[session.to_host].events.fire_event("s2s-stream-features", { origin = session, features = features });
421 (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");
424 log("debug", "Sending stream features: %s", tostring(features));
427 elseif session.direction == "outgoing" then
428 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
429 if not attr.id then error("stream response did not give us a streamid!!!"); end
430 session.streamid = attr.id;
432 -- Send unauthed buffer
433 -- (stanzas which are fine to send before dialback)
434 -- Note that this is *not* the stanza queue (which
435 -- we can only send if auth succeeds) :)
436 local send_buffer = session.send_buffer;
437 if send_buffer and #send_buffer > 0 then
438 log("debug", "Sending s2s send_buffer now...");
439 for i, data in ipairs(send_buffer) do
440 session.sends2s(tostring(data));
441 send_buffer[i] = nil;
444 session.send_buffer = nil;
446 -- If server is pre-1.0, don't wait for features, just do dialback
447 if session.version < 1.0 then
448 if not session.dialback_verifying then
449 log("debug", "Initiating dialback...");
450 initiate_dialback(session);
452 mark_connected(session);
456 session.notopen = nil;
459 function streamclosed(session)
460 (session.log or log)("debug", "Received </stream:stream>");
464 function initiate_dialback(session)
465 -- generate dialback key
466 session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
467 session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
468 session.log("info", "sent dialback key on outgoing s2s stream");
471 function generate_dialback(id, to, from)
472 return sha256_hash(id..to..from..hosts[from].dialback_secret, true);
475 function verify_dialback(id, to, from, key)
476 return key == generate_dialback(id, to, from);
479 function make_authenticated(session, host)
480 if not session.secure then
481 local local_host = session.direction == "incoming" and session.to_host or session.from_host;
482 if config.get(local_host, "core", "s2s_require_encryption") then
484 condition = "policy-violation",
485 text = "Encrypted server-to-server communication is required but was not "
486 ..((session.direction == "outgoing" and "offered") or "used")
490 if session.type == "s2sout_unauthed" then
491 session.type = "s2sout";
492 elseif session.type == "s2sin_unauthed" then
493 session.type = "s2sin";
495 session.hosts[host].authed = true;
497 elseif session.type == "s2sin" and host then
498 session.hosts[host].authed = true;
502 session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
504 mark_connected(session);
509 -- Stream is authorised, and ready for normal stanzas
510 function mark_connected(session)
511 local sendq, send = session.sendq, session.sends2s;
513 local from, to = session.from_host, session.to_host;
515 session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
517 local send_to_host = send_to_host;
518 function session.send(data) send_to_host(to, from, data); end
520 local event_data = { session = session };
521 if session.type == "s2sout" then
522 prosody.events.fire_event("s2sout-established", event_data);
523 hosts[session.from_host].events.fire_event("s2sout-established", event_data);
525 prosody.events.fire_event("s2sin-established", event_data);
526 hosts[session.to_host].events.fire_event("s2sin-established", event_data);
529 if session.direction == "outgoing" then
531 session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
532 for i, data in ipairs(sendq) do
539 session.srv_hosts = nil;
543 local resting_session = { -- Resting, not dead
545 type = "s2s_destroyed";
546 open_stream = function (session)
547 session.log("debug", "Attempt to open stream on resting session");
549 close = function (session)
550 session.log("debug", "Attempt to close already-closed session");
552 filter = function (type, data) return data; end;
553 }; resting_session.__index = resting_session;
555 function retire_session(session)
556 local log = session.log or log;
557 for k in pairs(session) do
558 if k ~= "trace" and k ~= "log" and k ~= "id" then
563 function session.send(data) log("debug", "Discarding data sent to resting session: %s", tostring(data)); end
564 function session.data(data) log("debug", "Discarding data received from resting session: %s", tostring(data)); end
565 return setmetatable(session, resting_session);
568 function destroy_session(session, reason)
569 if session.destroyed then return; end
570 (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
572 if session.direction == "outgoing" then
573 hosts[session.from_host].s2sout[session.to_host] = nil;
574 bounce_sendq(session, reason);
575 elseif session.direction == "incoming" then
576 incoming_s2s[session] = nil;
579 local event_data = { session = session, reason = reason };
580 if session.type == "s2sout" then
581 prosody.events.fire_event("s2sout-destroyed", event_data);
582 if hosts[session.from_host] then
583 hosts[session.from_host].events.fire_event("s2sout-destroyed", event_data);
585 elseif session.type == "s2sin" then
586 prosody.events.fire_event("s2sin-destroyed", event_data);
587 if hosts[session.to_host] then
588 hosts[session.to_host].events.fire_event("s2sin-destroyed", event_data);
592 retire_session(session); -- Clean session until it is GC'd