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 (Throwable throwable) {
52 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": error resolving SRV record (direct TLS)",throwable);
53 }
54 try {
55 results.addAll(resolveSrv(domain,false));
56 } catch (Throwable throwable) {
57 Log.d(Config.LOGTAG,Resolver.class.getSimpleName()+": error resolving SRV record (STARTTLS)",throwable);
58 }
59 if (results.size() == 0) {
60 results.addAll(resolveNoSrvRecords(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> resolveNoSrvRecords(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 && withCnames) {
115 for (CNAME cname : resolveWithFallback(dnsName, CNAME.class, false).getAnswersOrEmptySet()) {
116 results.addAll(resolveNoSrvRecords(cname.name, false));
117 }
118 }
119 } catch (Throwable throwable) {
120 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + "error resolving fallback records",throwable);
121 }
122 results.add(Result.createDefault(dnsName));
123 return results;
124 }
125
126 private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type) throws IOException {
127 return resolveWithFallback(dnsName,type,validateHostname());
128 }
129
130 private static <D extends Data> ResolverResult<D> resolveWithFallback(DNSName dnsName, Class<D> type, boolean validateHostname) throws IOException {
131 if (!validateHostname) {
132 return ResolverApi.INSTANCE.resolve(dnsName, type);
133 }
134 try {
135 final ResolverResult<D> r = DnssecResolverApi.INSTANCE.resolveDnssecReliable(dnsName, type);
136 if (r.wasSuccessful()) {
137 if (r.getAnswers().isEmpty() && type.equals(SRV.class)) {
138 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": resolving SRV records of " + dnsName.toString() + " with DNSSEC yielded empty result");
139 }
140 return r;
141 }
142 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", r.getResolutionUnsuccessfulException());
143 } catch (DNSSECResultNotAuthenticException e) {
144 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", e);
145 } catch (IOException e) {
146 throw e;
147 } catch (Throwable throwable) {
148 Log.d(Config.LOGTAG, Resolver.class.getSimpleName() + ": error resolving " + type.getSimpleName() + " with DNSSEC. Trying DNS instead.", throwable);
149 }
150 return ResolverApi.INSTANCE.resolve(dnsName, type);
151 }
152
153 private static boolean validateHostname() {
154 return SERVICE != null && SERVICE.getBooleanPreference("validate_hostname", R.bool.validate_hostname);
155 }
156
157 public static class Result implements Comparable<Result> {
158 private InetAddress ip;
159 private DNSName hostname;
160 private int port = 5222;
161 private boolean directTls = false;
162 private boolean authenticated =false;
163 private int priority;
164
165 public InetAddress getIp() {
166 return ip;
167 }
168
169 public int getPort() {
170 return port;
171 }
172
173 public DNSName getHostname() {
174 return hostname;
175 }
176
177 public boolean isDirectTls() {
178 return directTls;
179 }
180
181 public boolean isAuthenticated() {
182 return authenticated;
183 }
184
185 @Override
186 public String toString() {
187 return "Result{" +
188 "ip='" + (ip==null?null:ip.getHostAddress()) + '\'' +
189 ", hostame='" + hostname.toString() + '\'' +
190 ", port=" + port +
191 ", directTls=" + directTls +
192 ", authenticated=" + authenticated +
193 ", priority=" + priority +
194 '}';
195 }
196
197 @Override
198 public int compareTo(@NonNull Result result) {
199 if (result.priority == priority) {
200 if (directTls == result.directTls) {
201 if (ip == null && result.ip == null) {
202 return 0;
203 } else if (ip != null && result.ip != null) {
204 if (ip instanceof Inet4Address && result.ip instanceof Inet4Address) {
205 return 0;
206 } else {
207 return ip instanceof Inet4Address ? -1 : 1;
208 }
209 } else {
210 return ip != null ? -1 : 1;
211 }
212 } else {
213 return directTls ? -1 : 1;
214 }
215 } else {
216 return priority - result.priority;
217 }
218 }
219
220 public static Result fromRecord(SRV srv, boolean directTls) {
221 Result result = new Result();
222 result.port = srv.port;
223 result.hostname = srv.name;
224 result.directTls = directTls;
225 result.priority = srv.priority;
226 return result;
227 }
228
229 public static Result createDefault(DNSName hostname, InetAddress ip) {
230 Result result = new Result();
231 result.port = 5222;
232 result.hostname = hostname;
233 result.ip = ip;
234 return result;
235 }
236
237 public static Result createDefault(DNSName hostname) {
238 return createDefault(hostname,null);
239 }
240 }
241
242}