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

项目:xTun-android    文件:Utils.java   
public static String resolve(String host, int addrType) {
    try {
        Lookup lookup = new Lookup(host, addrType);
        SimpleResolver resolver = new SimpleResolver("114.114.114.114");
        resolver.setTimeout(5);
        lookup.setResolver(resolver);
        Record[] result = lookup.run();
        if (result == null) return null;

        List<Record> records = java.util.Arrays.asList(result);
        java.util.Collections.shuffle(records);
        for (Record record : records) {
            if (addrType == Type.A) {
                return ((ARecord) record).getAddress().getHostAddress();
            } else if (addrType == Type.AAAA) {
                return ((AAAARecord) record).getAddress().getHostAddress();
            }
        }

    } catch (Exception ex) {
        return null;
    }

    return null;
}
项目: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");
}
项目:plum    文件:DnsResolver.java   
/**
 * resolves an A record by its name using a specified DNS host and port
 *
 * @param resolverHost name server hostname or IP address
 * @param resolverPort name server port
 * @param name         the DNS name of the A record - the name to resolve
 * @return a comma separated list of IP addresses or an empty string when unable to resolve
 */
public String resolveHostByName(String resolverHost, int resolverPort, String name) {
    try {
        SimpleResolver resolver = new SimpleResolver(resolverHost);
        resolver.setPort(resolverPort);

        Lookup lookup = new Lookup(name, A);
        Record[] records = lookup.run();
        if (records != null) {
            List<String> addresses =
                    of(records)
                            .filter(it -> it instanceof ARecord)
                            .map(it -> ((ARecord) it).getAddress().getHostAddress())
                            .collect(toList());

            return collectionToCommaDelimitedString(addresses);
        } else {
            return "";
        }
    } catch (UnknownHostException | TextParseException e) {
        log.warn("unable to resolve using A record " + name, e);
        return "";
    }
}
项目: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    文件:DDNS.java   
private static HashMap<String, String> getDynamicMap() {
    HashMap<String, String> dynamicMap = new HashMap<>();
    aDynamics.forEach((host, records) -> {
        StringBuilder sb = new StringBuilder();
        for (Record record : records) {
            if (record instanceof ARecord) {
                sb.append(((ARecord) record).getAddress().getHostAddress());
            } else if (record instanceof CNAMERecord) {
                sb.append(((CNAMERecord) record).getTarget().
                        toString(true).toLowerCase());
            }
            sb.append(',');
        }
        dynamicMap.put(host, sb.substring(0, Math.max(sb.length() - 1, 0)));
    });
    return dynamicMap;
}
项目:mireka    文件:AddressLookupTest.java   
@Test
public void testQueryAddresses() throws SendException {
    new Expectations() {
        {
            lookup.run();
            result =
                    new Record[] {
                            new ARecord(HOST1_EXAMPLE_COM_NAME, 0, 0, IP1),
                            new ARecord(HOST1_EXAMPLE_COM_NAME, 0, 0, IP2)

                    };

        }
    };

    InetAddress[] addresses =
            addressLookup.queryAddresses(HOST1_EXAMPLE_COM_NAME);

    InetAddress[] expected = new InetAddress[] { IP1, IP2 };
    assertArrayEquals(expected, 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()]);
}
项目:yeti    文件:ForwardLookupHelper.java   
public static List<ForwardLookupResult> getARecord(String hostName, String domainName) throws TextParseException {
    List<ForwardLookupResult> entries = null;
    if (hostName != null && !hostName.isEmpty() && domainName != null && !domainName.isEmpty()) {
        Record[] recs = new Lookup(hostName, Type.A).run();
        if (recs != null) {
            if (recs.length > 0) {
                entries = new ArrayList<>();
                for (Record record : recs) {
                    ForwardLookupResult foundSubDomain = new ForwardLookupResult(domainName);
                    foundSubDomain.setHostName(hostName);
                    String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                    foundSubDomain.setIpAddress(ipAddress);
                    foundSubDomain.setLookupType("A");
                    entries.add(foundSubDomain);
                }
            }
        }
    }
    return entries;
}
项目:yeti    文件:DNS.java   
public static List<ARecordResult> getARecord(String hostName) throws TextParseException {
    List<ARecordResult> entries = null;

    Record[] recs = new Lookup(hostName, Type.A).run();
    if (recs != null) {
        if (recs.length > 0) {
            entries = new ArrayList<>();
            for (Record record : recs) {
                ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName));
                foundSubDomain.setHostName(hostName);
                String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                foundSubDomain.setIpAddress(ipAddress);
                foundSubDomain.setLookupType("A");
                entries.add(foundSubDomain);
            }
        }
    }

    return entries;
}
项目:yeti    文件:DataAPI.java   
public List<ARecordResult> getARecord(String hostName) throws TextParseException {
    List<ARecordResult> entries = null;

    Record[] recs = new Lookup(hostName, Type.A).run();
    if (recs != null) {
        if (recs.length > 0) {
            entries = new ArrayList<>();
            for (Record record : recs) {
                ARecordResult foundSubDomain = new ARecordResult(NetworkTools.getDomainFromHost(hostName));
                foundSubDomain.setHostName(hostName);
                String ipAddress = ((ARecord) record).getAddress().getHostAddress();
                foundSubDomain.setIpAddress(ipAddress);
                foundSubDomain.setLookupType("A");
                entries.add(foundSubDomain);
            }
        }
    }

    return entries;
}
项目: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."));
}
项目:James    文件:DNSJavaService.java   
/**
 * @see org.apache.james.dnsservice.api.DNSService#getByName(String)
 */
