Search in sources :

Example 1 with Resolver

use of org.xbill.DNS.Resolver in project nhin-d by DirectProject.

the class DNSCertificateStore method createExResolver.

protected ExtendedResolver createExResolver(String[] servers, int retries, int timeout) {
    // create a default ExtendedResolver
    ExtendedResolver extendedResolver;
    try {
        extendedResolver = new ExtendedResolver();
    } catch (UnknownHostException e) {
        LOGGER.error("", e);
        throw new IllegalStateException("unable to create default ExtendedResolver", e);
    }
    // remove all resolvers from default ExtendedResolver
    Resolver[] resolvers = extendedResolver.getResolvers();
    if (!ArrayUtils.isEmpty(resolvers)) {
        for (Resolver resolver : resolvers) {
            extendedResolver.deleteResolver(resolver);
        }
    }
    // add the specified servers
    if (!ArrayUtils.isEmpty(servers)) {
        for (String server : servers) {
            // support for IP addresses instead of names
            server = server.replaceFirst("\\.$", "");
            try {
                // create and add a SimpleResolver for each server
                SimpleResolver simpleResolver = new SimpleResolver(server);
                extendedResolver.addResolver(simpleResolver);
            } catch (UnknownHostException e) {
                LOGGER.debug("unable to add resolver for " + server, e);
                continue;
            }
        }
        extendedResolver.setRetries(retries);
        extendedResolver.setTimeout(timeout);
        extendedResolver.setTCP(true);
    }
    return extendedResolver;
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) UnknownHostException(java.net.UnknownHostException) SimpleResolver(org.xbill.DNS.SimpleResolver) ExtendedResolver(org.xbill.DNS.ExtendedResolver) Resolver(org.xbill.DNS.Resolver) SimpleResolver(org.xbill.DNS.SimpleResolver)

Example 2 with Resolver

use of org.xbill.DNS.Resolver in project opennms by OpenNMS.

the class DNSResolutionMonitor method poll.

