DNSHelper.java

  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.util.ArrayList;
 17import java.util.Collections;
 18import java.util.Random;
 19import java.util.TreeMap;
 20
 21import android.os.Bundle;
 22import android.util.Log;
 23
 24public class DNSHelper {
 25	protected static Client client = new Client();
 26
 27	public static Bundle getSRVRecord(String host) throws IOException {
 28		String dns[] = client.findDNS();
 29
 30		if (dns != null) {
 31			// we have a list of DNS servers, let's go
 32			for (String dnsserver : dns) {
 33				InetAddress ip = InetAddress.getByName(dnsserver);
 34				Bundle b = queryDNS(host, ip);
 35				if (b.containsKey("name")) {
 36					return b;
 37				}
 38			}
 39		}
 40
 41		// fallback
 42		return queryDNS(host, InetAddress.getByName("8.8.8.8"));
 43	}
 44
 45	public static Bundle queryDNS(String host, InetAddress dnsServer) {
 46		Bundle namePort = new Bundle();
 47		try {
 48			String qname = "_xmpp-client._tcp." + host;
 49			Log.d("xmppService", "using dns server: " + dnsServer.getHostAddress()
 50					+ " to look up " + host);
 51			DNSMessage message =
 52					client.query(
 53							qname,
 54							TYPE.ANY,
 55							CLASS.IN,
 56							dnsServer.getHostAddress());
 57
 58			// How should we handle priorities and weight?
 59			// Wikipedia has a nice article about priorities vs. weights:
 60			// https://en.wikipedia.org/wiki/SRV_record#Provisioning_for_high_service_availability
 61
 62			// we bucket the SRV records based on priority, pick per priority
 63			// a random order respecting the weight, and dump that priority by
 64			// priority
 65
 66			TreeMap<Integer, ArrayList<SRV>> priorities =
 67					new TreeMap<Integer, ArrayList<SRV>>();
 68			TreeMap<String, ArrayList<String>> ips4 =
 69					new TreeMap<String, ArrayList<String>>();
 70			TreeMap<String, ArrayList<String>> ips6 =
 71					new TreeMap<String, ArrayList<String>>();
 72
 73			for (Record[] rrset : new Record[][]{ message.getAnswers(),
 74					message.getAdditionalResourceRecords()}) {
 75				for (Record rr : rrset) {
 76					Data d = rr.getPayload();
 77					if (d instanceof SRV && NameUtil.idnEquals(qname,rr.getName())) {
 78						SRV srv = (SRV) d;
 79						if (!priorities.containsKey(srv.getPriority())) {
 80							priorities.put(srv.getPriority(), 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<SRV>(priorities.size() * 2 + 1);
103			for (ArrayList<SRV> s: priorities.values()) {
104
105				// trivial case
106				if (s.size() <= 1) {
107					result.addAll(s);
108					continue;
109				}
110
111				long totalweight = 0l;
112				for (SRV srv: s) {
113					totalweight += srv.getWeight();
114				}
115
116				while (totalweight > 0l && s.size() > 0) {
117					long p = (rnd.nextLong() & 0x7fffffffffffffffl) % 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 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 (IOException e) {
166			Log.e("xmppService", "io execpiton during dns", e);
167			namePort.putString("error", "timeout");
168		}
169		return namePort;
170	}
171
172	static int calcPort(byte hb, byte lb) {
173		int port = ((int) hb << 8) | ((int) lb & 0xFF);
174		if (port >= 0) {
175			return port;
176		} else {
177			return 65536 + port;
178		}
179	}
180
181	final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
182
183	public static String bytesToHex(byte[] bytes) {
184		char[] hexChars = new char[bytes.length * 2];
185		for (int j = 0; j < bytes.length; j++) {
186			int v = bytes[j] & 0xFF;
187			hexChars[j * 2] = hexArray[v >>> 4];
188			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
189		}
190		return new String(hexChars);
191	}
192}