org.xbill.DNS.Name Java Examples

The following examples show how to use org.xbill.DNS.Name. 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: DNSJavaServiceTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void testMXCatches() throws Exception {
    doAnswer(new ZoneCacheLookupRecordsAnswer(loadZone("test-zone.com.")))
            .when(mockedCache).lookupRecords(any(Name.class), anyInt(), anyInt());
    dnsServer.setCache(mockedCache);

    // dnsServer.setLookupper(new ZoneLookupper(z));
    Collection<String> res = dnsServer.findMXRecords("test-zone.com.");
    try {
        res.add("");
        fail("MX Collection should not be modifiable");
    } catch (UnsupportedOperationException e) {
        LOGGER.info("Ignored error", e);
    }
    assertThat(res.size()).isEqualTo(1);
    assertThat(res.iterator().next()).isEqualTo("mail.test-zone.com.");
}
 
Example #4
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 #5
Source File: DNSJavaService.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public String getHostName(InetAddress addr) {
    TimeMetric timeMetric = metricFactory.timer("getHostName");
    String result;
    Name name = ReverseMap.fromAddress(addr);
    Record[] records = lookupNoException(name.toString(), Type.PTR, "PTR");

    try {
        if (records == null) {
            result = addr.getHostAddress();
        } else {
            PTRRecord ptr = (PTRRecord) records[0];
            result = ptr.getTarget().toString();
        }
        return result;
    } finally {
        timeMetric.stopAndPublish();
    }
}
 
Example #6
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 #7
Source File: SimpleDoTResolver.java    From androdns with Apache License 2.0 6 votes vote down vote up
private Message
sendAXFR(Message query) throws IOException {
    Name qname = query.getQuestion().getName();
    ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(qname, address, tsig);
    xfrin.setTimeout((int)(getTimeout() / 1000));
    xfrin.setLocalAddress(localAddress);
    try {
        xfrin.run();
    }
    catch (ZoneTransferException e) {
        throw new WireParseException(e.getMessage());
    }
    List records = xfrin.getAXFR();
    Message response = new Message(query.getHeader().getID());
    response.getHeader().setFlag(Flags.AA);
    response.getHeader().setFlag(Flags.QR);
    response.addRecord(query.getQuestion(), Section.QUESTION);
    Iterator it = records.iterator();
    while (it.hasNext())
        response.addRecord((Record)it.next(), Section.ANSWER);
    return response;
}
 
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: Output.java    From helios with Apache License 2.0 6 votes vote down vote up
public static String shortHostname(final String host) {
  final Name root = Name.fromConstantString(".");
  final Name hostname;
  try {
    hostname = Name.fromString(host, root);
  } catch (TextParseException e) {
    throw new IllegalArgumentException("Invalid hostname '" + host + "'");
  }

  final ResolverConfig currentConfig = ResolverConfig.getCurrentConfig();
  if (currentConfig != null) {
    final Name[] searchPath = currentConfig.searchPath();
    if (searchPath != null) {
      for (final Name domain : searchPath) {
        if (hostname.subdomain(domain)) {
          return hostname.relativize(domain).toString();
        }
      }
    }
  }
  return hostname.toString();
}
 
Example #10
Source File: HostResolverTest.java    From helios with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
  final HostResolver resolver = new HostResolver(ALL_HOSTS, new Name[]{});
  // fully spec'd that's in allHosts
  assertEquals("host1.bar.com", resolver.resolveName("host1.bar.com"));

  // fully spec'd not in allHosts
  assertEquals("whee.bar.com", resolver.resolveName("whee.bar.com"));

  // can disambiguate on unique prefix
  assertEquals("host1.bar.com", resolver.resolveName("host1.bar"));

  // can disambiguate on unique prefix
  assertEquals("host1.bar.com", resolver.resolveName("host1.b"));

  // falls through when can't disambiguate (here, w/o search paths)
  assertEquals("host1", resolver.resolveName("host1"));
}
 
Example #11
Source File: MxLookup.java    From mireka with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #12
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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));
        }
    };
}
 
Example #13
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
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;
        }
    };
}
 
Example #15
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #17
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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());
    }
}
 
Example #18
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: MxLookupTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #20
Source File: MxLookupTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #21
Source File: lookup.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void printAnswer(String name, Lookup lookup) {
  System.out.print(name + ":");
  int result = lookup.getResult();
  if (result != Lookup.SUCCESSFUL) {
    System.out.print(" " + lookup.getErrorString());
  }
  System.out.println();
  Name[] aliases = lookup.getAliases();
  if (aliases.length > 0) {
    System.out.print("# aliases: ");
    for (int i = 0; i < aliases.length; i++) {
      System.out.print(aliases[i]);
      if (i < aliases.length - 1) {
        System.out.print(" ");
      }
    }
    System.out.println();
  }
  if (lookup.getResult() == Lookup.SUCCESSFUL) {
    Record[] answers = lookup.getAnswers();
    for (Record answer : answers) {
      System.out.println(answer);
    }
  }
}
 
Example #22
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 #23
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 #24
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Zone findBestZone(Name name) {
  Zone foundzone;
  foundzone = znames.get(name);
  if (foundzone != null) {
    return foundzone;
  }
  int labels = name.labels();
  for (int i = 1; i < labels; i++) {
    Name tname = new Name(name, i);
    foundzone = znames.get(tname);
    if (foundzone != null) {
      return foundzone;
    }
  }
  return null;
}
 
Example #25
Source File: jnamed.java    From dnsjava with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public <T extends Record> RRset findExactMatch(Name name, int type, int dclass, boolean glue) {
  Zone zone = findBestZone(name);
  if (zone != null) {
    return zone.findExactMatch(name, type);
  } else {
    List<RRset> rrsets;
    Cache cache = getCache(dclass);
    if (glue) {
      rrsets = cache.findAnyRecords(name, type);
    } else {
      rrsets = cache.findRecords(name, type);
    }
    if (rrsets == null) {
      return null;
    } else {
      return rrsets.get(0); /* not quite right */
    }
  }
}
 
Example #26
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #27
Source File: DirectImmediateSenderTest.java    From mireka with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #28
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 #29
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 #30
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
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);
  }
}