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