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