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;
 13import eu.siacs.conversations.Config;
 14import eu.siacs.conversations.xmpp.jid.Jid;
 15
 16import java.io.IOException;
 17import java.net.InetAddress;
 18import java.net.SocketTimeoutException;
 19import java.util.ArrayList;
 20import java.util.Collections;
 21import java.util.Random;
 22import java.util.TreeMap;
 23
 24import android.os.Bundle;
 25import android.util.Log;
 26
 27public class DNSHelper {
 28	protected static Client client = new Client();
 29
 30	public static Bundle getSRVRecord(final Jid jid) throws IOException {
 31        final String host = jid.getDomainpart();
 32		String dns[] = client.findDNS();
 33
 34		if (dns != null) {
 35			for (String dnsserver : dns) {
 36				InetAddress ip = InetAddress.getByName(dnsserver);
 37				Bundle b = queryDNS(host, ip);
 38				if (b.containsKey("values")) {
 39					return b;
 40				} else if (b.containsKey("error")
 41						&& "nosrv".equals(b.getString("error", null))) {
 42					return b;
 43				}
 44			}
 45		}
 46		return queryDNS(host, InetAddress.getByName("8.8.8.8"));
 47	}
 48
 49	public static Bundle queryDNS(String host, InetAddress dnsServer) {
 50		Bundle bundle = new Bundle();
 51		try {
 52			String qname = "_xmpp-client._tcp." + host;
 53			Log.d(Config.LOGTAG,
 54					"using dns server: " + dnsServer.getHostAddress()
 55							+ " to look up " + host);
 56			DNSMessage message = client.query(qname, TYPE.SRV, 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 = new TreeMap<>();
 68			TreeMap<String, ArrayList<String>> ips4 = new TreeMap<>();
 69			TreeMap<String, ArrayList<String>> ips6 = new TreeMap<>();
 70
 71			for (Record[] rrset : new Record[][] { message.getAnswers(),
 72					message.getAdditionalResourceRecords() }) {
 73				for (Record rr : rrset) {
 74					Data d = rr.getPayload();
 75					if (d instanceof SRV
 76							&& NameUtil.idnEquals(qname, rr.getName())) {
 77						SRV srv = (SRV) d;
 78						if (!priorities.containsKey(srv.getPriority())) {
 79							priorities.put(srv.getPriority(),
 80									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<>(
103					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)
119							% totalweight;
120					int i = 0;
121					while (p > 0) {
122						p -= s.get(i++).getPriority();
123					}
124					if (i>0) i--;
125					// remove is expensive, but we have only a few entries
126					// anyway
127					SRV srv = s.remove(i);
128					totalweight -= srv.getWeight();
129					result.add(srv);
130				}
131
132				Collections.shuffle(s, rnd);
133				result.addAll(s);
134
135			}
136
137			if (result.size() == 0) {
138				bundle.putString("error", "nosrv");
139				return bundle;
140			}
141			ArrayList<Bundle> values = new ArrayList<>();
142			for (SRV srv : result) {
143				if (ips6.containsKey(srv.getName())) {
144					values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips6));
145				}
146				if (ips4.containsKey(srv.getName())) {
147					values.add(createNamePortBundle(srv.getName(),srv.getPort(),ips4));
148				}
149				values.add(createNamePortBundle(srv.getName(),srv.getPort(),null));
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	private static Bundle createNamePortBundle(String name, int port, TreeMap<String, ArrayList<String>> ips) {
161		Bundle namePort = new Bundle();
162		namePort.putString("name", name);
163		namePort.putInt("port", port);
164		if (ips!=null) {
165			ArrayList<String> ip = ips.get(name);
166			Collections.shuffle(ip, new Random());
167			namePort.putString("ip", ip.get(0));
168		}
169		return namePort;
170	}
171
172	final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
173
174	public static String bytesToHex(byte[] bytes) {
175		char[] hexChars = new char[bytes.length * 2];
176		for (int j = 0; j < bytes.length; j++) {
177			int v = bytes[j] & 0xFF;
178			hexChars[j * 2] = hexArray[v >>> 4];
179			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
180		}
181		return new String(hexChars);
182	}
183}