use of org.xbill.DNS.SimpleResolver 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;
}
use of org.xbill.DNS.SimpleResolver in project opennms by OpenNMS.
the class DnsMonitorIT method testDnsJavaWithDnsServer.
@Test
public void testDnsJavaWithDnsServer() throws TextParseException, UnknownHostException {
final Lookup l = new Lookup("example.com", Type.AAAA);
// make sure we use a temporary cache so don't get results from a previously cached query
// from another test
l.setCache(null);
final SimpleResolver resolver = new SimpleResolver("::1");
resolver.setPort(9153);
l.setResolver(resolver);
l.run();
System.out.println("result: " + l.getResult());
final Record[] answers = l.getAnswers();
assertEquals(answers.length, 1);
final Record record = answers[0];
System.err.println(record.getTTL());
if (l.getResult() == Lookup.SUCCESSFUL) {
System.out.println(l.getAnswers()[0].rdataToString());
}
assertTrue(l.getResult() == Lookup.SUCCESSFUL);
}
use of org.xbill.DNS.SimpleResolver in project camel by apache.
the class DnsDigProducer method process.
@Override
public void process(Exchange exchange) throws Exception {
String server = exchange.getIn().getHeader(DnsConstants.DNS_SERVER, String.class);
SimpleResolver resolver = new SimpleResolver(server);
int type = Type.value(exchange.getIn().getHeader(DnsConstants.DNS_TYPE, String.class));
if (type == -1) {
// default: if unparsable value given, use A.
type = Type.A;
}
String dclassValue = exchange.getIn().getHeader(DnsConstants.DNS_CLASS, String.class);
if (dclassValue == null) {
dclassValue = "";
}
int dclass = DClass.value(dclassValue);
if (dclass == -1) {
// by default, value is IN.
dclass = DClass.IN;
}
Name name = Name.fromString(exchange.getIn().getHeader(DnsConstants.DNS_NAME, String.class), Name.root);
Record rec = Record.newRecord(name, type, dclass);
Message query = Message.newQuery(rec);
Message response = resolver.send(query);
exchange.getIn().setBody(response);
}
use of org.xbill.DNS.SimpleResolver 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));
}
}
use of org.xbill.DNS.SimpleResolver in project opennms by OpenNMS.
the class DnsMonitor method pollDNS.
private PollStatus pollDNS(final TimeoutTracker timeoutTracker, final int port, final InetAddress address, final String lookup, final List<Integer> fatalCodes, int minAnswers, int maxAnswers) {
final String addr = InetAddressUtils.str(address);
for (timeoutTracker.reset(); timeoutTracker.shouldRetry(); timeoutTracker.nextAttempt()) {
try {
final Name name = Name.fromString(lookup, Name.root);
final SimpleResolver resolver = new SimpleResolver();
resolver.setAddress(new InetSocketAddress(addr, port));
resolver.setLocalAddress((InetSocketAddress) null);
double timeout = timeoutTracker.getSoTimeout() / 1000d;
resolver.setTimeout((timeout < 1 ? 1 : (int) timeout));
final Record question = Record.newRecord(name, Type.A, DClass.IN);
final Message query = Message.newQuery(question);
PollStatus status;
timeoutTracker.startAttempt();
final Message response = resolver.send(query);
double responseTime = timeoutTracker.elapsedTimeInMillis();
final Integer rcode = response.getHeader().getRcode();
LOG.debug("received response code: {}", rcode);
if (fatalCodes.contains(rcode)) {
status = PollStatus.unavailable("Received an invalid DNS response for address: " + addr);
LOG.debug(status.getReason());
return status;
} else if (minAnswers != DEFAULT_MIN_ANSWERS || maxAnswers != DEFAULT_MAX_ANSWERS) {
int numAnswers = response.getSectionArray(Section.ANSWER).length;
boolean tooFewAnswers = numAnswers < minAnswers;
boolean tooManyAnswers = numAnswers > maxAnswers;
if (tooFewAnswers) {
status = PollStatus.unavailable("Response contained only " + numAnswers + " answer(s), but at least " + minAnswers + " answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
if (tooManyAnswers) {
status = PollStatus.unavailable("Response contained " + numAnswers + " answer(s), but " + maxAnswers + " or fewer answers(s) are needed.");
LOG.warn(status.getReason());
return status;
}
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received with {} answer(s), responseTime = {}ms", numAnswers, responseTime);
return status;
} else {
status = PollStatus.up(responseTime);
LOG.debug("valid DNS response received, responseTime = {}ms", responseTime);
return status;
}
} catch (final InterruptedIOException e) {
// No response received, retry without marking the poll failed. If we get this condition over and over until
// the retries are exhausted, it will leave serviceStatus null and we'll get the log message at the bottom
} catch (final NoRouteToHostException e) {
String reason1 = "No route to host exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final ConnectException e) {
String reason1 = "Connection exception for address: " + addr;
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
} catch (final IOException e) {
String reason1 = "IOException while polling address: " + addr + " " + e.getMessage();
LOG.debug(reason1, e);
return PollStatus.unavailable(reason1);
}
}
String reason = "Never received valid DNS response for address: " + addr;
LOG.debug(reason);
return PollStatus.unavailable(reason);
}
Aggregations