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