a8fe4d0f573337ccf336d14eafbfcdff95762fd6
[prosody.git] / core / s2smanager.lua
1
2 local hosts = hosts;
3 local sessions = sessions;
4 local socket = require "socket";
5 local format = string.format;
6 local t_insert, t_sort = table.insert, table.sort;
7 local get_traceback = debug.traceback;
8 local tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber
9     = tostring, pairs, ipairs, getmetatable, print, newproxy, error, tonumber;
10
11 local connlisteners_get = require "net.connlisteners".get;
12 local wraptlsclient = require "net.server".wraptlsclient;
13 local modulemanager = require "core.modulemanager";
14 local st = require "stanza";
15 local stanza = st.stanza;
16
17 local uuid_gen = require "util.uuid".generate;
18
19 local logger_init = require "util.logger".init;
20
21 local log = logger_init("s2smanager");
22
23 local md5_hash = require "util.hashes".md5;
24
25 local dialback_secret = "This is very secret!!! Ha!";
26
27 local dns = require "net.dns";
28
29 module "s2smanager"
30
31 local function compare_srv_priorities(a,b) return a.priority < b.priority or a.weight < b.weight; end
32
33 function send_to_host(from_host, to_host, data)
34         if data.name then data = tostring(data); end
35         local host = hosts[from_host].s2sout[to_host];
36         if host then
37                 -- We have a connection to this host already
38                 if host.type == "s2sout_unauthed" and ((not data.xmlns) or data.xmlns == "jabber:client" or data.xmlns == "jabber:server") then
39                         (host.log or log)("debug", "trying to send over unauthed s2sout to "..to_host..", authing it now...");
40                         if not host.notopen and not host.dialback_key then
41                                 host.log("debug", "dialback had not been initiated");
42                                 initiate_dialback(host);
43                         end
44                         
45                         -- Queue stanza until we are able to send it
46                         if host.sendq then t_insert(host.sendq, data);
47                         else host.sendq = { data }; end
48                 elseif host.type == "local" or host.type == "component" then
49                         log("error", "Trying to send a stanza to ourselves??")
50                         log("error", "Traceback: %s", get_traceback());
51                         log("error", "Stanza: %s", tostring(data));
52                 else
53                         (host.log or log)("debug", "going to send stanza to "..to_host.." from "..from_host);
54                         -- FIXME
55                         if host.from_host ~= from_host then
56                                 log("error", "WARNING! This might, possibly, be a bug, but it might not...");
57                                 log("error", "We are going to send from %s instead of %s", tostring(host.from_host), tostring(from_host));
58                         end
59                         host.sends2s(data);
60                         host.log("debug", "stanza sent over "..host.type);
61                 end
62         else
63                 log("debug", "opening a new outgoing connection for this stanza");
64                 local host_session = new_outgoing(from_host, to_host);
65                 -- Store in buffer
66                 host_session.sendq = { data };
67         end
68 end
69
70 local open_sessions = 0;
71
72 function new_incoming(conn)
73         local session = { conn = conn, type = "s2sin_unauthed", direction = "incoming" };
74         if true then
75                 session.trace = newproxy(true);
76                 getmetatable(session.trace).__gc = function () open_sessions = open_sessions - 1; print("s2s session got collected, now "..open_sessions.." s2s sessions are allocated") end;
77         end
78         open_sessions = open_sessions + 1;
79         local w, log = conn.write, logger_init("s2sin"..tostring(conn):match("[a-f0-9]+$"));
80         session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
81         return session;
82 end
83
84 function new_outgoing(from_host, to_host)
85                 local host_session = { to_host = to_host, from_host = from_host, notopen = true, type = "s2sout_unauthed", direction = "outgoing" };
86                 hosts[from_host].s2sout[to_host] = host_session;
87                 local cl = connlisteners_get("xmppserver");
88                 
89                 local conn, handler = socket.tcp()
90                 
91                 --FIXME: Below parameters (ports/ip) are incorrect (use SRV)
92                 
93                 local connect_host, connect_port = to_host, 5269;
94                 
95                 local answer = dns.lookup("_xmpp-server._tcp."..to_host..".", "SRV");
96                 
97                 if answer then
98                         log("debug", to_host.." has SRV records, handling...");
99                         local srv_hosts = {};
100                         host_session.srv_hosts = srv_hosts;
101                         for _, record in ipairs(answer) do
102                                 t_insert(srv_hosts, record.srv);
103                         end
104                         t_sort(srv_hosts, compare_srv_priorities);
105                         
106                         local srv_choice = srv_hosts[1];
107                         if srv_choice then
108                                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
109                                 log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
110                         end
111                 end
112                 
113                 conn:settimeout(0);
114                 local success, err = conn:connect(connect_host, connect_port);
115                 if not success and err ~= "timeout" then
116                         log("warn", "s2s connect() failed: %s", err);
117                 end
118                 
119                 conn = wraptlsclient(cl, conn, connect_host, connect_port, 0, 1, hosts[from_host].ssl_ctx );
120                 host_session.conn = conn;
121                 
122                 -- Register this outgoing connection so that xmppserver_listener knows about it
123                 -- otherwise it will assume it is a new incoming connection
124                 cl.register_outgoing(conn, host_session);
125                 
126                 local log;
127                 do
128                         local conn_name = "s2sout"..tostring(conn):match("[a-f0-9]*$");
129                         log = logger_init(conn_name);
130                         host_session.log = log;
131                 end
132                 
133                 local w = conn.write;
134                 host_session.sends2s = function (t) log("debug", "sending: %s", tostring(t)); w(tostring(t)); end
135                 
136                 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));
137                  
138                 return host_session;
139 end
140
141 function streamopened(session, attr)
142         local send = session.sends2s;
143         
144         session.version = tonumber(attr.version) or 0;
145         if session.version >= 1.0 and not (attr.to and attr.from) then
146                 print("to: "..tostring(attr.to).." from: "..tostring(attr.from));
147                 log("warn", (session.to_host or "(unknown)").." failed to specify 'to' or 'from' hostname as per RFC");
148         end
149         
150         if session.direction == "incoming" then
151                 -- Send a reply stream header
152                 
153                 for k,v in pairs(attr) do print("", tostring(k), ":::", tostring(v)); end
154                 
155                 session.to_host = attr.to;
156                 session.from_host = attr.from;
157         
158                 session.streamid = uuid_gen();
159                 print(session, session.from_host, "incoming s2s stream opened");
160                 send("<?xml version='1.0'?>");
161                 send(stanza("stream:stream", { version = '1.0', xmlns='jabber:server', ["xmlns:db"]='jabber:server:dialback', ["xmlns:stream"]='http://etherx.jabber.org/streams', id=session.streamid, from=session.to_host }):top_tag());
162                 if session.to_host and not hosts[session.to_host] then
163                         -- Attempting to connect to a host we don't serve
164                         session:close("host-unknown");
165                         return;
166                 end
167                 if session.version >= 1.0 then
168                         send(st.stanza("stream:features")
169                                         :tag("dialback", { xmlns='urn:xmpp:features:dialback' }):tag("optional"):up():up());
170                 end
171         elseif session.direction == "outgoing" then
172                 -- If we are just using the connection for verifying dialback keys, we won't try and auth it
173                 if not attr.id then error("stream response did not give us a streamid!!!"); end
174                 session.streamid = attr.id;
175         
176                 if not session.dialback_verifying then
177                         initiate_dialback(session);
178                 else
179                         mark_connected(session);
180                 end
181         end
182
183         session.notopen = nil;
184 end
185
186 function initiate_dialback(session)
187         -- generate dialback key
188         session.dialback_key = generate_dialback(session.streamid, session.to_host, session.from_host);
189         session.sends2s(format("<db:result from='%s' to='%s'>%s</db:result>", session.from_host, session.to_host, session.dialback_key));
190         session.log("info", "sent dialback key on outgoing s2s stream");
191 end
192
193 function generate_dialback(id, to, from)
194         return md5_hash(id..to..from..dialback_secret); -- FIXME: See XEP-185 and XEP-220
195 end
196
197 function verify_dialback(id, to, from, key)
198         return key == generate_dialback(id, to, from);
199 end
200
201 function make_authenticated(session)
202         if session.type == "s2sout_unauthed" then
203                 session.type = "s2sout";
204         elseif session.type == "s2sin_unauthed" then
205                 session.type = "s2sin";
206         else
207                 return false;
208         end
209         session.log("info", "connection is now authenticated");
210         
211         mark_connected(session);
212         
213         return true;
214 end
215
216 function mark_connected(session)
217         local sendq, send = session.sendq, session.sends2s;
218         
219         local from, to = session.from_host, session.to_host;
220         
221         session.log("debug", session.direction.." s2s connection "..from.."->"..to.." is now complete");
222         
223         local send_to_host = send_to_host;
224         function session.send(data) send_to_host(to, from, data); end
225         
226         
227         if session.direction == "outgoing" then
228                 if sendq then
229                         session.log("debug", "sending "..#sendq.." queued stanzas across new outgoing connection to "..session.to_host);
230                         for i, data in ipairs(sendq) do
231                                 send(data);
232                                 sendq[i] = nil;
233                         end
234                         session.sendq = nil;
235                 end
236         end
237 end
238
239 function destroy_session(session)
240         (session.log or log)("info", "Destroying "..tostring(session.direction).." session "..tostring(session.from_host).."->"..tostring(session.to_host));
241         
242         -- FIXME: Flush sendq here/report errors to originators
243         
244         if session.direction == "outgoing" then
245                 hosts[session.from_host].s2sout[session.to_host] = nil;
246         end
247         
248         for k in pairs(session) do
249                 if k ~= "trace" then
250                         session[k] = nil;
251                 end
252         end
253 end
254
255 return _M;