net.server_event: Check the buffer *length*, not the buffer itself (Fixes 100% cpu...
[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 function module.add_host(module)
139         if module:get_option_boolean("disallow_s2s", false) then
140                 module:log("warn", "The 'disallow_s2s' config option is deprecated, please see http://prosody.im/doc/s2s#disabling");
141                 return nil, "This host has disallow_s2s set";
142         end
143         module:hook("route/remote", route_to_existing_session, -1);
144         module:hook("route/remote", route_to_new_session, -10);
145         module:hook("s2s-authenticated", make_authenticated, -1);
146 end
147
148 -- Stream is authorised, and ready for normal stanzas
149 function mark_connected(session)
150         local sendq = session.sendq;
151         
152         local from, to = session.from_host, session.to_host;
153         
154         session.log("info", "%s s2s connection %s->%s complete", session.direction, from, to);
155
156         local event_data = { session = session };
157         if session.type == "s2sout" then
158                 fire_global_event("s2sout-established", event_data);
159                 hosts[from].events.fire_event("s2sout-established", event_data);
160         else
161                 local host_session = hosts[to];
162                 session.send = function(stanza)
163                         return host_session.events.fire_event("route/remote", { from_host = to, to_host = from, stanza = stanza });
164                 end;
165
166                 fire_global_event("s2sin-established", event_data);
167                 hosts[to].events.fire_event("s2sin-established", event_data);
168         end
169         
170         if session.direction == "outgoing" then
171                 if sendq then
172                         session.log("debug", "sending %d queued stanzas across new outgoing connection to %s", #sendq, session.to_host);
173                         local send = session.sends2s;
174                         for i, data in ipairs(sendq) do
175                                 send(data[1]);
176                                 sendq[i] = nil;
177                         end
178                         session.sendq = nil;
179                 end
180                 
181                 session.ip_hosts = nil;
182                 session.srv_hosts = nil;
183         end
184 end
185
186 function make_authenticated(event)
187         local session, host = event.session, event.host;
188         if not session.secure then
189                 if require_encryption or (secure_auth and not(insecure_domains[host])) or secure_domains[host] then
190                         session:close({
191                                 condition = "policy-violation",
192                                 text = "Encrypted server-to-server communication is required but was not "
193                                        ..((session.direction == "outgoing" and "offered") or "used")
194                         });
195                 end
196         end
197         if hosts[host] then
198                 session:close({ condition = "undefined-condition", text = "Attempt to authenticate as a host we serve" });
199         end
200         if session.type == "s2sout_unauthed" then
201                 session.type = "s2sout";
202         elseif session.type == "s2sin_unauthed" then
203                 session.type = "s2sin";
204                 if host then
205                         if not session.hosts[host] then session.hosts[host] = {}; end
206                         session.hosts[host].authed = true;
207                 end
208         elseif session.type == "s2sin" and host then
209                 if not session.hosts[host] then session.hosts[host] = {}; end
210                 session.hosts[host].authed = true;
211         else
212                 return false;
213         end
214         session.log("debug", "connection %s->%s is now authenticated for %s", session.from_host, session.to_host, host);
215         
216         mark_connected(session);
217         
218         return true;
219 end
220
221 --- Helper to check that a session peer's certificate is valid
222 local function check_cert_status(session)
223         local host = session.direction == "outgoing" and session.to_host or session.from_host
224         local conn = session.conn:socket()
225         local cert
226         if conn.getpeercertificate then
227                 cert = conn:getpeercertificate()
228         end
229
230         if cert then
231                 local chain_valid, errors;
232                 if conn.getpeerverification then
233                         chain_valid, errors = conn:getpeerverification();
234                 elseif conn.getpeerchainvalid then -- COMPAT mw/luasec-hg
235                         chain_valid, errors = conn:getpeerchainvalid();
236                         errors = (not chain_valid) and { { errors } } or nil;
237                 else
238                         chain_valid, errors = false, { { "Chain verification not supported by this version of LuaSec" } };
239                 end
240                 -- Is there any interest in printing out all/the number of errors here?
241                 if not chain_valid then
242                         (session.log or log)("debug", "certificate chain validation result: invalid");
243                         for depth, t in pairs(errors or NULL) do
244                                 (session.log or log)("debug", "certificate error(s) at depth %d: %s", depth-1, table.concat(t, ", "))
245                         end
246                         session.cert_chain_status = "invalid";
247                 else
248                         (session.log or log)("debug", "certificate chain validation result: valid");
249                         session.cert_chain_status = "valid";
250
251                         -- We'll go ahead and verify the asserted identity if the
252                         -- connecting server specified one.
253                         if host then
254                                 if cert_verify_identity(host, "xmpp-server", cert) then
255                                         session.cert_identity_status = "valid"
256                                 else
257                                         session.cert_identity_status = "invalid"
258                                 end
259                                 (session.log or log)("debug", "certificate identity validation result: %s", session.cert_identity_status);
260                         end
261                 end
262         end
263         return module:fire_event("s2s-check-certificate", { host = host, session = session, cert = cert });
264 end
265
266 --- XMPP stream event handlers
267
268 local stream_callbacks = { default_ns = "jabber:server", handlestanza =  core_process_stanza };
269
270 local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
271
272 function stream_callbacks.streamopened(session, attr)
273         session.version = tonumber(attr.version) or 0;
274         
275         -- TODO: Rename session.secure to session.encrypted
276         if session.secure == false then
277                 session.secure = true;
278
279                 -- Check if TLS compression is used
280                 local sock = session.conn:socket();
281                 if sock.info then
282                         session.compressed = sock:info"compression";
283                 elseif sock.compression then
284                         session.compressed = sock:compression(); --COMPAT mw/luasec-hg
285                 end
286         end
287
288         if session.direction == "incoming" then
289                 -- Send a reply stream header
290                 
291                 -- Validate to/from
292                 local to, from = nameprep(attr.to), nameprep(attr.from);
293                 if not to and attr.to then -- COMPAT: Some servers do not reliably set 'to' (especially on stream restarts)
294                         session:close({ condition = "improper-addressing", text = "Invalid 'to' address" });
295                         return;
296                 end
297                 if not from and attr.from then -- COMPAT: Some servers do not reliably set 'from' (especially on stream restarts)
298                         session:close({ condition = "improper-addressing", text = "Invalid 'from' address" });
299                         return;
300                 end
301                 
302                 -- Set session.[from/to]_host if they have not been set already and if
303                 -- this session isn't already authenticated
304                 if session.type == "s2sin_unauthed" and from and not session.from_host then
305                         session.from_host = from;
306                 elseif from ~= session.from_host then
307                         session:close({ condition = "improper-addressing", text = "New stream 'from' attribute does not match original" });
308                         return;
309                 end
310                 if session.type == "s2sin_unauthed" and to and not session.to_host then
311                         session.to_host = to;
312                 elseif to ~= session.to_host then
313                         session:close({ condition = "improper-addressing", text = "New stream 'to' attribute does not match original" });
314                         return;
315                 end
316                 
317                 -- For convenience we'll put the sanitised values into these variables
318                 to, from = session.to_host, session.from_host;
319                 
320                 session.streamid = uuid_gen();
321                 (session.log or log)("debug", "Incoming s2s received %s", st.stanza("stream:stream", attr):top_tag());
322                 if to then
323                         if not hosts[to] then
324                                 -- Attempting to connect to a host we don't serve
325                                 session:close({
326                                         condition = "host-unknown";
327                                         text = "This host does not serve "..to
328                                 });
329                                 return;
330                         elseif not hosts[to].modules.s2s then
331                                 -- Attempting to connect to a host that disallows s2s
332                                 session:close({
333                                         condition = "policy-violation";
334                                         text = "Server-to-server communication is disabled for this host";
335                                 });
336                                 return;
337                         end
338                 end
339
340                 if hosts[from] then
341                         session:close({ condition = "undefined-condition", text = "Attempt to connect from a host we serve" });
342                         return;
343                 end
344
345                 if session.secure and not session.cert_chain_status then
346                         if check_cert_status(session) == false then
347                                 return;
348                         end
349                 end
350
351                 session:open_stream(session.to_host, session.from_host)
352                 session.notopen = nil;
353                 if session.version >= 1.0 then
354                         local features = st.stanza("stream:features");
355                         
356                         if to then
357                                 hosts[to].events.fire_event("s2s-stream-features", { origin = session, features = features });
358                         else
359                                 (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");
360                         end
361                         
362                         log("debug", "Sending stream features: %s", tostring(features));
363                         session.sends2s(features);
364                 end
365         elseif session.direction == "outgoing" then
366                 session.notopen = nil;
367                 if not attr.id then
368                         log("error", "Stream response did not give us a stream id!");
369                         session:close({ condition = "undefined-condition", text = "Missing stream ID" });
370                         return;
371                 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 end
404
405 function stream_callbacks.streamclosed(session)
406         (session.log or log)("debug", "Received </stream:stream>");
407         session:close(false);
408 end
409
410 function stream_callbacks.error(session, error, data)
411         if error == "no-stream" then
412                 session.log("debug", "Invalid opening stream header (%s)", (data:gsub("^([^\1]+)\1", "{%1}")));
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 session.ip 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 session.ip 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 or "", to = to or "",
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.streamid = nil;
535                 session.stream:reset();
536         end
537
538         session.open_stream = session_open_stream;
539         
540         local filter = session.filter;
541         function session.data(data)
542                 data = filter("bytes/in", data);
543                 if data then
544                         local ok, err = stream:feed(data);
545                         if ok then return; end
546                         (session.log or log)("warn", "Received invalid XML: %s", data);
547                         (session.log or log)("warn", "Problem was: %s", err);
548                         session:close("not-well-formed");
549                 end
550         end
551
552         session.close = session_close;
553
554         local handlestanza = stream_callbacks.handlestanza;
555         function session.dispatch_stanza(session, stanza)
556                 return handlestanza(session, stanza);
557         end
558
559         add_task(connect_timeout, function ()
560                 if session.type == "s2sin" or session.type == "s2sout" then
561                         return; -- Ok, we're connected
562                 elseif session.type == "s2s_destroyed" then
563                         return; -- Session already destroyed
564                 end
565                 -- Not connected, need to close session and clean up
566                 (session.log or log)("debug", "Destroying incomplete session %s->%s due to inactivity",
567                 session.from_host or "(unknown)", session.to_host or "(unknown)");
568                 session:close("connection-timeout");
569         end);
570 end
571
572 function listener.onconnect(conn)
573         conn:setoption("keepalive", opt_keepalives);
574         local session = sessions[conn];
575         if not session then -- New incoming connection
576                 session = s2s_new_incoming(conn);
577                 sessions[conn] = session;
578                 session.log("debug", "Incoming s2s connection");
579
580                 local filter = initialize_filters(session);
581                 local w = conn.write;
582                 session.sends2s = function (t)
583                         log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)"));
584                         if t.name then
585                                 t = filter("stanzas/out", t);
586                         end
587                         if t then
588                                 t = filter("bytes/out", tostring(t));
589                                 if t then
590                                         return w(conn, t);
591                                 end
592                         end
593                 end
594         
595                 initialize_session(session);
596         else -- Outgoing session connected
597                 session:open_stream(session.from_host, session.to_host);
598         end
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                                 (session.log or log)("debug", "...so we're going to try another target");
626                                 return; -- Session lives for now
627                         end
628                 end
629                 (session.log or log)("debug", "s2s disconnected: %s->%s (%s)", tostring(session.from_host), tostring(session.to_host), tostring(err or "connection closed"));
630                 s2s_destroy_session(session, err);
631         end
632 end
633
634 function listener.register_outgoing(conn, session)
635         session.direction = "outgoing";
636         sessions[conn] = session;
637         initialize_session(session);
638 end
639
640 function listener.ondetach(conn)
641         sessions[conn] = nil;
642 end
643
644 function check_auth_policy(event)
645         local host, session = event.host, event.session;
646         local must_secure = secure_auth;
647
648         if not must_secure and secure_domains[host] then
649                 must_secure = true;
650         elseif must_secure and insecure_domains[host] then
651                 must_secure = false;
652         end
653         
654         if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") then
655                 module:log("warn", "Forbidding insecure connection to/from %s", host or session.ip or "(unknown host)");
656                 if session.direction == "incoming" then
657                         session:close({ condition = "not-authorized", text = "Your server's certificate is invalid, expired, or not trusted by "..session.to_host });
658                 else -- Close outgoing connections without warning
659                         session:close(false);
660                 end
661                 return false;
662         end
663 end
664
665 module:hook("s2s-check-certificate", check_auth_policy, -1);
666
667 s2sout.set_listener(listener);
668
669 module:hook("server-stopping", function(event)
670         local reason = event.reason;
671         for _, session in pairs(sessions) do
672                 session:close{ condition = "system-shutdown", text = reason };
673         end
674 end, -200);
675
676
677
678 module:provides("net", {
679         name = "s2s";
680         listener = listener;
681         default_port = 5269;
682         encryption = "starttls";
683         multiplex = {
684                 pattern = "^<.*:stream.*%sxmlns%s*=%s*(['\"])jabber:server%1.*>";
685         };
686 });
687