Resolver.java

  1package eu.siacs.conversations.utils;
  2
  3import android.content.ContentValues;
  4import android.database.Cursor;
  5import android.support.annotation.NonNull;
  6import android.util.Log;
  7
  8import java.io.IOException;
  9import java.lang.reflect.Field;
 10import java.net.Inet4Address;
 11import java.net.InetAddress;
 12import java.net.UnknownHostException;
 13import java.util.ArrayList;
 14import java.util.Collections;
 15import java.util.List;
 16
 17import de.measite.minidns.AbstractDNSClient;
 18import de.measite.minidns.DNSClient;
 19import de.measite.minidns.DNSName;
 20import de.measite.minidns.Question;
 21import de.measite.minidns.Record;
 22import de.measite.minidns.dnssec.DNSSECResultNotAuthenticException;
 23import de.measite.minidns.dnsserverlookup.AndroidUsingExec;
 24import de.measite.minidns.hla.DnssecResolverApi;
 25import de.measite.minidns.hla.ResolverApi;
 26import de.measite.minidns.hla.ResolverResult;
 27import de.measite.minidns.iterative.ReliableDNSClient;
 28import de.measite.minidns.record.A;
 29import de.measite.minidns.record.AAAA;
 30import de.measite.minidns.record.CNAME;
 31import de.measite.minidns.record.Data;
 32import de.measite.minidns.record.InternetAddressRR;
 33import de.measite.minidns.record.SRV;
 34import eu.siacs.conversations.Config;
 35import eu.siacs.conversations.R;
 36import eu.siacs.conversations.services.XmppConnectionService;
 37
 38public class Resolver {
 39
 40    private static final String DIRECT_TLS_SERVICE = "_xmpps-client";
 41    private static final String STARTTLS_SERICE = "_xmpp-client";
 42
 43    private static XmppConnectionService SERVICE = null;
 44
 45
 46    public static void init(XmppConnectionService service) {
 47        Resolver.SERVICE = service;
 48        DNSClient.removeDNSServerLookupMechanism(AndroidUsingExec.INSTANCE);
 49        DNSClient.addDnsServerLookupMechanism(AndroidUsingExecLowPriority.INSTANCE);
 50        DNSClient.addDnsServerLookupMechanism(new AndroidUsingLinkProperties(service));
 51        final AbstractDNSClient client = ResolverApi.INSTANCE.getClient();
 52        if (client instanceof ReliableDNSClient) {
 53            disableHardcodedDnsServers((ReliableDNSClient) client);
 54        }
 55    }
 56
 57    private static void disableHardcodedDnsServers(ReliableDNSClient reliableDNSClient) {
 58        try {
 59            final Field dnsClientField = ReliableDNSClient.class.getDeclaredField("dnsClient");
 60            dnsClientField.setAccessible(true);
 61            final DNSClient dnsClient = (DNSClient) dnsClientField.get(reliableDNSClient);
 62            dnsClient.getDataSource().setTimeout(3000);
 63            final Field useHardcodedDnsServers = DNSClient.class.getDeclaredField("useHardcodedDnsServers");
 64            useHardcodedDnsServers.setAccessible(true);
 65            useHardcodedDnsServers.setBoolean(dnsClient, false);
 66        } catch (NoSuchFieldException | IllegalAccessException e) {
 67            Log.e(Config.LOGTAG, "Unable to disable hardcoded DNS servers", e);
 68        }
 69    }
 70
 71    public static List<Result> fromHardCoded(String hostname, int port) {
 72        Result result = new Result();
 73        result.hostname = DNSName.from(hostname);
 74        result.port = port;
 75        result.directTls = port == 443 || port == 5223;
 76        result.authenticated = true;
 77        return Collections.singletonList(result);
 78    }
 79
 80
 81    public static List<Result> resolve(String domain) {
 82        final  List<Result> ipResults = fromIpAddress(domain);
 83        if (ipResults.size() > 0) {
 84            return ipResults;
 85        }
 86        final List<Result> results = new ArrayList<>();
 87        final List<Result> fallbackResults = new ArrayList<>();
 88        Thread[] threads = new Thread[3];
 89        threads[0] = new Thread(() -> {
 90            try {
 91                final List<Result> list = resolveSrv(domain, true);
 92                synchronized (results) {
 93                    results.addAll(list);
 94                }
 95            } catch (Throwable throwable) {
 96                Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving SRV record (direct TLS)", throwable);
 97            }
 98        });
 99        threads[1] = new Thread(() -> {
100            try {
101                final List<Result> list = resolveSrv(domain, false);
102                synchronized (results) {
103                    results.addAll(list);
104                }
105            } catch (Throwable throwable) {
106                Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving SRV record (STARTTLS)", throwable);
107            }
108        });
109        threads[2] = new Thread(() -> {
110            List<Result> list = resolveNoSrvRecords(DNSName.from(domain), true);
111            synchronized (fallbackResults) {
112                fallbackResults.addAll(list);
113            }
114        });
115        for (Thread thread : threads) {
116            thread.start();
117        }
118        try {
119            threads[0].join();
120            threads[1].join();
121            if (results.size() > 0) {
122                threads[2].interrupt();
123                synchronized (results) {
124                    Collections.sort(results);
125                    Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": " + results.toString());
126                    return new ArrayList<>(results);
127                }
128            } else {
129                threads[2].join();
130                synchronized (fallbackResults) {
131                    Collections.sort(fallbackResults);
132                    Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": " + fallbackResults.toString());
133                    return new ArrayList<>(fallbackResults);
134                }
135            }
136        } catch (InterruptedException e) {
137            for (Thread thread : threads) {
138                thread.interrupt();
139            }
140            return Collections.emptyList();
141        }
142    }
143
144    private static List<Result> fromIpAddress(String domain) {
145        if (!IP.matches(domain)) {
146            return Collections.emptyList();
147        }
148        try {
149            Result result = new Result();
150            result.ip = InetAddress.getByName(domain);
151            result.port = 5222;
152            return Collections.singletonList(result);
153        } catch (UnknownHostException e) {
154            return Collections.emptyList();
155        }
156    }
157
158    private static List<Result> resolveSrv(String domain, final boolean directTls) throws IOException {
159        DNSName dnsName = DNSName.from((directTls ? DIRECT_TLS_SERVICE : STARTTLS_SERICE) + "._tcp." + domain);
160        ResolverResult<SRV> result = resolveWithFallback(dnsName, SRV.class);
161        final List<Result> results = new ArrayList<>();
162        final List<Thread> threads = new ArrayList<>();
163        for (SRV record : result.getAnswersOrEmptySet()) {
164            if (record.name.length() == 0 && record.priority == 0) {
165                continue;
166            }
167            threads.add(new Thread(() -> {
168                final List<Result> ipv4s = resolveIp(record, A.class, result.isAuthenticData(), directTls);
169                if (ipv4s.size() == 0) {
170                    Result resolverResult = Result.fromRecord(record, directTls);
171                    resolverResult.authenticated = resolverResult.isAuthenticated();
172                    ipv4s.add(resolverResult);
173                }
174                synchronized (results) {
175                    results.addAll(ipv4s);
176                }
177
178            }));
179            threads.add(new Thread(() -> {
180                final List<Result> ipv6s = resolveIp(record, AAAA.class, result.isAuthenticData(), directTls);
181                synchronized (results) {
182                    results.addAll(ipv6s);
183                }
184            }));
185        }
186        for (Thread thread : threads) {
187            thread.start();
188        }
189        for (Thread thread : threads) {
190            try {
191                thread.join();
192            } catch (InterruptedException e) {
193                return Collections.emptyList();
194            }
195        }
196        return results;
197    }
198
199    private static <D extends InternetAddressRR> List<Result> resolveIp(SRV srv, Class<D> type, boolean authenticated, boolean directTls) {
200        List<Result> list = new ArrayList<>();
201        try {
202            ResolverResult<D> results = resolveWithFallback(srv.name, type, authenticated);
203            for (D record : results.getAnswersOrEmptySet()) {
204                Result resolverResult = Result.fromRecord(srv, directTls);
205                resolverResult.authenticated = results.isAuthenticData() && authenticated;
206                resolverResult.ip = record.getInetAddress();
207                list.add(resolverResult);
208            }
209        } catch (Throwable t) {
210            Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " " + t.getMessage());
211        }
212        return list;
213    }
214
215    private static List<Result> resolveNoSrvRecords(DNSName dnsName, boolean withCnames) {
216        List<Result> results = new ArrayList<>();
217        try {
218            for (A a : resolveWithFallback(dnsName, A.class, false).getAnswersOrEmptySet()) {
219                results.add(Result.createDefault(dnsName, a.getInetAddress()));
220            }
221            for (AAAA aaaa : resolveWithFallback(dnsName, AAAA.class, false).getAnswersOrEmptySet()) {
222                results.add(Result.createDefault(dnsName, aaaa.getInetAddress()));
223            }
224            if (results.size() == 0 && withCnames) {
225                for (CNAME cname : resolveWithFallback(dnsName, CNAME.class, false).getAnswersOrEmptySet()) {
226                    results.addAll(resolveNoSrvRecords(cname.name, false));
227                }
228            }
229        } catch (Throwable throwable) {
230            Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + "error resolving fallback records", throwable);
231        }
232        results.add(Result.createDefault(dnsName));
233        return results;
234    }
235
236    private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type) throws IOException {
237        return resolveWithFallback(dnsName, type, validateHostname());
238    }
239
240    private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type, boolean validateHostname) throws IOException {
241        final Question question = new Question(dnsName, Record.TYPE.getType(type));
242        if (!validateHostname) {
243            return ResolverApi.INSTANCE.resolve(question);
244        }
245        try {
246            return DnssecResolverApi.INSTANCE.resolveDnssecReliable(question);
247        } catch (DNSSECResultNotAuthenticException e) {
248            Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", e);
249        } catch (IOException e) {
250            throw e;
251        } catch (Throwable throwable) {
252            Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", throwable);
253        }
254        return ResolverApi.INSTANCE.resolve(question);
255    }
256
257    private static boolean validateHostname() {
258        return SERVICE != null && SERVICE.getBooleanPreference("validate_hostname", R.bool.validate_hostname);
259    }
260
261    public static class Result implements Comparable<Result> {
262        public static final String DOMAIN = "domain";
263        public static final String IP = "ip";
264        public static final String HOSTNAME = "hostname";
265        public static final String PORT = "port";
266        public static final String PRIORITY = "priority";
267        public static final String DIRECT_TLS = "directTls";
268        public static final String AUTHENTICATED = "authenticated";
269        private InetAddress ip;
270        private DNSName hostname;
271        private int port = 5222;
272        private boolean directTls = false;
273        private boolean authenticated = false;
274        private int priority;
275
276        static Result fromRecord(SRV srv, boolean directTls) {
277            Result result = new Result();
278            result.port = srv.port;
279            result.hostname = srv.name;
280            result.directTls = directTls;
281            result.priority = srv.priority;
282            return result;
283        }
284
285        static Result createDefault(DNSName hostname, InetAddress ip) {
286            Result result = new Result();
287            result.port = 5222;
288            result.hostname = hostname;
289            result.ip = ip;
290            return result;
291        }
292
293        static Result createDefault(DNSName hostname) {
294            return createDefault(hostname, null);
295        }
296
297        public static Result fromCursor(Cursor cursor) {
298            final Result result = new Result();
299            try {
300                result.ip = InetAddress.getByAddress(cursor.getBlob(cursor.getColumnIndex(IP)));
301            } catch (UnknownHostException e) {
302                result.ip = null;
303            }
304            result.hostname = DNSName.from(cursor.getString(cursor.getColumnIndex(HOSTNAME)));
305            result.port = cursor.getInt(cursor.getColumnIndex(PORT));
306            result.priority = cursor.getInt(cursor.getColumnIndex(PRIORITY));
307            result.authenticated = cursor.getInt(cursor.getColumnIndex(AUTHENTICATED)) > 0;
308            result.directTls = cursor.getInt(cursor.getColumnIndex(DIRECT_TLS)) > 0;
309            return result;
310        }
311
312        @Override
313        public boolean equals(Object o) {
314            if (this == o) return true;
315            if (o == null || getClass() != o.getClass()) return false;
316
317            Result result = (Result) o;
318
319            if (port != result.port) return false;
320            if (directTls != result.directTls) return false;
321            if (authenticated != result.authenticated) return false;
322            if (priority != result.priority) return false;
323            if (ip != null ? !ip.equals(result.ip) : result.ip != null) return false;
324            return hostname != null ? hostname.equals(result.hostname) : result.hostname == null;
325        }
326
327        @Override
328        public int hashCode() {
329            int result = ip != null ? ip.hashCode() : 0;
330            result = 31 * result + (hostname != null ? hostname.hashCode() : 0);
331            result = 31 * result + port;
332            result = 31 * result + (directTls ? 1 : 0);
333            result = 31 * result + (authenticated ? 1 : 0);
334            result = 31 * result + priority;
335            return result;
336        }
337
338        public InetAddress getIp() {
339            return ip;
340        }
341
342        public int getPort() {
343            return port;
344        }
345
346        public DNSName getHostname() {
347            return hostname;
348        }
349
350        public boolean isDirectTls() {
351            return directTls;
352        }
353
354        public boolean isAuthenticated() {
355            return authenticated;
356        }
357
358        @Override
359        public String toString() {
360            return "Result{" +
361                    "ip='" + (ip == null ? null : ip.getHostAddress()) + '\'' +
362                    ", hostame='" + hostname.toString() + '\'' +
363                    ", port=" + port +
364                    ", directTls=" + directTls +
365                    ", authenticated=" + authenticated +
366                    ", priority=" + priority +
367                    '}';
368        }
369
370        @Override
371        public int compareTo(@NonNull Result result) {
372            if (result.priority == priority) {
373                if (directTls == result.directTls) {
374                    if (ip == null && result.ip == null) {
375                        return 0;
376                    } else if (ip != null && result.ip != null) {
377                        if (ip instanceof Inet4Address && result.ip instanceof Inet4Address) {
378                            return 0;
379                        } else {
380                            return ip instanceof Inet4Address ? -1 : 1;
381                        }
382                    } else {
383                        return ip != null ? -1 : 1;
384                    }
385                } else {
386                    return directTls ? -1 : 1;
387                }
388            } else {
389                return priority - result.priority;
390            }
391        }
392
393        public ContentValues toContentValues() {
394            final ContentValues contentValues = new ContentValues();
395            contentValues.put(IP, ip == null ? null : ip.getAddress());
396            contentValues.put(HOSTNAME, hostname.toString());
397            contentValues.put(PORT, port);
398            contentValues.put(PRIORITY, priority);
399            contentValues.put(DIRECT_TLS, directTls ? 1 : 0);
400            contentValues.put(AUTHENTICATED, authenticated ? 1 : 0);
401            return contentValues;
402        }
403    }
404
405}