666022d12d0346e64a079a1510c9681d170c1273
[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 fire_event = require "core.eventmanager".fire_event;
31 local uuid_gen = require "util.uuid".generate;
32
33 local logger_init = require "util.logger".init;
34
35 local log = logger_init("s2smanager");
36
37 local sha256_hash = require "util.hashes".sha256;
38
39 local dialback_secret = uuid_gen();
40
41 local adns, dns = require "net.adns", require "net.dns";
42 local config = require "core.configmanager";
43 local connect_timeout = config.get("*", "core", "s2s_timeout") or 60;
44 local dns_timeout = config.get("*", "core", "dns_timeout") or 60;
45 local max_dns_depth = config.get("*", "core", "dns_max_depth") or 3;
46
47 incoming_s2s = {};
48 _G.prosody.incoming_s2s = incoming_s2s;
49 local incoming_s2s = incoming_s2s;
50
51 module "s2smanager"
52
53 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
54
55 local function bounce_sendq(session)
56         local sendq = session.sendq;
57         if sendq then
58                 session.log("info", "sending error replies for "..#sendq.." queued stanzas because of failed outgoing connection to "..tostring(session.to_host));
59                 local dummy = {
60                         type = "s2sin";
61                         send = function(s)
62                                 (session.log or log)("error", "Replying to to an s2s error reply, please report this! Traceback: %s", get_traceback());
63                         end;
64                         dummy = true;
65                 };
66                 for i, data in ipairs(sendq) do
67                         local reply = data[2];
68                         local xmlns = reply.attr.xmlns;
69                         if not xmlns or xmlns == "jabber:client" or xmlns == "jabber:server" then
70                                 reply.attr.type = "error";
71                                 reply:tag("error", {type = "cancel"})
72                                         :tag("remote-server-not-found", {xmlns = "urn:ietf:params:xml:ns:xmpp-stanzas"}):up();
73                                 core_process_stanza(dummy, reply);
74                         end
75                         sendq[i] = nil;
76                 end
77                 session.sendq = nil;
78         end
79 end
80
81 function send_to_host(from_host, to_host, data)
82         if not hosts[from_host] then
83                 log("warn", "Attempt to send stanza from %s - a host we don't serve", from_host);
84                 return false;
85         end
86         local host = hosts[from_host].s2sout[to_host];
87         if host then
88                 -- We have a connection to this host already
89                 if host.type == "s2sout_unauthed" and (data.name ~= "db:verify" or not host.dialback_key) and ((not data.xmlns) or data.xmlns == "jabber:client" or data.xmlns == "jabber:server") then
90                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host);
91                         
92                         -- Queue stanza until we are able to send it
93                         if host.sendq then t_insert(host.sendq, {tostring(data), st.reply(data)});
94                         else host.sendq = { {tostring(data), st.reply(data)} }; end
95                         host.log("debug", "stanza [%s] queued ", data.name);
96                 elseif host.type == "local" or host.type == "component" then
97                         log("error", "Trying to send a stanza to ourselves??")
98                         log("error", "Traceback: %s", get_traceback());
99                         log("error", "Stanza: %s", tostring(data));
100                 else
101                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
102                         -- FIXME
103                         if host.from_host ~= from_host then
104                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
105                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
106                         end
107                         host.sends2s(data);
108                         host.log("debug", "stanza sent over "..host.type);
109                 end
110         else
111                 log("debug", "opening a new outgoing connection for this stanza");
112                 local host_session = new_outgoing(from_host, to_host);
113
114                 -- Store in buffer
115                 host_session.sendq = { {tostring(data), st.reply(data)} };
116                 log("debug", "stanza [%s] queued until connection complete", tostring(data.name));
117                 if (not host_session.connecting) and (not host_session.conn) then
118                         log("warn", "Connection to %s failed already, destroying session...", to_host);
119                         destroy_session(host_session);
120                 end
121         end
122 end
123
124 local open_sessions = 0;
125
126 function new_incoming(conn)
127         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming", hosts = {} };
128         if true then
129                 session.trace = newproxy(true);
130                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; end;
131         end
132         open_sessions = open_sessions + 1;
133         local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
134         session.log = log;
135         session.sends2s = function (t) log("debug", "sending: %s", t.top_tag and t:top_tag() or t:match("^([^>]*>?)")); w(conn, tostring(t)); end
136         incoming_s2s[session] = true;
137         add_task(connect_timeout, function ()
138                 if session.conn ~= conn or
139                    session.type == "s2sin" then
140                         return; -- Ok, we're connect[ed|ing]
141                 end
142                 -- Not connected, need to close session and clean up
143                 (session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity", 
144                     session.from_host or "(unknown)", session.to_host or "(unknown)");
145                 session:close("connection-timeout");
146         end);
147         return session;
148 end
149
150 function new_outgoing(from_host, to_host)
151                 local host_session = { to_host = to_host, from_host = from_host, host = from_host, 
152                                        notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
153                 
154                 hosts[from_host].s2sout[to_host] = host_session;
155                 
156                 local log;
157                 do
158                         local conn_name = "s2sout"..tostring(host_session):match("[a-f0-9]*$");
159                         log = logger_init(conn_name);
160                         host_session.log = log;
161                 end
162                 
163                 -- Kick the connection attempting machine
164                 attempt_connection(host_session);
165                 
166                 if not host_session.sends2s then                
167                         -- A sends2s which buffers data (until the stream is opened)
168                         -- note that data in this buffer will be sent before the stream is authed
169                         -- and will not be ack'd in any way, successful or otherwise
170                         local buffer;
171                         function host_session.sends2s(data)
172                                 if not buffer then
173                                         buffer = {};
174                                         host_session.send_buffer = buffer;
175                                 end
176                                 log("debug", "Buffering data on unconnected s2sout to %s", to_host);
177                                 buffer[#buffer+1] = data;
178                                 log("debug", "Buffered item %d: %s", #buffer, tostring(data));
179                         end
180                         
181                 end
182
183                 return host_session;
184 end
185
186
187 function attempt_connection(host_session, err)
188         local from_host, to_host = host_session.from_host, host_session.to_host;
189         local connect_host, connect_port = idna_to_ascii(to_host), 5269;
190         
191         if not connect_host then
192                 return false;
193         end
194         
195         if not err then -- This is our first attempt
196                 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
197                 host_session.connecting = true;
198                 local handle;
199                 handle = adns.lookup(function (answer)
200                         handle = nil;
201                         host_session.connecting = nil;
202                         if answer then
203                                 log("debug", to_host.." has SRV records, handling...");
204                                 local srv_hosts = {};
205                                 host_session.srv_hosts = srv_hosts;
206                                 for _, record in ipairs(answer) do
207                                         t_insert(srv_hosts, record.srv);
208                                 end
209                                 t_sort(srv_hosts, compare_srv_priorities);
210                                 
211                                 local srv_choice = srv_hosts[1];
212                                 host_session.srv_choice = 1;
213                                 if srv_choice then
214                                         connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
215                                         log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
216                                 end
217                         else
218                                 log("debug", to_host.." has no SRV records, falling back to A");
219                         end
220                         -- Try with SRV, or just the plain hostname if no SRV
221                         local ok, err = try_connect(host_session, connect_host, connect_port);
222                         if not ok then
223                                 if not attempt_connection(host_session, err) then
224                                         -- No more attempts will be made
225                                         destroy_session(host_session);
226                                 end
227                         end
228                 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
229                 
230                 -- Set handler for DNS timeout
231                 add_task(dns_timeout, function ()
232                         if handle then
233                                 adns.cancel(handle, true);
234                         end
235                 end);
236                 
237                 log("debug", "DNS lookup for %s sent, waiting for response before we can connect", to_host);
238                 return true; -- Attempt in progress
239         elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
240                 host_session.srv_choice = host_session.srv_choice + 1;
241                 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
242                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
243                 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
244         else
245                 host_session.log("info", "Out of connection options, can't connect to %s", tostring(host_session.to_host));
246                 -- We're out of options
247                 return false;
248         end
249         
250         if not (connect_host and connect_port) then
251                 -- Likely we couldn't resolve DNS
252                 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));
253                 return false;
254         end
255         
256         return try_connect(host_session, connect_host, connect_port);
257 end
258
259 function try_connect(host_session, connect_host, connect_port)
260         host_session.connecting = true;
261         local handle;
262         handle = adns.lookup(function (reply)
263                 handle = nil;
264                 host_session.connecting = nil;
265                 
266                 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
267                 if not (reply and reply[#reply] and reply[#reply].a) then
268                         local count = max_dns_depth;
269                         reply = dns.peek(connect_host, "CNAME", "IN");
270                         while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
271                                 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
272                                 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
273                                 count = count - 1;
274                         end
275                 end
276                 -- end of CNAME resolving
277                 
278                 if reply and reply[#reply] and reply[#reply].a then
279                         log("debug", "DNS reply for %s gives us %s", connect_host, reply[#reply].a);
280                         return make_connect(host_session, reply[#reply].a, connect_port);
281                 else
282                         log("debug", "DNS lookup failed to get a response for %s", connect_host);
283                         if not attempt_connection(host_session, "name resolution failed") then -- Retry if we can
284                                 log("debug", "No other records to try for %s - destroying", host_session.to_host);
285                                 destroy_session(host_session); -- End of the line, we can't
286                         end
287                 end
288         end, connect_host, "A", "IN");
289
290         -- Set handler for DNS timeout
291         add_task(dns_timeout, function ()
292                 if handle then
293                         adns.cancel(handle, true);
294                 end
295         end);
296                 
297         return true;
298 end
299
300 function make_connect(host_session, connect_host, connect_port)
301         host_session.log("info", "Beginning new connection attempt to %s (%s:%d)", host_session.to_host, connect_host, connect_port);
302         -- Ok, we're going to try to connect
303         
304         local from_host, to_host = host_session.from_host, host_session.to_host;
305         
306         local conn, handler = socket.tcp()
307
308         conn:settimeout(0);
309         local success, err = conn:connect(connect_host, connect_port);
310         if not success and err ~= "timeout" then
311                 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host, connect_port, err);
312                 return false, err;
313         end
314         
315         local cl = connlisteners_get("xmppserver");
316         conn = wrapclient(conn, connect_host, connect_port, cl, cl.default_mode or 1, hosts[from_host].ssl_ctx, false );
317         host_session.conn = conn;
318         
319         -- Register this outgoing connection so that xmppserver_listener knows about it
320         -- otherwise it will assume it is a new incoming connection
321         cl.register_outgoing(conn, host_session);
322         
323         local w, log = conn.write, host_session.log;
324         host_session.sends2s = function (t) log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?")); w(conn, tostring(t)); end
325         
326         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));
327         log("debug", "Connection attempt in progress...");
328         add_task(connect_timeout, function ()
329                 if host_session.conn ~= conn or
330                    host_session.type == "s2sout" or
331                    host_session.connecting then
332                         return; -- Ok, we're connect[ed|ing]
333                 end
334                 -- Not connected, need to close session and clean up
335                 (host_session.log or log)("warn", "Destroying incomplete session %s->%s due to inactivity", 
336                     host_session.from_host or "(unknown)", host_session.to_host or "(unknown)");
337                 host_session:close("connection-timeout");
338         end);
339         return true;
340 end
341
342 function streamopened(session, attr)
343         local send = session.sends2s;
344         
345         -- TODO: #29: SASL/TLS on s2s streams
346         session.version = tonumber(attr.version) or 0;
347         
348         if session.secure == false then
349                 session.secure = true;
350         end
351         
352         if session.version >= 1.0 and not (attr.to and attr.from) then
353                 
354                 (session.log or log)("warn", "Remote of stream "..(session.from_host or "(unknown)").."->"..(session.to_host or "(unknown)")
355                         .." failed to specify to (%s) and/or from (%s) hostname as per RFC", tostring(attr.to), tostring(attr.from));
356         end
357         
358         if session.direction == "incoming" then
359                 -- Send a reply stream header
360                 session.to_host = attr.to and nameprep(attr.to);
361                 session.from_host = attr.from and nameprep(attr.from);
362         
363                 session.streamid = uuid_gen();
364                 (session.log or log)("debug", "incoming s2s received <stream:stream>");
365                 send("<?xml version='1.0'?>");
366                 send(stanza("stream:stream", { xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', 
367                                 ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host, version=(session.version > 0 and "1.0" or nil) }):top_tag());
368                 if session.to_host and not hosts[session.to_host] then
369                         -- Attempting to connect to a host we don't serve
370                         session:close({ condition = "host-unknown"; text = "This host does not serve "..session.to_host });
371                         return;
372                 end
373                 if session.version >= 1.0 then
374                         local features = st.stanza("stream:features");
375                                                         
376                         if session.to_host then
377                                 hosts[session.to_host].events.fire_event("s2s-stream-features", { session = session, features = features });
378                         else
379                                 (session.log or log)("warn", "No 'to' on stream header from %s means we can't offer any features", session.from_host or "unknown host");
380                         end
381                         
382                         log("debug", "Sending stream features: %s", tostring(features));
383                         send(features);
384                 end
385         elseif session.direction == "outgoing" then
386                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
387                 if not attr.id then error("stream response did not give us a streamid!!!"); end
388                 session.streamid = attr.id;
389         
390                 -- Send unauthed buffer
391                 -- (stanzas which are fine to send before dialback)
392                 -- Note that this is *not* the stanza queue (which 
393                 -- we can only send if auth succeeds) :)
394                 local send_buffer = session.send_buffer;
395                 if send_buffer and #send_buffer > 0 then
396                         log("debug", "Sending s2s send_buffer now...");
397                         for i, data in ipairs(send_buffer) do
398                                 session.sends2s(tostring(data));
399                                 send_buffer[i] = nil;
400                         end
401                 end
402                 session.send_buffer = nil;
403         
404                 -- If server is pre-1.0, don't wait for features, just do dialback
405                 if session.version < 1.0 then
406                         if not session.dialback_verifying then
407                                 log("debug", "Initiating dialback...");
408                                 initiate_dialback(session);
409                         else
410                                 mark_connected(session);
411                         end
412                 end
413         end
414
415         session.notopen = nil;
416 end
417
418 function streamclosed(session)
419         (session.log or log)("debug", "</stream:stream>");
420         if session.sends2s then
421                 session.sends2s("</stream:stream>");
422         end
423         session.notopen = true;
424 end
425
426 function initiate_dialback(session)
427         -- generate dialback key
428         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
429         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
430         session.log("info", "sent dialback key on outgoing s2s stream");
431 end
432
433 function generate_dialback(id, to, from)
434         return sha256_hash(id..to..from..dialback_secret, true);
435 end
436
437 function verify_dialback(id, to, from, key)
438         return key == generate_dialback(id, to, from);
439 end
440
441 function make_authenticated(session, host)
442         if session.type == "s2sout_unauthed" then
443                 session.type = "s2sout";
444         elseif session.type == "s2sin_unauthed" then
445                 session.type = "s2sin";
446                 if host then
447                         session.hosts[host].authed = true;
448                 end
449         elseif session.type == "s2sin" and host then
450                 session.hosts[host].authed = true;
451         else
452                 return false;
453         end
454         session.log("debug", "connection %s->%s is now authenticated", session.from_host or "(unknown)", session.to_host or "(unknown)");
455         
456         mark_connected(session);
457         
458         return true;
459 end
460
461 -- Stream is authorised, and ready for normal stanzas
462 function mark_connected(session)
463         local sendq, send = session.sendq, session.sends2s;
464         
465         local from, to = session.from_host, session.to_host;
466         
467         session.log("info", session.direction.." s2s connection "..from.."->"..to.." complete");
468         
469         local send_to_host = send_to_host;
470         function session.send(data) send_to_host(to, from, data); end
471         
472         
473         if session.direction == "outgoing" then
474                 if sendq then
475                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
476                         for i, data in ipairs(sendq) do
477                                 send(data[1]);
478                                 sendq[i] = nil;
479                         end
480                         session.sendq = nil;
481                 end
482                 
483                 session.srv_hosts = nil;
484         end
485 end
486
487 function destroy_session(session)
488         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
489         
490         if session.direction == "outgoing" then
491                 hosts[session.from_host].s2sout[session.to_host] = nil;
492                 bounce_sendq(session);
493         elseif session.direction == "incoming" then
494                 incoming_s2s[session] = nil;
495         end
496         
497         for k in pairs(session) do
498                 if k ~= "trace" then
499                         session[k] = nil;
500                 end
501         end
502 end
503
504 return _M;