public InetAddress getByName(String host) throws UnknownHostException {
    String name = allowIPLiteral(host);

    try {
        // Check if its local
        if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) {
            return getLocalHost();
        }

        return org.xbill.DNS.Address.getByAddress(name);
    } catch (UnknownHostException e) {
        Record[] records = lookupNoException(name, Type.A, "A");

        if (records != null && records.length >= 1) {
            ARecord a = (ARecord) records[0];
            return InetAddress.getByAddress(name, a.getAddress().getAddress());
        } else
            throw e;
    }
}
项目:James    文件:DNSJavaService.java   
/**
 * @see org.apache.james.dnsservice.api.DNSService#getAllByName(String)
 */
public InetAddress[] getAllByName(String host) throws UnknownHostException {
    String name = allowIPLiteral(host);
    try {
        // Check if its local
        if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) {
            return new InetAddress[] { getLocalHost() };
        }

        InetAddress addr = org.xbill.DNS.Address.getByAddress(name);
        return new InetAddress[] { addr };
    } catch (UnknownHostException e) {
        Record[] records = lookupNoException(name, Type.A, "A");

        if (records != null && records.length >= 1) {
            InetAddress[] addrs = new InetAddress[records.length];
            for (int i = 0; i < records.length; i++) {
                ARecord a = (ARecord) records[i];
                addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress());
            }
            return addrs;
        } else
            throw e;
    }
}
项目: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());
}
项目:cloud-meter    文件:DNSCacheManager.java   
/**
 * Sends DNS request via system or custom DNS resolver
 */
