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