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