Java 类org.xbill.DNS.Name 实例源码

项目:open-rmbt    文件:Helperfunctions.java   
public static String reverseDNSLookup(final InetAddress adr)
{
    try
    {
        final Name name = ReverseMap.fromAddress(adr);

        final Lookup lookup = new Lookup(name, Type.PTR);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof PTRRecord)
                {
                    final PTRRecord ptr = (PTRRecord) record;
                    return ptr.getTarget().toString();
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
项目:openvisualtraceroute    文件:DNSLookupService.java   
/**
 * Dns lookup more efficient than the INetAddress.getHostName(ip)
 *
 * @param hostIp
 * @return
 * @throws IOException
 */
public String dnsLookup(final String hostIp) {
    try {
        final Name name = ReverseMap.fromAddress(hostIp);
        final int type = Type.PTR;
        final int dclass = DClass.IN;
        final Record rec = Record.newRecord(name, type, dclass);
        final Message query = Message.newQuery(rec);

        final Message response = _resolver.send(query);

        final Record[] answers = response.getSectionArray(Section.ANSWER);
        if (answers.length > 0) {
            String ret = answers[0].rdataToString();
            if (ret.endsWith(".")) {
                ret = ret.substring(0, ret.length() - 1);
            }
            return ret;
        }
    } catch (final IOException e) {
        LOGGER.warn("Failed to resolve hostname for " + hostIp, e);
    }
    return UNKNOWN_HOST;
}
项目:nomulus    文件:DnsMessageTransportTest.java   
@Test
public void testSentMessageTooLongThrowsException() throws Exception {
  Update oversize = new Update(Name.fromString("tld", Name.root));
  for (int i = 0; i < 2000; i++) {
    oversize.add(
        ARecord.newRecord(
            Name.fromString("test-extremely-long-name-" + i + ".tld", Name.root),
            Type.A,
            DClass.IN));
  }
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  when(mockSocket.getOutputStream()).thenReturn(outputStream);
  IllegalArgumentException thrown =
      expectThrows(IllegalArgumentException.class, () -> resolver.send(oversize));
  assertThat(thrown).hasMessageThat().contains("message larger than maximum");
}
项目:Camel    文件:DnsRecordConverter.java   
/**
 * @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];
    }
}
项目:Wilma    文件:CERTConverter.java   
/** Builds a CERT record from a Certificate associated with a key also in DNS */
public static CERTRecord
buildRecord(Name name, int dclass, long ttl, Certificate cert, int tag,
        int alg)
{
    int type;
    byte [] data;

    try {
        if (cert instanceof X509Certificate) {
            type = CERTRecord.PKIX;
            data = cert.getEncoded();
        }
        else
            return null;

        return new CERTRecord(name, dclass, ttl, type, tag, alg, data);
    }
    catch (CertificateException e) {
        if (Options.check("verboseexceptions"))
            System.err.println("Cert build exception:" + e);
        return null;
    }
}
项目:plum    文件:DnsResolver.java   
private String resolveHostByName(Resolver resolver, Name target) {
    Lookup lookup = new Lookup(target, A);
    if (resolver != null) {
        lookup.setResolver(resolver);
    }
    Record[] records = lookup.run();
    Optional<InetAddress> address = of(records)
            .filter(it -> it instanceof ARecord)
            .map(a -> ((ARecord) a).getAddress())
            .findFirst();
    if (address.isPresent()) {
        return address.get().getHostAddress();
    } else {
        log.warn("unknown name: " + target);
        return null;
    }
}
项目:ddns    文件:TestDatagram.java   
public static void main(String[] args) throws Exception {
    try (DatagramSocket socket = new DatagramSocket()) {
        Message message = new Message();
        Header header = message.getHeader();
        header.setOpcode(Opcode.QUERY);
        header.setID(1);
        header.setRcode(Rcode.NOERROR);
        header.setFlag(Flags.RD);
        message.addRecord(Record.newRecord(new Name("www.xqbase.com."), Type.A, DClass.IN), Section.QUESTION);
        byte[] data = message.toWire();
        DatagramPacket packet = new DatagramPacket(data, data.length, new InetSocketAddress("localhost", 53));
        socket.send(packet);
        data = new byte[65536];
        packet = new DatagramPacket(data, data.length);
        socket.setSoTimeout(2000);
        socket.receive(packet);
        Message response = new Message(Bytes.left(data, packet.getLength()));
        System.out.println(response);
    }
}
项目:mireka    文件:MxLookup.java   
/**
 * Returns an ordered host name list based on the MX records of the domain.
 * The first has the highest priority. If the domain has no MX records, then
 * it returns the host itself. Records with the same priority are shuffled
 * randomly.
 * 
 * @see <a href="http://tools.ietf.org/html/rfc5321#section-5.1">RFC 5321
 *      Simple Mail Transfer Protocol - Locating the Target Host</a>
 */
public Name[] queryMxTargets(Domain domain) throws MxLookupException {
    MXRecord[] records = queryMxRecords(domain);
    if (records.length == 0) {
        logger.debug("Domain {} has no MX records, using an implicit "
                + "MX record targetting the host", domain);
        return implicitMxTargetForDomain(domain);
    } else {
        //
        ArrayList<MXRecord> list =
                new ArrayList<MXRecord>(Arrays.asList(records));
        Collections.shuffle(list);
        // This sort is guaranteed to be stable: equal elements will not be
        // reordered as a result of the sort, so shuffle remains in effect
        Collections.sort(list, mxRecordPriorityComparator);
        list.toArray(records);
        return convertMxRecordsToHostNames(records);
    }
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test
public void testSendToAddressLiteralVerifyNoDns() throws SendException,
        RecipientsWereRejectedException, PostponeException {

    sender.send(adaAddressLiteralMail);

    new Verifications() {
        {
            mxLookup.queryMxTargets((Domain)any);
            times = 0;

            addressLookup.queryAddresses((Name)any);
            times = 0;

            mailToHostTransmitter.transmit((Mail) any, null);

            client.setMtaAddress(new MtaAddress(ADDRESS_LITERAL, IP));
        }
    };
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test
public void testSendToDomain() throws SendException,
        RecipientsWereRejectedException, PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result = new Name[] { HOST1_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = new InetAddress[] { IP_ADDRESS_ONLY };

            client.setMtaAddress(new MtaAddress("host1.example.com", IP));

            mailToHostTransmitter.transmit((Mail) any, null);
        }
    };

    sender.send(mail);
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test
public void testSendFirstMxCannotBeResolved() throws SendException,
        RecipientsWereRejectedException, PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result =
                    new Name[] { HOST1_EXAMPLE_COM_NAME,
                            HOST2_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = permanentSendException;
            result = new InetAddress[] { IP2 };

            client.setMtaAddress(new MtaAddress("host2.example.com", IP2));

            mailToHostTransmitter.transmit((Mail) any, null);
        }
    };

    sender.send(mail);
}
项目:mireka    文件:DirectImmediateSenderTest.java   
private void twoMxDnsExpectation() throws SendException {
    new NonStrictExpectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result =
                    new Name[] { HOST1_EXAMPLE_COM_NAME,
                            HOST2_EXAMPLE_COM_NAME };
            times = 1;

            addressLookup.queryAddresses((Name)any);
            result = new InetAddress[] { IP1 };
            result = new InetAddress[] { IP2 };
            times = 2;
        }
    };
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test(expected = SendException.class)
public void testSendFirstHostHasPermanentProblem() throws SendException,
        RecipientsWereRejectedException, PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result =
                    new Name[] { HOST1_EXAMPLE_COM_NAME,
                            HOST2_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = new InetAddress[] { IP1 };

            mailToHostTransmitter.transmit((Mail) any, null);
            result = permanentSendException;
        }
    };

    sender.send(mail);
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test
public void testSendSingleHostPermanentlyCannotBeResolved()
        throws SendException, RecipientsWereRejectedException,
        PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result = new Name[] { HOST1_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = permanentSendException;
        }
    };

    try {
        sender.send(mail);
        fail("An exception must have been thrown");
    } catch (SendException e) {
        assertFalse(e.errorStatus().shouldRetry());
    }
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test
public void testSendSingleHostTemporarilyCannotBeResolved()
        throws SendException, RecipientsWereRejectedException,
        PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result = new Name[] { HOST1_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = transientSendException;
        }
    };

    try {
        sender.send(mail);
        fail("An exception must have been thrown");
    } catch (SendException e) {
        assertTrue(e.errorStatus().shouldRetry());
    }
}
项目:mireka    文件:DirectImmediateSenderTest.java   
@Test(expected = PostponeException.class)
public void testSendSingleHostPostponeException() throws SendException,
        RecipientsWereRejectedException, PostponeException {
    new Expectations() {
        {
            mxLookup.queryMxTargets((Domain)any);
            result = new Name[] { HOST1_EXAMPLE_COM_NAME };

            addressLookup.queryAddresses((Name)any);
            result = new InetAddress[] { IP1 };

            mailToHostTransmitter.transmit((Mail) any, null);
            result = POSTPONE_EXCEPTION;
        }
    };

    sender.send(mail);
}
项目:mireka    文件:MxLookupTest.java   
@Test()
public void testNoMxRecords() throws MxLookupException {
    new Expectations() {
        {
            lookup.run();
            result = null;

            lookup.getResult();
            result = Lookup.TYPE_NOT_FOUND;
        }

    };

    Name[] targets = mxLookup.queryMxTargets(EXAMPLE_COM_DOMAIN);
    assertArrayEquals(new Name[] { EXAMPLE_COM_NAME }, targets);
}
项目:mireka    文件:MxLookupTest.java   
@Test()
public void testSamePriorityReallyShuffled() throws MxLookupException {
    new Expectations() {
        {
            lookup.run();
            result =
                    new MXRecord[] { HOST1_PRIORITY10, HOST2_PRIORITY10,
                            HOST3_PRIORITY10, HOST4_PRIORITY10 };
        }

    };

    final int COUNT_OF_TEST_RUNS = 4;
    List<Name[]> listOfResults = new ArrayList<Name[]>();
    for (int i = 0; i < COUNT_OF_TEST_RUNS; i++) {
        listOfResults.add(mxLookup.queryMxTargets(EXAMPLE_COM_DOMAIN));
    }

    assertTrue(reallyShuffled(listOfResults));
}
项目:dnsjava-recursive-resolver    文件:RecursiveResolver.java   
private String[] findAddressesRecursive(Set<Name> stack, Name target) throws IOException {
    String[] ipv4Addresses = null;
    String[] ipv6Addresses = null;
    Message ipv4 = lookup(stack, getRoots(), Message.newQuery(Record.newRecord(target, Type.A, DClass.IN)));
    if (ipv4 != null)
        ipv4Addresses = findAddresses(target, ipv4.getSectionArray(Section.ANSWER));
    Message ipv6 = lookup(stack, getRoots(), Message.newQuery(Record.newRecord(target, Type.AAAA, DClass.IN)));
    if (ipv6 != null)
        ipv6Addresses = findAddresses(target, ipv6.getSectionArray(Section.ANSWER));

    String[] addresses = new String[0];
    if (ipv4Addresses != null)
        addresses = ipv4Addresses;
    if (ipv6Addresses != null) {
        String[] concatAddresses = new String[addresses.length + ipv6Addresses.length];
        System.arraycopy(addresses, 0, concatAddresses, 0, addresses.length);
        System.arraycopy(ipv6Addresses, 0, concatAddresses, addresses.length, ipv6Addresses.length);
        addresses = concatAddresses;
    }

    if (addresses.length == 0)
        return null;
    return addresses;
}
项目:dnsjava-recursive-resolver    文件:RecursiveResolver.java   
private String[] findAddresses(Name target, Record[] records) {
    ArrayList<String> addresses = new ArrayList<String>();
    for (Record record : records) {
        if (target == null || target.equals(record.getName())) {
            int recordType = record.getType();
            if (Type.A == recordType)
                addresses.add(((ARecord)record).getAddress().getHostAddress());
            else if (Type.AAAA == recordType)
                addresses.add(((AAAARecord)record).getAddress().getHostAddress());
        }
    }

    if (addresses.size() == 0)
        return null;
    return addresses.toArray(new String[addresses.size()]);
}
项目:opennmszh    文件:DnsProvisioningAdapter.java   
private void doUpdate(AdapterOperation op) {
    OnmsNode node = null;
    log().debug("doUpdate: operation: " + op.getType().name());
    try {
        node = m_nodeDao.get(op.getNodeId());
        DnsRecord record = new DnsRecord(node);
        log().debug("doUpdate: DnsRecord: hostname: " + record.getHostname() + " zone: " + record.getZone() + " ip address " + record.getIp().getHostAddress());
        DnsRecord oldRecord = m_nodeDnsRecordMap.get(Integer.valueOf(node.getId()));

        Update update = new Update(Name.fromString(record.getZone()));

        if (oldRecord != null && oldRecord.getHostname() != record.getHostname()) {
            update.delete(Name.fromString(oldRecord.getHostname()), Type.A);
        }
        update.replace(Name.fromString(record.getHostname()), Type.A, 3600, record.getIp().getHostAddress());
        m_resolver.send(update);

        m_nodeDnsRecordMap.put(Integer.valueOf(op.getNodeId()), record);
    } catch (Throwable e) {
        log().error("addNode: Error handling node added event.", e);
        sendAndThrow(op.getNodeId(), e);
    }
}
项目:opennmszh    文件:DnsProvisioningAdapter.java   
private void doDelete(AdapterOperation op) {
    try {
        DnsRecord record = m_nodeDnsRecordMap.get(Integer.valueOf(op.getNodeId()));

        if (record != null) {
            Update update = new Update(Name.fromString(record.getZone()));
            update.delete(Name.fromString(record.getHostname()), Type.A);
            m_resolver.send(update);

            m_nodeDnsRecordMap.remove(Integer.valueOf(op.getNodeId()));
        }
    } catch (Throwable e) {
        log().error("deleteNode: Error handling node deleted event.", e);
        sendAndThrow(op.getNodeId(), e);
    }
}
项目:opennmszh    文件:ReverseDnsProvisioningAdapter.java   
private void doUpdate(AdapterOperation op) {
    log().debug("doUpdate: operation: " + op.getType().name());
    for (ReverseDnsRecord record : m_reverseDnsProvisioningAdapterService.get(op.getNodeId()) ) {
        log().debug("doUpdate: ReverseDnsRecord: hostname: " + record.getHostname() + " zone: " + record.getZone() + " ip address: " + record.getIp().getHostAddress());
        try {
            Update update = new Update(Name.fromString(record.getZone()));
            Name ptrRecord=ReverseMap.fromAddress(record.getIp());
            update.replace(ptrRecord, Type.PTR, 3600, record.getHostname());
            m_resolver.send(update);
            m_reverseDnsProvisioningAdapterService.update(op.getNodeId(),record);
        } catch (Exception e) {
            log().error("updateNode: Error handling updated event.", e);
            sendAndThrow(op.getNodeId(), e);
        }
    }
}
项目:dnssecjava    文件:NSEC3ValUtils.java   
/**
 * Given a hash and a candidate NSEC3Record, determine if that NSEC3Record
 * covers the hash. Covers specifically means that the hash is in between
 * the owner and next hashes and does not equal either.
 * 
 * @param nsec3 The candidate NSEC3Record.
 * @param zonename The zone name.
 * @param hash The precalculated hash.
 * @return True if the NSEC3Record covers the hash.
 */