@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Get the name to query for
    final Name name;
    final String lookup = ParameterMap.getKeyedString(parameters, PARM_LOOKUP, svc.getNodeLabel());
    try {
        name = new Name(lookup);
    } catch (final TextParseException e) {
        return PollStatus.unavailable("Invalid record name '" + lookup + "': " + e.getMessage());
    }
    Set<Integer> recordTypes = new TreeSet<>();
    // Determine if records for IPv4 and/or IPv6 re required
    final String resolutionType = ParameterMap.getKeyedString(parameters, PARM_RESOLUTION_TYPE, PARM_RESOLUTION_TYPE_DEFAULT);
    final String recordTypesParam = ParameterMap.getKeyedString(parameters, PARM_RECORD_TYPES, "");
    Boolean matchAll = Boolean.TRUE;
    if ("".equals(recordTypesParam)) {
        if (PARM_RESOLUTION_TYPE_V4.equalsIgnoreCase(resolutionType) || PARM_RESOLUTION_TYPE_BOTH.equalsIgnoreCase(resolutionType) || PARM_RESOLUTION_TYPE_EITHER.equalsIgnoreCase(resolutionType)) {
            recordTypes.add(Type.A);
        }
        if (PARM_RESOLUTION_TYPE_V6.equalsIgnoreCase(resolutionType) || PARM_RESOLUTION_TYPE_BOTH.equalsIgnoreCase(resolutionType) || PARM_RESOLUTION_TYPE_EITHER.equalsIgnoreCase(resolutionType)) {
            recordTypes.add(Type.AAAA);
        }
        if (PARM_RESOLUTION_TYPE_EITHER.equals(resolutionType)) {
            matchAll = Boolean.FALSE;
        }
    } else {
        for (final String type : recordTypesParam.split(",")) {
            final Integer typeValue = Type.value(type);
            if (typeValue == -1) {
                LOG.error("Invalid record type '{}' specified in record-types list.", type);
            } else {
                recordTypes.add(typeValue);
            }
        }
    }
    // Build a resolver object used for lookups
    final String nameserver = ParameterMap.getKeyedString(parameters, PARM_NAMESERVER, null);
    final Resolver resolver;
    try {
        if (nameserver == null) {
            // Use system-defined resolvers
            resolver = new ExtendedResolver();
        } else {
            if ("::1".equals(nameserver)) {
                resolver = new SimpleResolver(nameserver);
            } else if (nameserver.matches("^\\[[\\d:]+\\]:\\d+$")) {
                // IPv6 address with port number
                final Integer pos = nameserver.lastIndexOf(":");
                String hostname = nameserver.substring(0, pos);
                hostname = hostname.substring(1, hostname.length() - 1);
                final Integer port = Integer.valueOf(nameserver.substring(pos + 1));
                LOG.debug("nameserver: hostname={}, port={}", hostname, port);
                resolver = new SimpleResolver(hostname);
                resolver.setPort(port);
            } else if (nameserver.matches("^\\S+:\\d+$")) {
                // hostname with port number
                final Integer pos = nameserver.lastIndexOf(":");
                final String hostname = nameserver.substring(0, pos);
                final String port = nameserver.substring(pos + 1);
                LOG.debug("nameserver: hostname={}, port={}", hostname, port);
                resolver = new SimpleResolver(hostname);
                resolver.setPort(Integer.getInteger(port));
            } else {
                // hostname or ip address
                resolver = new SimpleResolver(nameserver);
            }
        }
    } catch (final UnknownHostException e) {
        return PollStatus.unavailable("Unable to resolve nameserver '" + nameserver + "': " + e.getMessage());
    }
    // Start resolving the records
    final long start = System.currentTimeMillis();
    // Resolve the name
    Set<String> foundTypes = new TreeSet<>();
    Set<String> notFoundTypes = new TreeSet<>();
    recordTypes.forEach((type) -> {
        if (resolve(name, resolver, type)) {
            foundTypes.add(Type.string(type));
        } else {
            LOG.warn("Unable to resolve host '{}' for type '{}'", name, Type.string(type));
            notFoundTypes.add(Type.string(type));
        }
    });
    // Resolving succeeded - checking results
    final long end = System.currentTimeMillis();
    LOG.debug("foundTypes: {}", foundTypes);
    LOG.debug("notFoundTypes: {}", notFoundTypes);
    // Check if result is valid
    if (foundTypes.isEmpty() && !notFoundTypes.isEmpty()) {
        return PollStatus.unavailable("Unable to resolve host '" + name + "'");
    } else if (!foundTypes.isEmpty() && !notFoundTypes.isEmpty() && matchAll) {
        return PollStatus.unavailable("'" + name + "' could be resolved to types [" + foundTypes + "], but not for types [" + notFoundTypes + "]");
    } else {
        return PollStatus.available((double) (end - start));
    }
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) SimpleResolver(org.xbill.DNS.SimpleResolver) ExtendedResolver(org.xbill.DNS.ExtendedResolver) Resolver(org.xbill.DNS.Resolver) UnknownHostException(java.net.UnknownHostException) SimpleResolver(org.xbill.DNS.SimpleResolver) Name(org.xbill.DNS.Name) TreeSet(java.util.TreeSet) TextParseException(org.xbill.DNS.TextParseException)

Example 3 with Resolver

use of org.xbill.DNS.Resolver in project whirr by apache.

the class FastDnsResolver method apply.

/**
 * Resolve the reverse dns name for the given IP address
 *
 * @param hostIp
 *      host IP address
 * @return
 *      the resolved DNS name or in some cases the IP address as a string
 */
@Override
public String apply(String hostIp) {
    try {
        Resolver resolver = new ExtendedResolver();
        resolver.setTimeout(timeoutInSeconds);
        resolver.setTCP(true);
        Name name = ReverseMap.fromAddress(hostIp);
        Record record = Record.newRecord(name, Type.PTR, DClass.IN);
        Message response = resolver.send(newQuery(record));
        Record[] answers = response.getSectionArray(Section.ANSWER);
        if (answers.length == 0) {
            LOG.warn("no answer to DNS resolution attempt for " + hostIp + "; using fallback");
            return fallback(hostIp);
        } else {
            String reverseAddress = answers[0].rdataToString();
            return reverseAddress.endsWith(".") ? reverseAddress.substring(0, reverseAddress.length() - 1) : reverseAddress;
        }
    } catch (SocketTimeoutException e) {
        return hostIp;
    /* same response as standard Java on timeout */
    } catch (IOException e) {
        // suggests eg firewall block DNS lookup or similar
        LOG.warn("error in DNS resolution attempt for " + hostIp + " (" + e + "); using fallback");
        return fallback(hostIp);
    }
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) SocketTimeoutException(java.net.SocketTimeoutException) ExtendedResolver(org.xbill.DNS.ExtendedResolver) Resolver(org.xbill.DNS.Resolver) Message(org.xbill.DNS.Message) Record(org.xbill.DNS.Record) IOException(java.io.IOException) Name(org.xbill.DNS.Name)

