1package eu.siacs.conversations.utils;
2
3import android.content.Context;
4import android.support.annotation.NonNull;
5import android.util.Log;
6
7import java.io.IOException;
8import java.net.Inet4Address;
9import java.net.InetAddress;
10import java.util.ArrayList;
11import java.util.Collections;
12import java.util.HashSet;
13import java.util.List;
14
15import de.measite.minidns.DNSClient;
16import de.measite.minidns.DNSName;
17import de.measite.minidns.dnssec.DNSSECResultNotAuthenticException;
18import de.measite.minidns.hla.DnssecResolverApi;
19import de.measite.minidns.hla.ResolverApi;
20import de.measite.minidns.hla.ResolverResult;
21import de.measite.minidns.record.A;
22import de.measite.minidns.record.AAAA;
23import de.measite.minidns.record.CNAME;
24import de.measite.minidns.record.Data;
25import de.measite.minidns.record.InternetAddressRR;
26import de.measite.minidns.record.SRV;
27import de.measite.minidns.util.MultipleIoException;
28import eu.siacs.conversations.Config;
29import eu.siacs.conversations.R;
30import eu.siacs.conversations.services.XmppConnectionService;
31
32public class Resolver {
33
34 private static final String DIRECT_TLS_SERVICE = "_xmpps-client";
35 private static final String STARTTLS_SERICE = "_xmpp-client";
36
37 private static final String NETWORK_IS_UNREACHABLE = "Network is unreachable";
38
39 private static XmppConnectionService SERVICE = null;
40
41
42 public static void registerXmppConnectionService(XmppConnectionService service) {
43 Resolver.SERVICE = service;
44 registerLookupMechanism(service);
45 }
46
47 private static void registerLookupMechanism(Context context) {
48 DNSClient.addDnsServerLookupMechanism(new AndroidUsingLinkProperties(context));
49 }
50
51 public static List<Result> resolve(String domain) throws NetworkIsUnreachableException {
52 List<Result> results = new ArrayList<>();
53 HashSet<String> messages = new HashSet<>();
54 try {
55 results.addAll(resolveSrv(domain, true));
56 } catch (MultipleIoException e) {
57 messages.addAll(extractMessages(e));
58 } catch (Throwable throwable) {
59 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": error resolving SRV record (direct TLS)",throwable);
60 }
61 try {
62 results.addAll(resolveSrv(domain, false));
63 } catch (MultipleIoException e) {
64 messages.addAll(extractMessages(e));
65 } catch (Throwable throwable) {
66 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": error resolving SRV record (STARTTLS)",throwable);
67 }
68 if (results.size() == 0) {
69 if (messages.size() == 1 && messages.contains(NETWORK_IS_UNREACHABLE)) {
70 throw new NetworkIsUnreachableException();
71 }
72 results.addAll(resolveNoSrvRecords(DNSName.from(domain),true));
73 }
74 Collections.sort(results);
75 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": "+results.toString());
76 return results;
77 }
78
79 private static HashSet<String> extractMessages(MultipleIoException e) {
80 HashSet<String> messages = new HashSet<>();
81 for(Exception inner : e.getExceptions()) {
82 if (inner instanceof MultipleIoException) {
83 messages.addAll(extractMessages((MultipleIoException) inner));
84 } else {
85 messages.add(inner.getMessage());
86 }
87 }
88 return messages;
89 }
90
91 private static List<Result> resolveSrv(String domain, final boolean directTls) throws IOException {
92 if (Thread.currentThread().isInterrupted()) {
93 return Collections.emptyList();
94 }
95 DNSName dnsName = DNSName.from((directTls ? DIRECT_TLS_SERVICE : STARTTLS_SERICE)+"._tcp."+domain);
96 ResolverResult<SRV> result = resolveWithFallback(dnsName,SRV.class);
97 List<Result> results = new ArrayList<>();
98 for(SRV record : result.getAnswersOrEmptySet()) {
99 final boolean addedIPv4 = results.addAll(resolveIp(record,A.class,result.isAuthenticData(),directTls));
100 results.addAll(resolveIp(record,AAAA.class,result.isAuthenticData(),directTls));
101 if (!addedIPv4 && !Thread.currentThread().isInterrupted()) {
102 Result resolverResult = Result.fromRecord(record, directTls);
103 resolverResult.authenticated = resolverResult.isAuthenticated();
104 results.add(resolverResult);
105 }
106 }
107 return results;
108 }
109
110 private static <D extends InternetAddressRR> List<Result> resolveIp(SRV srv, Class<D> type, boolean authenticated, boolean directTls) {
111 if (Thread.currentThread().isInterrupted()) {
112 return Collections.emptyList();
113 }
114 List<Result> list = new ArrayList<>();
115 try {
116 //TODO fix the DNSName.from(srv.name.toString() workaround once minidns 0.2.2 is out
117 ResolverResult<D> results = resolveWithFallback(DNSName.from(srv.name.toString()),type, authenticated);
118 for (D record : results.getAnswersOrEmptySet()) {
119 Result resolverResult = Result.fromRecord(srv, directTls);
120 resolverResult.authenticated = results.isAuthenticData() && authenticated;
121 resolverResult.ip = record.getInetAddress();
122 list.add(resolverResult);
123 }
124 } catch (Throwable t) {
125 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": error resolving "+type.getSimpleName()+" "+t.getMessage());
126 }
127 return list;
128 }
129
130 private static List<Result> resolveNoSrvRecords(DNSName dnsName, boolean withCnames) {
131 List<Result> results = new ArrayList<>();
132 try {
133 for(A a : resolveWithFallback(dnsName,A.class,false).getAnswersOrEmptySet()) {
134 results.add(Result.createDefault(dnsName,a.getInetAddress()));
135 }
136 for(AAAA aaaa : resolveWithFallback(dnsName,AAAA.class,false).getAnswersOrEmptySet()) {
137 results.add(Result.createDefault(dnsName,aaaa.getInetAddress()));
138 }
139 if (results.size() == 0 && withCnames) {
140 for (CNAME cname : resolveWithFallback(dnsName, CNAME.class, false).getAnswersOrEmptySet()) {
141 results.addAll(resolveNoSrvRecords(cname.name, false));
142 }
143 }
144 } catch (Throwable throwable) {
145 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + "error resolving fallback records",throwable);
146 }
147 results.add(Result.createDefault(dnsName));
148 return results;
149 }
150
151 private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type) throws IOException {
152 return resolveWithFallback(dnsName,type,validateHostname());
153 }
154
155 private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type, boolean validateHostname) throws IOException {
156 if (!validateHostname) {
157 return ResolverApi.INSTANCE.resolve(dnsName, type);
158 }
159 try {
160 final ResolverResult<D> r = DnssecResolverApi.INSTANCE.resolveDnssecReliable(dnsName, type);
161 if (r.wasSuccessful()) {
162 if (r.getAnswers().isEmpty() && type.equals(SRV.class)) {
163 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": resolving SRV records of " + dnsName.toString() + " with DNSSEC yielded empty result");
164 }
165 return r;
166 }
167 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", r.getResolutionUnsuccessfulException());
168 } catch (DNSSECResultNotAuthenticException e) {
169 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", e);
170 } catch (IOException e) {
171 throw e;
172 } catch (Throwable throwable) {
173 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", throwable);
174 }
175 return ResolverApi.INSTANCE.resolve(dnsName, type);
176 }
177
178 private static boolean validateHostname() {
179 return SERVICE != null && SERVICE.getBooleanPreference("validate_hostname", R.bool.validate_hostname);
180 }
181
182 public static class Result implements Comparable<Result> {
183 private InetAddress ip;
184 private DNSName hostname;
185 private int port = 5222;
186 private boolean directTls = false;
187 private boolean authenticated =false;
188 private int priority;
189
190 public InetAddress getIp() {
191 return ip;
192 }
193
194 public int getPort() {
195 return port;
196 }
197
198 public DNSName getHostname() {
199 return hostname;
200 }
201
202 public boolean isDirectTls() {
203 return directTls;
204 }
205
206 public boolean isAuthenticated() {
207 return authenticated;
208 }
209
210 @Override
211 public String toString() {
212 return "Result{" +
213 "ip='" + (ip==null?null:ip.getHostAddress()) + '\'' +
214 ", hostame='" + hostname.toString() + '\'' +
215 ", port=" + port +
216 ", directTls=" + directTls +
217 ", authenticated=" + authenticated +
218 ", priority=" + priority +
219 '}';
220 }
221
222 @Override
223 public int compareTo(@NonNull Result result) {
224 if (result.priority == priority) {
225 if (directTls == result.directTls) {
226 if (ip == null && result.ip == null) {
227 return 0;
228 } else if (ip != null && result.ip != null) {
229 if (ip instanceof Inet4Address && result.ip instanceof Inet4Address) {
230 return 0;
231 } else {
232 return ip instanceof Inet4Address ? -1 : 1;
233 }
234 } else {
235 return ip != null ? -1 : 1;
236 }
237 } else {
238 return directTls ? -1 : 1;
239 }
240 } else {
241 return priority - result.priority;
242 }
243 }
244
245 public static Result fromRecord(SRV srv, boolean directTls) {
246 Result result = new Result();
247 result.port = srv.port;
248 result.hostname = srv.name;
249 result.directTls = directTls;
250 result.priority = srv.priority;
251 return result;
252 }
253
254 public static Result createDefault(DNSName hostname, InetAddress ip) {
255 Result result = new Result();
256 result.port = 5222;
257 result.hostname = hostname;
258 result.ip = ip;
259 return result;
260 }
261
262 public static Result createDefault(DNSName hostname) {
263 return createDefault(hostname,null);
264 }
265 }
266 public static class NetworkIsUnreachableException extends Exception {
267
268 }
269
270}