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