Example 4 with Resolver

use of org.xbill.DNS.Resolver in project camel by apache.

the class DnsRecordConverter method toRecord.

/**
     * @param ip, like "192.168.1.1"
     * @return the complete DNS record for that IP.
     */
@Converter
public static Record toRecord(String ip) throws IOException {
    Resolver res = new ExtendedResolver();
    Name name = ReverseMap.fromAddress(ip);
    int type = Type.PTR;
    int dclass = DClass.IN;
    Record rec = Record.newRecord(name, type, dclass);
    Message query = Message.newQuery(rec);
    Message response = res.send(query);
    Record[] answers = response.getSectionArray(Section.ANSWER);
    if (answers.length == 0) {
        return null;
    } else {
        return answers[0];
    }
}
Also used : ExtendedResolver(org.xbill.DNS.ExtendedResolver) ExtendedResolver(org.xbill.DNS.ExtendedResolver) Resolver(org.xbill.DNS.Resolver) Message(org.xbill.DNS.Message) Record(org.xbill.DNS.Record) Name(org.xbill.DNS.Name) Converter(org.apache.camel.Converter)

Example 5 with Resolver

use of org.xbill.DNS.Resolver in project Signal-Android by WhisperSystems.

the class CustomDns method lookup.

@Override
@NonNull
public List<InetAddress> lookup(@NonNull String hostname) throws UnknownHostException {
    Resolver resolver = new SimpleResolver(dnsHostname);
    Lookup lookup = doLookup(hostname);
    lookup.setResolver(resolver);
    Record[] records = lookup.run();
    if (records != null) {
        List<InetAddress> ipv4Addresses = Stream.of(records).filter(r -> r.getType() == Type.A).map(r -> (ARecord) r).map(ARecord::getAddress).toList();
        if (ipv4Addresses.size() > 0) {
            return ipv4Addresses;
        }
    }
    throw new UnknownHostException(hostname);
}
Also used : Stream(com.annimon.stream.Stream) NonNull(androidx.annotation.NonNull) UnknownHostException(java.net.UnknownHostException) Dns(okhttp3.Dns) InetAddress(java.net.InetAddress) Log(org.signal.core.util.logging.Log) Type(org.xbill.DNS.Type) List(java.util.List) ARecord(org.xbill.DNS.ARecord) SimpleResolver(org.xbill.DNS.SimpleResolver) Record(org.xbill.DNS.Record) Resolver(org.xbill.DNS.Resolver) Lookup(org.xbill.DNS.Lookup) SimpleResolver(org.xbill.DNS.SimpleResolver) Resolver(org.xbill.DNS.Resolver) UnknownHostException(java.net.UnknownHostException) Lookup(org.xbill.DNS.Lookup) ARecord(org.xbill.DNS.ARecord) Record(org.xbill.DNS.Record) SimpleResolver(org.xbill.DNS.SimpleResolver) InetAddress(java.net.InetAddress) NonNull(androidx.annotation.NonNull)

Aggregations

Resolver (org.xbill.DNS.Resolver)5 ExtendedResolver (org.xbill.DNS.ExtendedResolver)4 UnknownHostException (java.net.UnknownHostException)3 Name (org.xbill.DNS.Name)3 Record (org.xbill.DNS.Record)3 SimpleResolver (org.xbill.DNS.SimpleResolver)3 Message (org.xbill.DNS.Message)2 NonNull (androidx.annotation.NonNull)1 Stream (com.annimon.stream.Stream)1 IOException (java.io.IOException)1 InetAddress (java.net.InetAddress)1 SocketTimeoutException (java.net.SocketTimeoutException)1 List (java.util.List)1 TreeSet (java.util.TreeSet)1 Dns (okhttp3.Dns)1 Converter (org.apache.camel.Converter)1 Log (org.signal.core.util.logging.Log)1 ARecord (org.xbill.DNS.ARecord)1 Lookup (org.xbill.DNS.Lookup)1 TextParseException (org.xbill.DNS.TextParseException)1