DNSHelper.java

  1package eu.siacs.conversations.utils;
  2
  3import android.annotation.TargetApi;
  4import android.content.Context;
  5import android.net.ConnectivityManager;
  6import android.net.LinkProperties;
  7import android.net.Network;
  8import android.net.RouteInfo;
  9import android.os.Build;
 10import android.os.Bundle;
 11import android.os.Parcelable;
 12import android.util.Log;
 13
 14import java.io.IOException;
 15import java.net.Inet4Address;
 16import java.net.InetAddress;
 17import java.net.SocketTimeoutException;
 18import java.net.UnknownHostException;
 19import java.util.ArrayList;
 20import java.util.Collections;
 21import java.util.List;
 22import java.util.Locale;
 23import java.util.Random;
 24import java.util.TreeMap;
 25import java.util.Map;
 26import java.util.regex.Pattern;
 27
 28import de.measite.minidns.Client;
 29import de.measite.minidns.DNSMessage;
 30import de.measite.minidns.Record;
 31import de.measite.minidns.Record.CLASS;
 32import de.measite.minidns.Record.TYPE;
 33import de.measite.minidns.record.A;
 34import de.measite.minidns.record.AAAA;
 35import de.measite.minidns.record.Data;
 36import de.measite.minidns.record.SRV;
 37import de.measite.minidns.util.NameUtil;
 38import eu.siacs.conversations.Config;
 39import eu.siacs.conversations.xmpp.jid.Jid;
 40
 41public class DNSHelper {
 42
 43	public static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
 44	public static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
 45	public static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
 46	public static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
 47	public static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
 48
 49	protected static Client client = new Client();
 50
 51	protected static Context context;
 52
 53	public static Bundle getSRVRecord(final Jid jid, Context context) throws IOException {
 54		DNSHelper.context = context;
 55        final String host = jid.getDomainpart();
 56		final List<InetAddress> servers = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? getDnsServers(context) : getDnsServersPreLollipop();
 57		Bundle b = new Bundle();
 58		boolean interrupted = false;
 59		for(InetAddress server : servers) {
 60			if (Thread.currentThread().isInterrupted()) {
 61				interrupted = true;
 62				break;
 63			}
 64			b = queryDNS(host, server);
 65			if (b.containsKey("values")) {
 66				return b;
 67			}
 68		}
 69		if (!b.containsKey("values")) {
 70			Log.d(Config.LOGTAG,(interrupted ? "Thread interrupted during DNS query" :"all dns queries failed") + ". provide fallback A record");
 71			ArrayList<Parcelable> values = new ArrayList<>();
 72			values.add(createNamePortBundle(host, 5222, false));
 73			b.putParcelableArrayList("values",values);
 74		}
 75		return b;
 76	}
 77
 78	@TargetApi(21)
 79	private static List<InetAddress> getDnsServers(Context context) {
 80		List<InetAddress> servers = new ArrayList<>();
 81		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 82		Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
 83		if (networks == null) {
 84			return getDnsServersPreLollipop();
 85		}
 86		for(int i = 0; i < networks.length; ++i) {
 87			LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]);
 88			if (linkProperties != null) {
 89				if (hasDefaultRoute(linkProperties)) {
 90					servers.addAll(0, getIPv4First(linkProperties.getDnsServers()));
 91				} else {
 92					servers.addAll(getIPv4First(linkProperties.getDnsServers()));
 93				}
 94			}
 95		}
 96		if (servers.size() > 0) {
 97			Log.d(Config.LOGTAG, "used lollipop variant to discover dns servers in " + networks.length + " networks");
 98		}
 99		return servers.size() > 0 ? servers : getDnsServersPreLollipop();
