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