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