private boolean nsec3Covers(NSEC3Record nsec3, Name zonename, byte[] hash) {
    if (!new Name(nsec3.getName(), 1).equals(zonename)) {
        return false;
    }

    byte[] owner = new base32(base32.Alphabet.BASE32HEX, false, false).fromString(nsec3.getName().getLabelString(0));
    byte[] next = nsec3.getNext();

    // This is the "normal case: owner < next and owner < hash < next
    ByteArrayComparator bac = new ByteArrayComparator();
    if (bac.compare(owner, hash) < 0 && bac.compare(hash, next) < 0) {
        return true;
    }

    // this is the end of zone case:
    // next <= owner && (hash > owner || hash < next)
    if (bac.compare(next, owner) <= 0 && (bac.compare(hash, owner) > 0 || bac.compare(hash, next) < 0)) {
        return true;
    }

    // Otherwise, the NSEC3 does not cover the hash.
    return false;
}
项目:dnssecjava    文件:NSEC3ValUtils.java   
/**
 * Given a pre-hashed name, find a covering NSEC3 from among a list of
 * NSEC3s.
 * 
 * @param name The name to consider.
 * @param zonename The name of the zone.
 * @param nsec3s The list of NSEC3s present in a message.
 * @return A covering NSEC3 if one is present, null otherwise.
 */
