aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/eu/siacs/conversations/utils/DNSHelper.java
blob: 1568eb8c4189220a3b02c3b0afd71c5d13776263 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package eu.siacs.conversations.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.RouteInfo;
import android.os.Build;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Pattern;

import de.measite.minidns.Client;
import de.measite.minidns.DNSMessage;
import de.measite.minidns.Record;
import de.measite.minidns.Record.CLASS;
import de.measite.minidns.Record.TYPE;
import de.measite.minidns.record.Data;
import de.measite.minidns.record.SRV;
import de.measite.minidns.util.NameUtil;
import de.thedevstack.android.logcat.Logging;
import de.thedevstack.conversationsplus.ConversationsPlusApplication;
import de.thedevstack.conversationsplus.dto.SrvRecord;
import eu.siacs.conversations.Config;
import eu.siacs.conversations.xmpp.jid.Jid;

public class DNSHelper {
    private static final String CLIENT_SRV_PREFIX = "_xmpp-client._tcp.";
    private static final String SECURE_CLIENT_SRV_PREFIX = "_xmpps-client._tcp.";
	private static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
	private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
	private static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
	private static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
	private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");

	protected static Client client = new Client();

    static {
        client.setTimeout(Config.PING_TIMEOUT * 1000);
    }

    /**
     * Queries the SRV record for the server JID.
     * This method uses all available Domain Name Servers.
     * @param jid the server JID
     * @return TreeSet with SrvRecords. If no SRV record is found for JID an empty TreeSet is returned.
     */
    public static final TreeSet<SrvRecord> querySrvRecord(Jid jid) {
        String host = jid.getDomainpart();
        TreeSet<SrvRecord> result = new TreeSet<>();

        final List<InetAddress> dnsServers = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? getDnsServers() : getDnsServersPreLollipop();

        if (dnsServers != null) {
            for (InetAddress dnsServer : dnsServers) {
                result = querySrvRecord(host, dnsServer);
                if (!result.isEmpty()) {
                    break;
                }
            }
        }

        return result;
    }

	@TargetApi(21)
	private static List<InetAddress> getDnsServers() {
		List<InetAddress> servers = new ArrayList<>();
		ConnectivityManager connectivityManager = (ConnectivityManager) ConversationsPlusApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
		Network[] networks = connectivityManager == null ? null : connectivityManager.getAllNetworks();
		if (networks == null) {
			return getDnsServersPreLollipop();
		}
		for(int i = 0; i < networks.length; ++i) {
			LinkProperties linkProperties = connectivityManager.getLinkProperties(networks[i]);
			if (linkProperties != null) {
				if (hasDefaultRoute(linkProperties)) {
					servers.addAll(0, linkProperties.getDnsServers());
				} else {
					servers.addAll(linkProperties.getDnsServers());
				}
			}
		}
		if (servers.size() > 0) {
            Logging.d("dns", "used lollipop variant to discover dns servers in " + networks.length + " networks");
		}
		return servers.size() > 0 ? servers : getDnsServersPreLollipop();
	}

	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
	private static boolean hasDefaultRoute(LinkProperties linkProperties) {
		for(RouteInfo route: linkProperties.getRoutes()) {
			if (route.isDefaultRoute()) {
				return true;
			}
		}
		return false;
	}

	private static List<InetAddress> getDnsServersPreLollipop() {
		List<InetAddress> servers = new ArrayList<>();
		String[] dns = client.findDNS();
		for(int i = 0; i < dns.length; ++i) {
			try {
				servers.add(InetAddress.getByName(dns[i]));
			} catch (UnknownHostException e) {
				//ignore
			}
		}
		return servers;
	}

    /**
     * Queries the SRV record for an host from the given Domain Name Server.
     * @param host the host to query for
     * @param dnsServerAddress the DNS to query on
     * @return TreeSet with SrvRecords.
     */
    private static final TreeSet<SrvRecord> querySrvRecord(String host, InetAddress dnsServerAddress) {
        TreeSet<SrvRecord> result = new TreeSet<>();
        querySrvRecord(host, dnsServerAddress, false, result);
        querySrvRecord(host, dnsServerAddress, true, result);
        return result;
    }

    private static final void querySrvRecord(String host, InetAddress dnsServerAddress, boolean tlsSrvRecord, TreeSet<SrvRecord> result) {
        String qname = (tlsSrvRecord ? SECURE_CLIENT_SRV_PREFIX : CLIENT_SRV_PREFIX) + host;
        String dnsServerHostAddress = dnsServerAddress.getHostAddress();
        Logging.d("dns", "using dns server: " + dnsServerHostAddress + " to look up " + qname);
        try {
            DNSMessage message = client.query(qname, TYPE.SRV, CLASS.IN, dnsServerHostAddress);
            Record[] rrset = message.getAnswers();
            for (Record rr : rrset) {
                Data d = rr.getPayload();
                if (d instanceof SRV && NameUtil.idnEquals(qname, rr.getName())) {
                    SRV srv = (SRV) d;
                    SrvRecord srvRecord = new SrvRecord(srv.getPriority(), srv.getName(), srv.getPort(), tlsSrvRecord);
                    result.add(srvRecord);
                }
            }
        } catch (IOException e) {
            Logging.d("dns", "Error while retrieving SRV record '" + qname + "' for '" + host + "' from DNS '" + dnsServerHostAddress + "': " + e.getMessage());
        }
    }

	public static boolean isIp(final String server) {
		return server != null && (
				PATTERN_IPV4.matcher(server).matches()
				|| PATTERN_IPV6.matcher(server).matches()
				|| PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
				|| PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
				|| PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
	}
}