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("values")) {
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 bundle = 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 bundle.putString("error", "nosrv");
137 return bundle;
138 }
139 ArrayList<Bundle> values = new ArrayList<Bundle>();
140 for (SRV srv : result) {
141 Bundle namePort = new Bundle();
142 namePort.putString("name", srv.getName());
143 namePort.putInt("port", srv.getPort());
144 if (ips4.containsKey(srv.getName())) {
145 ArrayList<String> ip = ips4.get(srv.getName());
146 Collections.shuffle(ip, rnd);
147 namePort.putString("ipv4", ip.get(0));
148 }
149 values.add(namePort);
150 }
151 bundle.putParcelableArrayList("values", values);
152 } catch (SocketTimeoutException e) {
153 bundle.putString("error", "timeout");
154 } catch (Exception e) {
155 bundle.putString("error", "unhandled");
156 }
157 return bundle;
158 }
159
160 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
161
162 public static String bytesToHex(byte[] bytes) {
163 char[] hexChars = new char[bytes.length * 2];
164 for (int j = 0; j < bytes.length; j++) {
165 int v = bytes[j] & 0xFF;
166 hexChars[j * 2] = hexArray[v >>> 4];
167 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
168 }
169 return new String(hexChars);
170 }
171}