private NSEC3Record findCoveringNSEC3(Name name, Name zonename, List<SRRset> nsec3s) {
    for (SRRset set : nsec3s) {
        try {
            NSEC3Record nsec3 = (NSEC3Record)set.first();
            byte[] hash = nsec3.hashName(name);
            if (this.nsec3Covers(nsec3, zonename, hash)) {
                return nsec3;
            }
        }
        catch (NoSuchAlgorithmException e) {
            logger.debug("Unrecognized NSEC3 in set:" + set, e);
        }
    }

    return null;
}
项目:dnssecjava    文件:ValidatingResolver.java   
private void processDNSKEYResponse(Message request, SMessage response, FindKeyState state) {
    Name qname = request.getQuestion().getName();
    int qclass = request.getQuestion().getDClass();

    SRRset dnskeyRrset = response.findAnswerRRset(qname, Type.DNSKEY, qclass);
    if (dnskeyRrset == null) {
        // If the DNSKEY rrset was missing, this is the end of the line.
        state.keyEntry = KeyEntry.newBadKeyEntry(qname, qclass, DEFAULT_TA_BAD_KEY_TTL);
        state.keyEntry.setBadReason(R.get("dnskey.no_rrset", qname));
        return;
    }

    state.keyEntry = this.valUtils.verifyNewDNSKEYs(dnskeyRrset, state.dsRRset, DEFAULT_TA_BAD_KEY_TTL);

    // If the key entry isBad or isNull, then we can move on to the next
    // state.
    if (!state.keyEntry.isGood()) {
        return;
    }

    // The DNSKEY validated, so cache it as a trusted key rrset.
    this.keyCache.store(state.keyEntry);

    // If good, we stay in the FINDKEY state.
    this.processFindKey(state);
}
项目:dnssecjava    文件:ValUtils.java   
/**
 * Determines whether the given {@link NSECRecord} proves that there is no
 * {@link DSRecord} for <code>qname</code>.
 * 
 * @param nsec The NSEC that should prove the non-existence.
 * @param qname The name for which the prove is made.
 * @return {@link SecurityStatus#BOGUS} when the NSEC is from the child
 *         domain or indicates that there indeed is a DS record,
 *         {@link SecurityStatus#INSECURE} when there is not even a prove
 *         for a NS record, {@link SecurityStatus#SECURE} when there is no
 *         DS record.
 */
