Merge 0.9->0.10
[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
30 local s2sout = module:require("s2sout");
31
32 local connect_timeout = module:get_option_number("s2s_timeout", 90);
33 local stream_close_timeout = module:get_option_number("s2s_close_timeout", 5);
34 local opt_keepalives = module:get_option_boolean("s2s_tcp_keepalives", module:get_option_boolean("tcp_keepalives", true));
35 local secure_auth = module:get_option_boolean("s2s_secure_auth", false); -- One day...
36 local secure_domains, insecure_domains =
37         module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
38 local require_encryption = module:get_option_boolean("s2s_require_encryption", false);
39
40 local measure_connections = module:measure("connections", "counter");
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 local function keepalive(event)
139         return event.session.sends2s(' ');
140 end
141
142 module:hook("s2s-read-timeout", keepalive, -1);
143
144 function module.add_host(module)
145         if module:get_option_boolean("disallow_s2s", false) then
146                 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
147                 return nil, "This host has disallow_s2s set";
148         end
149         module:hook("route/remote", route_to_existing_session, -1);
150         module:hook("route/remote", route_to_new_session, -10);
151         module:hook("s2s-authenticated", make_authenticated, -1);
152         module:hook("s2s-read-timeout", keepalive, -1);
153         module:hook_stanza("http://etherx.jabber.org/streams", "features", function (session, stanza)
154                 if session.type == "s2sout" then
155                         -- Stream is authenticated and we are seem to be done with feature negotiation,
156                         -- so the stream is ready for stanzas.  RFC 6120 Section 4.3
157                         mark_connected(session);
158                         return true;
159                 elseif not session.dialback_verifying then
160                         session.log("warn", "No SASL EXTERNAL offer and Dialback doesn't seem to be enabled, giving up");
161                         session:close();
162                         return false;
163                 end
164         end, -1);
165 end
166
167 -- Stream is authorised, and ready for normal stanzas
168 function mark_connected(session)
169         local sendq, send = session.sendq, session.sends2s;
170
171         local from, to = session.from_host, session.to_host;
172
173         session.log("info", "%s s2s connection %s->%s complete", session.direction:gsub("^.", string.upper), from, to);
174
175         local event_data = { session = session };
176         if session.type == "s2sout" then
177                 fire_global_event("s2sout-established", event_data);
178                 hosts[from].events.fire_event("s2sout-established", event_data);
179         else
180                 local host_session = hosts[to];
181                 session.send = function(stanza)
182                         return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
183                 end;
184
185                 fire_global_event("s2sin-established", event_data);
186                 hosts[to].events.fire_event("s2sin-established", event_data);
187         end
188
189         if session.direction == "outgoing" then
190                 if sendq then
191                         session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
192                         for i, data in ipairs(sendq) do
193                                 send(data[1]);
194                                 sendq[i] = nil;
195                         end
196                         session.sendq = nil;
197                 end
198
199                 session.ip_hosts = nil;
200                 session.srv_hosts = nil;
201         end
202 end
203
204 function make_authenticated(event)
205         local session, host = event.session, event.host;
206         if not session.secure then
207                 if require_encryption or (secure_auth and not(insecure_domains[host])) or secure_domains[host] then
208                         session:close({
209                                 condition = "policy-violation",
210                                 text = "Encrypted server-to-server communication is required but was not "
211                                        ..((session.direction == "outgoing" and "offered") or "used")
212                         });
213                 end
214         end
215         if hosts[host] then
216                 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
217         end
218         if session.type == "s2sout_unauthed" then
219                 session.type = "s2sout";
220         elseif session.type == "s2sin_unauthed" then
221                 session.type = "s2sin";
222                 if host then
223                         if not session.hosts[host] then session.hosts[host] = {}; end
224                         session.hosts[host].authed = true;
225                 end
226         elseif session.type == "s2sin" and host then
227                 if not session.hosts[host] then session.hosts[host] = {}; end
228                 session.hosts[host].authed = true;
229         else
230                 return false;
231         end
232         session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
233
234         if (session.type == "s2sout" and session.external_auth ~= "succeeded") or session.type == "s2sin" then
235                 -- Stream either used dialback for authentication or is an incoming stream.
236                 mark_connected(session);
237         end
238
239         return true;
240 end
241
242 --- Helper to check that a session peer's certificate is valid
243 function check_cert_status(session)
244         local host = session.direction == "outgoing" and session.to_host or session.from_host
245         local conn = session.conn:socket()
246         local cert
247         if conn.getpeercertificate then
248                 cert = conn:getpeercertificate()
249         end
250
251         return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
252 end
253
254 --- XMPP stream event handlers
255
256 local stream_callbacks = { default_ns = "jabber:server", handlestanza =  core_process_stanza };
257
258 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
259
260 function stream_callbacks.streamopened(session, attr)
261         local send = session.sends2s;
262
263         session.version = tonumber(attr.version) or 0;
264
265         -- TODO: Rename session.secure to session.encrypted
266         if session.secure == false then
267                 session.secure = true;
268                 session.encrypted = true;
269
270                 local sock = session.conn:socket();
271                 if sock.info then
272                         local info = sock:info();
273                         (session.log or log)("info", "Stream encrypted (%s with %s)", info.protocol, info.cipher);
274                         session.compressed = info.compression;
275                 else
276                         (session.log or log)("info", "Stream encrypted");
277                         session.compressed = sock.compression and sock:compression(); --COMPAT mw/luasec-hg
278                 end
279         end
280
281         if session.direction == "incoming" then
282                 -- Send a reply stream header
283
284                 -- Validate to/from
285                 local to, from = nameprep(attr.to), nameprep(attr.from);
286                 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
287                         session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
288                         return;
289                 end
290                 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
291                         session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
292                         return;
293                 end
294
295                 -- Set session.[from/to]_host if they have not been set already and if
296                 -- this session isn't already authenticated
297                 if session.type == "s2sin_unauthed" and from and not session.from_host then
298                         session.from_host = from;
299                 elseif from ~= session.from_host then
300                         session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
301                         return;
302                 end
303                 if session.type == "s2sin_unauthed" and to and not session.to_host then
304                         session.to_host = to;
305                 elseif to ~= session.to_host then
306                         session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
307                         return;
308                 end
309
310                 -- For convenience we'll put the sanitised values into these variables
311                 to, from = session.to_host, session.from_host;
312
313                 session.streamid = uuid_gen();
314                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
315                 if to then
316                         if not hosts[to] then
317                                 -- Attempting to connect to a host we don't serve
318                                 session:close({
319                                         condition = "host-unknown";
320                                         text = "This host does not serve "..to
321                                 });
322                                 return;
323                         elseif not hosts[to].modules.s2s then
324                                 -- Attempting to connect to a host that disallows s2s
325                                 session:close({
326                                         condition = "policy-violation";
327                                         text = "Server-to-server communication is disabled for this host";
328                                 });
329                                 return;
330                         end
331                 end
332
333                 if hosts[from] then
334                         session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
335                         return;
336                 end
337
338                 if session.secure and not session.cert_chain_status then
339                         if check_cert_status(session) == false then
340                                 return;
341                         end
342                 end
343
344                 session:open_stream(session.to_host, session.from_host)
345                 if session.version >= 1.0 then
346                         local features = st.stanza("stream:features");
347
348                         if to then
349                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
350                         else
351                                 (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");
352                         end
353
354                         log("debug", "Sending stream features: %s", tostring(features));
355                         send(features);
356                 end
357                 session.notopen = nil;
358         elseif session.direction == "outgoing" then
359                 session.notopen = nil;
360                 if not attr.id then
361                         log("error", "Stream response did not give us a stream id!");
362                         session:close({ condition = "undefined-condition", text = "Missing stream ID" });
363                         return;
364                 end
365                 session.streamid = attr.id;
366
367                 if session.secure and not session.cert_chain_status then
368                         if check_cert_status(session) == false then
369                                 return;
370                         end
371                 end
372
373                 -- Send unauthed buffer
374                 -- (stanzas which are fine to send before dialback)
375                 -- Note that this is *not* the stanza queue (which
376                 -- we can only send if auth succeeds) :)
377                 local send_buffer = session.send_buffer;
378                 if send_buffer and #send_buffer > 0 then
379                         log("debug", "Sending s2s send_buffer now...");
380                         for i, data in ipairs(send_buffer) do
381                                 session.sends2s(tostring(data));
382                                 send_buffer[i] = nil;
383                         end
384                 end
385                 session.send_buffer = nil;
386
387                 -- If server is pre-1.0, don't wait for features, just do dialback
388                 if session.version < 1.0 then
389                         if not session.dialback_verifying then
390                                 hosts[session.from_host].events.fire_event("s2sout-authenticate-legacy", { origin = session });
391                         else
392                                 mark_connected(session);
393                         end
394                 end
395         end
396 end
397
398 function stream_callbacks.streamclosed(session)
399         (session.log or log)("debug", "Received </stream:stream>");
400         session:close(false);
401 end
402
403 function stream_callbacks.error(session, error, data)
404         if error == "no-stream" then
405                 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
406                 session:close("invalid-namespace");
407         elseif error == "parse-error" then
408                 session.log("debug", "Server-to-server XML parse error: %s", tostring(error));
409                 session:close("not-well-formed");
410         elseif error == "stream-error" then
411                 local condition, text = "undefined-condition";
412                 for child in data:children() do
413                         if child.attr.xmlns == xmlns_xmpp_streams then
414                                 if child.name ~= "text" then
415                                         condition = child.name;
416                                 else
417                                         text = child:get_text();
418                                 end
419                                 if condition ~= "undefined-condition" and text then
420                                         break;
421                                 end
422                         end
423                 end
424                 text = condition .. (text and (" ("..text..")") or "");
425                 session.log("info", "Session closed by remote with error: %s", text);
426                 session:close(nil, text);
427         end
428 end
429
430 local function handleerr(err) log("error", "Traceback[s2s]: %s", traceback(tostring(err), 2)); end
431 function stream_callbacks.handlestanza(session, stanza)
432         if stanza.attr.xmlns == "jabber:client" then --COMPAT: Prosody pre-0.6.2 may send jabber:client
433                 stanza.attr.xmlns = nil;
434         end
435         stanza = session.filter("stanzas/in", stanza);
436         if stanza then
437                 return xpcall(function () return core_process_stanza(session, stanza) end, handleerr);
438         end
439 end
440
441 local listener = {};
442
443 --- Session methods
444 local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
445 local function session_close(session, reason, remote_reason)
446         local log = session.log or log;
447         if session.conn then
448                 if session.notopen then
449                         if session.direction == "incoming" then
450                                 session:open_stream(session.to_host, session.from_host);
451                         else
452                                 session:open_stream(session.from_host, session.to_host);
453                         end
454                 end
455                 if reason then -- nil == no err, initiated by us, false == initiated by remote
456                         if type(reason) == "string" then -- assume stream error
457                                 log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, reason);
458                                 session.sends2s(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
459                         elseif type(reason) == "table" then
460                                 if reason.condition then
461                                         local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
462                                         if reason.text then
463                                                 stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
464                                         end
465                                         if reason.extra then
466                                                 stanza:add_child(reason.extra);
467                                         end
468                                         log("debug", "Disconnecting %s[%s], <stream:error> is: %s", session.host or session.ip or "(unknown host)", session.type, tostring(stanza));
469                                         session.sends2s(stanza);
470                                 elseif reason.name then -- a stanza
471                                         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));
472                                         session.sends2s(reason);
473                                 end
474                         end
475                 end
476
477                 session.sends2s("</stream:stream>");
478                 function session.sends2s() return false; end
479
480                 local reason = remote_reason or (reason and (reason.text or reason.condition)) or reason;
481                 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");
482
483                 -- Authenticated incoming stream may still be sending us stanzas, so wait for </stream:stream> from remote
484                 local conn = session.conn;
485                 if reason == nil and not session.notopen and session.type == "s2sin" then
486                         add_task(stream_close_timeout, function ()
487                                 if not session.destroyed then
488                                         session.log("warn", "Failed to receive a stream close response, closing connection anyway...");
489                                         s2s_destroy_session(session, reason);
490                                         conn:close();
491                                 end
492                         end);
493                 else
494                         s2s_destroy_session(session, reason);
495                         conn:close(); -- Close immediately, as this is an outgoing connection or is not authed
496                 end
497         end
498 end
499
500 function session_stream_attrs(session, from, to, attr)
501         if not from or (hosts[from] and hosts[from].modules.dialback) then
502                 attr["xmlns:db"] = 'jabber:server:dialback';
503         end
504         if not from then
505                 attr.from = '';
506         end
507         if not to then
508                 attr.to = '';
509         end
510 end
511
512 -- Session initialization logic shared by incoming and outgoing
513 local function initialize_session(session)
514         local stream = new_xmpp_stream(session, stream_callbacks);
515         local log = session.log or log;
516         session.stream = stream;
517
518         session.notopen = true;
519
520         function session.reset_stream()
521                 session.notopen = true;
522                 session.streamid = nil;
523                 session.stream:reset();
524         end
525
526         session.stream_attrs = session_stream_attrs;
527
528         local filter = initialize_filters(session);
529         local conn = session.conn;
530         local w = conn.write;
531
532         function session.sends2s(t)
533                 log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^[^>]*>?"));
534                 if t.name then
535                         t = filter("stanzas/out", t);
536                 end
537                 if t then
538                         t = filter("bytes/out", tostring(t));
539                         if t then
540                                 return w(conn, t);
541                         end
542                 end
543         end
544
545         function session.data(data)
546                 data = filter("bytes/in", data);
547                 if data then
548                         local ok, err = stream:feed(data);
549                         if ok then return; end
550                         log("warn", "Received invalid XML: %s", data);
551                         log("warn", "Problem was: %s", err);
552                         session:close("not-well-formed");
553                 end
554         end
555
556         session.close = session_close;
557
558         local handlestanza = stream_callbacks.handlestanza;
559         function session.dispatch_stanza(session, stanza)
560                 return handlestanza(session, stanza);
561         end
562
563         module:fire_event("s2s-created", { session = session });
564
565         add_task(connect_timeout, function ()
566                 if session.type == "s2sin" or session.type == "s2sout" then
567                         return; -- Ok, we're connected
568                 elseif session.type == "s2s_destroyed" then
569                         return; -- Session already destroyed
570                 end
571                 -- Not connected, need to close session and clean up
572                 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
573                 session.from_host or "(unknown)", session.to_host or "(unknown)");
574                 session:close("connection-timeout");
575         end);
576 end
577
578 function listener.onconnect(conn)
579         measure_connections(1);
580         conn:setoption("keepalive", opt_keepalives);
581         local session = sessions[conn];
582         if not session then -- New incoming connection
583                 session = s2s_new_incoming(conn);
584                 sessions[conn] = session;
585                 session.log("debug", "Incoming s2s connection");
586                 initialize_session(session);
587         else -- Outgoing session connected
588                 session:open_stream(session.from_host, session.to_host);
589         end
590         session.ip = conn:ip();
591 end
592
593 function listener.onincoming(conn, data)
594         local session = sessions[conn];
595         if session then
596                 session.data(data);
597         end
598 end
599
600 function listener.onstatus(conn, status)
601         if status == "ssl-handshake-complete" then
602                 local session = sessions[conn];
603                 if session and session.direction == "outgoing" then
604                         session.log("debug", "Sending stream header...");
605                         session:open_stream(session.from_host, session.to_host);
606                 end
607         end
608 end
609
610 function listener.ondisconnect(conn, err)
611         measure_connections(-1);
612         local session = sessions[conn];
613         if session then
614                 sessions[conn] = nil;
615                 if err and session.direction == "outgoing" and session.notopen then
616                         (session.log or log)("debug", "s2s connection attempt failed: %s", err);
617                         if s2sout.attempt_connection(session, err) then
618                                 return; -- Session lives for now
619                         end
620                 end
621                 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
622                 s2s_destroy_session(session, err);
623         end
624 end
625
626 function listener.onreadtimeout(conn)
627         local session = sessions[conn];
628         if session then
629                 return (hosts[session.host] or prosody).events.fire_event("s2s-read-timeout", { session = session });
630         end
631 end
632
633 function listener.register_outgoing(conn, session)
634         sessions[conn] = session;
635         initialize_session(session);
636 end
637
638 function listener.ondetach(conn)
639         sessions[conn] = nil;
640 end
641
642 function check_auth_policy(event)
643         local host, session = event.host, event.session;
644         local must_secure = secure_auth;
645
646         if not must_secure and secure_domains[host] then
647                 must_secure = true;
648         elseif must_secure and insecure_domains[host] then
649                 must_secure = false;
650         end
651
652         if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") then
653                 module:log("warn", "Forbidding insecure connection to/from %s", host or session.ip or "(unknown host)");
654                 if session.direction == "incoming" then
655                         session:close({ condition = "not-authorized", text = "Your server's certificate is invalid, expired, or not trusted by "..session.to_host });
656                 else -- Close outgoing connections without warning
657                         session:close(false);
658                 end
659                 return false;
660         end
661 end
662
663 module:hook("s2s-check-certificate", check_auth_policy, -1);
664
665 s2sout.set_listener(listener);
666
667 module:hook("server-stopping", function(event)
668         local reason = event.reason;
669         for _, session in pairs(sessions) do
670                 session:close{ condition = "system-shutdown", text = reason };
671         end
672 end,500);
673
674
675
676 module:provides("net", {
677         name = "s2s";
678         listener = listener;
679         default_port = 5269;
680         encryption = "starttls";
681         multiplex = {
682                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
683         };
684 });
685