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;
13
14import java.io.IOException;
15import java.net.InetAddress;
16import java.net.SocketTimeoutException;
17import java.util.ArrayList;
18import java.util.Collections;
19import java.util.Random;
20import java.util.TreeMap;
21
22import android.os.Bundle;
23import android.util.Log;
24
25public class DNSHelper {
26 protected static Client client = new Client();
27
28 public static Bundle getSRVRecord(String host) throws IOException {
29 String dns[] = client.findDNS();
30
31 if (dns != null) {
32 // we have a list of DNS servers, let's go
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 }
39 }
40 }
41
42 // fallback
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("xmppService", "using dns server: " + dnsServer.getHostAddress()
51 + " to look up " + host);
52 DNSMessage message =
53 client.query(
54 qname,
55 TYPE.SRV,
56 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 =
68 new TreeMap<Integer, ArrayList<SRV>>();
69 TreeMap<String, ArrayList<String>> ips4 =
70 new TreeMap<String, ArrayList<String>>();
71 TreeMap<String, ArrayList<String>> ips6 =
72 new TreeMap<String, ArrayList<String>>();
73
74 for (Record[] rrset : new Record[][]{ message.getAnswers(),
75 message.getAdditionalResourceRecords()}) {
76 for (Record rr : rrset) {
77 Data d = rr.getPayload();
78 if (d instanceof SRV && NameUtil.idnEquals(qname,rr.getName())) {
79 SRV srv = (SRV) d;
80 if (!priorities.containsKey(srv.getPriority())) {
81 priorities.put(srv.getPriority(), new ArrayList<SRV>(2));
82 }
83 priorities.get(srv.getPriority()).add(srv);
84 }
85 if (d instanceof A) {
86 A arecord = (A) d;
87 if (!ips4.containsKey(rr.getName())) {
88 ips4.put(rr.getName(), new ArrayList<String>(3));
89 }
90 ips4.get(rr.getName()).add(arecord.toString());
91 }
92 if (d instanceof AAAA) {
93 AAAA aaaa = (AAAA) d;
94 if (!ips6.containsKey(rr.getName())) {
95 ips6.put(rr.getName(), new ArrayList<String>(3));
96 }
97 ips6.get(rr.getName()).add("[" + aaaa.toString() + "]");
98 }
99 }
100 }
101
102 Random rnd = new Random();
103 ArrayList<SRV> result = new ArrayList<SRV>(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) % totalweight;
119 int i = 0;
120 while (p > 0) {
121 p -= s.get(i++).getPriority();
122 }
123 i--;
124 // remove is expensive, but we have only a few entries 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 Log.d("xmppService", "timeout during dns");
168 namePort.putString("error", "timeout");
169 } catch (Exception e) {
170 Log.d("xmppService","unhandled exception in sub project");
171 namePort.putString("error", "unhandled");
172 }
173 return namePort;
174 }
175
176 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
177
178 public static String bytesToHex(byte[] bytes) {
179 char[] hexChars = new char[bytes.length * 2];
180 for (int j = 0; j < bytes.length; j++) {
181 int v = bytes[j] & 0xFF;
182 hexChars[j * 2] = hexArray[v >>> 4];
183 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
184 }
185 return new String(hexChars);
186 }
187}