Merge 0.10->trunk
[prosody.git] / plugins / mod_s2s / mod_s2s.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 module:set_global();
10
11 local prosody = prosody;
12 local hosts = prosody.hosts;
13 local core_process_stanza = prosody.core_process_stanza;
14
15 local tostring, type = tostring, type;
16 local t_insert = table.insert;
17 local xpcall, traceback = xpcall, debug.traceback;
18
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;
30
31 local s2sout = module:require("s2sout");
32
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);
40
41 local measure_connections = module:measure("connections", "counter");
42
43 local sessions = module:shared("sessions");
44
45 local runner_callbacks = {};
46
47 local log = module._log;
48
49 --- Handle stanzas to remote domains
50
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));
56         local dummy = {
57                 type = "s2sin";
58                 send = function(s)
59                         (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
60                 end;
61                 dummy = true;
62                 close = function ()
63                         (session.log or log)("error", "Attempting to close the dummy origin of s2s error replies, please report this! Traceback: %s", traceback());
64                 end;
65         };
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();
72                         if reason then
73                                 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
74                                         :text("Server-to-server connection failed: "..reason):up();
75                         end
76                         core_process_stanza(dummy, reply);
77                 end
78                 sendq[i] = nil;
79         end
80         session.sendq = nil;
81 end
82
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);
88                 return false;
89         end
90         if hosts[to_host] then
91                 log("warn", "Attempt to route stanza to a remote %s - a host we do serve?!", from_host);
92                 return false;
93         end
94         local host = hosts[from_host].s2sout[to_host];
95         if host then
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);
99
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);
104                         return true;
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));
109                         return false;
110                 else
111                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
112                         -- FIXME
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));
116                         end
117                         if host.sends2s(stanza) then
118                                 host.log("debug", "stanza sent over %s", host.type);
119                                 return true;
120                         end
121                 end
122         end
123 end
124
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);
130
131         -- Store in buffer
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");
139                 return false;
140         end
141         return true;
142 end
143
144 local function keepalive(event)
145         return event.session.sends2s(' ');
146 end
147
148 module:hook("s2s-read-timeout", keepalive, -1);
149
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";
154         end
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);
164                         return true;
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");
167                         session:close();
168                         return false;
169                 end
170         end, -1);
171 end
172
173 -- Stream is authorised, and ready for normal stanzas
174 function mark_connected(session)
175         local sendq = session.sendq;
176
177         local from, to = session.from_host, session.to_host;
178
179         session.log("info", "%s s2s connection %s->%s complete", session.direction:gsub("^.", string.upper), from, to);
180
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);
185         else
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 });
189                 end;
190
191                 fire_global_event("s2sin-established", event_data);
192                 hosts[to].events.fire_event("s2sin-established", event_data);
193         end
194
195         if session.direction == "outgoing" then
196                 if sendq 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
200                                 send(data[1]);
201                                 sendq[i] = nil;
202                         end
203                         session.sendq = nil;
204                 end
205
206                 session.ip_hosts = nil;
207                 session.srv_hosts = nil;
208         end
209 end
210
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
215                         session:close({
216                                 condition = "policy-violation",
217                                 text = "Encrypted server-to-server communication is required but was not "
218                                        ..((session.direction == "outgoing" and "offered") or "used")
219                         });
220                 end
221         end
222         if hosts[host] then
223                 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
224         end
225         if session.type == "s2sout_unauthed" then
226                 session.type = "s2sout";
227         elseif session.type == "s2sin_unauthed" then
228                 session.type = "s2sin";
229                 if host then
230                         if not session.hosts[host] then session.hosts[host] = {}; end
231                         session.hosts[host].authed = true;
232                 end
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;
236         else
237                 return false;
238         end
239         session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
240
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);
244         end
245
246         return true;
247 end
248
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()
253         local cert
254         if conn.getpeercertificate then
255                 cert = conn:getpeercertificate()
256         end
257
258         return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
259 end
260
261 --- XMPP stream event handlers
262
263 local stream_callbacks = { default_ns = "jabber:server" };
264
265 function stream_callbacks.handlestanza(session, stanza)
266         stanza = session.filter("stanzas/in", stanza);
267         session.thread:run(stanza);
268 end
269
270 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
271
272 function stream_callbacks.streamopened(session, attr)
273         -- run _streamopened in async context
274         session.thread:run({ attr = attr });
275 end
276
277 function stream_callbacks._streamopened(session, attr)
278         session.version = tonumber(attr.version) or 0;
279
280         -- TODO: Rename session.secure to session.encrypted
281         if session.secure == false then
282                 session.secure = true;
283                 session.encrypted = true;
284
285                 local sock = session.conn:socket();
286                 if sock.info then
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;
290                 else
291                         (session.log or log)("info", "Stream encrypted");
292                         session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
293                 end
294         end
295
296         if session.direction == "incoming" then
297                 -- Send a reply stream header
298
299                 -- Validate to/from
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" });
303                         return;
304                 end
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" });
307                         return;
308                 end
309
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" });
316                         return;
317                 end
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" });
322                         return;
323                 end
324
325                 -- For convenience we'll put the sanitised values into these variables
326                 to, from = session.to_host, session.from_host;
327
328                 session.streamid = uuid_gen();
329                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
330                 if to then
331                         if not hosts[to] then
332                                 -- Attempting to connect to a host we don't serve
333                                 session:close({
334                                         condition = "host-unknown";
335                                         text = "This host does not serve "..to
336                                 });
337                                 return;
338                         elseif not hosts[to].modules.s2s then
339                                 -- Attempting to connect to a host that disallows s2s
340                                 session:close({
341                                         condition = "policy-violation";
342                                         text = "Server-to-server communication is disabled for this host";
343                                 });
344                                 return;
345                         end
346                 end
347
348                 if hosts[from] then
349                         session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
350                         return;
351                 end
352
353                 if session.secure and not session.cert_chain_status then
354                         if check_cert_status(session) == false then
355                                 return;
356                         end
357                 end
358
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");
363
364                         if to then
365                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
366                         else
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 });
369                         end
370
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);
374                         else
375                                 (session.log or log)("warn", "No features to offer, giving up");
376                                 session:close({ condition = "undefined-condition", text = "No features to offer" });
377                         end
378                 end
379         elseif session.direction == "outgoing" then
380                 session.notopen = nil;
381                 if not attr.id then
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" });
384                         return;
385                 end
386                 session.streamid = attr.id;
387
388                 if session.secure and not session.cert_chain_status then
389                         if check_cert_status(session) == false then
390                                 return;
391                         end
392                 end
393
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;
404                         end
405                 end
406                 session.send_buffer = nil;
407
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 });
412                         else
413                                 mark_connected(session);
414                         end
415                 end
416         end
417 end
418
419 function stream_callbacks.streamclosed(session)
420         (session.log or log)("debug", "Received </stream:stream>");
421         session:close(false);
422 end
423
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;
437                                 else
438                                         text = child:get_text();
439                                 end
440                                 if condition ~= "undefined-condition" and text then
441                                         break;
442                                 end
443                         end
444                 end
445                 text = condition .. (text and (" ("..text..")") or "");
446                 session.log("info", "Session closed by remote with error: %s", text);
447                 session:close(nil, text);
448         end
449 end
450
451 local listener = {};
452
453 --- Session methods
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;
457         if session.conn then
458                 if session.notopen then
459                         if session.direction == "incoming" then
460                                 session:open_stream(session.to_host, session.from_host);
461                         else
462                                 session:open_stream(session.from_host, session.to_host);
463                         end
464                 end
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();
472                                         if reason.text then
473                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
474                                         end
475                                         if reason.extra then
476                                                 stanza:add_child(reason.extra);
477                                         end
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);
483                                 end
484                         end
485                 end
486
487                 session.sends2s("</stream:stream>");
488                 function session.sends2s() return false; end
489
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");
492
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);
500                                         conn:close();
501                                 end
502                         end);
503                 else
504                         s2s_destroy_session(session, reason);
505                         conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
506                 end
507         end
508 end
509
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';
513         end
514         if not from then
515                 attr.from = '';
516         end
517         if not to then
518                 attr.to = '';
519         end
520 end
521
522 -- Session initialization logic shared by incoming and outgoing
523 local function initialize_session(session)
524         local stream = new_xmpp_stream(session, stream_callbacks);
525
526         session.thread = runner(function (stanza)
527                 if stanza.name == nil then
528                         stream_callbacks._streamopened(session, stanza.attr);
529                 else
530                         core_process_stanza(session, stanza);
531                 end
532         end, runner_callbacks, session);
533
534         local log = session.log or log;
535         session.stream = stream;
536
537         session.notopen = true;
538
539         function session.reset_stream()
540                 session.notopen = true;
541                 session.streamid = nil;
542                 session.stream:reset();
543         end
544
545         session.stream_attrs = session_stream_attrs;
546
547         local filter = initialize_filters(session);
548         local conn = session.conn;
549         local w = conn.write;
550
551         function session.sends2s(t)
552                 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^[^>]*>?"));
553                 if t.name then
554                         t = filter("stanzas/out", t);
555                 end
556                 if t then
557                         t = filter("bytes/out", tostring(t));
558                         if t then
559                                 return w(conn, t);
560                         end
561                 end
562         end
563
564         function session.data(data)
565                 data = filter("bytes/in", data);
566                 if data then
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");
572                 end
573         end
574
575         session.close = session_close;
576
577         local handlestanza = stream_callbacks.handlestanza;
578         function session.dispatch_stanza(session, stanza)
579                 return handlestanza(session, stanza);
580         end
581
582         module:fire_event("s2s-created", { session = session });
583
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
589                 end
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");
594         end);
595 end
596
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();
600 end
601
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();
605 end
606
607 function runner_callbacks:error(err)
608         (self.data.log or log)("error", "Traceback[s2s]: %s", err);
609 end
610
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);
622         end
623         session.ip = conn:ip();
624 end
625
626 function listener.onincoming(conn, data)
627         local session = sessions[conn];
628         if session then
629                 session.data(data);
630         end
631 end
632
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);
639                 end
640         end
641 end
642
643 function listener.ontimeout(conn)
644         -- Called instead of onconnect when the connection times out
645         measure_connections(1);
646 end
647
648 function listener.ondisconnect(conn, err)
649         measure_connections(-1);
650         local session = sessions[conn];
651         if session then
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
657                         end
658                 end
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);
661         end
662 end
663
664 function listener.onreadtimeout(conn)
665         local session = sessions[conn];
666         local host = session.host or session.to_host;
667         if session then
668                 return (hosts[host] or prosody).events.fire_event("s2s-read-timeout", { session = session });
669         end
670 end
671
672 function listener.register_outgoing(conn, session)
673         sessions[conn] = session;
674         initialize_session(session);
675 end
676
677 function listener.ondetach(conn)
678         sessions[conn] = nil;
679 end
680
681 function check_auth_policy(event)
682         local host, session = event.host, event.session;
683         local must_secure = secure_auth;
684
685         if not must_secure and secure_domains[host] then
686                 must_secure = true;
687         elseif must_secure and insecure_domains[host] then
688                 must_secure = false;
689         end
690
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);
697                 end
698                 return false;
699         end
700 end
701
702 module:hook("s2s-check-certificate", check_auth_policy, -1);
703
704 s2sout.set_listener(listener);
705
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 };
710         end
711 end, -200);
712
713
714
715 module:provides("net", {
716         name = "s2s";
717         listener = listener;
718         default_port = 5269;
719         encryption = "starttls";
720         multiplex = {
721                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
722         };
723 });
724