public static SecurityStatus nsecProvesNoDS(NSECRecord nsec, Name qname) {
    // Could check to make sure the qname is a subdomain of nsec
    if ((nsec.hasType(Type.SOA) && !Name.root.equals(qname)) || nsec.hasType(Type.DS)) {
        // SOA present means that this is the NSEC from the child, not the
        // parent (so it is the wrong one) -> cannot happen because the
        // keyset is always from the parent zone and doesn't validate the
        // NSEC
        // DS present means that there should have been a positive response
        // to the DS query, so there is something wrong.
        return SecurityStatus.BOGUS;
    }

    if (!nsec.hasType(Type.NS)) {
        // If there is no NS at this point at all, then this doesn't prove
        // anything one way or the other.
        return SecurityStatus.INSECURE;
    }

    // Otherwise, this proves no DS.
    return SecurityStatus.SECURE;
}
项目:megatron-java    文件:IpAddressUtil.java   
private static String reverseDnsLookupUsingDnsJavaSimpleResolver(long ipAddress) throws IOException {
    String result = null;
    byte[] address = convertLongAddressToBuf(ipAddress);
    Name name = ReverseMap.fromAddress(InetAddress.getByAddress(address));
    Record record = Record.newRecord(name, Type.PTR, DClass.IN);
    Message query = Message.newQuery(record);
    Message response = simpleResolver.send(query);
    Record[] answers = response.getSectionArray(Section.ANSWER);
    if (answers.length != 0) {
        // If PTR-record exists this will be at index 1 or above (more than one PTR-record may exist)
        Record answer = (answers.length > 1) ? answers[1] : answers[0];  
        result = answer.rdataToString();
        // remove trailing "."
        result = result.endsWith(".") ? result.substring(0, result.length() - 1) : result;
    } else {
        throw new IOException("Empty DNS response.");
    }
    return result;
}
项目:OpenNMS    文件:DnsProvisioningAdapter.java   
private void doDelete(AdapterOperation op) {
    try {
        DnsRecord record = m_nodeDnsRecordMap.get(Integer.valueOf(op.getNodeId()));

        if (record != null) {
            Update update = new Update(Name.fromString(record.getZone()));
            update.delete(Name.fromString(record.getHostname()), Type.A);
            m_resolver.send(update);

            m_nodeDnsRecordMap.remove(Integer.valueOf(op.getNodeId()));
        }
    } catch (Throwable e) {
        log().error("deleteNode: Error handling node deleted event.", e);
        sendAndThrow(op.getNodeId(), e);
    }
}
项目:dnssecjava    文件:TestInvalid.java   
@Test
public void testUnsignedThatMustBeSigned() throws IOException {
    Name query = Name.fromString("www.ingotronic.ch.");

    // prepare a faked, unsigned response message that must have a signature
    // to be valid
    Message message = new Message();
    message.addRecord(Record.newRecord(query, Type.A, DClass.IN), Section.QUESTION);
    message.addRecord(new ARecord(query, Type.A, DClass.IN, InetAddress.getByName(localhost)), Section.ANSWER);
    add("www.ingotronic.ch./A", message);

    Message response = resolver.send(createMessage("www.ingotronic.ch./A"));
    assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD));
    assertEquals(Rcode.SERVFAIL, response.getRcode());
    assertEquals("validate.bogus.missingsig", getReason(response));
}
项目:dnssecjava    文件:TestInvalid.java   
@Test
public void testModifiedSignature() throws IOException {
    Name query = Name.fromString("www.ingotronic.ch.");

    // prepare a faked, unsigned response message that must have a signature
    // to be valid
    Message message = new Message();
    message.addRecord(Record.newRecord(query, Type.A, DClass.IN), Section.QUESTION);
    message.addRecord(new ARecord(query, Type.A, DClass.IN, InetAddress.getByName(localhost)), Section.ANSWER);
    message.addRecord(new RRSIGRecord(query, DClass.IN, 0, Type.A, Algorithm.RSASHA256, 5, new Date(System.currentTimeMillis() + 5000), new Date(System.currentTimeMillis() - 5000), 1234, Name.fromString("ingotronic.ch."), new byte[] { 1, 2, 3 }), Section.ANSWER);
    add("www.ingotronic.ch./A", message);

    Message response = resolver.send(createMessage("www.ingotronic.ch./A"));
    assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD));
    assertEquals(Rcode.SERVFAIL, response.getRcode());
    assertTrue(getReason(response).startsWith("failed.answer.positive:{ www.ingotronic.ch."));
}
项目:dnssecjava    文件:TestBase.java   
protected String getReason(Message m) {
    for (RRset set : m.getSectionRRsets(Section.ADDITIONAL)) {
        if (set.getName().equals(Name.root) && set.getType() == Type.TXT && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) {
            StringBuilder sb = new StringBuilder();
            @SuppressWarnings("unchecked")
            List<String> strings = (List<String>)((TXTRecord)set.first()).getStrings();
            for (String part : strings){
                sb.append(part);
            }

            return sb.toString();
        }
    }

    return null;
}
项目:James    文件:DNSJavaServiceTest.java   
protected void setUp() throws Exception {
    dnsServer = new TestableDNSServer();
    DefaultConfigurationBuilder db = new DefaultConfigurationBuilder();

    db.load(new ByteArrayInputStream("<dnsserver><autodiscover>true</autodiscover><authoritative>false</authoritative></dnsserver>".getBytes()));
    dnsServer.setLog(LoggerFactory.getLogger("MockLog"));
    dnsServer.configure(db);
    dnsServer.init();

    defaultCache = Lookup.getDefaultCache(DClass.IN);
    defaultResolver = Lookup.getDefaultResolver();
    defaultSearchPaths = Lookup.getDefaultSearchPath();
    Lookup.setDefaultCache(null, DClass.IN);
    Lookup.setDefaultResolver(null);
    Lookup.setDefaultSearchPath(new Name[] {});
}
项目:open-rmbt    文件:Helperfunctions.java   
public static Name getReverseIPName(final InetAddress adr, final Name postfix)
{
    final byte[] addr = adr.getAddress();
    final StringBuilder sb = new StringBuilder();
    if (addr.length == 4)
        for (int i = addr.length - 1; i >= 0; i--)
        {
            sb.append(addr[i] & 0xFF);
            if (i > 0)
                sb.append(".");
        }
    else
    {
        final int[] nibbles = new int[2];
        for (int i = addr.length - 1; i >= 0; i--)
        {
            nibbles[0] = (addr[i] & 0xFF) >> 4;
            nibbles[1] = addr[i] & 0xFF & 0xF;
            for (int j = nibbles.length - 1; j >= 0; j--)
            {
                sb.append(Integer.toHexString(nibbles[j]));
                if (i > 0 || j > 0)
                    sb.append(".");
            }
        }
    }
    try
    {
        return Name.fromString(sb.toString(), postfix);
    }
    catch (final TextParseException e)
    {
        throw new IllegalStateException("name cannot be invalid");
    }
}
项目:open-rmbt    文件:Helperfunctions.java   
public static Long getASN(final InetAddress adr)
{
    try
    {
        final Name postfix;
        if (adr instanceof Inet6Address)
            postfix = Name.fromConstantString("origin6.asn.cymru.com");
        else
            postfix = Name.fromConstantString("origin.asn.cymru.com");

        final Name name = getReverseIPName(adr, postfix);
        System.out.println("lookup: " + name);

        final Lookup lookup = new Lookup(name, Type.TXT);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return new Long(parts[0].split(" ")[0]);
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
项目:open-rmbt    文件:Helperfunctions.java   
public static String getASName(final long asn)
{
    try
    {
        final Name postfix = Name.fromConstantString("asn.cymru.com.");
        final Name name = new Name(String.format("AS%d", asn), postfix);
        System.out.println("lookup: " + name);

        final Lookup lookup = new Lookup(name, Type.TXT);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        System.out.println(strings);

                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return parts[4];
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
项目:open-rmbt    文件:Helperfunctions.java   
public static String getAScountry(final long asn)
{
    try
    {
        final Name postfix = Name.fromConstantString("asn.cymru.com.");
        final Name name = new Name(String.format("AS%d", asn), postfix);
        System.out.println("lookup: " + name);

        final Lookup lookup = new Lookup(name, Type.TXT);
        lookup.setResolver(new SimpleResolver());
        lookup.setCache(null);
        final Record[] records = lookup.run();
        if (lookup.getResult() == Lookup.SUCCESSFUL)
            for (final Record record : records)
                if (record instanceof TXTRecord)
                {
                    final TXTRecord txt = (TXTRecord) record;
                    @SuppressWarnings("unchecked")
                    final List<String> strings = txt.getStrings();
                    if (strings != null && !strings.isEmpty())
                    {
                        final String result = strings.get(0);
                        final String[] parts = result.split(" ?\\| ?");
                        if (parts != null && parts.length >= 1)
                            return parts[1];
                    }
                }
    }
    catch (final Exception e)
    {
    }
    return null;
}
项目:dnsjnio-demo    文件:Utils.java   
public static synchronized Message makeQuery(String nameString, int id) throws TextParseException {
    Name name = Name.fromString(nameString, Name.root);
    Record question = Record.newRecord(name, Type.A, DClass.ANY);
    Message query = Message.newQuery(question);
    query.getHeader().setID(id);
    return query;
}
项目:dns66    文件:DnsPacketProxyTest.java   
@Test
public void testDnsQuery() throws Exception {
    Message message = Message.newQuery(new ARecord(new Name("notblocked.example.com."),
            0x01,
            3600,
            Inet4Address.getByAddress(new byte[]{0, 0, 0, 0})
    ));

    UdpPacket.Builder payLoadBuilder = new UdpPacket.Builder()
            .srcPort(UdpPort.DOMAIN)
            .dstPort(UdpPort.DOMAIN)
            .srcAddr(InetAddress.getByAddress(new byte[]{8, 8, 4, 4}))
            .dstAddr(InetAddress.getByAddress(new byte[]{8, 8, 8, 8}))
            .correctChecksumAtBuild(true)
            .correctLengthAtBuild(true)
            .payloadBuilder(
                    new UnknownPacket.Builder()
                            .rawData(message.toWire())
            );

    IpPacket ipOutPacket = new IpV4Packet.Builder()
            .version(IpVersion.IPV4)
            .tos(IpV4Rfc791Tos.newInstance((byte) 0))
            .protocol(IpNumber.UDP)
            .srcAddr((Inet4Address) Inet4Address.getByAddress(new byte[]{8, 8, 4, 4}))
            .dstAddr((Inet4Address) Inet4Address.getByAddress(new byte[]{8, 8, 8, 8}))
            .correctChecksumAtBuild(true)
            .correctLengthAtBuild(true)
            .payloadBuilder(payLoadBuilder)
            .build();

    dnsPacketProxy.handleDnsRequest(ipOutPacket.getRawData());

    assertNull(mockEventLoop.lastResponse);
    assertNotNull(mockEventLoop.lastOutgoing);
    assertEquals(Inet4Address.getByAddress(new byte[]{8, 8, 8, 8}), mockEventLoop.lastOutgoing.getAddress());
}
项目:nomulus    文件:DnsUpdateWriter.java   
private Name toAbsoluteName(String name) {
  try {
    return Name.fromString(name, Name.root);
  } catch (TextParseException e) {
    throw new RuntimeException(
        String.format("toAbsoluteName failed for name: %s in zone: %s", name, zoneName), e);
  }
}