util.sasl: Fix 2 global sets (one a tpyo)
[prosody.git] / core / s2smanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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
10
11 local hosts = hosts;
12 local sessions = sessions;
13 local core_process_stanza = function(a, b) core_process_stanza(a, b); end
14 local add_task = require "util.timer".add_task;
15 local socket = require "socket";
16 local format = string.format;
17 local t_insert, t_sort = table.insert, table.sort;
18 local get_traceback = debug.traceback;
19 local tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber
20     = tostring, pairs, ipairs, getmetatable, newproxy, error, tonumber;
21
22 local idna_to_ascii = require "util.encodings".idna.to_ascii;
23 local connlisteners_get = require "net.connlisteners".get;
24 local wrapclient = require "net.server".wrapclient;
25 local modulemanager = require "core.modulemanager";
26 local st = require "stanza";
27 local stanza = st.stanza;
28 local nameprep = require "util.encodings".stringprep.nameprep;
29
30 local uuid_gen = require "util.uuid".generate;
31
32 local logger_init = require "util.logger".init;
33
34 local log = logger_init("s2smanager");
35
36 local sha256_hash = require "util.hashes".sha256;
37
38 local dialback_secret = uuid_gen();
39
40 local adns = require "net.adns";
41
42 local dns_timeout = config.get("*", "core", "dns_timeout") or 60;
43
44 incoming_s2s = {};
45 local incoming_s2s = incoming_s2s;
46
47 module "s2smanager"
48
49 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
50
51 local function bounce_sendq(session)
52         local sendq = session.sendq;
53         if sendq then
54                 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
55                 local dummy = {
56                         type = "s2sin";
57                         send = function(s)
58                                 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
59                         end;
60                         dummy = true;
61                 };
62                 for i, data in ipairs(sendq) do
63                         local reply = data[2];
64                         local xmlns = reply.attr.xmlns;
65                         if not xmlns or xmlns == "jabber:client" or xmlns == "jabber:server" then
66                                 reply.attr.type = "error";
67                                 reply:tag("error", {type = "cancel"})
68                                         :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
69                                 core_process_stanza(dummy, reply);
70                         end
71                         sendq[i] = nil;
72                 end
73                 session.sendq = nil;
74         end
75 end
76
77 function send_to_host(from_host, to_host, data)
78         local host = hosts[from_host].s2sout[to_host];
79         if host then
80                 -- We have a connection to this host already
81                 if host.type == "s2sout_unauthed" and data.name ~= "db:verify" and ((not data.xmlns) or data.xmlns == "jabber:client" or data.xmlns == "jabber:server") then
82                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
83                         if not host.notopen and not host.dialback_key and host.sends2s then
84                                 host.log("debug", "dialback had not been initiated");
85                                 initiate_dialback(host);
86                         end
87                         
88                         -- Queue stanza until we are able to send it
89                         if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
90                         else host.sendq = { {tostring(data), st.reply(data)} }; end
91                         host.log("debug", "stanza [%s] queued ", data.name);
92                 elseif host.type == "local" or host.type == "component" then
93                         log("error", "Trying to send a stanza to ourselves??")
94                         log("error", "Traceback: %s", get_traceback());
95                         log("error", "Stanza: %s", tostring(data));
96                 else
97                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
98                         -- FIXME
99                         if host.from_host ~= from_host then
100                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
101                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
102                         end
103                         host.sends2s(data);
104                         host.log("debug", "stanza sent over "..host.type);
105                 end
106         else
107                 log("debug", "opening a new outgoing connection for this stanza");
108                 local host_session = new_outgoing(from_host, to_host);
109                 -- Store in buffer
110                 host_session.sendq = { {tostring(data), st.reply(data)} };
111                 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
112                 if (not host_session.connecting) and (not host_session.conn) then
113                         log("warn", "Connection to %s failed already, destroying session...", to_host);
114                         destroy_session(host_session);
115                 end
116         end
117 end
118
119 local open_sessions = 0;
120
121 function new_incoming(conn)
122         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
123         if true then
124                 session.trace = newproxy(true);
125                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
126         end
127         open_sessions = open_sessions + 1;
128         local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
129         session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
130         incoming_s2s[session] = true;
131         return session;
132 end
133
134 function new_outgoing(from_host, to_host)
135                 local host_session = { to_host = to_host, from_host = from_host, notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
136                 hosts[from_host].s2sout[to_host] = host_session;
137                 
138                 local log;
139                 do
140                         local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
141                         log = logger_init(conn_name);
142                         host_session.log = log;
143                 end
144                 
145                 -- This is the first call, can't fail (the first step is DNS lookup)
146                 attempt_connection(host_session);
147                 
148                 if not host_session.sends2s then                
149                         -- A sends2s which buffers data (until the stream is opened)
150                         -- note that data in this buffer will be sent before the stream is authed
151                         -- and will not be ack'd in any way, successful or otherwise
152                         local buffer;
153                         function host_session.sends2s(data)
154                                 if not buffer then
155                                         buffer = {};
156                                         host_session.send_buffer = buffer;
157                                 end
158                                 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
159                                 buffer[#buffer+1] = data;
160                                 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
161                         end
162                         
163                 end
164
165                 return host_session;
166 end
167
168
169 function attempt_connection(host_session, err)
170         local from_host, to_host = host_session.from_host, host_session.to_host;
171         local connect_host, connect_port = idna_to_ascii(to_host), 5269;
172         
173         if not err then -- This is our first attempt
174                 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
175                 host_session.connecting = true;
176                 local answer, handle;
177                 handle = adns.lookup(function (answer)
178                         handle = nil;
179                         host_session.connecting = nil;
180                         if answer then
181                                 log("debug", to_host.." has SRV records, handling...");
182                                 local srv_hosts = {};
183                                 host_session.srv_hosts = srv_hosts;
184                                 for _, record in ipairs(answer) do
185                                         t_insert(srv_hosts, record.srv);
186                                 end
187                                 t_sort(srv_hosts, compare_srv_priorities);
188                                 
189                                 local srv_choice = srv_hosts[1];
190                                 host_session.srv_choice = 1;
191                                 if srv_choice then
192                                         connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
193                                         log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
194                                 end
195                         else
196                                 log("debug", to_host.." has no SRV records, falling back to A");
197                         end
198                         -- Try with SRV, or just the plain hostname if no SRV
199                         local ok, err = try_connect(host_session, connect_host, connect_port);
200                         if not ok then
201                                 if not attempt_connection(host_session, err) then
202                                         -- No more attempts will be made
203                                         destroy_session(host_session);
204                                 end
205                         end
206                 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
207                 
208                 -- Set handler for DNS timeout
209                 add_task(dns_timeout, function ()
210                         if handle then
211                                 adns.cancel(handle, true);
212                         end
213                 end);
214                 
215                 log("debug", "DNS lookup for %s sent, waiting for response before we can connect", to_host);
216                 return true; -- Attempt in progress
217         elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
218                 host_session.srv_choice = host_session.srv_choice + 1;
219                 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
220                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
221                 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
222         else
223                 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
224                 -- We're out of options
225                 return false;
226         end
227         
228         if not (connect_host and connect_port) then
229                 -- Likely we couldn't resolve DNS
230                 log("warn", "Hmm, we're without a host (%s) and port (%s) to connect to for %s, giving up :(", tostring(connect_host), tostring(connect_port), tostring(to_host));
231                 return false;
232         end
233         
234         return try_connect(host_session, connect_host, connect_port);
235 end
236
237 function try_connect(host_session, connect_host, connect_port)
238         host_session.log("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
239         -- Ok, we're going to try to connect
240         
241         local from_host, to_host = host_session.from_host, host_session.to_host;
242         
243         local conn, handler = socket.tcp()
244
245         conn:settimeout(0);
246         local success, err = conn:connect(connect_host, connect_port);
247         if not success and err ~= "timeout" then
248                 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
249                 return false, err;
250         end
251         
252         local cl = connlisteners_get("xmppserver");
253         conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1, hosts[from_host].ssl_ctx, false );
254         host_session.conn = conn;
255         
256         -- Register this outgoing connection so that xmppserver_listener knows about it
257         -- otherwise it will assume it is a new incoming connection
258         cl.register_outgoing(conn, host_session);
259         
260         local w = conn.write;
261         host_session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
262         
263         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' xml:lang='en'>]], from_host, to_host));
264         log("debug", "Connection attempt in progress...");
265         return true;
266 end
267
268 function streamopened(session, attr)
269         local send = session.sends2s;
270         
271         -- TODO: #29: SASL/TLS on s2s streams
272         session.version = 0; --tonumber(attr.version) or 0;
273         
274         if session.version >= 1.0 and not (attr.to and attr.from) then
275                 log("warn", (session.to_host or "(unknown)").." failed to specify 'to' or 'from' hostname as per RFC");
276         end
277         
278         if session.direction == "incoming" then
279                 -- Send a reply stream header
280                 session.to_host = attr.to and nameprep(attr.to);
281                 session.from_host = attr.from and nameprep(attr.from);
282         
283                 session.streamid = uuid_gen();
284                 (session.log or log)("debug", "incoming s2s received <stream:stream>");
285                 send("<?xml version='1.0'?>");
286                 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', 
287                                 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host }):top_tag());
288                 if session.to_host and not hosts[session.to_host] then
289                         -- Attempting to connect to a host we don't serve
290                         session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
291                         return;
292                 end
293                 if session.version >= 1.0 then
294                         send(st.stanza("stream:features")
295                                         :tag("dialback", { xmlns='urn:xmpp:features:dialback' }):tag("optional"):up():up());
296                 end
297         elseif session.direction == "outgoing" then
298                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
299                 if not attr.id then error("stream response did not give us a streamid!!!"); end
300                 session.streamid = attr.id;
301         
302                 -- Send unauthed buffer
303                 -- (stanzas which are fine to send before dialback)
304                 -- Note that this is *not* the stanza queue (which 
305                 -- we can only send if auth succeeds) :)
306                 local send_buffer = session.send_buffer;
307                 if send_buffer and #send_buffer > 0 then
308                         log("debug", "Sending s2s send_buffer now...");
309                         for i, data in ipairs(send_buffer) do
310                                 session.sends2s(tostring(data));
311                                 send_buffer[i] = nil;
312                         end
313                 end
314                 session.send_buffer = nil;
315         
316                 if not session.dialback_verifying then
317                         initiate_dialback(session);
318                 else
319                         mark_connected(session);
320                 end
321         end
322
323         session.notopen = nil;
324 end
325
326 function streamclosed(session)
327         (session.log or log)("debug", "</stream:stream>");
328         if session.sends2s then
329                 session.sends2s("</stream:stream>");
330         end
331         session.notopen = true;
332 end
333
334 function initiate_dialback(session)
335         -- generate dialback key
336         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
337         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
338         session.log("info", "sent dialback key on outgoing s2s stream");
339 end
340
341 function generate_dialback(id, to, from)
342         return sha256_hash(id..to..from..dialback_secret, true);
343 end
344
345 function verify_dialback(id, to, from, key)
346         return key == generate_dialback(id, to, from);
347 end
348
349 function make_authenticated(session, host)
350         if session.type == "s2sout_unauthed" then
351                 session.type = "s2sout";
352         elseif session.type == "s2sin_unauthed" then
353                 session.type = "s2sin";
354                 if host then
355                         session.hosts[host].authed = true;
356                 end
357         elseif session.type == "s2sin" and host then
358                 session.hosts[host].authed = true;
359         else
360                 return false;
361         end
362         session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
363         
364         mark_connected(session);
365         
366         return true;
367 end
368
369 function mark_connected(session)
370         local sendq, send = session.sendq, session.sends2s;
371         
372         local from, to = session.from_host, session.to_host;
373         
374         session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
375         
376         local send_to_host = send_to_host;
377         function session.send(data) send_to_host(to, from, data); end
378         
379         
380         if session.direction == "outgoing" then
381                 if sendq then
382                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
383                         for i, data in ipairs(sendq) do
384                                 send(data[1]);
385                                 sendq[i] = nil;
386                         end
387                         session.sendq = nil;
388                 end
389                 
390                 session.srv_hosts = nil;
391         end
392 end
393
394 function destroy_session(session)
395         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
396         
397         if session.direction == "outgoing" then
398                 hosts[session.from_host].s2sout[session.to_host] = nil;
399                 bounce_sendq(session);
400         elseif session.direction == "incoming" then
401                 incoming_s2s[session] = nil;
402         end
403         
404         for k in pairs(session) do
405                 if k ~= "trace" then
406                         session[k] = nil;
407                 end
408         end
409 end
410
411 return _M;