001/**
002 *
003 * Copyright 2003-2005 Jive Software, 2016 Florian Schmaus.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack.util;
018
019import java.util.ArrayList;
020import java.util.Collections;
021import java.util.LinkedList;
022import java.util.List;
023import java.util.SortedMap;
024import java.util.TreeMap;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode;
029import org.jivesoftware.smack.util.dns.DNSResolver;
030import org.jivesoftware.smack.util.dns.SmackDaneProvider;
031import org.jivesoftware.smack.util.dns.HostAddress;
032import org.jivesoftware.smack.util.dns.SRVRecord;
033
034/**
035 * Utility class to perform DNS lookups for XMPP services.
036 *
037 * @author Matt Tucker
038 * @author Florian Schmaus
039 */
040public class DNSUtil {
041
042    private static final Logger LOGGER = Logger.getLogger(DNSUtil.class.getName());
043    private static DNSResolver dnsResolver = null;
044    private static SmackDaneProvider daneProvider;
045
046    /**
047     * International Domain Name transformer.
048     * <p>
049     * Used to transform Unicode representations of the Domain Name to ASCII in
050     * order to perform a DNS request with the ASCII representation.
051     * 'java.net.IDN' is available since Android API 9, but as long as Smack
052     * requires API 8, we are going to need this. This part is going to get
053     * removed once Smack depends on Android API 9 or higher.
054     * </p>
055     */
056    private static StringTransformer idnaTransformer = new StringTransformer() {
057        @Override
058        public String transform(String string) {
059            return string;
060        }
061    };
062
063    /**
064     * Set the DNS resolver that should be used to perform DNS lookups.
065     *
066     * @param resolver
067     */
068    public static void setDNSResolver(DNSResolver resolver) {
069        dnsResolver = Objects.requireNonNull(resolver);
070    }
071
072    /**
073     * Returns the current DNS resolved used to perform DNS lookups.
074     *
075     * @return the active DNSResolver
076     */
077    public static DNSResolver getDNSResolver() {
078        return dnsResolver;
079    }
080
081    /**
082     * Set the DANE provider that should be used when DANE is enabled.
083     *
084     * @param daneProvider
085     */
086    public static void setDaneProvider(SmackDaneProvider daneProvider) {
087        daneProvider = Objects.requireNonNull(daneProvider);
088    }
089
090    /**
091     * Returns the currently active DANE provider used when DANE is enabled.
092     *
093     * @return the active DANE provider
094     */
095    public static SmackDaneProvider getDaneProvider() {
096        return daneProvider;
097    }
098
099    /**
100     * Set the IDNA (Internationalizing Domain Names in Applications, RFC 3490) transformer.
101     * <p>
102     * You usually want to wrap 'java.net.IDN.toASCII()' into a StringTransformer here.
103     * </p>
104     * @param idnaTransformer
105     */
106    public static void setIdnaTransformer(StringTransformer idnaTransformer) {
107        if (idnaTransformer == null) {
108            throw new NullPointerException();
109        }
110        DNSUtil.idnaTransformer = idnaTransformer;
111    }
112
113    private static enum DomainType {
114        Server,
115        Client,
116        ;
117    }
118
119    /**
120     * Returns a list of HostAddresses under which the specified XMPP server can be reached at for client-to-server
121     * communication. A DNS lookup for a SRV record in the form "_xmpp-client._tcp.example.com" is attempted, according
122     * to section 3.2.1 of RFC 6120. If that lookup fails, it's assumed that the XMPP server lives at the host resolved
123     * by a DNS lookup at the specified domain on the default port of 5222.
124     * <p>
125     * As an example, a lookup for "example.com" may return "im.example.com:5269".
126     * </p>
127     *
128     * @param domain the domain.
129     * @param failedAddresses on optional list that will be populated with host addresses that failed to resolve.
130     * @return List of HostAddress, which encompasses the hostname and port that the
131     *      XMPP server can be reached at for the specified domain.
132     */
133    public static List<HostAddress> resolveXMPPServiceDomain(String domain, List<HostAddress> failedAddresses, DnssecMode dnssecMode) {
134        domain = idnaTransformer.transform(domain);
135
136        return resolveDomain(domain, DomainType.Client, failedAddresses, dnssecMode);
137    }
138
139    /**
140     * Returns a list of HostAddresses under which the specified XMPP server can be reached at for server-to-server
141     * communication. A DNS lookup for a SRV record in the form "_xmpp-server._tcp.example.com" is attempted, according
142     * to section 3.2.1 of RFC 6120. If that lookup fails , it's assumed that the XMPP server lives at the host resolved
143     * by a DNS lookup at the specified domain on the default port of 5269.
144     * <p>
145     * As an example, a lookup for "example.com" may return "im.example.com:5269".
146     * </p>
147     *
148     * @param domain the domain.
149     * @param failedAddresses on optional list that will be populated with host addresses that failed to resolve.
150     * @return List of HostAddress, which encompasses the hostname and port that the
151     *      XMPP server can be reached at for the specified domain.
152     */
153    public static List<HostAddress> resolveXMPPServerDomain(String domain, List<HostAddress> failedAddresses, DnssecMode dnssecMode) {
154        domain = idnaTransformer.transform(domain);
155
156        return resolveDomain(domain, DomainType.Server, failedAddresses, dnssecMode);
157    }
158
159    /**
160     * 
161     * @param domain the domain.
162     * @param domainType the XMPP domain type, server or client.
163     * @param failedAddresses a list that will be populated with host addresses that failed to resolve.
164     * @return a list of resolver host addresses for this domain.
165     */
166    private static List<HostAddress> resolveDomain(String domain, DomainType domainType,
167                    List<HostAddress> failedAddresses, DnssecMode dnssecMode) {
168        if (dnsResolver == null) {
169            throw new IllegalStateException("No DNS Resolver active in Smack");
170        }
171
172        List<HostAddress> addresses = new ArrayList<HostAddress>();
173
174        // Step one: Do SRV lookups
175        String srvDomain;
176        switch (domainType) {
177        case Server:
178            srvDomain = "_xmpp-server._tcp." + domain;
179            break;
180        case Client:
181            srvDomain = "_xmpp-client._tcp." + domain;
182            break;
183        default:
184            throw new AssertionError();
185        }
186
187        List<SRVRecord> srvRecords = dnsResolver.lookupSRVRecords(srvDomain, failedAddresses, dnssecMode);
188        if (srvRecords != null && !srvRecords.isEmpty()) {
189            if (LOGGER.isLoggable(Level.FINE)) {
190                String logMessage = "Resolved SRV RR for " + srvDomain + ":";
191                for (SRVRecord r : srvRecords)
192                    logMessage += " " + r;
193                LOGGER.fine(logMessage);
194            }
195            List<HostAddress> sortedRecords = sortSRVRecords(srvRecords);
196            addresses.addAll(sortedRecords);
197        } else {
198            LOGGER.info("Could not resolve DNS SRV resource records for " + srvDomain + ". Consider adding those.");
199        }
200
201        int defaultPort = -1;
202        switch (domainType) {
203        case Client:
204            defaultPort = 5222;
205            break;
206        case Server:
207            defaultPort = 5269;
208            break;
209        }
210        // Step two: Add the hostname to the end of the list
211        HostAddress hostAddress = dnsResolver.lookupHostAddress(domain, defaultPort, failedAddresses, dnssecMode);
212        if (hostAddress != null) {
213            addresses.add(hostAddress);
214        }
215
216        return addresses;
217    }
218
219    /**
220     * Sort a given list of SRVRecords as described in RFC 2782
221     * Note that we follow the RFC with one exception. In a group of the same priority, only the first entry
222     * is calculated by random. The others are ore simply ordered by their priority.
223     * 
224     * @param records
225     * @return the list of resolved HostAddresses
226     */
227    private static List<HostAddress> sortSRVRecords(List<SRVRecord> records) {
228        // RFC 2782, Usage rules: "If there is precisely one SRV RR, and its Target is "."
229        // (the root domain), abort."
230        if (records.size() == 1 && records.get(0).getFQDN().equals("."))
231            return Collections.emptyList();
232
233        // sorting the records improves the performance of the bisection later
234        Collections.sort(records);
235
236        // create the priority buckets
237        SortedMap<Integer, List<SRVRecord>> buckets = new TreeMap<Integer, List<SRVRecord>>();
238        for (SRVRecord r : records) {
239            Integer priority = r.getPriority();
240            List<SRVRecord> bucket = buckets.get(priority);
241            // create the list of SRVRecords if it doesn't exist
242            if (bucket == null) {
243                bucket = new LinkedList<SRVRecord>();
244                buckets.put(priority, bucket);
245            }
246            bucket.add(r);
247        }
248
249        List<HostAddress> res = new ArrayList<HostAddress>(records.size());
250
251        for (Integer priority : buckets.keySet()) {
252            List<SRVRecord> bucket = buckets.get(priority);
253            int bucketSize;
254            while ((bucketSize = bucket.size()) > 0) {
255                int[] totals = new int[bucketSize];
256                int running_total = 0;
257                int count = 0;
258                int zeroWeight = 1;
259
260                for (SRVRecord r : bucket) {
261                    if (r.getWeight() > 0) {
262                        zeroWeight = 0;
263                        break;
264                    }
265                }
266
267                for (SRVRecord r : bucket) {
268                    running_total += (r.getWeight() + zeroWeight);
269                    totals[count] = running_total;
270                    count++;
271                }
272                int selectedPos;
273                if (running_total == 0) {
274                    // If running total is 0, then all weights in this priority
275                    // group are 0. So we simply select one of the weights randomly
276                    // as the other 'normal' algorithm is unable to handle this case
277                    selectedPos = (int) (Math.random() * bucketSize);
278                } else {
279                    double rnd = Math.random() * running_total;
280                    selectedPos = bisect(totals, rnd);
281                }
282                // add the SRVRecord that was randomly chosen on it's weight
283                // to the start of the result list
284                SRVRecord chosenSRVRecord = bucket.remove(selectedPos);
285                res.add(chosenSRVRecord);
286            }
287        }
288
289        return res;
290    }
291
292    // TODO this is not yet really bisection just a stupid linear search
293    private static int bisect(int[] array, double value) {
294        int pos = 0;
295        for (int element : array) {
296            if (value < element)
297                break;
298            pos++;
299        }
300        return pos;
301    }
302
303}