1package eu.siacs.conversations.utils;
2
3import android.annotation.TargetApi;
4import android.content.Context;
5import android.net.ConnectivityManager;
6import android.net.LinkProperties;
7import android.net.Network;
8import android.os.Build;
9import android.os.Bundle;
10import android.util.Log;
11
12import java.io.IOException;
13import java.net.InetAddress;
14import java.net.SocketTimeoutException;
15import java.net.UnknownHostException;
16import java.util.ArrayList;
17import java.util.Collections;
18import java.util.List;
19import java.util.Random;
20import java.util.TreeMap;
21import java.util.regex.Pattern;
22
23import de.measite.minidns.Client;
24import de.measite.minidns.DNSMessage;
25import de.measite.minidns.Record;
26import de.measite.minidns.Record.CLASS;
27import de.measite.minidns.Record.TYPE;
28import de.measite.minidns.record.A;
29import de.measite.minidns.record.AAAA;
30import de.measite.minidns.record.Data;
31import de.measite.minidns.record.SRV;
32import de.measite.minidns.util.NameUtil;
33import eu.siacs.conversations.Config;
34import eu.siacs.conversations.xmpp.jid.Jid;
35
36public class DNSHelper {
37
38 public static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
39 public static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
40 public static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
41 public static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
42 public static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
43
44 protected static Client client = new Client();
45
46 public static Bundle getSRVRecord(final Jid jid, Context context) throws IOException {
47 final String host = jid.getDomainpart();
48 final List<InetAddress> servers = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? getDnsServers(context) : getDnsServersPreLolipop();
49 Bundle b = null;
50 for(InetAddress server : servers) {
51 b = queryDNS(host, server);
52 if (b.containsKey("values")) {
53 return b;
54 }
55 }
56 return b;
57 }
58
59 @TargetApi(21)
60 private static List<InetAddress> getDnsServers(Context context) {
61 List<InetAddress> servers = new ArrayList<>();
62 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
63 Network[] networks = connectivityManager.getAllNetworks();
64 for(int i = 0; i < networks.length; ++i) {
65 LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]);
66 servers.addAll(linkProperties.getDnsServers());
67 }
68 return servers.size() > 0 ? servers : getDnsServersPreLolipop();
69 }
70
71 private static List<InetAddress> getDnsServersPreLolipop() {
72 List<InetAddress> servers = new ArrayList<>();
73 String[] dns = client.findDNS();
74 for(int i = 0; i < dns.length; ++i) {
75 try {
76 servers.add(InetAddress.getByName(dns[i]));
77 } catch (UnknownHostException e) {
78 //ignore
79 }
80 }
81 return servers;
82 }
83
84 public static Bundle queryDNS(String host, InetAddress dnsServer) {
85 Bundle bundle = new Bundle();
86 try {
87 client.setTimeout(Config.PING_TIMEOUT * 1000);
88 String qname = "_xmpp-client._tcp." + host;
89 Log.d(Config.LOGTAG, "using dns server: " + dnsServer.getHostAddress() + " to look up " + host);
90 DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN, dnsServer.getHostAddress());
91
92 TreeMap<Integer, ArrayList<SRV>> priorities = new TreeMap<>();
93 TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>();
94 TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>();
95
96 for (Record[] rrset : new Record[][] { message.getAnswers(), message.getAdditionalResourceRecords() }) {
97 for (Record rr : rrset) {
98 Data d = rr.getPayload();
99 if (d instanceof SRV && NameUtil.idnEquals(qname, rr.getName())) {
100 SRV srv = (SRV) d;
101 if (!priorities.containsKey(srv.getPriority())) {
102 priorities.put(srv.getPriority(),new ArrayList<SRV>());
103 }
104 priorities.get(srv.getPriority()).add(srv);
105 }
106 if (d instanceof A) {
107 A a = (A) d;
108 if (!ips4.containsKey(rr.getName())) {
109 ips4.put(rr.getName(), new ArrayList<String>());
110 }
111 ips4.get(rr.getName()).add(a.toString());
112 }
113 if (d instanceof AAAA) {
114 AAAA aaaa = (AAAA) d;
115 if (!ips6.containsKey(rr.getName())) {
116 ips6.put(rr.getName(), new ArrayList<String>());
117 }
118 ips6.get(rr.getName()).add("[" + aaaa.toString() + "]");
119 }
120 }
121 }
122
123 ArrayList<SRV> result = new ArrayList<>();
124 for (ArrayList<SRV> s : priorities.values()) {
125 result.addAll(s);
126 }
127
128 ArrayList<Bundle> values = new ArrayList<>();
129 if (result.size() == 0) {
130 DNSMessage response;
131 try {
132 response = client.query(host, TYPE.A, CLASS.IN, dnsServer.getHostAddress());
133 for (int i = 0; i < response.getAnswers().length; ++i) {
134 values.add(createNamePortBundle(host, 5222, response.getAnswers()[i].getPayload()));
135 }
136 } catch (SocketTimeoutException e) {
137 Log.d(Config.LOGTAG,"ignoring timeout exception when querying A record on "+dnsServer.getHostAddress());
138 }
139 try {
140 response = client.query(host, TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
141 for (int i = 0; i < response.getAnswers().length; ++i) {
142 values.add(createNamePortBundle(host, 5222, response.getAnswers()[i].getPayload()));
143 }
144 } catch (SocketTimeoutException e) {
145 Log.d(Config.LOGTAG,"ignoring timeout exception when querying AAAA record on "+dnsServer.getHostAddress());
146 }
147 values.add(createNamePortBundle(host,5222));
148 bundle.putParcelableArrayList("values", values);
149 return bundle;
150 }
151 for (SRV srv : result) {
152 if (ips6.containsKey(srv.getName())) {
153 values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6));
154 } else {
155 try {
156 DNSMessage response = client.query(srv.getName(), TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
157 for (int i = 0; i < response.getAnswers().length; ++i) {
158 values.add(createNamePortBundle(srv.getName(), srv.getPort(), response.getAnswers()[i].getPayload()));
159 }
160 } catch (SocketTimeoutException e) {
161 Log.d(Config.LOGTAG,"ignoring timeout exception when querying AAAA record on "+dnsServer.getHostAddress());
162 }
163 }
164 if (ips4.containsKey(srv.getName())) {
165 values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4));
166 } else {
167 DNSMessage response = client.query(srv.getName(), TYPE.A, CLASS.IN, dnsServer.getHostAddress());
168 for(int i = 0; i < response.getAnswers().length; ++i) {
169 values.add(createNamePortBundle(srv.getName(),srv.getPort(),response.getAnswers()[i].getPayload()));
170 }
171 }
172 values.add(createNamePortBundle(srv.getName(), srv.getPort()));
173 }
174 bundle.putParcelableArrayList("values", values);
175 } catch (SocketTimeoutException e) {
176 bundle.putString("error", "timeout");
177 } catch (Exception e) {
178 bundle.putString("error", "unhandled");
179 }
180 return bundle;
181 }
182
183 private static Bundle createNamePortBundle(String name, int port) {
184 Bundle namePort = new Bundle();
185 namePort.putString("name", name);
186 namePort.putInt("port", port);
187 return namePort;
188 }
189
190 private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) {
191 Bundle namePort = new Bundle();
192 namePort.putString("name", name);
193 namePort.putInt("port", port);
194 if (ips!=null) {
195 ArrayList<String> ip = ips.get(name);
196 Collections.shuffle(ip, new Random());
197 namePort.putString("ip", ip.get(0));
198 }
199 return namePort;
200 }
201
202 private static Bundle createNamePortBundle(String name, int port, Data data) {
203 Bundle namePort = new Bundle();
204 namePort.putString("name", name);
205 namePort.putInt("port", port);
206 if (data instanceof A) {
207 namePort.putString("ip", data.toString());
208 } else if (data instanceof AAAA) {
209 namePort.putString("ip","["+data.toString()+"]");
210 }
211 return namePort;
212 }
213
214 public static boolean isIp(final String server) {
215 return PATTERN_IPV4.matcher(server).matches()
216 || PATTERN_IPV6.matcher(server).matches()
217 || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
218 || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
219 || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches();
220 }
221}