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