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