Search in sources :

Example 1 with RRset

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

the class ConfigServiceDNSStore method processGenericRecordRequest.

/**
	 * Processes all DNS requests except CERT records.
	 * @param name The record name.
	 * @param type The record type.
	 * @return Returns a set of record responses to the request.
	 * @throws DNSException
	 */
protected RRset processGenericRecordRequest(String name, int type) throws DNSException {
    DnsRecord[] records;
    try {
        records = proxy.getDNSByNameAndType(name, type);
    } catch (Exception e) {
        throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "DNS service proxy call for DNS records failed: " + e.getMessage(), e);
    }
    if (records == null || records.length == 0)
        return null;
    RRset retVal = new RRset();
    try {
        for (DnsRecord record : records) {
            Record rec = Record.newRecord(Name.fromString(record.getName()), record.getType(), record.getDclass(), record.getTtl(), record.getData());
            retVal.addRR(rec);
        }
    } catch (Exception e) {
        throw new DNSException(DNSError.newError(Rcode.SERVFAIL), "Failure while parsing generic record data: " + e.getMessage(), e);
    }
    return retVal;
}
Also used : RRset(org.xbill.DNS.RRset) CERTRecord(org.xbill.DNS.CERTRecord) Record(org.xbill.DNS.Record) DnsRecord(org.nhind.config.DnsRecord) DnsRecord(org.nhind.config.DnsRecord) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException)

Example 2 with RRset

use of org.xbill.DNS.RRset 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;
}
Also used : Message(org.xbill.DNS.Message) RRset(org.xbill.DNS.RRset) ArrayList(java.util.ArrayList) CertificateConversionException(org.nhindirect.config.model.exceptions.CertificateConversionException) Name(org.xbill.DNS.Name) Header(org.xbill.DNS.Header) Iterator(java.util.Iterator) Collection(java.util.Collection) CERTRecord(org.xbill.DNS.CERTRecord) Record(org.xbill.DNS.Record) DnsRecord(org.nhind.config.DnsRecord)

Example 3 with RRset

use of org.xbill.DNS.RRset 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);
    }
}
Also used : SetResponse(org.xbill.DNS.SetResponse) Message(org.xbill.DNS.Message) ArrayList(java.util.ArrayList) RRset(org.xbill.DNS.RRset) CNAMERecord(org.xbill.DNS.CNAMERecord) ARecord(org.xbill.DNS.ARecord) Record(org.xbill.DNS.Record) NSRecord(org.xbill.DNS.NSRecord) MXRecord(org.xbill.DNS.MXRecord) Name(org.xbill.DNS.Name)

Example 4 with RRset

use of org.xbill.DNS.RRset 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);
    }
}
Also used : Message(org.xbill.DNS.Message) ArrayList(java.util.ArrayList) RRset(org.xbill.DNS.RRset) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) SetResponse(org.xbill.DNS.SetResponse) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException)

Example 5 with RRset

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

the class DNSServer method addGlue.

private void addGlue(final Message response, final Name name, final int flags) {
    final RRset a = findExactMatch(name, Type.A, DClass.IN, true);
    if (a == null)
        return;
    addRRset(name, response, a, Section.ADDITIONAL, flags);
}
Also used : RRset(org.xbill.DNS.RRset)

Aggregations

RRset (org.xbill.DNS.RRset)11 Message (org.xbill.DNS.Message)4 Record (org.xbill.DNS.Record)4 SetResponse (org.xbill.DNS.SetResponse)4 ArrayList (java.util.ArrayList)3 CertificateConversionException (org.nhindirect.config.model.exceptions.CertificateConversionException)3 CERTRecord (org.xbill.DNS.CERTRecord)3 CNAMERecord (org.xbill.DNS.CNAMERecord)3 Name (org.xbill.DNS.Name)3 Zone (org.xbill.DNS.Zone)3 DnsRecord (org.nhind.config.DnsRecord)2 DNAMERecord (org.xbill.DNS.DNAMERecord)2 Header (org.xbill.DNS.Header)2 DataOutputStream (java.io.DataOutputStream)1 IOException (java.io.IOException)1 InterruptedIOException (java.io.InterruptedIOException)1 URL (java.net.URL)1 X509Certificate (java.security.cert.X509Certificate)1 RSAKey (java.security.interfaces.RSAKey)1 Collection (java.util.Collection)1