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