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