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