100	}
101
102	private static List<InetAddress> getIPv4First(List<InetAddress> in) {
103		List<InetAddress> out = new ArrayList<>();
104		for(InetAddress addr : in) {
105			if (addr instanceof Inet4Address) {
106				out.add(0, addr);
107			} else {
108				out.add(addr);
109			}
110		}
111		return out;
112	}
113
114	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
115	private static boolean hasDefaultRoute(LinkProperties linkProperties) {
116		for(RouteInfo route: linkProperties.getRoutes()) {
117			if (route.isDefaultRoute()) {
118				return true;
119			}
120		}
121		return false;
122	}
123
124	private static List<InetAddress> getDnsServersPreLollipop() {
125		List<InetAddress> servers = new ArrayList<>();
126		String[] dns = client.findDNS();
127		for(int i = 0; i < dns.length; ++i) {
128			try {
129				servers.add(InetAddress.getByName(dns[i]));
130			} catch (UnknownHostException e) {
131				//ignore
132			}
133		}
134		return servers;
135	}
136
137	private static class TlsSrv {
138		private final SRV srv;
139		private final boolean tls;
140
141		public TlsSrv(SRV srv, boolean tls) {
142			this.srv = srv;
143			this.tls = tls;
144		}
145	}
146
147	private static void fillSrvMaps(final String qname, final InetAddress dnsServer, final Map<Integer, List<TlsSrv>> priorities, final Map<String, List<String>> ips4, final Map<String, List<String>> ips6, final boolean tls) throws IOException {
148		final DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN, dnsServer.getHostAddress());
149		for (Record[] rrset : new Record[][] { message.getAnswers(), message.getAdditionalResourceRecords() }) {
150			for (Record rr : rrset) {
151				Data d = rr.getPayload();
152				final String name = rr.getName() != null ? rr.getName().toLowerCase(Locale.US) : null;
153				if (d instanceof SRV && NameUtil.idnEquals(qname, name)) {
154					SRV srv = (SRV) d;
155					if (!priorities.containsKey(srv.getPriority())) {
156						priorities.put(srv.getPriority(),new ArrayList<TlsSrv>());
157					}
158					priorities.get(srv.getPriority()).add(new TlsSrv(srv, tls));
159				} else if (d instanceof SRV) {
160					Log.d(Config.LOGTAG,"found unrecognized SRV record with name: "+name);
161				}
162				if (d instanceof A) {
163					A a = (A) d;
164					if (!ips4.containsKey(name)) {
165						ips4.put(name, new ArrayList<String>());
166					}
167					ips4.get(name).add(a.toString());
168				}
169				if (d instanceof AAAA) {
170					AAAA aaaa = (AAAA) d;
171					if (!ips6.containsKey(name)) {
172						ips6.put(name, new ArrayList<String>());
173					}
174					ips6.get(name).add("[" + aaaa.toString() + "]");
175				}
176			}
177		}
178	}
179
180	public static Bundle queryDNS(String host, InetAddress dnsServer) {
181		Bundle bundle = new Bundle();
182		try {
183			client.setTimeout(Config.SOCKET_TIMEOUT * 1000);
184			final String qname = "_xmpp-client._tcp." + host.toLowerCase(Locale.US);
185			final String tlsQname = "_xmpps-client._tcp." + host.toLowerCase(Locale.US);
186			Log.d(Config.LOGTAG, "using dns server: " + dnsServer.getHostAddress() + " to look up " + host);
187
188			final Map<Integer, List<TlsSrv>> priorities = new TreeMap<>();
189			final Map<String, List<String>> ips4 = new TreeMap<>();
190			final Map<String, List<String>> ips6 = new TreeMap<>();
191
192			fillSrvMaps(qname, dnsServer, priorities, ips4, ips6, false);
193			fillSrvMaps(tlsQname, dnsServer, priorities, ips4, ips6, true);
194
195			final List<TlsSrv> result = new ArrayList<>();
196			for (final List<TlsSrv> s : priorities.values()) {
197				result.addAll(s);
198			}
199
200			final ArrayList<Bundle> values = new ArrayList<>();
201			if (result.size() == 0) {
202				DNSMessage response;
203				try {
204					response = client.query(host, TYPE.A, CLASS.IN, dnsServer.getHostAddress());
205					for (int i = 0; i < response.getAnswers().length; ++i) {
206						values.add(createNamePortBundle(host, 5222, response.getAnswers()[i].getPayload(), false));
207					}
208				} catch (SocketTimeoutException e) {
209					Log.d(Config.LOGTAG,"ignoring timeout exception when querying A record on "+dnsServer.getHostAddress());
210				}
211				try {
212					response = client.query(host, TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
213					for (int i = 0; i < response.getAnswers().length; ++i) {
214						values.add(createNamePortBundle(host, 5222, response.getAnswers()[i].getPayload(), false));
215					}
216				} catch (SocketTimeoutException e) {
217					Log.d(Config.LOGTAG,"ignoring timeout exception when querying AAAA record on "+dnsServer.getHostAddress());
218				}
219				values.add(createNamePortBundle(host, 5222, false));
220				bundle.putParcelableArrayList("values", values);
221				return bundle;
222			}
223			for (final TlsSrv tlsSrv : result) {
224				final SRV srv = tlsSrv.srv;
225				final String name = srv.getName() != null ? srv.getName().toLowerCase(Locale.US) : null;
226				if (ips6.containsKey(name)) {
227					values.add(createNamePortBundle(name,srv.getPort(),ips6, tlsSrv.tls));
228				} else {
229					try {
230						DNSMessage response = client.query(name, TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
231						for (int i = 0; i < response.getAnswers().length; ++i) {
232							values.add(createNamePortBundle(name, srv.getPort(), response.getAnswers()[i].getPayload(), tlsSrv.tls));
233						}
234					} catch (SocketTimeoutException e) {
235						Log.d(Config.LOGTAG,"ignoring timeout exception when querying AAAA record on "+dnsServer.getHostAddress());
236					}
237				}
238				if (ips4.containsKey(name)) {
239					values.add(createNamePortBundle(name,srv.getPort(),ips4, tlsSrv.tls));
240				} else {
241					DNSMessage response = client.query(name, TYPE.A, CLASS.IN, dnsServer.getHostAddress());
242					for(int i = 0; i < response.getAnswers().length; ++i) {
243						values.add(createNamePortBundle(name,srv.getPort(),response.getAnswers()[i].getPayload(), tlsSrv.tls));
244					}
245				}
246				values.add(createNamePortBundle(name, srv.getPort(), tlsSrv.tls));
247			}
248			bundle.putParcelableArrayList("values", values);
249		} catch (SocketTimeoutException e) {
250			bundle.putString("error", "timeout");
251		} catch (Exception e) {
252			bundle.putString("error", "unhandled");
253		}
254		return bundle;
255	}
256
257	private static Bundle createNamePortBundle(String name, int port, final boolean tls) {
258		Bundle namePort = new Bundle();
259		namePort.putString("name", name);
260		namePort.putBoolean("tls", tls);
261		namePort.putInt("port", port);
262		return namePort;
263	}
264
265	private static Bundle createNamePortBundle(String name, int port, Map<String, List<String>> ips, final boolean tls) {
266		Bundle namePort = new Bundle();
267		namePort.putString("name", name);
268		namePort.putBoolean("tls", tls);
269		namePort.putInt("port", port);
270		if (ips!=null) {
271			List<String> ip = ips.get(name);
272			Collections.shuffle(ip, new Random());
273			namePort.putString("ip", ip.get(0));
274		}
275		return namePort;
276	}
277
278	private static Bundle createNamePortBundle(String name, int port, Data data, final boolean tls) {
279		Bundle namePort = new Bundle();
280		namePort.putString("name", name);
281		namePort.putBoolean("tls", tls);
282		namePort.putInt("port", port);
283		if (data instanceof A) {
284			namePort.putString("ip", data.toString());
285		} else if (data instanceof AAAA) {
286			namePort.putString("ip","["+data.toString()+"]");
287		}
288		return namePort;
289	}
290
291	public static boolean isIp(final String server) {
292		return server != null && (
293				PATTERN_IPV4.matcher(server).matches()
294				|| PATTERN_IPV6.matcher(server).matches()
295				|| PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
296				|| PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
297				|| PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
298	}
299}