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