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