use of org.xbill.DNS.Message 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.Message in project nhin-d by DirectProject.
the class ProxyDNSStore method get.
/**
* {@inheritDoc}
*/
@Override
public Message get(Message dnsMsg) throws DNSException {
ExtendedResolver resolver = createExResolver(servers, port, 2, 2000);
// try UPD first
Message response = null;
try {
response = resolver.send(dnsMsg);
} catch (IOException e) {
/* no-op */
}
if (response == null) {
// try TCP
resolver.setTCP(true);
try {
response = resolver.send(dnsMsg);
} catch (IOException e) {
/* no-op */
}
}
return response;
}
use of org.xbill.DNS.Message in project nhin-d by DirectProject.
the class ConfigServiceDNSStore method get.
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public Message get(Message request) throws DNSException {
LOGGER.trace("get(Message) Entered");
/* for testing time out cases
try
{
Thread.sleep(1000000);
}
catch (Exception e)
{
}
*/
if (request == null)
throw new DNSException(DNSError.newError(Rcode.FORMERR));
Header header = request.getHeader();
if (header.getFlag(Flags.QR) || header.getRcode() != Rcode.NOERROR)
throw new DNSException(DNSError.newError(Rcode.FORMERR));
if (header.getOpcode() != Opcode.QUERY)
throw new DNSException(DNSError.newError(Rcode.NOTIMP));
Record question = request.getQuestion();
if (question == null || question.getDClass() != DClass.IN) {
throw new DNSException(DNSError.newError(Rcode.NOTIMP));
}
Record queryRecord = request.getQuestion();
Name name = queryRecord.getName();
int type = queryRecord.getType();
if (LOGGER.isDebugEnabled()) {
StringBuilder builder = new StringBuilder("Recieved Query Request:");
builder.append("\r\n\tName: " + name.toString());
builder.append("\r\n\tType: " + type);
builder.append("\r\n\tDClass: " + queryRecord.getDClass());
LOGGER.debug(builder.toString());
}
Collection<Record> lookupRecords = null;
switch(question.getType()) {
case Type.A:
case Type.MX:
case Type.SOA:
case Type.SRV:
case Type.NS:
case Type.CNAME:
{
try {
final RRset set = processGenericRecordRequest(name.toString(), type);
if (set != null) {
lookupRecords = new ArrayList<Record>();
Iterator<Record> iter = set.rrs();
while (iter.hasNext()) lookupRecords.add(iter.next());
}
} catch (Exception e) {
throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "DNS service proxy call failed: " + e.getMessage(), e);
}
break;
}
case Type.CERT:
{
final RRset set = processCERTRecordRequest(name.toString());
if (set != null) {
lookupRecords = new ArrayList<Record>();
Iterator<Record> iter = set.rrs();
while (iter.hasNext()) lookupRecords.add(iter.next());
}
break;
}
case Type.ANY:
{
Collection<Record> genRecs = processGenericANYRecordRequest(name.toString());
RRset certRecs = processCERTRecordRequest(name.toString());
if (genRecs != null || certRecs != null) {
lookupRecords = new ArrayList<Record>();
if (genRecs != null)
lookupRecords.addAll(genRecs);
if (certRecs != null) {
Iterator<Record> iter = certRecs.rrs();
while (iter.hasNext()) lookupRecords.add(iter.next());
}
}
break;
}
default:
{
LOGGER.debug("Query Type " + type + " not implemented");
throw new DNSException(DNSError.newError(Rcode.NOTIMP), "Query Type " + type + " not implemented");
}
}
if (lookupRecords == null || lookupRecords.size() == 0) {
LOGGER.debug("No records found.");
return null;
}
final Message response = new Message(request.getHeader().getID());
response.getHeader().setFlag(Flags.QR);
if (request.getHeader().getFlag(Flags.RD))
response.getHeader().setFlag(Flags.RD);
response.addRecord(queryRecord, Section.QUESTION);
final Iterator<Record> iter = lookupRecords.iterator();
while (iter.hasNext()) response.addRecord(iter.next(), Section.ANSWER);
// we are authoritative only
response.getHeader().setFlag(Flags.AA);
// look for an SOA record
final Record soaRecord = checkForSoaRecord(name.toString());
if (soaRecord != null)
response.addRecord(soaRecord, Section.AUTHORITY);
LOGGER.trace("get(Message) Exit");
return response;
}
use of org.xbill.DNS.Message in project GNS by MobilityFirst.
the class NameResolution method lookupDnsCache.
/**
* Look up the local dns server cache.
* Returns a {@link Message}.
*
* @param query
* @param dnsCache
* @return a Message
*/
public static Message lookupDnsCache(Message query, Cache dnsCache) {
// check for queries we can't handle
int type = query.getQuestion().getType();
// Was the query legitimate or implemented?
if (!Type.isRR(type) && type != Type.ANY) {
return errorMessage(query, Rcode.NOTIMP);
}
// extract the domain (guid) and field from the query
final Name requestedName = query.getQuestion().getName();
final byte[] rawName = requestedName.toWire();
final String lookupName = querytoStringForGNS(rawName);
NameResolution.getLogger().log(Level.FINER, "Looking up name in cache: {0}", lookupName);
SetResponse lookupresult = dnsCache.lookupRecords(requestedName, Type.ANY, Credibility.NORMAL);
if (lookupresult.isSuccessful()) {
Message response = new Message(query.getHeader().getID());
response.getHeader().setFlag(Flags.QR);
if (query.getHeader().getFlag(Flags.RD)) {
response.getHeader().setFlag(Flags.RA);
}
response.addRecord(query.getQuestion(), Section.QUESTION);
response.getHeader().setFlag(Flags.AA);
ArrayList<Name> cnameNames = new ArrayList<>();
// Write the response
for (RRset rrset : lookupresult.answers()) {
NameResolution.getLogger().log(Level.FINE, "{0}\n", rrset.toString());
Iterator<?> rrItr = rrset.rrs();
while (rrItr.hasNext()) {
Record curRecord = (Record) rrItr.next();
response.addRecord(curRecord, Section.ANSWER);
if (curRecord.getType() == Type.CNAME) {
cnameNames.add(((CNAMERecord) curRecord).getAlias());
}
}
}
if (cnameNames.isEmpty()) {
return response;
}
// For all CNAMES in the response, add their A records
for (Name cname : cnameNames) {
NameResolution.getLogger().log(Level.FINE, "Looking up CNAME in cache: {0}", cname.toString());
SetResponse lookUpResult = dnsCache.lookupRecords(cname, Type.ANY, Credibility.NORMAL);
if (lookUpResult.isSuccessful()) {
for (RRset rrset : lookUpResult.answers()) {
NameResolution.getLogger().log(Level.FINE, "{0}\n", rrset.toString());
Iterator<?> rrItr = rrset.rrs();
while (rrItr.hasNext()) {
Record curRecord = (Record) rrItr.next();
response.addRecord(curRecord, Section.ANSWER);
}
}
}
}
return response;
} else {
return errorMessage(query, Rcode.NOTIMP);
}
}
use of org.xbill.DNS.Message in project GNS by MobilityFirst.
the class LookupWorker method generateReply.
/**
* Queries DNS and/or GNS servers for DNS records.
*
* Note: a null return value means that the caller doesn't need to do
* anything. Currently this only happens if this is an AXFR request over TCP.
*/
private Message generateReply(Message query) {
long startTime = System.currentTimeMillis();
NameResolution.getLogger().log(Level.FINE, "Incoming request:\n {0}", query.toString());
// If it's not a query we just ignore it.
if (query.getHeader().getFlag(Flags.QR)) {
return null;
}
long checkStart = System.currentTimeMillis();
// Check for wierd queries we can't handle.
Message errorMessage;
if ((errorMessage = NameResolution.checkForErroneousQueries(query)) != null) {
return errorMessage;
}
DelayProfiler.updateDelay("checkForErroneousQueries", checkStart);
// If we're not consulting the DNS server as well just send the query to GNS.
if (dnsServer == null) {
Message result = NameResolution.lookupGnsServer(incomingPacket.getAddress(), query, handler);
DelayProfiler.updateDelay("generateReply", startTime);
return result;
}
// Otherwise as a first step before performing GNS/DNS lookup we check our own local cache.
if (dnsCache != null) {
Message tempQuery = (Message) query.clone();
Message result = NameResolution.lookupDnsCache(tempQuery, dnsCache);
if (result.getHeader().getRcode() == Rcode.NOERROR) {
NameResolution.getLogger().log(Level.FINE, "Responding the request from cache {0}", NameResolution.queryAndResponseToString(query, result));
return result;
}
}
// Create a clone of the query for duplicating the request to GNS and DNS
Message dnsQuery = (Message) query.clone();
List<LookupTask> tasks;
if (gnsServer == null) {
// We make two tasks to check the DNS and GNS in parallel
tasks = Arrays.asList(// Create GNS lookup task
new LookupTask(query, handler), // Create DNS lookup task
new LookupTask(dnsQuery, dnsServer, handler));
} else {
tasks = Arrays.asList(// Create GNS lookup task
new LookupTask(query, gnsServer, true, /* isGNS */
handler), // Create DNS lookup task
new LookupTask(dnsQuery, dnsServer, false, /* isGNS */
handler));
}
// A little bit of overkill for two tasks, but it's really not that much longer (if any) than
// the altenative. Plus it's cool and trendy to use futures.
ExecutorService executor = Executors.newFixedThreadPool(2);
ExecutorCompletionService<Message> completionService = new ExecutorCompletionService<>(executor);
List<Future<Message>> futures = new ArrayList<>(2);
for (Callable<Message> task : tasks) {
futures.add(completionService.submit(task));
}
Message successResponse = null;
Message errorResponse = null;
// loop throught the tasks getting results as they complete
for (LookupTask task : tasks) {
// this is just doing things twice btw
try {
Message result = completionService.take().get();
if (result.getHeader().getRcode() == Rcode.NOERROR) {
successResponse = result;
break;
} else {
// squirrel this away for later in case we get no successes
errorResponse = result;
}
} catch (ExecutionException e) {
NameResolution.getLogger().log(Level.WARNING, "Problem handling lookup task: {0}", e);
} catch (InterruptedException e) {
NameResolution.getLogger().log(Level.WARNING, "Lookup task interrupted: {0}", e);
}
}
// Shutdown the executor threadpool
executor.shutdown();
if (successResponse != null) {
// Cache the successful response
try {
SetResponse addMsgResponse = dnsCache.addMessage(successResponse);
if (!addMsgResponse.isSuccessful()) {
RRset[] answers = successResponse.getSectionRRsets(Section.ANSWER);
boolean isAuth = successResponse.getHeader().getFlag(Flags.AA);
int qClass = successResponse.getQuestion().getDClass();
for (int i = 0; i < answers.length; i++) {
if (answers[i].getDClass() != qClass) {
continue;
}
int cred = getCred(Section.ANSWER, isAuth);
dnsCache.addRRset(answers[i], cred);
NameResolution.getLogger().log(Level.FINE, "Records added to cache {0}", answers[i].toString());
}
}
} catch (NullPointerException e) {
NameResolution.getLogger().log(Level.WARNING, "Failed to add a dns response to cache{0}", e);
}
return successResponse;
} else if (errorResponse != null) {
// currently this is returning the second error response... do we care?
return errorResponse;
} else {
return NameResolution.errorMessage(query, Rcode.NXDOMAIN);
}
}
Aggregations