org.xbill.DNS.DClass Java Examples

The following examples show how to use org.xbill.DNS.DClass. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IpAddressUtil.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: DNSLookupService.java    From openvisualtraceroute with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #3
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private RRset makeDelegationSignerSet(DomainBase domain) {
  RRset signerSet = new RRset();
  for (DelegationSignerData signerData : domain.getDsData()) {
    DSRecord dsRecord =
        new DSRecord(
            toAbsoluteName(domain.getDomainName()),
            DClass.IN,
            dnsDefaultDsTtl.getStandardSeconds(),
            signerData.getKeyTag(),
            signerData.getAlgorithm(),
            signerData.getDigestType(),
            signerData.getDigest());
    signerSet.addRR(dsRecord);
  }
  return signerSet;
}
 
Example #4
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
void doProhibit(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    if ((type = Type.value(token.value)) < 0) {
      throw new IOException("Invalid type: " + token.value);
    }
  } else {
    type = Type.ANY;
  }
  record = Record.newRecord(name, type, DClass.NONE, 0);
  query.addRecord(record, Section.PREREQ);
  print(record);
}
 
Example #5
Source File: DnsMessageTransportTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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 =
      assertThrows(IllegalArgumentException.class, () -> resolver.send(oversize));
  assertThat(thrown).hasMessageThat().contains("message larger than maximum");
}
 
Example #6
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
Record parseRR(Tokenizer st, int classValue, long TTLValue) throws IOException {
  Name name = st.getName(zone);
  long ttl;
  int type;

  String s = st.getString();

  try {
    ttl = TTL.parseTTL(s);
    s = st.getString();
  } catch (NumberFormatException e) {
    ttl = TTLValue;
  }

  if (DClass.value(s) >= 0) {
    classValue = DClass.value(s);
    s = st.getString();
  }

  if ((type = Type.value(s)) < 0) {
    throw new IOException("Invalid type: " + s);
  }

  return Record.fromString(name, type, classValue, ttl, st, zone);
}
 
Example #7
Source File: DNSJavaServiceTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    dnsServer = new TestableDNSServer();

    dnsServer.configure(FileConfigurationProvider.getConfig(new ByteArrayInputStream(DNS_SERVER_CONFIG)));
    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[]{});

    dnsServer.setResolver(null);
    mockedCache = mock(Cache.class);
}
 
Example #8
Source File: XBillDnsSrvResolverTest.java    From dns-java with Apache License 2.0 6 votes vote down vote up
private Message messageWithNodes(String query, String[] names) throws TextParseException {
  Name queryName = Name.fromString(query);
  Record question = Record.newRecord(queryName, Type.SRV, DClass.IN);
  Message queryMessage = Message.newQuery(question);
  Message result = new Message();
  result.setHeader(queryMessage.getHeader());
  result.addRecord(question, Section.QUESTION);

  for (String name1 : names) {
    result.addRecord(
        new SRVRecord(queryName, DClass.IN, 1, 1, 1, 8080, Name.fromString(name1)),
        Section.ANSWER);
  }

  return result;
}
 
Example #9
Source File: DNSJavaServiceTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown() throws Exception {
    dnsServer.setCache(null);
    dnsServer = null;
    Lookup.setDefaultCache(defaultCache, DClass.IN);
    Lookup.setDefaultResolver(defaultResolver);
    Lookup.setDefaultSearchPath(defaultSearchPaths);
}
 
Example #10
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void addGlue(Message response, Name name, int flags) {
  RRset a = findExactMatch(name, Type.A, DClass.IN, true);
  if (a == null) {
    return;
  }
  addRRset(name, response, a, Section.ADDITIONAL, flags);
}
 
Example #11
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void doDelete(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  String s;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    s = token.value;
    if (DClass.value(s) >= 0) {
      s = st.getString();
    }
    if ((type = Type.value(s)) < 0) {
      throw new IOException("Invalid type: " + s);
    }
    token = st.get();
    boolean iseol = token.isEOL();
    st.unget();
    if (!iseol) {
      record = Record.fromString(name, type, DClass.NONE, 0, st, zone);
    } else {
      record = Record.newRecord(name, type, DClass.ANY, 0);
    }
  } else {
    record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
  }

  query.addRecord(record, Section.UPDATE);
  print(record);
}
 
