1package eu.siacs.conversations.utils;
2
3import de.measite.minidns.Client;
4import de.measite.minidns.DNSMessage;
5import de.measite.minidns.Record;
6import de.measite.minidns.Record.TYPE;
7import de.measite.minidns.Record.CLASS;
8import de.measite.minidns.record.SRV;
9import de.measite.minidns.record.A;
10import de.measite.minidns.record.AAAA;
11import de.measite.minidns.record.Data;
12import de.measite.minidns.util.NameUtil;
13import eu.siacs.conversations.Config;
14import eu.siacs.conversations.xmpp.jid.Jid;
15
16import java.io.IOException;
17import java.net.InetAddress;
18import java.net.SocketTimeoutException;
19import java.util.ArrayList;
20import java.util.Collections;
21import java.util.Random;
22import java.util.TreeMap;
23
24import android.os.Bundle;
25import android.util.Log;
26
27public class DNSHelper {
28 protected static Client client = new Client();
29
30 public static Bundle getSRVRecord(final Jid jid) throws IOException {
31 final String host = jid.getDomainpart();
32 String dns[] = client.findDNS();
33
34 if (dns != null) {
35 for (String dnsserver : dns) {
36 InetAddress ip = InetAddress.getByName(dnsserver);
37 Bundle b = queryDNS(host, ip);
38 if (b.containsKey("values")) {
39 return b;
40 } else if (b.containsKey("error")
41 && "nosrv".equals(b.getString("error", null))) {
42 return b;
43 }
44 }
45 }
46 return queryDNS(host, InetAddress.getByName("8.8.8.8"));
47 }
48
49 public static Bundle queryDNS(String host, InetAddress dnsServer) {
50 Bundle bundle = new Bundle();
51 try {
52 String qname = "_xmpp-client._tcp." + host;
53 Log.d(Config.LOGTAG,
54 "using dns server: " + dnsServer.getHostAddress()
55 + " to look up " + host);
56 DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN,
57 dnsServer.getHostAddress());
58
59 // How should we handle priorities and weight?
60 // Wikipedia has a nice article about priorities vs. weights:
61 // https://en.wikipedia.org/wiki/SRV_record#Provisioning_for_high_service_availability
62
63 // we bucket the SRV records based on priority, pick per priority
64 // a random order respecting the weight, and dump that priority by
65 // priority
66
67 TreeMap<Integer, ArrayList<SRV>> priorities = new TreeMap<>();
68 TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>();
69 TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>();
70
71 for (Record[] rrset : new Record[][] { message.getAnswers(),
72 message.getAdditionalResourceRecords() }) {
73 for (Record rr : rrset) {
74 Data d = rr.getPayload();
75 if (d instanceof SRV
76 && NameUtil.idnEquals(qname, rr.getName())) {
77 SRV srv = (SRV) d;
78 if (!priorities.containsKey(srv.getPriority())) {
79 priorities.put(srv.getPriority(),
80 new ArrayList<SRV>(2));
81 }
82 priorities.get(srv.getPriority()).add(srv);
83 }
84 if (d instanceof A) {
85 A arecord = (A) d;
86 if (!ips4.containsKey(rr.getName())) {
87 ips4.put(rr.getName(), new ArrayList<String>(3));
88 }
89 ips4.get(rr.getName()).add(arecord.toString());
90 }
91 if (d instanceof AAAA) {
92 AAAA aaaa = (AAAA) d;
93 if (!ips6.containsKey(rr.getName())) {
94 ips6.put(rr.getName(), new ArrayList<String>(3));
95 }
96 ips6.get(rr.getName()).add("[" + aaaa.toString() + "]");
97 }
98 }
99 }
100
101 Random rnd = new Random();
102 ArrayList<SRV> result = new ArrayList<>(
103 priorities.size() * 2 + 1);
104 for (ArrayList<SRV> s : priorities.values()) {
105
106 // trivial case
107 if (s.size() <= 1) {
108 result.addAll(s);
109 continue;
110 }
111
112 long totalweight = 0l;
113 for (SRV srv : s) {
114 totalweight += srv.getWeight();
115 }
116
117 while (totalweight > 0l && s.size() > 0) {
118 long p = (rnd.nextLong() & 0x7fffffffffffffffl)
119 % totalweight;
120 int i = 0;
121 while (p > 0) {
122 p -= s.get(i++).getPriority();
123 }
124 if (i>0) i--;
125 // remove is expensive, but we have only a few entries
126 // anyway
127 SRV srv = s.remove(i);
128 totalweight -= srv.getWeight();
129 result.add(srv);
130 }
131
132 Collections.shuffle(s, rnd);
133 result.addAll(s);
134
135 }
136
137 if (result.size() == 0) {
138 bundle.putString("error", "nosrv");
139 return bundle;
140 }
141 ArrayList<Bundle> values = new ArrayList<>();
142 for (SRV srv : result) {
143 if (ips6.containsKey(srv.getName())) {
144 values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6));
145 } else {
146 DNSMessage response = client.query(srv.getName(), TYPE.AAAA, CLASS.IN, dnsServer.getHostAddress());
147 if (response.getAnswers().length >= 1) {
148 values.add(createNamePortBundle(srv.getName(),srv.getPort(),response.getAnswers()[0].getPayload()));
149 }
150 }
151 if (ips4.containsKey(srv.getName())) {
152 values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4));
153 } else {
154 DNSMessage response = client.query(srv.getName(), TYPE.A, CLASS.IN, dnsServer.getHostAddress());
155 if (response.getAnswers().length >= 1) {
156 values.add(createNamePortBundle(srv.getName(),srv.getPort(),response.getAnswers()[0].getPayload()));
157 }
158 }
159 values.add(createNamePortBundle(srv.getName(), srv.getPort()));
160 }
161 bundle.putParcelableArrayList("values", values);
162 } catch (SocketTimeoutException e) {
163 bundle.putString("error", "timeout");
164 } catch (Exception e) {
165 bundle.putString("error", "unhandled");
166 }
167 return bundle;
168 }
169
170 private static Bundle createNamePortBundle(String name, int port) {
171 Bundle namePort = new Bundle();
172 namePort.putString("name", name);
173 namePort.putInt("port", port);
174 return namePort;
175 }
176
177 private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) {
178 Bundle namePort = new Bundle();
179 namePort.putString("name", name);
180 namePort.putInt("port", port);
181 if (ips!=null) {
182 ArrayList<String> ip = ips.get(name);
183 Collections.shuffle(ip, new Random());
184 namePort.putString("ip", ip.get(0));
185 }
186 return namePort;
187 }
188
189 private static Bundle createNamePortBundle(String name, int port, Data data) {
190 Bundle namePort = new Bundle();
191 namePort.putString("name", name);
192 namePort.putInt("port", port);
193 if (data instanceof A) {
194 namePort.putString("ip", data.toString());
195 } else if (data instanceof AAAA) {
196 namePort.putString("ip","["+data.toString()+"]");
197 }
198 return namePort;
199 }
200
201 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
202
203 public static String bytesToHex(byte[] bytes) {
204 char[] hexChars = new char[bytes.length * 2];
205 for (int j = 0; j < bytes.length; j++) {
206 int v = bytes[j] & 0xFF;
207 hexChars[j * 2] = hexArray[v >>> 4];
208 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
209 }
210 return new String(hexChars);
211 }
212}