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