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