mod_s2s: Lower "Beginning new connection attempt" message from info to debug level
[prosody.git] / plugins / mod_s2s / s2sout.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 --- Module containing all the logic for connecting to a remote server
10
11 local portmanager = require "core.portmanager";
12 local wrapclient = require "net.server".wrapclient;
13 local initialize_filters = require "util.filters".initialize;
14 local idna_to_ascii = require "util.encodings".idna.to_ascii;
15 local new_ip = require "util.ip".new_ip;
16 local rfc6724_dest = require "util.rfc6724".destination;
17 local socket = require "socket";
18 local adns = require "net.adns";
19 local dns = require "net.dns";
20 local t_insert, t_sort, ipairs = table.insert, table.sort, ipairs;
21 local local_addresses = require "util.net".local_addresses;
22
23 local s2s_destroy_session = require "core.s2smanager".destroy_session;
24
25 local log = module._log;
26
27 local sources = {};
28 local has_ipv4, has_ipv6;
29
30 local dns_timeout = module:get_option_number("dns_timeout", 15);
31 dns.settimeout(dns_timeout);
32 local max_dns_depth = module:get_option_number("dns_max_depth", 3);
33
34 local s2sout = {};
35
36 local s2s_listener;
37
38
39 function s2sout.set_listener(listener)
40         s2s_listener = listener;
41 end
42
43 local function compare_srv_priorities(a,b)
44         return a.priority < b.priority or (a.priority == b.priority and a.weight > b.weight);
45 end
46
47 function s2sout.initiate_connection(host_session)
48         initialize_filters(host_session);
49         host_session.version = 1;
50
51         -- Kick the connection attempting machine into life
52         if not s2sout.attempt_connection(host_session) then
53                 -- Intentionally not returning here, the
54                 -- session is needed, connected or not
55                 s2s_destroy_session(host_session);
56         end
57
58         if not host_session.sends2s then
59                 -- A sends2s which buffers data (until the stream is opened)
60                 -- note that data in this buffer will be sent before the stream is authed
61                 -- and will not be ack'd in any way, successful or otherwise
62                 local buffer;
63                 function host_session.sends2s(data)
64                         if not buffer then
65                                 buffer = {};
66                                 host_session.send_buffer = buffer;
67                         end
68                         log("debug", "Buffering data on unconnected s2sout to %s", tostring(host_session.to_host));
69                         buffer[#buffer+1] = data;
70                         log("debug", "Buffered item %d: %s", #buffer, tostring(data));
71                 end
72         end
73 end
74
75 function s2sout.attempt_connection(host_session, err)
76         local to_host = host_session.to_host;
77         local connect_host, connect_port = to_host and idna_to_ascii(to_host), 5269;
78
79         if not connect_host then
80                 return false;
81         end
82
83         if not err then -- This is our first attempt
84                 log("debug", "First attempt to connect to %s, starting with SRV lookup...", to_host);
85                 host_session.connecting = true;
86                 local handle;
87                 handle = adns.lookup(function (answer)
88                         handle = nil;
89                         host_session.connecting = nil;
90                         if answer and #answer > 0 then
91                                 log("debug", "%s has SRV records, handling...", to_host);
92                                 local srv_hosts = { answer = answer };
93                                 host_session.srv_hosts = srv_hosts;
94                                 for _, record in ipairs(answer) do
95                                         t_insert(srv_hosts, record.srv);
96                                 end
97                                 if #srv_hosts == 1 and srv_hosts[1].target == "." then
98                                         log("debug", "%s does not provide a XMPP service", to_host);
99                                         s2s_destroy_session(host_session, err); -- Nothing to see here
100                                         return;
101                                 end
102                                 t_sort(srv_hosts, compare_srv_priorities);
103
104                                 local srv_choice = srv_hosts[1];
105                                 host_session.srv_choice = 1;
106                                 if srv_choice then
107                                         connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
108                                         log("debug", "Best record found, will connect to %s:%d", connect_host, connect_port);
109                                 end
110                         else
111                                 log("debug", "%s has no SRV records, falling back to A/AAAA", to_host);
112                         end
113                         -- Try with SRV, or just the plain hostname if no SRV
114                         local ok, err = s2sout.try_connect(host_session, connect_host, connect_port);
115                         if not ok then
116                                 if not s2sout.attempt_connection(host_session, err) then
117                                         -- No more attempts will be made
118                                         s2s_destroy_session(host_session, err);
119                                 end
120                         end
121                 end, "_xmpp-server._tcp."..connect_host..".", "SRV");
122
123                 return true; -- Attempt in progress
124         elseif host_session.ip_hosts then
125                 return s2sout.try_connect(host_session, connect_host, connect_port, err);
126         elseif host_session.srv_hosts and #host_session.srv_hosts > host_session.srv_choice then -- Not our first attempt, and we also have SRV
127                 host_session.srv_choice = host_session.srv_choice + 1;
128                 local srv_choice = host_session.srv_hosts[host_session.srv_choice];
129                 connect_host, connect_port = srv_choice.target or to_host, srv_choice.port or connect_port;
130                 host_session.log("info", "Connection failed (%s). Attempt #%d: This time to %s:%d", tostring(err), host_session.srv_choice, connect_host, connect_port);
131         else
132                 host_session.log("info", "Failed in all attempts to connect to %s", tostring(host_session.to_host));
133                 -- We're out of options
134                 return false;
135         end
136
137         if not (connect_host and connect_port) then
138                 -- Likely we couldn't resolve DNS
139                 log("warn", "Hmm, we're without a host (%s) and port (%s) to connect to for %s, giving up :(", tostring(connect_host), tostring(connect_port), tostring(to_host));
140                 return false;
141         end
142
143         return s2sout.try_connect(host_session, connect_host, connect_port);
144 end
145
146 function s2sout.try_next_ip(host_session)
147         host_session.connecting = nil;
148         host_session.ip_choice = host_session.ip_choice + 1;
149         local ip = host_session.ip_hosts[host_session.ip_choice];
150         local ok, err= s2sout.make_connect(host_session, ip.ip, ip.port);
151         if not ok then
152                 if not s2sout.attempt_connection(host_session, err or "closed") then
153                         err = err and (": "..err) or "";
154                         s2s_destroy_session(host_session, "Connection failed"..err);
155                 end
156         end
157 end
158
159 function s2sout.try_connect(host_session, connect_host, connect_port, err)
160         host_session.connecting = true;
161
162         if not err then
163                 local IPs = {};
164                 host_session.ip_hosts = IPs;
165                 local handle4, handle6;
166                 local have_other_result = not(has_ipv4) or not(has_ipv6) or false;
167
168                 if has_ipv4 then
169                         handle4 = adns.lookup(function (reply, err)
170                                 handle4 = nil;
171
172                                 -- COMPAT: This is a compromise for all you CNAME-(ab)users :)
173                                 if not (reply and reply[#reply] and reply[#reply].a) then
174                                         local count = max_dns_depth;
175                                         reply = dns.peek(connect_host, "CNAME", "IN");
176                                         while count > 0 and reply and reply[#reply] and not reply[#reply].a and reply[#reply].cname do
177                                                 log("debug", "Looking up %s (DNS depth is %d)", tostring(reply[#reply].cname), count);
178                                                 reply = dns.peek(reply[#reply].cname, "A", "IN") or dns.peek(reply[#reply].cname, "CNAME", "IN");
179                                                 count = count - 1;
180                                         end
181                                 end
182                                 -- end of CNAME resolving
183
184                                 if reply and reply[#reply] and reply[#reply].a then
185                                         for _, ip in ipairs(reply) do
186                                                 log("debug", "DNS reply for %s gives us %s", connect_host, ip.a);
187                                                 IPs[#IPs+1] = new_ip(ip.a, "IPv4");
188                                         end
189                                 end
190
191                                 if have_other_result then
192                                         if #IPs > 0 then
193                                                 rfc6724_dest(host_session.ip_hosts, sources);
194                                                 for i = 1, #IPs do
195                                                         IPs[i] = {ip = IPs[i], port = connect_port};
196                                                 end
197                                                 host_session.ip_choice = 0;
198                                                 s2sout.try_next_ip(host_session);
199                                         else
200                                                 log("debug", "DNS lookup failed to get a response for %s", connect_host);
201                                                 host_session.ip_hosts = nil;
202                                                 if not s2sout.attempt_connection(host_session, "name resolution failed") then -- Retry if we can
203                                                         log("debug", "No other records to try for %s - destroying", host_session.to_host);
204                                                         err = err and (": "..err) or "";
205                                                         s2s_destroy_session(host_session, "DNS resolution failed"..err); -- End of the line, we can't
206                                                 end
207                                         end
208                                 else
209                                         have_other_result = true;
210                                 end
211                         end, connect_host, "A", "IN");
212                 else
213                         have_other_result = true;
214                 end
215
216                 if has_ipv6 then
217                         handle6 = adns.lookup(function (reply, err)
218                                 handle6 = nil;
219
220                                 if reply and reply[#reply] and reply[#reply].aaaa then
221                                         for _, ip in ipairs(reply) do
222                                                 log("debug", "DNS reply for %s gives us %s", connect_host, ip.aaaa);
223                                                 IPs[#IPs+1] = new_ip(ip.aaaa, "IPv6");
224                                         end
225                                 end
226
227                                 if have_other_result then
228                                         if #IPs > 0 then
229                                                 rfc6724_dest(host_session.ip_hosts, sources);
230                                                 for i = 1, #IPs do
231                                                         IPs[i] = {ip = IPs[i], port = connect_port};
232                                                 end
233                                                 host_session.ip_choice = 0;
234                                                 s2sout.try_next_ip(host_session);
235                                         else
236                                                 log("debug", "DNS lookup failed to get a response for %s", connect_host);
237                                                 host_session.ip_hosts = nil;
238                                                 if not s2sout.attempt_connection(host_session, "name resolution failed") then -- Retry if we can
239                                                         log("debug", "No other records to try for %s - destroying", host_session.to_host);
240                                                         err = err and (": "..err) or "";
241                                                         s2s_destroy_session(host_session, "DNS resolution failed"..err); -- End of the line, we can't
242                                                 end
243                                         end
244                                 else
245                                         have_other_result = true;
246                                 end
247                         end, connect_host, "AAAA", "IN");
248                 else
249                         have_other_result = true;
250                 end
251                 return true;
252         elseif host_session.ip_hosts and #host_session.ip_hosts > host_session.ip_choice then -- Not our first attempt, and we also have IPs left to try
253                 s2sout.try_next_ip(host_session);
254         else
255                 host_session.ip_hosts = nil;
256                 if not s2sout.attempt_connection(host_session, "out of IP addresses") then -- Retry if we can
257                         log("debug", "No other records to try for %s - destroying", host_session.to_host);
258                         err = err and (": "..err) or "";
259                         s2s_destroy_session(host_session, "Connecting failed"..err); -- End of the line, we can't
260                         return false;
261                 end
262         end
263
264         return true;
265 end
266
267 function s2sout.make_connect(host_session, connect_host, connect_port)
268         (host_session.log or log)("debug", "Beginning new connection attempt to %s ([%s]:%d)", host_session.to_host, connect_host.addr, connect_port);
269
270         -- Reset secure flag in case this is another
271         -- connection attempt after a failed STARTTLS
272         host_session.secure = nil;
273
274         local conn, handler;
275         local proto = connect_host.proto;
276         if proto == "IPv4" then
277                 conn, handler = socket.tcp();
278         elseif proto == "IPv6" and socket.tcp6 then
279                 conn, handler = socket.tcp6();
280         else
281                 handler = "Unsupported protocol: "..tostring(proto);
282         end
283
284         if not conn then
285                 log("warn", "Failed to create outgoing connection, system error: %s", handler);
286                 return false, handler;
287         end
288
289         conn:settimeout(0);
290         local success, err = conn:connect(connect_host.addr, connect_port);
291         if not success and err ~= "timeout" then
292                 log("warn", "s2s connect() to %s (%s:%d) failed: %s", host_session.to_host, connect_host.addr, connect_port, err);
293                 return false, err;
294         end
295
296         conn = wrapclient(conn, connect_host.addr, connect_port, s2s_listener, "*a");
297         host_session.conn = conn;
298
299         local filter = initialize_filters(host_session);
300         local w, log = conn.write, host_session.log;
301         host_session.sends2s = function (t)
302                 log("debug", "sending: %s", (t.top_tag and t:top_tag()) or t:match("^[^>]*>?"));
303                 if t.name then
304                         t = filter("stanzas/out", t);
305                 end
306                 if t then
307                         t = filter("bytes/out", tostring(t));
308                         if t then
309                                 return w(conn, tostring(t));
310                         end
311                 end
312         end
313
314         -- Register this outgoing connection so that xmppserver_listener knows about it
315         -- otherwise it will assume it is a new incoming connection
316         s2s_listener.register_outgoing(conn, host_session);
317
318         log("debug", "Connection attempt in progress...");
319         return true;
320 end
321
322 module:hook_global("service-added", function (event)
323         if event.name ~= "s2s" then return end
324
325         local s2s_sources = portmanager.get_active_services():get("s2s");
326         if not s2s_sources then
327                 module:log("warn", "s2s not listening on any ports, outgoing connections may fail");
328                 return;
329         end
330         for source, _ in pairs(s2s_sources) do
331                 if source == "*" or source == "0.0.0.0" then
332                         for _, addr in ipairs(local_addresses("ipv4", true)) do
333                                 sources[#sources + 1] = new_ip(addr, "IPv4");
334                         end
335                 elseif source == "::" then
336                         for _, addr in ipairs(local_addresses("ipv6", true)) do
337                                 sources[#sources + 1] = new_ip(addr, "IPv6");
338                         end
339                 else
340                         sources[#sources + 1] = new_ip(source, (source:find(":") and "IPv6") or "IPv4");
341                 end
342         end
343         for i = 1,#sources do
344                 if sources[i].proto == "IPv6" then
345                         has_ipv6 = true;
346                 elseif sources[i].proto == "IPv4" then
347                         has_ipv4 = true;
348                 end
349         end
350 end);
351
352 return s2sout;