mod_s2s: Mark stream as opened earlier for outgoing connections, fixes double stream...
[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 local NULL = {};
19
20 local add_task = require "util.timer".add_task;
21 local st = require "util.stanza";
22 local initialize_filters = require "util.filters".initialize;
23 local nameprep = require "util.encodings".stringprep.nameprep;
24 local new_xmpp_stream = require "util.xmppstream".new;
25 local s2s_new_incoming = require "core.s2smanager".new_incoming;
26 local s2s_new_outgoing = require "core.s2smanager".new_outgoing;
27 local s2s_destroy_session = require "core.s2smanager".destroy_session;
28 local uuid_gen = require "util.uuid".generate;
29 local cert_verify_identity = require "util.x509".verify_identity;
30 local fire_global_event = prosody.events.fire_event;
31
32 local s2sout = module:require("s2sout");
33
34 local connect_timeout = module:get_option_number("s2s_timeout", 90);
35 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
36 local opt_keepalives = module:get_option_boolean("s2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
37 local secure_auth = module:get_option_boolean("s2s_secure_auth", false); -- One day...
38 local secure_domains, insecure_domains =
39         module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
40 local require_encryption = module:get_option_boolean("s2s_require_encryption", false);
41
42 local sessions = module:shared("sessions");
43
44 local log = module._log;
45
46 --- Handle stanzas to remote domains
47
48 local bouncy_stanzas = { message = true, presence = true, iq = true };
49 local function bounce_sendq(session, reason)
50         local sendq = session.sendq;
51         if not sendq then return; end
52         session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
53         local dummy = {
54                 type = "s2sin";
55                 send = function(s)
56                         (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", traceback());
57                 end;
58                 dummy = true;
59         };
60         for i, data in ipairs(sendq) do
61                 local reply = data[2];
62                 if reply and not(reply.attr.xmlns) and bouncy_stanzas[reply.name] then
63                         reply.attr.type = "error";
64                         reply:tag("error", {type = "cancel"})
65                                 :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
66                         if reason then
67                                 reply:tag("text", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"})
68                                         :text("Server-to-server connection failed: "..reason):up();
69                         end
70                         core_process_stanza(dummy, reply);
71                 end
72                 sendq[i] = nil;
73         end
74         session.sendq = nil;
75 end
76
77 -- Handles stanzas to existing s2s sessions
78 function route_to_existing_session(event)
79         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
80         if not hosts[from_host] then
81                 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
82                 return false;
83         end
84         if hosts[to_host] then
85                 log("warn", "Attempt to route stanza to a remote %s - a host we do serve?!", from_host);
86                 return false;
87         end
88         local host = hosts[from_host].s2sout[to_host];
89         if host then
90                 -- We have a connection to this host already
91                 if host.type == "s2sout_unauthed" and (stanza.name ~= "db:verify" or not host.dialback_key) then
92                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
93
94                         -- Queue stanza until we are able to send it
95                         if host.sendq then t_insert(host.sendq, {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)});
96                         else host.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} }; end
97                         host.log("debug", "stanza [%s] queued ", stanza.name);
98                         return true;
99                 elseif host.type == "local" or host.type == "component" then
100                         log("error", "Trying to send a stanza to ourselves??")
101                         log("error", "Traceback: %s", traceback());
102                         log("error", "Stanza: %s", tostring(stanza));
103                         return false;
104                 else
105                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
106                         -- FIXME
107                         if host.from_host ~= from_host then
108                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
109                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
110                         end
111                         if host.sends2s(stanza) then
112                                 host.log("debug", "stanza sent over %s", host.type);
113                                 return true;
114                         end
115                 end
116         end
117 end
118
119 -- Create a new outgoing session for a stanza
120 function route_to_new_session(event)
121         local from_host, to_host, stanza = event.from_host, event.to_host, event.stanza;
122         log("debug", "opening a new outgoing connection for this stanza");
123         local host_session = s2s_new_outgoing(from_host, to_host);
124
125         -- Store in buffer
126         host_session.bounce_sendq = bounce_sendq;
127         host_session.sendq = { {tostring(stanza), stanza.attr.type ~= "error" and stanza.attr.type ~= "result" and st.reply(stanza)} };
128         log("debug", "stanza [%s] queued until connection complete", tostring(stanza.name));
129         s2sout.initiate_connection(host_session);
130         if (not host_session.connecting) and (not host_session.conn) then
131                 log("warn", "Connection to %s failed already, destroying session...", to_host);
132                 s2s_destroy_session(host_session, "Connection failed");
133                 return false;
134         end
135         return true;
136 end
137
138 function module.add_host(module)
139         if module:get_option_boolean("disallow_s2s", false) then
140                 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
141                 return nil, "This host has disallow_s2s set";
142         end
143         module:hook("route/remote", route_to_existing_session, -1);
144         module:hook("route/remote", route_to_new_session, -10);
145         module:hook("s2s-authenticated", make_authenticated, -1);
146 end
147
148 -- Stream is authorised, and ready for normal stanzas
149 function mark_connected(session)
150         local sendq, send = session.sendq, session.sends2s;
151         
152         local from, to = session.from_host, session.to_host;
153         
154         session.log("info", "%s s2s connection %s->%s complete", session.direction, from, to);
155
156         local event_data = { session = session };
157         if session.type == "s2sout" then
158                 fire_global_event("s2sout-established", event_data);
159                 hosts[from].events.fire_event("s2sout-established", event_data);
160         else
161                 local host_session = hosts[to];
162                 session.send = function(stanza)
163                         return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
164                 end;
165
166                 fire_global_event("s2sin-established", event_data);
167                 hosts[to].events.fire_event("s2sin-established", event_data);
168         end
169         
170         if session.direction == "outgoing" then
171                 if sendq then
172                         session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
173                         for i, data in ipairs(sendq) do
174                                 send(data[1]);
175                                 sendq[i] = nil;
176                         end
177                         session.sendq = nil;
178                 end
179                 
180                 session.ip_hosts = nil;
181                 session.srv_hosts = nil;
182         end
183 end
184
185 function make_authenticated(event)
186         local session, host = event.session, event.host;
187         if not session.secure then
188                 if require_encryption or (secure_auth and not(insecure_domains[host])) or secure_domains[host] then
189                         session:close({
190                                 condition = "policy-violation",
191                                 text = "Encrypted server-to-server communication is required but was not "
192                                        ..((session.direction == "outgoing" and "offered") or "used")
193                         });
194                 end
195         end
196         if hosts[host] then
197                 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
198         end
199         if session.type == "s2sout_unauthed" then
200                 session.type = "s2sout";
201         elseif session.type == "s2sin_unauthed" then
202                 session.type = "s2sin";
203                 if host then
204                         if not session.hosts[host] then session.hosts[host] = {}; end
205                         session.hosts[host].authed = true;
206                 end
207         elseif session.type == "s2sin" and host then
208                 if not session.hosts[host] then session.hosts[host] = {}; end
209                 session.hosts[host].authed = true;
210         else
211                 return false;
212         end
213         session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
214         
215         mark_connected(session);
216         
217         return true;
218 end
219
220 --- Helper to check that a session peer's certificate is valid
221 local function check_cert_status(session)
222         local host = session.direction == "outgoing" and session.to_host or session.from_host
223         local conn = session.conn:socket()
224         local cert
225         if conn.getpeercertificate then
226                 cert = conn:getpeercertificate()
227         end
228
229         if cert then
230                 local chain_valid, errors;
231                 if conn.getpeerverification then
232                         chain_valid, errors = conn:getpeerverification();
233                 elseif conn.getpeerchainvalid then -- COMPAT mw/luasec-hg
234                         chain_valid, errors = conn:getpeerchainvalid();
235                         errors = (not chain_valid) and { { errors } } or nil;
236                 else
237                         chain_valid, errors = false, { { "Chain verification not supported by this version of LuaSec" } };
238                 end
239                 -- Is there any interest in printing out all/the number of errors here?
240                 if not chain_valid then
241                         (session.log or log)("debug", "certificate chain validation result: invalid");
242                         for depth, t in pairs(errors or NULL) do
243                                 (session.log or log)("debug", "certificate error(s) at depth %d: %s", depth-1, table.concat(t, ", "))
244                         end
245                         session.cert_chain_status = "invalid";
246                 else
247                         (session.log or log)("debug", "certificate chain validation result: valid");
248                         session.cert_chain_status = "valid";
249
250                         -- We'll go ahead and verify the asserted identity if the
251                         -- connecting server specified one.
252                         if host then
253                                 if cert_verify_identity(host, "xmpp-server", cert) then
254                                         session.cert_identity_status = "valid"
255                                 else
256                                         session.cert_identity_status = "invalid"
257                                 end
258                                 (session.log or log)("debug", "certificate identity validation result: %s", session.cert_identity_status);
259                         end
260                 end
261         end
262         return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
263 end
264
265 --- XMPP stream event handlers
266
267 local stream_callbacks = { default_ns = "jabber:server", handlestanza =  core_process_stanza };
268
269 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
270
271 function stream_callbacks.streamopened(session, attr)
272         local send = session.sends2s;
273         
274         session.version = tonumber(attr.version) or 0;
275         
276         -- TODO: Rename session.secure to session.encrypted
277         if session.secure == false then
278                 session.secure = true;
279
280                 -- Check if TLS compression is used
281                 local sock = session.conn:socket();
282                 if sock.info then
283                         session.compressed = sock:info"compression";
284                 elseif sock.compression then
285                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
286                 end
287         end
288
289         if session.direction == "incoming" then
290                 -- Send a reply stream header
291                 
292                 -- Validate to/from
293                 local to, from = nameprep(attr.to), nameprep(attr.from);
294                 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
295                         session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
296                         return;
297                 end
298                 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
299                         session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
300                         return;
301                 end
302                 
303                 -- Set session.[from/to]_host if they have not been set already and if
304                 -- this session isn't already authenticated
305                 if session.type == "s2sin_unauthed" and from and not session.from_host then
306                         session.from_host = from;
307                 elseif from ~= session.from_host then
308                         session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
309                         return;
310                 end
311                 if session.type == "s2sin_unauthed" and to and not session.to_host then
312                         session.to_host = to;
313                 elseif to ~= session.to_host then
314                         session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
315                         return;
316                 end
317                 
318                 -- For convenience we'll put the sanitised values into these variables
319                 to, from = session.to_host, session.from_host;
320                 
321                 session.streamid = uuid_gen();
322                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
323                 if to then
324                         if not hosts[to] then
325                                 -- Attempting to connect to a host we don't serve
326                                 session:close({
327                                         condition = "host-unknown";
328                                         text = "This host does not serve "..to
329                                 });
330                                 return;
331                         elseif not hosts[to].modules.s2s then
332                                 -- Attempting to connect to a host that disallows s2s
333                                 session:close({
334                                         condition = "policy-violation";
335                                         text = "Server-to-server communication is disabled for this host";
336                                 });
337                                 return;
338                         end
339                 end
340
341                 if hosts[from] then
342                         session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
343                         return;
344                 end
345
346                 if session.secure and not session.cert_chain_status then
347                         if check_cert_status(session) == false then
348                                 return;
349                         end
350                 end
351
352                 session:open_stream(session.to_host, session.from_host)
353                 if session.version >= 1.0 then
354                         local features = st.stanza("stream:features");
355                         
356                         if to then
357                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
358                         else
359                                 (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");
360                         end
361                         
362                         log("debug", "Sending stream features: %s", tostring(features));
363                         send(features);
364                 end
365                 session.notopen = nil;
366         elseif session.direction == "outgoing" then
367                 session.notopen = nil;
368                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
369                 if not attr.id then error("stream response did not give us a streamid!!!"); end
370                 session.streamid = attr.id;
371
372                 if session.secure and not session.cert_chain_status then
373                         if check_cert_status(session) == false then
374                                 return;
375                         end
376                 end
377
378                 -- Send unauthed buffer
379                 -- (stanzas which are fine to send before dialback)
380                 -- Note that this is *not* the stanza queue (which
381                 -- we can only send if auth succeeds) :)
382                 local send_buffer = session.send_buffer;
383                 if send_buffer and #send_buffer > 0 then
384                         log("debug", "Sending s2s send_buffer now...");
385                         for i, data in ipairs(send_buffer) do
386                                 session.sends2s(tostring(data));
387                                 send_buffer[i] = nil;
388                         end
389                 end
390                 session.send_buffer = nil;
391         
392                 -- If server is pre-1.0, don't wait for features, just do dialback
393                 if session.version < 1.0 then
394                         if not session.dialback_verifying then
395                                 hosts[session.from_host].events.fire_event("s2sout-authenticate-legacy", { origin = session });
396                         else
397                                 mark_connected(session);
398                         end
399                 end
400         end
401 end
402
403 function stream_callbacks.streamclosed(session)
404         (session.log or log)("debug", "Received </stream:stream>");
405         session:close(false);
406 end
407
408 function stream_callbacks.error(session, error, data)
409         if error == "no-stream" then
410                 session:close("invalid-namespace");
411         elseif error == "parse-error" then
412                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
413                 session:close("not-well-formed");
414         elseif error == "stream-error" then
415                 local condition, text = "undefined-condition";
416                 for child in data:children() do
417                         if child.attr.xmlns == xmlns_xmpp_streams then
418                                 if child.name ~= "text" then
419                                         condition = child.name;
420                                 else
421                                         text = child:get_text();
422                                 end
423                                 if condition ~= "undefined-condition" and text then
424                                         break;
425                                 end
426                         end
427                 end
428                 text = condition .. (text and (" ("..text..")") or "");
429                 session.log("info", "Session closed by remote with error: %s", text);
430                 session:close(nil, text);
431         end
432 end
433
434 local function handleerr(err) log("error", "Traceback[s2s]: %s", traceback(tostring(err), 2)); end
435 function stream_callbacks.handlestanza(session, stanza)
436         if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
437                 stanza.attr.xmlns = nil;
438         end
439         stanza = session.filter("stanzas/in", stanza);
440         if stanza then
441                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
442         end
443 end
444
445 local listener = {};
446
447 --- Session methods
448 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
449 local function session_close(session, reason, remote_reason)
450         local log = session.log or log;
451         if session.conn then
452                 if session.notopen then
453                         if session.direction == "incoming" then
454                                 session:open_stream(session.to_host, session.from_host);
455                         else
456                                 session:open_stream(session.from_host, session.to_host);
457                         end
458                 end
459                 if reason then -- nil == no err, initiated by us, false == initiated by remote
460                         if type(reason) == "string" then -- assume stream error
461                                 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, reason);
462                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
463                         elseif type(reason) == "table" then
464                                 if reason.condition then
465                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
466                                         if reason.text then
467                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
468                                         end
469                                         if reason.extra then
470                                                 stanza:add_child(reason.extra);
471                                         end
472                                         log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, tostring(stanza));
473                                         session.sends2s(stanza);
474                                 elseif reason.name then -- a stanza
475                                         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));
476                                         session.sends2s(reason);
477                                 end
478                         end
479                 end
480
481                 session.sends2s("</stream:stream>");
482                 function session.sends2s() return false; end
483                 
484                 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason;
485                 session.log("info", "%s s2s stream %s->%s closed: %s", session.direction, session.from_host or "(unknown host)", session.to_host or "(unknown host)", reason or "stream closed");
486                 
487                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
488                 local conn = session.conn;
489                 if reason == nil and not session.notopen and session.type == "s2sin" then
490                         add_task(stream_close_timeout, function ()
491                                 if not session.destroyed then
492                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
493                                         s2s_destroy_session(session, reason);
494                                         conn:close();
495                                 end
496                         end);
497                 else
498                         s2s_destroy_session(session, reason);
499                         conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
500                 end
501         end
502 end
503
504 function session_open_stream(session, from, to)
505         local attr = {
506                 ["xmlns:stream"] = 'http://etherx.jabber.org/streams',
507                 xmlns = 'jabber:server',
508                 version = session.version and (session.version > 0 and "1.0" or nil),
509                 ["xml:lang"] = 'en',
510                 id = session.streamid,
511                 from = from, to = to,
512         }
513         if not from or (hosts[from] and hosts[from].modules.dialback) then
514                 attr["xmlns:db"] = 'jabber:server:dialback';
515         end
516
517         session.sends2s("<?xml version='1.0'?>");
518         session.sends2s(st.stanza("stream:stream", attr):top_tag());
519         return true;
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         session.stream = stream;
526         
527         session.notopen = true;
528                 
529         function session.reset_stream()
530                 session.notopen = true;
531                 session.stream:reset();
532         end
533
534         session.open_stream = session_open_stream;
535         
536         local filter = session.filter;
537         function session.data(data)
538                 data = filter("bytes/in", data);
539                 if data then
540                         local ok, err = stream:feed(data);
541                         if ok then return; end
542                         (session.log or log)("warn", "Received invalid XML: %s", data);
543                         (session.log or log)("warn", "Problem was: %s", err);
544                         session:close("not-well-formed");
545                 end
546         end
547
548         session.close = session_close;
549
550         local handlestanza = stream_callbacks.handlestanza;
551         function session.dispatch_stanza(session, stanza)
552                 return handlestanza(session, stanza);
553         end
554
555         add_task(connect_timeout, function ()
556                 if session.type == "s2sin" or session.type == "s2sout" then
557                         return; -- Ok, we're connected
558                 elseif session.type == "s2s_destroyed" then
559                         return; -- Session already destroyed
560                 end
561                 -- Not connected, need to close session and clean up
562                 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
563                 session.from_host or "(unknown)", session.to_host or "(unknown)");
564                 session:close("connection-timeout");
565         end);
566 end
567
568 function listener.onconnect(conn)
569         conn:setoption("keepalive", opt_keepalives);
570         local session = sessions[conn];
571         if not session then -- New incoming connection
572                 session = s2s_new_incoming(conn);
573                 sessions[conn] = session;
574                 session.log("debug", "Incoming s2s connection");
575
576                 local filter = initialize_filters(session);
577                 local w = conn.write;
578                 session.sends2s = function (t)
579                         log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
580                         if t.name then
581                                 t = filter("stanzas/out", t);
582                         end
583                         if t then
584                                 t = filter("bytes/out", tostring(t));
585                                 if t then
586                                         return w(conn, t);
587                                 end
588                         end
589                 end
590         
591                 initialize_session(session);
592         else -- Outgoing session connected
593                 session:open_stream(session.from_host, session.to_host);
594         end
595 end
596
597 function listener.onincoming(conn, data)
598         local session = sessions[conn];
599         if session then
600                 session.data(data);
601         end
602 end
603         
604 function listener.onstatus(conn, status)
605         if status == "ssl-handshake-complete" then
606                 local session = sessions[conn];
607                 if session and session.direction == "outgoing" then
608                         session.log("debug", "Sending stream header...");
609                         session:open_stream(session.from_host, session.to_host);
610                 end
611         end
612 end
613
614 function listener.ondisconnect(conn, err)
615         local session = sessions[conn];
616         if session then
617                 sessions[conn] = nil;
618                 if err and session.direction == "outgoing" and session.notopen then
619                         (session.log or log)("debug", "s2s connection attempt failed: %s", err);
620                         if s2sout.attempt_connection(session, err) then
621                                 (session.log or log)("debug", "...so we're going to try another target");
622                                 return; -- Session lives for now
623                         end
624                 end
625                 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
626                 s2s_destroy_session(session, err);
627         end
628 end
629
630 function listener.register_outgoing(conn, session)
631         session.direction = "outgoing";
632         sessions[conn] = session;
633         initialize_session(session);
634 end
635
636 function check_auth_policy(event)
637         local host, session = event.host, event.session;
638         local must_secure = secure_auth;
639
640         if not must_secure and secure_domains[host] then
641                 must_secure = true;
642         elseif must_secure and insecure_domains[host] then
643                 must_secure = false;
644         end
645         
646         if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") then
647                 module:log("warn", "Forbidding insecure connection to/from %s", host or session.ip or "(unknown host)");
648                 if session.direction == "incoming" then
649                         session:close({ condition = "not-authorized", text = "Your server's certificate is invalid, expired, or not trusted by "..session.to_host });
650                 else -- Close outgoing connections without warning
651                         session:close(false);
652                 end
653                 return false;
654         end
655 end
656
657 module:hook("s2s-check-certificate", check_auth_policy, -1);
658
659 s2sout.set_listener(listener);
660
661 module:hook("server-stopping", function(event)
662         local reason = event.reason;
663         for _, session in pairs(sessions) do
664                 session:close{ condition = "system-shutdown", text = reason };
665         end
666 end,500);
667
668
669
670 module:provides("net", {
671         name = "s2s";
672         listener = listener;
673         default_port = 5269;
674         encryption = "starttls";
675         multiplex = {
676                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
677         };
678 });
679