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