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.
11 local prosody = prosody;
12 local hosts = prosody.hosts;
13 local core_process_stanza = prosody.core_process_stanza;
15 local tostring, type = tostring, type;
16 local t_insert = table.insert;
17 local xpcall, traceback = xpcall, debug.traceback;
19 local add_task = require "util.timer".add_task;
20 local st = require "util.stanza";
21 local initialize_filters = require "util.filters".initialize;
22 local nameprep = require "util.encodings".stringprep.nameprep;
23 local new_xmpp_stream = require "util.xmppstream".new;
24 local s2s_new_incoming = require "core.s2smanager".new_incoming;
25 local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
26 local s2s_destroy_session = require "core.s2smanager".destroy_session;
27 local uuid_gen = require "util.uuid".generate;
28 local fire_global_event = prosody.events.fire_event;
29 local runner = require "util.async".runner;
31 local s2sout = module:require("s2sout");
33 local connect_timeout = module:get_option_number("s2s_timeout", 90);
34 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
35 local opt_keepalives = module:get_option_boolean("s2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
36 local secure_auth = module:get_option_boolean("s2s_secure_auth", false); -- One day...
37 local secure_domains, insecure_domains =
38 module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
39 local require_encryption = module:get_option_boolean("s2s_require_encryption", false);
41 local measure_connections = module:measure("connections", "counter");
43 local sessions = module:shared("sessions");
45 local runner_callbacks = {};
47 local log = module._log;
49 --- Handle stanzas to remote domains
51 local bouncy_stanzas = { message = true, presence = true, iq = true };
52 local function bounce_sendq(session, reason)
53 local sendq = session.sendq;
54 if not sendq then return; end
55 session.log("info", "Sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
59 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
63 (session.log or log)("error", "Attempting to close the dummy origin of s2s error replies, please report this! Traceback: %s", traceback());
66 for i, data in ipairs(sendq) do
67 local reply = data[2];
68 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
69 reply.attr.type = "error";
70 reply:tag("error", {type = "cancel"})
71 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
73 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
74 :text("Server-to-server connection failed: "..reason):up();
76 core_process_stanza(dummy, reply);
83 -- Handles stanzas to existing s2s sessions
84 function route_to_existing_session(event)
85 local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
86 if not hosts[from_host] then
87 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
90 if hosts[to_host] then
91 log("warn", "Attempt to route stanza to a remote %s - a host we do serve?!", from_host);
94 local host = hosts[from_host].s2sout[to_host];
96 -- We have a connection to this host already
97 if host.type == "s2sout_unauthed" and (stanza.name ~= "db:verify" or not host.dialback_key) then
98 (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
100 -- Queue stanza until we are able to send it
101 if host.sendq then t_insert(host.sendq, {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)});
102 else host.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} }; end
103 host.log("debug", "stanza [%s] queued ", stanza.name);
105 elseif host.type == "local" or host.type == "component" then
106 log("error", "Trying to send a stanza to ourselves??")
107 log("error", "Traceback: %s", traceback());
108 log("error", "Stanza: %s", tostring(stanza));
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));
117 if host.sends2s(stanza) then
118 host.log("debug", "stanza sent over %s", host.type);
125 -- Create a new outgoing session for a stanza
126 function route_to_new_session(event)
127 local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
128 log("debug", "opening a new outgoing connection for this stanza");
129 local host_session = s2s_new_outgoing(from_host, to_host);
132 host_session.bounce_sendq = bounce_sendq;
133 host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
134 log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));
135 s2sout.initiate_connection(host_session);
136 if (not host_session.connecting) and (not host_session.conn) then
137 log("warn", "Connection to %s failed already, destroying session...", to_host);
138 s2s_destroy_session(host_session, "Connection failed");
144 local function keepalive(event)
145 return event.session.sends2s(' ');
148 module:hook("s2s-read-timeout", keepalive, -1);
150 function module.add_host(module)
151 if module:get_option_boolean("disallow_s2s", false) then
152 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see https://prosody.im/doc/s2s#disabling");
153 return nil, "This host has disallow_s2s set";
155 module:hook("route/remote", route_to_existing_session, -1);
156 module:hook("route/remote", route_to_new_session, -10);
157 module:hook("s2s-authenticated", make_authenticated, -1);
158 module:hook("s2s-read-timeout", keepalive, -1);
159 module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
160 if session.type == "s2sout" then
161 -- Stream is authenticated and we are seem to be done with feature negotiation,
162 -- so the stream is ready for stanzas. RFC 6120 Section 4.3
163 mark_connected(session);
165 elseif not session.dialback_verifying then
166 session.log("warn", "No SASL EXTERNAL offer and Dialback doesn't seem to be enabled, giving up");
173 -- Stream is authorised, and ready for normal stanzas
174 function mark_connected(session)
175 local sendq = session.sendq;
177 local from, to = session.from_host, session.to_host;
179 session.log("info", "%s s2s connection %s->%s complete", session.direction:gsub("^.", string.upper), from, to);
181 local event_data = { session = session };
182 if session.type == "s2sout" then
183 fire_global_event("s2sout-established", event_data);
184 hosts[from].events.fire_event("s2sout-established", event_data);
186 local host_session = hosts[to];
187 session.send = function(stanza)
188 return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
191 fire_global_event("s2sin-established", event_data);
192 hosts[to].events.fire_event("s2sin-established", event_data);
195 if session.direction == "outgoing" then
197 session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
198 local send = session.sends2s;
199 for i, data in ipairs(sendq) do
206 session.ip_hosts = nil;
207 session.srv_hosts = nil;
211 function make_authenticated(event)
212 local session, host = event.session, event.host;
213 if not session.secure then
214 if require_encryption or (secure_auth and not(insecure_domains[host])) or secure_domains[host] then
216 condition = "policy-violation",
217 text = "Encrypted server-to-server communication is required but was not "
218 ..((session.direction == "outgoing" and "offered") or "used")
223 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
225 if session.type == "s2sout_unauthed" then
226 session.type = "s2sout";
227 elseif session.type == "s2sin_unauthed" then
228 session.type = "s2sin";
230 if not session.hosts[host] then session.hosts[host] = {}; end
231 session.hosts[host].authed = true;
233 elseif session.type == "s2sin" and host then
234 if not session.hosts[host] then session.hosts[host] = {}; end
235 session.hosts[host].authed = true;
239 session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
241 if (session.type == "s2sout" and session.external_auth ~= "succeeded") or session.type == "s2sin" then
242 -- Stream either used dialback for authentication or is an incoming stream.
243 mark_connected(session);
249 --- Helper to check that a session peer's certificate is valid
250 function check_cert_status(session)
251 local host = session.direction == "outgoing" and session.to_host or session.from_host
252 local conn = session.conn:socket()
254 if conn.getpeercertificate then
255 cert = conn:getpeercertificate()
258 return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
261 --- XMPP stream event handlers
263 local stream_callbacks = { default_ns = "jabber:server" };
265 function stream_callbacks.handlestanza(session, stanza)
266 stanza = session.filter("stanzas/in", stanza);
267 session.thread:run(stanza);
270 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
272 function stream_callbacks.streamopened(session, attr)
273 -- run _streamopened in async context
274 session.thread:run({ attr = attr });
277 function stream_callbacks._streamopened(session, attr)
278 session.version = tonumber(attr.version) or 0;
280 -- TODO: Rename session.secure to session.encrypted
281 if session.secure == false then
282 session.secure = true;
283 session.encrypted = true;
285 local sock = session.conn:socket();
287 local info = sock:info();
288 (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
289 session.compressed = info.compression;
291 (session.log or log)("info", "Stream encrypted");
292 session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
296 if session.direction == "incoming" then
297 -- Send a reply stream header
300 local to, from = nameprep(attr.to), nameprep(attr.from);
301 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
302 session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
305 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
306 session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
310 -- Set session.[from/to]_host if they have not been set already and if
311 -- this session isn't already authenticated
312 if session.type == "s2sin_unauthed" and from and not session.from_host then
313 session.from_host = from;
314 elseif from ~= session.from_host then
315 session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
318 if session.type == "s2sin_unauthed" and to and not session.to_host then
319 session.to_host = to;
320 elseif to ~= session.to_host then
321 session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
325 -- For convenience we'll put the sanitised values into these variables
326 to, from = session.to_host, session.from_host;
328 session.streamid = uuid_gen();
329 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
331 if not hosts[to] then
332 -- Attempting to connect to a host we don't serve
334 condition = "host-unknown";
335 text = "This host does not serve "..to
338 elseif not hosts[to].modules.s2s then
339 -- Attempting to connect to a host that disallows s2s
341 condition = "policy-violation";
342 text = "Server-to-server communication is disabled for this host";
349 session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
353 if session.secure and not session.cert_chain_status then
354 if check_cert_status(session) == false then
359 session:open_stream(session.to_host, session.from_host)
360 session.notopen = nil;
361 if session.version >= 1.0 then
362 local features = st.stanza("stream:features");
365 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
367 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", from or session.ip or "unknown host");
368 fire_global_event("s2s-stream-features-legacy", { origin = session, features = features });
371 if ( session.type == "s2sin" or session.type == "s2sout" ) or features.tags[1] then
372 log("debug", "Sending stream features: %s", tostring(features));
373 session.sends2s(features);
375 (session.log or log)("warn", "No features to offer, giving up");
376 session:close({ condition = "undefined-condition", text = "No features to offer" });
379 elseif session.direction == "outgoing" then
380 session.notopen = nil;
382 log("error", "Stream response from %s did not give us a stream id!", session.to_host);
383 session:close({ condition = "undefined-condition", text = "Missing stream ID" });
386 session.streamid = attr.id;
388 if session.secure and not session.cert_chain_status then
389 if check_cert_status(session) == false then
394 -- Send unauthed buffer
395 -- (stanzas which are fine to send before dialback)
396 -- Note that this is *not* the stanza queue (which
397 -- we can only send if auth succeeds) :)
398 local send_buffer = session.send_buffer;
399 if send_buffer and #send_buffer > 0 then
400 log("debug", "Sending s2s send_buffer now...");
401 for i, data in ipairs(send_buffer) do
402 session.sends2s(tostring(data));
403 send_buffer[i] = nil;
406 session.send_buffer = nil;
408 -- If server is pre-1.0, don't wait for features, just do dialback
409 if session.version < 1.0 then
410 if not session.dialback_verifying then
411 hosts[session.from_host].events.fire_event("s2sout-authenticate-legacy", { origin = session });
413 mark_connected(session);
419 function stream_callbacks.streamclosed(session)
420 (session.log or log)("debug", "Received </stream:stream>");
421 session:close(false);
424 function stream_callbacks.error(session, error, data)
425 if error == "no-stream" then
426 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
427 session:close("invalid-namespace");
428 elseif error == "parse-error" then
429 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
430 session:close("not-well-formed");
431 elseif error == "stream-error" then
432 local condition, text = "undefined-condition";
433 for child in data:children() do
434 if child.attr.xmlns == xmlns_xmpp_streams then
435 if child.name ~= "text" then
436 condition = child.name;
438 text = child:get_text();
440 if condition ~= "undefined-condition" and text then
445 text = condition .. (text and (" ("..text..")") or "");
446 session.log("info", "Session closed by remote with error: %s", text);
447 session:close(nil, text);
454 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
455 local function session_close(session, reason, remote_reason)
456 local log = session.log or log;
458 if session.notopen then
459 if session.direction == "incoming" then
460 session:open_stream(session.to_host, session.from_host);
462 session:open_stream(session.from_host, session.to_host);
465 if reason then -- nil == no err, initiated by us, false == initiated by remote
466 if type(reason) == "string" then -- assume stream error
467 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, reason);
468 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
469 elseif type(reason) == "table" then
470 if reason.condition then
471 local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
473 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
476 stanza:add_child(reason.extra);
478 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, tostring(stanza));
479 session.sends2s(stanza);
480 elseif reason.name then -- a stanza
481 log("debug", "Disconnecting %s->%s[%s], <stream:error> is: %s", session.from_host or "(unknown host)", session.to_host or "(unknown host)", session.type, tostring(reason));
482 session.sends2s(reason);
487 session.sends2s("</stream:stream>");
488 function session.sends2s() return false; end
490 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason;
491 session.log("info", "%s s2s stream %s->%s closed: %s", session.direction:gsub("^.", string.upper), session.from_host or "(unknown host)", session.to_host or "(unknown host)", reason or "stream closed");
493 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
494 local conn = session.conn;
495 if reason == nil and not session.notopen and session.type == "s2sin" then
496 add_task(stream_close_timeout, function ()
497 if not session.destroyed then
498 session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
499 s2s_destroy_session(session, reason);
504 s2s_destroy_session(session, reason);
505 conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
510 function session_stream_attrs(session, from, to, attr)
511 if not from or (hosts[from] and hosts[from].modules.dialback) then
512 attr["xmlns:db"] = 'jabber:server:dialback';
522 -- Session initialization logic shared by incoming and outgoing
523 local function initialize_session(session)
524 local stream = new_xmpp_stream(session, stream_callbacks);
526 session.thread = runner(function (stanza)
527 if stanza.name == nil then
528 stream_callbacks._streamopened(session, stanza.attr);
530 core_process_stanza(session, stanza);
532 end, runner_callbacks, session);
534 local log = session.log or log;
535 session.stream = stream;
537 session.notopen = true;
539 function session.reset_stream()
540 session.notopen = true;
541 session.streamid = nil;
542 session.stream:reset();
545 session.stream_attrs = session_stream_attrs;
547 local filter = initialize_filters(session);
548 local conn = session.conn;
549 local w = conn.write;
551 function session.sends2s(t)
552 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^[^>]*>?"));
554 t = filter("stanzas/out", t);
557 t = filter("bytes/out", tostring(t));
564 function session.data(data)
565 data = filter("bytes/in", data);
567 local ok, err = stream:feed(data);
568 if ok then return; end
569 log("warn", "Received invalid XML: %s", data);
570 log("warn", "Problem was: %s", err);
571 session:close("not-well-formed");
575 session.close = session_close;
577 local handlestanza = stream_callbacks.handlestanza;
578 function session.dispatch_stanza(session, stanza)
579 return handlestanza(session, stanza);
582 module:fire_event("s2s-created", { session = session });
584 add_task(connect_timeout, function ()
585 if session.type == "s2sin" or session.type == "s2sout" then
586 return; -- Ok, we're connected
587 elseif session.type == "s2s_destroyed" then
588 return; -- Session already destroyed
590 -- Not connected, need to close session and clean up
591 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
592 session.from_host or "(unknown)", session.to_host or "(unknown)");
593 session:close("connection-timeout");
597 function runner_callbacks:ready()
598 self.data.log("debug", "Runner %s ready (%s)", self.thread, coroutine.status(self.thread));
599 self.data.conn:resume();
602 function runner_callbacks:waiting()
603 self.data.log("debug", "Runner %s waiting (%s)", self.thread, coroutine.status(self.thread));
604 self.data.conn:pause();
607 function runner_callbacks:error(err)
608 (self.data.log or log)("error", "Traceback[s2s]: %s", err);
611 function listener.onconnect(conn)
612 measure_connections(1);
613 conn:setoption("keepalive", opt_keepalives);
614 local session = sessions[conn];
615 if not session then -- New incoming connection
616 session = s2s_new_incoming(conn);
617 sessions[conn] = session;
618 session.log("debug", "Incoming s2s connection");
619 initialize_session(session);
620 else -- Outgoing session connected
621 session:open_stream(session.from_host, session.to_host);
623 session.ip = conn:ip();
626 function listener.onincoming(conn, data)
627 local session = sessions[conn];
633 function listener.onstatus(conn, status)
634 if status == "ssl-handshake-complete" then
635 local session = sessions[conn];
636 if session and session.direction == "outgoing" then
637 session.log("debug", "Sending stream header...");
638 session:open_stream(session.from_host, session.to_host);
643 function listener.ontimeout(conn)
644 -- Called instead of onconnect when the connection times out
645 measure_connections(1);
648 function listener.ondisconnect(conn, err)
649 measure_connections(-1);
650 local session = sessions[conn];
652 sessions[conn] = nil;
653 if err and session.direction == "outgoing" and session.notopen then
654 (session.log or log)("debug", "s2s connection attempt failed: %s", err);
655 if s2sout.attempt_connection(session, err) then
656 return; -- Session lives for now
659 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
660 s2s_destroy_session(session, err);
664 function listener.onreadtimeout(conn)
665 local session = sessions[conn];
666 local host = session.host or session.to_host;
668 return (hosts[host] or prosody).events.fire_event("s2s-read-timeout", { session = session });
672 function listener.register_outgoing(conn, session)
673 sessions[conn] = session;
674 initialize_session(session);
677 function listener.ondetach(conn)
678 sessions[conn] = nil;
681 function check_auth_policy(event)
682 local host, session = event.host, event.session;
683 local must_secure = secure_auth;
685 if not must_secure and secure_domains[host] then
687 elseif must_secure and insecure_domains[host] then
691 if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") then
692 module:log("warn", "Forbidding insecure connection to/from %s", host or session.ip or "(unknown host)");
693 if session.direction == "incoming" then
694 session:close({ condition = "not-authorized", text = "Your server's certificate is invalid, expired, or not trusted by "..session.to_host });
695 else -- Close outgoing connections without warning
696 session:close(false);
702 module:hook("s2s-check-certificate", check_auth_policy, -1);
704 s2sout.set_listener(listener);
706 module:hook("server-stopping", function(event)
707 local reason = event.reason;
708 for _, session in pairs(sessions) do
709 session:close{ condition = "system-shutdown", text = reason };
715 module:provides("net", {
719 encryption = "starttls";
721 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";