001/** 002 * 003 * Copyright 2013-2017 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.dns.dnsjava; 018 019import java.net.InetAddress; 020import java.util.ArrayList; 021import java.util.List; 022 023import org.jivesoftware.smack.ConnectionConfiguration.DnssecMode; 024import org.jivesoftware.smack.initializer.SmackInitializer; 025import org.jivesoftware.smack.util.DNSUtil; 026import org.jivesoftware.smack.util.dns.DNSResolver; 027import org.jivesoftware.smack.util.dns.HostAddress; 028import org.jivesoftware.smack.util.dns.SRVRecord; 029 030import org.xbill.DNS.Lookup; 031import org.xbill.DNS.Record; 032import org.xbill.DNS.TextParseException; 033import org.xbill.DNS.Type; 034 035/** 036 * This implementation uses the <a href="http://www.dnsjava.org/">dnsjava</a> implementation for resolving DNS addresses. 037 * 038 */ 039public class DNSJavaResolver extends DNSResolver implements SmackInitializer { 040 041 private static final DNSJavaResolver instance = new DNSJavaResolver(); 042 043 public static DNSResolver getInstance() { 044 return instance; 045 } 046 047 public DNSJavaResolver() { 048 super(false); 049 } 050 051 @Override 052 protected List<SRVRecord> lookupSRVRecords0(String name, List<HostAddress> failedAddresses, DnssecMode dnssecMode) { 053 List<SRVRecord> res = new ArrayList<>(); 054 055 Lookup lookup; 056 try { 057 lookup = new Lookup(name, Type.SRV); 058 } 059 catch (TextParseException e) { 060 throw new IllegalStateException(e); 061 } 062 063 Record[] recs = lookup.run(); 064 if (recs == null) 065 return res; 066 067 for (Record record : recs) { 068 org.xbill.DNS.SRVRecord srvRecord = (org.xbill.DNS.SRVRecord) record; 069 if (srvRecord != null && srvRecord.getTarget() != null) { 070 String host = srvRecord.getTarget().toString(); 071 int port = srvRecord.getPort(); 072 int priority = srvRecord.getPriority(); 073 int weight = srvRecord.getWeight(); 074 075 List<InetAddress> hostAddresses = lookupHostAddress0(host, failedAddresses, dnssecMode); 076 if (shouldContinue(name, host, hostAddresses)) { 077 continue; 078 } 079 080 SRVRecord r = new SRVRecord(host, port, priority, weight, hostAddresses); 081 res.add(r); 082 } 083 } 084 085 return res; 086 } 087 088 public static void setup() { 089 DNSUtil.setDNSResolver(getInstance()); 090 } 091 092 @Override 093 public List<Exception> initialize() { 094 setup(); 095 return null; 096 } 097 098}