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