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