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