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