Example #12
Source File: update.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
void doRequire(Tokenizer st) throws IOException {
  Tokenizer.Token token;
  Name name;
  Record record;
  int type;

  name = st.getName(zone);
  token = st.get();
  if (token.isString()) {
    if ((type = Type.value(token.value)) < 0) {
      throw new IOException("Invalid type: " + token.value);
    }
    token = st.get();
    boolean iseol = token.isEOL();
    st.unget();
    if (!iseol) {
      record = Record.fromString(name, type, defaultClass, 0, st, zone);
    } else {
      record = Record.newRecord(name, type, DClass.ANY, 0);
    }
  } else {
    record = Record.newRecord(name, Type.ANY, DClass.ANY, 0);
  }

  query.addRecord(record, Section.PREREQ);
  print(record);
}
 
Example #13
Source File: XBillDnsSrvResolverTest.java    From dns-java with Apache License 2.0 5 votes vote down vote up
private Message messageWithRCode(String query, int rcode) throws TextParseException {
  Name queryName = Name.fromString(query);
  Record question = Record.newRecord(queryName, Type.SRV, DClass.IN);
  Message queryMessage = Message.newQuery(question);
  Message result = new Message();
  result.setHeader(queryMessage.getHeader());
  result.addRecord(question, Section.QUESTION);

  result.getHeader().setRcode(rcode);

  return result;
}
 
Example #14
Source File: SimpleLookupFactory.java    From dns-java with Apache License 2.0 5 votes vote down vote up
@Override
public Lookup forName(String fqdn) {
  try {
    final Lookup lookup = new Lookup(fqdn, Type.SRV, DClass.IN);
    if (resolver != null) {
      lookup.setResolver(resolver);
    }
    return lookup;
  } catch (TextParseException e) {
    throw new DnsException("unable to create lookup for name: " + fqdn, e);
  }
}
 
Example #15
Source File: RemoteHttpService.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected URIBuilder buildURI() throws TextParseException {
    final String host = serviceHost();
    final int port = servicePort();
    URIBuilder builder = new URIBuilder();
    builder.setScheme(serviceScheme());
    if (useSrvDns()) {
        List<LookupResult> results = dnsSrvResolver.resolve(host);
        if (results != null && !results.isEmpty()) {
            LookupResult result = results.get(0);
            builder.setHost(result.host());
            builder.setPort(result.port());
            // Consul sends the hostname back in its own namespace. Although the A record is included in the
            // "ADDITIONAL SECTION", Spotify SRV lookup doesn't translate, so we need to do the lookup manually.
            if (result.host().endsWith(".consul.")) {
                Record[] newResults = new Lookup(result.host(), Type.A, DClass.IN).run();
                if (newResults != null && newResults.length > 0) {
                    builder.setHost(newResults[0].rdataToString());
                } else {
                    throw new IllegalArgumentException("Unable to resolve service host " + host + " -> " + result.host() + " -> ???");
                }
            }
        } else {
            throw new IllegalArgumentException("Unable to resolve service host: " + host);
        }
    } else {
        builder.setHost(host);
        builder.setPort(port);
    }
    return builder;
}
 
Example #16
Source File: DnsMessageTransportTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
  simpleQuery =
      Message.newQuery(Record.newRecord(Name.fromString("example.com."), Type.A, DClass.IN));
  expectedResponse = responseMessageWithCode(simpleQuery, Rcode.NOERROR);
  when(mockFactory.createSocket(InetAddress.getByName(UPDATE_HOST), DnsMessageTransport.DNS_PORT))
      .thenReturn(mockSocket);
  resolver = new DnsMessageTransport(mockFactory, UPDATE_HOST, Duration.ZERO);
}
 
Example #17
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private RRset makeV6AddressSet(HostResource host) {
  RRset addressSet = new RRset();
  for (InetAddress address : host.getInetAddresses()) {
    if (address instanceof Inet6Address) {
      AAAARecord record =
          new AAAARecord(
              toAbsoluteName(host.getHostName()),
              DClass.IN,
              dnsDefaultATtl.getStandardSeconds(),
              address);
      addressSet.addRR(record);
    }
  }
  return addressSet;
}
 
Example #18
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private RRset makeAddressSet(HostResource host) {
  RRset addressSet = new RRset();
  for (InetAddress address : host.getInetAddresses()) {
    if (address instanceof Inet4Address) {
      ARecord record =
          new ARecord(
              toAbsoluteName(host.getHostName()),
              DClass.IN,
              dnsDefaultATtl.getStandardSeconds(),
              address);
      addressSet.addRR(record);
    }
  }
  return addressSet;
}
 
