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