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