Yet another fix for the makefile :)
[prosody.git] / core / s2smanager.lua
1
2 local hosts = hosts;
3 local sessions = sessions;
4 local socket = require "socket";
5 local format = string.format;
6 local t_insert, t_sort = table.insert, table.sort;
7 local get_traceback = debug.traceback;
8 local tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber
9     = tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber;
10
11 local idna_to_ascii = require "util.encodings".idna.to_ascii;
12 local connlisteners_get = require "net.connlisteners".get;
13 local wraptlsclient = require "net.server".wraptlsclient;
14 local modulemanager = require "core.modulemanager";
15 local st = require "stanza";
16 local stanza = st.stanza;
17
18 local uuid_gen = require "util.uuid".generate;
19
20 local logger_init = require "util.logger".init;
21
22 local log = logger_init("s2smanager");
23
24 local sha256_hash = require "util.hashes".sha256;
25
26 local dialback_secret = "This is very secret!!! Ha!";
27
28 local dns = require "net.dns";
29
30 module "s2smanager"
31
32 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
33
34 function send_to_host(from_host, to_host, data)
35         if data.name then data = tostring(data); end
36         local host = hosts[from_host].s2sout[to_host];
37         if host then
38                 -- We have a connection to this host already
39                 if host.type == "s2sout_unauthed" and ((not data.xmlns) or data.xmlns == "jabber:client" or data.xmlns == "jabber:server") then
40                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host..", authing it now...");
41                         if not host.notopen and not host.dialback_key then
42                                 host.log("debug", "dialback had not been initiated");
43                                 initiate_dialback(host);
44                         end
45                         
46                         -- Queue stanza until we are able to send it
47                         if host.sendq then t_insert(host.sendq, data);
48                         else host.sendq = { data }; end
49                 elseif host.type == "local" or host.type == "component" then
50                         log("error", "Trying to send a stanza to ourselves??")
51                         log("error", "Traceback: %s", get_traceback());
52                         log("error", "Stanza: %s", tostring(data));
53                 else
54                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
55                         -- FIXME
56                         if host.from_host ~= from_host then
57                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
58                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
59                         end
60                         host.sends2s(data);
61                         host.log("debug", "stanza sent over "..host.type);
62                 end
63         else
64                 log("debug", "opening a new outgoing connection for this stanza");
65                 local host_session = new_outgoing(from_host, to_host);
66                 -- Store in buffer
67                 host_session.sendq = { data };
68         end
69 end
70
71 local open_sessions = 0;
72
73 function new_incoming(conn)
74         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming" };
75         if true then
76                 session.trace = newproxy(true);
77                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("s2s session got collected, now "..open_sessions.." s2s sessions are allocated") end;
78         end
79         open_sessions = open_sessions + 1;
80         local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
81         session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
82         return session;
83 end
84
85 function new_outgoing(from_host, to_host)
86                 local host_session = { to_host = to_host, from_host = from_host, notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
87                 hosts[from_host].s2sout[to_host] = host_session;
88                 
89                 local log;
90                 do
91                         local conn_name = "s2sout"..tostring(conn):match("[a-f0-9]*$");
92                         log = logger_init(conn_name);
93                         host_session.log = log;
94                 end
95                 
96                 attempt_connection(host_session);
97                 
98                 return host_session;
99 end
100
101
102 function attempt_connection(host_session, err)
103         local from_host, to_host = host_session.from_host, host_session.to_host;
104         local conn, handler = socket.tcp()
105
106         local connect_host, connect_port = idna_to_ascii(to_host), 5269;
107         
108         if not err then -- This is our first attempt
109                 local answer = dns.lookup("_xmpp-server._tcp."..connect_host..".", "SRV");
110                 
111                 if answer then
112                         log("debug", to_host.." has SRV records, handling...");
113                         local srv_hosts = {};
114                         host_session.srv_hosts = srv_hosts;
115                         for _, record in ipairs(answer) do
116                                 t_insert(srv_hosts, record.srv);
117                         end
118                         t_sort(srv_hosts, compare_srv_priorities);
119                         
120                         local srv_choice = srv_hosts[1];
121                         host_session.srv_choice = 1;
122                         if srv_choice then
123                                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
124                                 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
125                         end
126                 end
127         elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
128                 host_session.srv_choice = host_session.srv_choice + 1;
129                 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
130                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
131                 host_session.log("debug", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
132         else
133                 host_session.log("debug", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
134                 -- We're out of options
135                 return false;
136         end
137         
138         -- Ok, we're going to try to connect
139         conn:settimeout(0);
140         local success, err = conn:connect(connect_host, connect_port);
141         if not success and err ~= "timeout" then
142                 log("warn", "s2s connect() failed: %s", err);
143         end
144         
145         local cl = connlisteners_get("xmppserver");
146         conn = wraptlsclient(cl, conn, connect_host, connect_port, 0, cl.default_mode or 1, hosts[from_host].ssl_ctx );
147         host_session.conn = conn;
148         
149         -- Register this outgoing connection so that xmppserver_listener knows about it
150         -- otherwise it will assume it is a new incoming connection
151         cl.register_outgoing(conn, host_session);
152         
153         local w = conn.write;
154         host_session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
155         
156         conn.write(format([[<stream:stream xmlns='jabber:server' xmlns:db='jabber:server:dialback' xmlns:stream='http://etherx.jabber.org/streams' from='%s' to='%s' version='1.0'>]], from_host, to_host));
157         return true;
158 end
159
160 function streamopened(session, attr)
161         local send = session.sends2s;
162         
163         session.version = tonumber(attr.version) or 0;
164         if session.version >= 1.0 and not (attr.to and attr.from) then
165                 --print("to: "..tostring(attr.to).." from: "..tostring(attr.from));
166                 log("warn", (session.to_host or "(unknown)").." failed to specify 'to' or 'from' hostname as per RFC");
167         end
168         
169         if session.direction == "incoming" then
170                 -- Send a reply stream header
171                 
172                 --for k,v in pairs(attr) do print("", tostring(k), ":::", tostring(v)); end
173                 
174                 session.to_host = attr.to;
175                 session.from_host = attr.from;
176         
177                 session.streamid = uuid_gen();
178                 (session.log or log)("debug", "incoming s2s received <stream:stream>");
179                 send("<?xml version='1.0'?>");
180                 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host }):top_tag());
181                 if session.to_host and not hosts[session.to_host] then
182                         -- Attempting to connect to a host we don't serve
183                         session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
184                         return;
185                 end
186                 if session.version >= 1.0 then
187                         send(st.stanza("stream:features")
188                                         :tag("dialback", { xmlns='urn:xmpp:features:dialback' }):tag("optional"):up():up());
189                 end
190         elseif session.direction == "outgoing" then
191                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
192                 if not attr.id then error("stream response did not give us a streamid!!!"); end
193                 session.streamid = attr.id;
194         
195                 if not session.dialback_verifying then
196                         initiate_dialback(session);
197                 else
198                         mark_connected(session);
199                 end
200         end
201
202         session.notopen = nil;
203 end
204
205 function initiate_dialback(session)
206         -- generate dialback key
207         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
208         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
209         session.log("info", "sent dialback key on outgoing s2s stream");
210 end
211
212 function generate_dialback(id, to, from)
213         return sha256_hash(id..to..from..dialback_secret, true);
214 end
215
216 function verify_dialback(id, to, from, key)
217         return key == generate_dialback(id, to, from);
218 end
219
220 function make_authenticated(session)
221         if session.type == "s2sout_unauthed" then
222                 session.type = "s2sout";
223         elseif session.type == "s2sin_unauthed" then
224                 session.type = "s2sin";
225         else
226                 return false;
227         end
228         session.log("info", "connection is now authenticated");
229         
230         mark_connected(session);
231         
232         return true;
233 end
234
235 function mark_connected(session)
236         local sendq, send = session.sendq, session.sends2s;
237         
238         local from, to = session.from_host, session.to_host;
239         
240         session.log("debug", session.direction.." s2s connection "..from.."->"..to.." is now complete");
241         
242         local send_to_host = send_to_host;
243         function session.send(data) send_to_host(to, from, data); end
244         
245         
246         if session.direction == "outgoing" then
247                 if sendq then
248                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
249                         for i, data in ipairs(sendq) do
250                                 send(data);
251                                 sendq[i] = nil;
252                         end
253                         session.sendq = nil;
254                 end
255         end
256 end
257
258 function destroy_session(session)
259         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
260         
261         -- FIXME: Flush sendq here/report errors to originators
262         
263         if session.direction == "outgoing" then
264                 hosts[session.from_host].s2sout[session.to_host] = nil;
265         end
266         
267         for k in pairs(session) do
268                 if k ~= "trace" then
269                         session[k] = nil;
270                 end
271         end
272 end
273
274 return _M;