Example #19
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private RRset makeNameServerSet(DomainBase domain) {
  RRset nameServerSet = new RRset();
  for (String hostName : domain.loadNameserverHostNames()) {
    NSRecord record =
        new NSRecord(
            toAbsoluteName(domain.getDomainName()),
            DClass.IN,
            dnsDefaultNsTtl.getStandardSeconds(),
            toAbsoluteName(hostName));
    nameServerSet.addRR(record);
  }
  return nameServerSet;
}
 
Example #20
Source File: OpenAliasHelper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(String... args) {
    //main();
    if (args.length != 1) return false;
    String name = args[0];
    if ((name == null) || (name.isEmpty()))
        return false; //pointless trying to lookup nothing
    Timber.d("Resolving %s", name);
    try {
        SimpleResolver sr = new SimpleResolver(DNSSEC_SERVERS[new Random().nextInt(DNSSEC_SERVERS.length)]);
        ValidatingResolver vr = new ValidatingResolver(sr);
        vr.setTimeout(0, DNS_LOOKUP_TIMEOUT);
        vr.loadTrustAnchors(new ByteArrayInputStream(ROOT.getBytes("ASCII")));
        Record qr = Record.newRecord(Name.fromConstantString(name + "."), Type.TXT, DClass.IN);
        Message response = vr.send(Message.newQuery(qr));
        final int rcode = response.getRcode();
        if (rcode != Rcode.NOERROR) {
            Timber.i("Rcode: %s", Rcode.string(rcode));
            for (RRset set : response.getSectionRRsets(Section.ADDITIONAL)) {
                if (set.getName().equals(Name.root) && set.getType() == Type.TXT
                        && set.getDClass() == ValidatingResolver.VALIDATION_REASON_QCLASS) {
                    Timber.i("Reason:  %s", ((TXTRecord) set.first()).getStrings().get(0));
                }
            }
            return false;
        } else {
            dnssec = response.getHeader().getFlag(Flags.AD);
            for (Record record : response.getSectionArray(Section.ANSWER)) {
                if (record.getType() == Type.TXT) {
                    txts.addAll(((TXTRecord) record).getStrings());
                }
            }
        }
    } catch (IOException | IllegalArgumentException ex) {
        return false;
    }
    return true;
}
 
Example #21
Source File: DNSJavaService.java    From james-project with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void init() throws Exception {
    LOGGER.debug("DNSService init...");

    // If no DNS servers were configured, default to local host
    if (dnsServers.isEmpty()) {
        try {
            dnsServers.add(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException ue) {
            dnsServers.add("127.0.0.1");
        }
    }

    // Create the extended resolver...
    final String[] serversArray = dnsServers.toArray(String[]::new);

    if (LOGGER.isInfoEnabled()) {
        for (String aServersArray : serversArray) {
            LOGGER.info("DNS Server is: " + aServersArray);
        }
    }

    try {
        resolver = new ExtendedResolver(serversArray);
    } catch (UnknownHostException uhe) {
        LOGGER.error("DNS service could not be initialized.  The DNS servers specified are not recognized hosts.", uhe);
        throw uhe;
    }

    cache = new Cache(DClass.IN);
    cache.setMaxEntries(maxCacheSize);
    cache.setMaxNCache(negativeCacheTTL);

    if (setAsDNSJavaDefault) {
        Lookup.setDefaultResolver(resolver);
        Lookup.setDefaultCache(cache, DClass.IN);
        Lookup.setDefaultSearchPath(searchPaths);
        LOGGER.info("Registered cache, resolver and search paths as DNSJava defaults");
    }

    // Cache the local hostname and local address. This is needed because
    // the following issues:
    // JAMES-787
    // JAMES-302
    InetAddress addr = getLocalHost();
    localCanonicalHostName = addr.getCanonicalHostName();
    localHostName = addr.getHostName();
    localAddress = addr.getHostAddress();

    LOGGER.debug("DNSService ...init end");
}
 
Example #22
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void addSecondaryZone(String zone, String remote)
    throws IOException, ZoneTransferException {
  Name zname = Name.fromString(zone, Name.root);
  Zone newzone = new Zone(zname, DClass.IN, remote);
  znames.put(zname, newzone);
}