private InetAddress[] requestLookup(String host) throws UnknownHostException {
    InetAddress[] addresses = null;
    if (isCustomResolver() && ((ExtendedResolver) resolver).getResolvers().length > 0) {
        try {
            Lookup lookup = new Lookup(host, Type.A);
            lookup.setCache(lookupCache);
            if (timeoutMs > 0) {
                resolver.setTimeout(timeoutMs / 1000, timeoutMs % 1000);
            }
            lookup.setResolver(resolver);
            Record[] records = lookup.run();
            if (records == null || records.length == 0) {
                throw new UnknownHostException("Failed to resolve host name: " + host);
            }
            addresses = new InetAddress[records.length];
            for (int i = 0; i < records.length; i++) {
                addresses[i] = ((ARecord) records[i]).getAddress();
            }
        } catch (TextParseException tpe) {
            log.debug("Failed to create Lookup object: " + tpe);
        }
    } else {
        addresses = systemDefaultDnsResolver.resolve(host);
        if (log.isDebugEnabled()) {
            log.debug("Cache miss: " + host + " Thread #" + JMeterContextService.getContext().getThreadNum()
                    + ", resolved with system resolver into " + Arrays.toString(addresses));
        }
    }
    return addresses;
}
项目:nomulus    文件:DnsUpdateWriter.java   
private RRset makeAddressSet(HostResource host) {
  RRset addressSet = new RRset();
  for (InetAddress address : host.getInetAddresses()) {
    if (address instanceof Inet4Address) {
      ARecord record =
          new ARecord(
              toAbsoluteName(host.getFullyQualifiedHostName()),
              DClass.IN,
              dnsDefaultATtl.getStandardSeconds(),
              address);
      addressSet.addRR(record);
    }
  }
  return addressSet;
}
项目:ddns    文件:DDNS.java   
private static void updateRecords(Map<String, Record[]> records,
        String host, String value, int ttl) throws IOException {
    if (value == null) {
        records.remove(host);
        return;
    }
    Name origin = new Name((host.endsWith(".") ? host : host + ".").replace('_', '-'));
    ArrayList<Record> recordList = new ArrayList<>();
    for (String s : value.split("[,;]")) {
        if (s.matches(".*[A-Z|a-z].*")) {
            CNAMERecord record = new CNAMERecord(origin, DClass.IN, ttl,
                    new Name(s.endsWith(".") ? s : s + "."));
            recordList.add(record);
            continue;
        }
        String[] ss = s.split("\\.");
        if (ss.length < 4) {
            continue;
        }
        byte[] ip = new byte[4];
        for (int i = 0; i < 4; i ++) {
            ip[i] = (byte) Numbers.parseInt(ss[i]);
        }
        recordList.add(new ARecord(origin, DClass.IN,
                ttl, InetAddress.getByAddress(ip)));
    }
    records.put(host, recordList.toArray(EMPTY_RECORDS));
}
项目:mireka    文件:AddressLookup.java   
private InetAddress[] convertAddressRecordsToAddresses(Record[] records) {
    InetAddress[] addresses = new InetAddress[records.length];
    for (int i = 0; i < records.length; i++) {
        Record record = records[i];
        if (record instanceof ARecord) {
            addresses[i] = ((ARecord) record).getAddress();
        } else if (record instanceof AAAARecord) {
            addresses[i] = ((AAAARecord) record).getAddress();
        } else {
            throw new RuntimeException();
        }
    }
    return addresses;
}
项目:onomate    文件:CreateAddressResourceRecordTests.java   
@Test
public void canResolveRecord() throws Exception {
    AcceptanceTestRunner runner = new AcceptanceTestRunner();
    runner.runUngarded(new AcceptanceScenario() {

        public void run(WebDriver driver, String deployedURL) throws Exception {
            int id = new SecureRandom().nextInt();
            final String systemTestBase = "system-tests.onomate.test";
            final String soaBase = "soa-" + id +"."+ systemTestBase;
            final String ns = "ns." + soaBase;
            final String contactName = "admin." + soaBase;
            final String aTestRecordHost = "a-test-record."+soaBase;
            final String aTestRecordAddress = "127.0.0.100";

            OnomateAssembly assembly = new OnomateAssembly(driver, deployedURL);
            OnomateAssembly.Dashboard board = assembly.gotoLanding().authenticate().newAuthority(soaBase, ns, contactName);
            board.authorityByZone(soaBase).details().createRecord(aTestRecordHost, RecordType.A, aTestRecordAddress);

            Lookup lookup = new Lookup(aTestRecordHost, Type.A);
            SimpleResolver resolver = new SimpleResolver();
            resolver.setAddress(InetAddress.getLocalHost());
            resolver.setPort(9101);
            lookup.setResolver(resolver);
            lookup.setCache(null);
            Record[] results = lookup.run();
            assertEquals(lookup.getResult(), Lookup.SUCCESSFUL, "Resolution to be completed succesfully");
            assertNotNull(results);
            assertEquals(results.length, 1);
            ARecord record = ((ARecord) results[0]);
            assertEquals(record.getName().toString(), aTestRecordHost+ ".");
            assertEquals(record.getAddress().getHostAddress(), aTestRecordAddress);
        }
    });
}
项目:yeti    文件:ForwardLookupHelper.java   
public static List<ForwardLookupResult> attemptZoneTransfer(String domain, List<ForwardLookupResult> nameServers) throws TextParseException {
    List<ForwardLookupResult> result = new ArrayList<>();

    ZoneTransferIn xfr;
    Iterator i = nameServers.iterator();
    for (ForwardLookupResult nameServer : nameServers) {
        try {
            xfr = ZoneTransferIn.newAXFR(new Name(domain), nameServer.getIpAddress(), null);
            List records = xfr.run();
            for (Iterator it = records.iterator(); it.hasNext();) {
                Record r = (Record) it.next();
                if (r.getType() == 1) {
                    ForwardLookupResult rec = new ForwardLookupResult(domain);
                    String hostName = ((ARecord) r).getName().toString().toLowerCase();

                    if (hostName.endsWith(".")) {
                        hostName = hostName.substring(0, hostName.length() - 1);
                    }

                    rec.setHostName(hostName);
                    rec.setIpAddress(((ARecord) r).getAddress().getHostAddress());
                    rec.setLookupType("A");
                    result.add(rec);
                }
            }
        } catch (IOException ioex) {
            Logger.getLogger("ForwardLookupHelper.attemptZoneTransfer").log(Level.WARNING, null, ioex);
        } catch (ZoneTransferException zex) {
            Log.debug("ForwardLookupHelper.attemptZoneTransfer: Failed zonetransfer");
        }
    }
    return result;
}
项目:yeti    文件:NetworkTools.java   
public static List<String> getIpFromHost(String hostname) throws TextParseException {
    List<String> result = new ArrayList<>();
    Record[] recs = new Lookup(hostname, Type.A).run();
    if (recs != null) {
        if (recs.length > 0) {
            for (Record rec : recs) {
                String ipAddress = ((ARecord) rec).getAddress().toString();
                result.add(ipAddress.replace("/", ""));
            }
        }
    }
    return result;
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testGetSectionByType() throws UnknownHostException {
    Message m = new Message();
    Record r1 = new ARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0}));
    m.addRecord(r1, Section.ANSWER);
    Record r2 = new AAAARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}));
    m.addRecord(r2, Section.ANSWER);
    SMessage sm = new SMessage(m);
    SRRset[] result = sm.getSectionRRsets(Section.ANSWER, Type.A);
    assertEquals(1, result.length);
    assertEquals(Type.A, result[0].getType());
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testRecordCountForIsValid() throws UnknownHostException {
    Message m = new Message();
    m.addRecord(new ARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0})), Section.ANSWER);
    SMessage sm = new SMessage(m);
    int count = sm.getCount(Section.ANSWER);
    assertEquals(1, count);
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testAnswerSectionSearchFound() throws UnknownHostException {
    Message m = new Message();
    Record r = new ARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0}));
    m.addRecord(r, Section.ANSWER);
    SMessage sm = new SMessage(m);
    SRRset result = sm.findAnswerRRset(Name.root, Type.A, DClass.IN);
    assertEquals(r, result.first());
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testAnswerSectionSearchNotFoundDifferentClass() throws UnknownHostException {
    Message m = new Message();
    Record r = new ARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0}));
    m.addRecord(r, Section.ANSWER);
    SMessage sm = new SMessage(m);
    SRRset result = sm.findAnswerRRset(Name.root, Type.A, DClass.CH);
    assertNull(result);
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testAnswerSectionSearchNotFoundDifferentType() throws UnknownHostException {
    Message m = new Message();
    Record r = new ARecord(Name.root, DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0}));
    m.addRecord(r, Section.ANSWER);
    SMessage sm = new SMessage(m);
    SRRset result = sm.findAnswerRRset(Name.root, Type.MX, DClass.IN);
    assertNull(result);
}
项目:dnssecjava    文件:TestSMessage.java   
@Test()
public void testAnswerSectionSearchNotFoundDifferentName() throws UnknownHostException, TextParseException {
    Message m = new Message();
    Record r = new ARecord(Name.fromString("asdf."), DClass.IN, 0, InetAddress.getByAddress(new byte[]{0,0,0,0}));
    m.addRecord(r, Section.ANSWER);
    SMessage sm = new SMessage(m);
    SRRset result = sm.findAnswerRRset(Name.root, Type.MX, DClass.IN);
    assertNull(result);
}
项目:dnssecjava    文件:TestWildcard.java   
@Test
public void testDsNodataFromWildcardNsecChild() throws IOException {
    Message m = Message.newQuery(Record.newRecord(Name.fromString("www.x.c.ingotronic.ch."), Type.A, DClass.IN));
    m.addRecord(new ARecord(Name.fromString("www.x.c.ingotronic.ch."), DClass.IN, 300, InetAddress.getLocalHost()), Section.ANSWER);
    add("www.x.c.ingotronic.ch./A", m);

    Message response = resolver.send(createMessage("www.x.c.ingotronic.ch./A"));
    assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD));
    assertEquals(Rcode.SERVFAIL, response.getRcode());
}
项目:dnssecjava    文件:TestWildcard.java   
@Test
public void testDsNodataFromWildcardNsecCovered() throws IOException {
    Message m = Message.newQuery(Record.newRecord(Name.fromString("www.x.ce.ingotronic.ch."), Type.A, DClass.IN));
    m.addRecord(new ARecord(Name.fromString("www.x.ce.ingotronic.ch."), DClass.IN, 300, InetAddress.getLocalHost()), Section.ANSWER);
    add("www.x.ce.ingotronic.ch./A", m);

    Message response = resolver.send(createMessage("www.x.ce.ingotronic.ch./A"));
    assertFalse("AD flag must not be set", response.getHeader().getFlag(Flags.AD));
    assertEquals(Rcode.SERVFAIL, response.getRcode());
}
项目:dnssecjava    文件:TestNormallyUnreachableCode.java   
@Test
public void testVerifyWithoutSignaturesIsBogus() {
    DnsSecVerifier verifier = new DnsSecVerifier();
    ARecord record = new ARecord(Name.root, DClass.IN, 120, localhost);
    RRset set = new RRset(record);
    RRset keys = new RRset();
    SecurityStatus result = verifier.verify(set, keys);
    assertEquals(SecurityStatus.BOGUS, result);
}
项目:dnssecjava    文件:TestNormallyUnreachableCode.java   
@Test
public void testCopyMessageWithoutQuestion() {
    Message m = new Message();
    m.addRecord(new ARecord(Name.root, DClass.IN, 120, localhost), Section.ANSWER);
    SMessage sm = new SMessage(m);
    assertEquals(m.toString(), sm.getMessage().toString());
}
项目:dnssecjava    文件:TestBase.java   
@SuppressWarnings("unchecked")
protected String firstA(Message response) {
    RRset[] sectionRRsets = response.getSectionRRsets(Section.ANSWER);
    if (sectionRRsets.length > 0) {
        Iterator<Record> rrs = sectionRRsets[0].rrs();
        while (rrs.hasNext()) {
            Record r = rrs.next();
            if (r.getType() == Type.A) {
                return ((ARecord)r).getAddress().getHostAddress();
            }
        }
    }

    return null;
}
项目:whiskers    文件:DNS.java   
@Override
protected boolean matchesSafely(Record record) {
    if(record==null || !(record instanceof ARecord))
        return false;

    ARecord arec = (ARecord)record;
    return arec.getAddress().equals(address);
}
项目:Virtual-Hosts    文件:DnsChange.java   
public static ByteBuffer handle_dns_packet(Packet packet) {
    if (DOMAINS_IP_MAPS == null) {
        Log.d(TAG, "DOMAINS_IP_MAPS IS NULL HOST FILE ERROR");
        return null;
    }
    try {
        ByteBuffer packet_buffer=packet.backingBuffer;
        packet_buffer.mark();
        byte[] tmp_bytes = new byte[packet_buffer.remaining()];
        packet_buffer.get(tmp_bytes);
        packet_buffer.reset();
        Message message = new Message(tmp_bytes);
        Name query_domain = message.getQuestion().getName();
        String query_string = query_domain.toString();
        Log.d(TAG, "query: " + query_domain);
        if (!DOMAINS_IP_MAPS.containsKey(query_string)) {
            query_string="."+query_string;
            int j=0;
            while (true){
                int i=query_string.indexOf(".",j);
                if (i==-1){
                    return null;
                }
                String str=query_string.substring(i);
                if("".equals(str)){
                    return null;
                }
                if(DOMAINS_IP_MAPS.containsKey(str)){
                    query_string=str;
                    break;
                }
                j=i+1;
            }
        }
        InetAddress address = Address.getByAddress(DOMAINS_IP_MAPS.get(query_string));
        ARecord a_record = new ARecord(query_domain, 1, 86400, address);
        message.addRecord(a_record, 1);
        message.getHeader().setFlag(Flags.QR);
        packet_buffer.limit(packet_buffer.capacity());
        packet_buffer.put(message.toWire());
        packet_buffer.limit(packet_buffer.position());
        packet_buffer.reset();
        packet.swapSourceAndDestination();
        packet.updateUDPBuffer(packet_buffer, packet_buffer.remaining());
        packet_buffer.position(packet_buffer.limit());
        Log.d(TAG, "hit: " + query_domain.toString() + " " + address.getHostName());
        return packet_buffer;
    } catch (Exception e) {
        Log.d(TAG, "dns hook error", e);
        return null;
    }

}
项目:dns66    文件:DnsPacketProxyTest.java   
@Test
public void testBlockedDnsQuery() throws Exception {
    Message message = Message.newQuery(new ARecord(new Name("blocked.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());

    assertNotNull(mockEventLoop.lastResponse);
    assertNull(mockEventLoop.lastOutgoing);
    assertTrue(mockEventLoop.lastResponse instanceof IpPacket);
    assertTrue(mockEventLoop.lastResponse.getPayload() instanceof UdpPacket);

    Message responseMsg = new Message(mockEventLoop.lastResponse.getPayload().getPayload().getRawData());
    assertEquals(NOERROR, responseMsg.getHeader().getRcode());
    assertArrayEquals(new Record[] {}, responseMsg.getSectionArray(Section.ANSWER));
    assertNotEquals(0, responseMsg.getSectionArray(Section.AUTHORITY).length);
    assertTrue(responseMsg.getSectionArray(Section.AUTHORITY)[0] instanceof SOARecord);
    assertTrue(responseMsg.getSectionArray(Section.AUTHORITY)[0].getTTL() > 0);
}
项目:dns66    文件:DnsPacketProxyTest.java   
@Test
public void testBlockedInet6DnsQuery() throws Exception {
    Message message = Message.newQuery(new ARecord(new Name("blocked.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((Inet6Address) Inet6Address.getByName("::0"))
            .dstAddr((Inet6Address) Inet6Address.getByName("::1"))
            .correctChecksumAtBuild(true)
            .correctLengthAtBuild(true)
            .payloadBuilder(
                    new UnknownPacket.Builder()
                            .rawData(message.toWire())
            );

    IpPacket ipOutPacket = new IpV6Packet.Builder()
            .version(IpVersion.IPV6)
            .trafficClass(IpV6SimpleTrafficClass.newInstance((byte) 0))
            .flowLabel(IpV6SimpleFlowLabel.newInstance(0))
            .nextHeader(IpNumber.UDP)
            .srcAddr((Inet6Address) Inet6Address.getByName("::0"))
            .dstAddr((Inet6Address) Inet6Address.getByName("::1"))
            .correctLengthAtBuild(true)
            .payloadBuilder(payLoadBuilder)
            .build();

    dnsPacketProxy.handleDnsRequest(ipOutPacket.getRawData());

    assertNotNull(mockEventLoop.lastResponse);
    assertNull(mockEventLoop.lastOutgoing);
    assertTrue(mockEventLoop.lastResponse instanceof IpPacket);
    assertTrue(mockEventLoop.lastResponse.getPayload() instanceof UdpPacket);

    Message responseMsg = new Message(mockEventLoop.lastResponse.getPayload().getPayload().getRawData());
    assertEquals(NOERROR, responseMsg.getHeader().getRcode());
    assertArrayEquals(new Record[] {}, responseMsg.getSectionArray(Section.ANSWER));
    assertNotEquals(0, responseMsg.getSectionArray(Section.AUTHORITY).length);
    assertTrue(responseMsg.getSectionArray(Section.AUTHORITY)[0] instanceof SOARecord);
    assertTrue(responseMsg.getSectionArray(Section.AUTHORITY)[0].getTTL() > 0);
}
项目:acme4j    文件:DnsServer.java   
/**
 * Processes a DNS query.
 *
 * @param sock
 *            Socket to listen to
 */
private void process(DatagramSocket sock) {
    try {
        byte[] in = new byte[UDP_SIZE];

        // Read the question
        DatagramPacket indp = new DatagramPacket(in, UDP_SIZE);
        indp.setLength(UDP_SIZE);
        sock.receive(indp);
        Message msg = new Message(in);
        Header header = msg.getHeader();

        Record question = msg.getQuestion();

        // Prepare a response
        Message response = new Message(header.getID());
        response.getHeader().setFlag(Flags.QR);
        response.addRecord(question, Section.QUESTION);

        Name name = question.getName();
        boolean hasRecords = false;

        String txt = txtRecords.get(name.toString(true));
        if (question.getType() == Type.TXT && txt != null) {
            response.addRecord(new TXTRecord(name, DClass.IN, TTL, txt), Section.ANSWER);
            hasRecords = true;
            LOG.info("dns-01: {} {} IN TXT \"{}\"", name, TTL, txt);
        }

        InetAddress a = aRecords.get(name.toString(true));
        if (question.getType() == Type.A && a != null) {
            response.addRecord(new ARecord(name, DClass.IN, TTL, a), Section.ANSWER);
            hasRecords = true;
            LOG.info("dns-01: {} {} IN A {}", name, TTL, a.getHostAddress());
        }

        if (!hasRecords) {
            response.getHeader().setRcode(Rcode.NXDOMAIN);
            LOG.warn("dns-01: Cannot answer: {}", question);
        }

        // Send the response
        byte[] resp = response.toWire();
        DatagramPacket outdp = new DatagramPacket(resp, resp.length, indp.getAddress(), indp.getPort());
        sock.send(outdp);
    } catch (Exception ex) {
        LOG.error("Failed to process query", ex);
    }
}
项目:opennmszh    文件:DnsRequisitionUrlConnection.java   
/**
 * Creates an instance of the JaxB annotated RequisionNode class.
 * 
 * @param rec
 * @return a populated RequisitionNode based on defaults and data from the
 *   A record returned from a DNS zone transfer query.
 */
private RequisitionNode createRequisitionNode(Record rec) {
    String addr = null;
    if ("A".equals(Type.string(rec.getType()))) {
        ARecord arec = (ARecord)rec;
        addr = StringUtils.stripStart(arec.getAddress().toString(), "/");
    } else if ("AAAA".equals(Type.string(rec.getType()))) {
        AAAARecord aaaarec = (AAAARecord)rec;
        addr = aaaarec.rdataToString();
    } else {
        throw new IllegalArgumentException("Invalid record type " + Type.string(rec.getType()) + ". A or AAAA expected.");
    }

    RequisitionNode n = new RequisitionNode();

    String host = rec.getName().toString();
    String nodeLabel = StringUtils.stripEnd(StringUtils.stripStart(host, "."), ".");

    n.setBuilding(getForeignSource());

    switch(m_foreignIdHashSource) {
        case 1:
            n.setForeignId(computeHashCode(nodeLabel));
            log().debug("Generating foreignId from hash of nodelabel " + nodeLabel);
            break;
        case 2:
            n.setForeignId(computeHashCode(addr));
            log().debug("Generating foreignId from hash of ipAddress " + addr);
            break;
        case 3:
            n.setForeignId(computeHashCode(nodeLabel+addr));
            log().debug("Generating foreignId from hash of nodelabel+ipAddress " + nodeLabel + addr);
            break;
        default:
            n.setForeignId(computeHashCode(nodeLabel));
            log().debug("Default case: Generating foreignId from hash of nodelabel " + nodeLabel);
            break;
    }
    n.setNodeLabel(nodeLabel);

    RequisitionInterface i = new RequisitionInterface();
    i.setDescr("DNS-" + Type.string(rec.getType()));
    i.setIpAddr(addr);
    i.setSnmpPrimary(PrimaryType.PRIMARY);
    i.setManaged(Boolean.TRUE);
    i.setStatus(Integer.valueOf(1));

    for (String service : m_services) {
        service = service.trim();
        i.insertMonitoredService(new RequisitionMonitoredService(service));
        log().debug("Adding provisioned service " + service);
        }

    n.putInterface(i);

    return n;
}
项目:opennmszh    文件:JUnitDNSServerExecutionListener.java   
/** {@inheritDoc} */
@Override
public void beforeTestMethod(final TestContext testContext) throws Exception {
    super.beforeTestMethod(testContext);

    final JUnitDNSServer config = findTestAnnotation(JUnitDNSServer.class, testContext);

    if (config == null) {
        return;
    }

    LogUtils.infof(this, "initializing DNS on port %d", config.port());

    m_server = new DNSServer();
    m_server.addPort(config.port());

    for (final DNSZone dnsZone : config.zones()) {
        String name = dnsZone.name();
        if (!name.endsWith(".")) {
            name = name + ".";
        }
        final Name zoneName = Name.fromString(name, Name.root);
        LogUtils.debugf(this, "zoneName = %s", zoneName);
        final Zone zone = new Zone(zoneName, new Record[] {
                new SOARecord(zoneName, DClass.IN, DEFAULT_TTL, zoneName, Name.fromString("admin." + name), 1, DEFAULT_TTL, DEFAULT_TTL, DEFAULT_TTL, DEFAULT_TTL),
                new NSRecord(zoneName, DClass.IN, DEFAULT_TTL, Name.fromString("resolver1.opendns.com.")),
                new NSRecord(zoneName, DClass.IN, DEFAULT_TTL, Name.fromString("resolver2.opendns.com.")),
                new ARecord(zoneName, DClass.IN, DEFAULT_TTL, InetAddressUtils.addr(dnsZone.v4address())),
                new AAAARecord(zoneName, DClass.IN, DEFAULT_TTL, InetAddressUtils.addr(dnsZone.v6address()))
        });
        LogUtils.debugf(this, "zone = %s", zone);

        for (final DNSEntry entry : dnsZone.entries()) {
            LogUtils.debugf(this, "adding entry: %s", entry);
            String hostname = entry.hostname();
            final Name recordName = Name.fromString(hostname, zoneName);
            LogUtils.debugf(this, "name = %s", recordName);
            if (entry.ipv6()) {
                zone.addRecord(new AAAARecord(recordName, DClass.IN, DEFAULT_TTL, InetAddressUtils.addr(entry.address())));
            } else {
                zone.addRecord(new ARecord(recordName, DClass.IN, DEFAULT_TTL, InetAddressUtils.addr(entry.address())));
            }
        }

        m_server.addZone(zone);
    }

    LogUtils.debugf(this, "starting DNS server");
    m_server.start();
    try {
        Thread.sleep(50);
    } catch (final InterruptedException e) {
        LogUtils.debugf(this, e, "interrupted while waiting for server to come up");
        Thread.currentThread().interrupt();
    }
}