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