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