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