Resolver.java

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