@Override public List<ServiceCallServer> getUpdatedListOfServers(String name) { final Lookup lookup = lookupFactory.apply(name); final Record[] records = lookup.run(); List<ServiceCallServer> servers; if (Objects.nonNull(records) && lookup.getResult() == Lookup.SUCCESSFUL) { servers = Arrays.stream(records) .filter(SRVRecord.class::isInstance) .map(SRVRecord.class::cast) .sorted(DnsServiceCallServer.COMPARATOR) .map(DnsServiceCallServer::new) .collect(Collectors.toList()); } else { servers = Collections.emptyList(); } return servers; }
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; }
/** * reverse lookup an IP address using a specified DNS host and port * * @param resolverHost name server hostname or IP address * @param resolverPort name server port * @param address the IP address to reverse lookup * @return a comma separated list of names or an empty string when unable to resolve */ public String reverseLookupByAddress(String resolverHost, int resolverPort, InetAddress address) { try { SimpleResolver resolver = new SimpleResolver(resolverHost); resolver.setPort(resolverPort); Lookup lookup = new Lookup(fromAddress(address), PTR); Record[] records = lookup.run(); if (records != null) { List<String> addresses = of(records) .filter(it -> it instanceof PTRRecord) .map(it -> ((PTRRecord) it).getTarget().toString()) .collect(toList()); return collectionToCommaDelimitedString(addresses); } else { return ""; } } catch (UnknownHostException e) { log.warn("unable to resolve using SRV record " + address, e); return ""; } }
static void doAXFR(Message response) throws IOException { System.out.println("; java dig 0.0 <> " + name + " axfr"); if (response.isSigned()) { System.out.print(";; TSIG "); if (response.isVerified()) System.out.println("ok"); else System.out.println("failed"); } if (response.getRcode() != Rcode.NOERROR) { System.out.println(response); return; } Record [] records = response.getSectionArray(Section.ANSWER); for (int i = 0; i < records.length; i++) System.out.println(records[i]); System.out.print(";; done ("); System.out.print(response.getHeader().getCount(Section.ANSWER)); System.out.print(" records, "); System.out.print(response.getHeader().getCount(Section.ADDITIONAL)); System.out.println(" additional)"); }
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; }
/** * 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; }
/** * Attempts to resolve an SMTP server address, given the destination e-mail address. * * @param email The e-mail address used for the lookup. * @return An optional, potentially containing */ protected Optional<String> resolve(String email) { Optional<String> domainOptional = extractDomain(email); if (!domainOptional.isPresent()) { return Optional.empty(); } String mailDomain = domainOptional.get(); try { Lookup dnsLookup = new Lookup(mailDomain, Type.MX); List<Record> records = Arrays.asList(dnsLookup.run()); if (records.isEmpty()) { return Optional.empty(); } return chooseBestRecord(records); } catch (TextParseException e) { e.printStackTrace(); } return Optional.empty(); }
/** * Chooses the best SMTP server, given a list of MX records. * TODO: Actually choose the best record! * * @param records The MX records. * @return An optional, possibly containing an SMTP server address. */ private Optional<String> chooseBestRecord(List<Record> records) { TreeMultimap<Integer, String> recordMap = decodeRecords(records); if(!recordMap.isEmpty()) { List<String> topRecords = new LinkedList<>(recordMap.asMap().firstEntry().getValue()); if(!topRecords.isEmpty()) { String record = topRecords.get(0); return Optional.of(record.substring(0, record.length() - 1)); } } return Optional.empty(); }
/** * Decodes a list of MX records into a tree map, ranking them automatically. * * @param records The list of MX records. * @return The tree map containing ranked MX records. */ private TreeMultimap<Integer, String> decodeRecords(List<Record> records) { TreeMultimap<Integer, String> recordMap = TreeMultimap.create(Ordering.natural(), Ordering.natural()); records.forEach(record -> { String[] split = record.rdataToString().split(" "); if (split.length >= 2) { try { int rank = Integer.parseInt(split[0]); String domain = split[1]; recordMap.put(rank, domain); } catch (NumberFormatException ex) { ex.printStackTrace(); } } }); return recordMap; }
public static int getPortFromResponse(Message m) { for (int i = 0; i < 4; i++) { try { // Can do something with the counts field here, instead of // cycling through all of these Record[] records = m.getSectionArray(i); if (records != null) { for (int j = 0; j < records.length; j++) { if ((records[j]).getClass().equals(TXTRecord.class)) { return Integer.valueOf( ((String) (((TXTRecord) (records[j])) .getStrings().get(0)))).intValue(); } } } } catch (IndexOutOfBoundsException e) { // carry on! } } return -999; }
@Override public List<SRVRecord> lookupSRVRecords(String name) throws TextParseException { List<SRVRecord> res = new ArrayList<SRVRecord>(); Lookup lookup = new Lookup(name, Type.SRV); Record[] recs = lookup.run(); if (recs == null) return res; for (Record record : recs) { org.xbill.DNS.SRVRecord srvRecord = (org.xbill.DNS.SRVRecord) record; if (srvRecord != null && srvRecord.getTarget() != null) { String host = srvRecord.getTarget().toString(); int port = srvRecord.getPort(); int priority = srvRecord.getPriority(); int weight = srvRecord.getWeight(); SRVRecord r = new SRVRecord(host, port, priority, weight); res.add(r); } } return res; }
/** * @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]; } }
@Test @Ignore("Testing behind nat produces timeouts") public void testDNSWithNameHeaderAndType() throws Exception { resultEndpoint.expectedMessageCount(1); resultEndpoint.expectedMessagesMatches(new Predicate() { public boolean matches(Exchange exchange) { Record[] record = (Record[]) exchange.getIn().getBody(); return record[0].getName().toString().equals("www.example.com."); } }); Map<String, Object> headers = new HashMap<String, Object>(); headers.put("dns.name", "www.example.com"); headers.put("dns.type", "A"); template.sendBodyAndHeaders("hello", headers); resultEndpoint.assertIsSatisfied(); }
/** * 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 ""; } }
/** * resolves the TXT field for a given name using a specified DNS host and port. This is useful, for example, * if you want to resolve abusers with: <a href="https://abusix.com/contactdb.html">https://abusix.com/contactdb.html</a> * * @param resolverHost name server hostname or IP address * @param resolverPort name server port * @param name the DNS name of the TXT record - the name to resolve * @return the resolved text */ public String resolveTextByName(String resolverHost, int resolverPort, String name) { try { SimpleResolver resolver = new SimpleResolver(resolverHost); resolver.setPort(resolverPort); Lookup lookup = new Lookup(name, TXT); Record[] records = lookup.run(); if (records != null) { List<String> addresses = of(records) .filter(it -> it instanceof TXTRecord) .map(it -> collectionToCommaDelimitedString(((TXTRecord) it).getStrings())) .collect(toList()); return collectionToCommaDelimitedString(addresses); } else { return ""; } } catch (UnknownHostException | TextParseException e) { log.warn("unable to resolve using TXT record " + name, e); return ""; } }
private String resolveSrvByName(Resolver resolver, String name) { try { Lookup lookup = new Lookup(name, SRV); if (resolver != null) { lookup.setResolver(resolver); } Record[] records = lookup.run(); if (records == null) { return null; } return of(records) .filter(it -> it instanceof SRVRecord) .map(srv -> resolveHostByName(resolver, ((SRVRecord) srv).getTarget()) + ":" + ((SRVRecord) srv).getPort()) .distinct() .collect(joining(",")); } catch (TextParseException e) { log.warn("unable to resolve using SRV record " + name, e); return null; } }
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; } }
public List<DNSServiceRecord> getMultiSRV(String key) throws ConfigException { String qkey = fullyQualify(key); List<DNSServiceRecord> result = new ArrayList<DNSServiceRecord>(); List<Record> list = m_records.get(makeHostKey(qkey)); if (list == null) { throw new NotFoundException("No such record: " + makeHostKey(qkey)); } for (Record r : list) { if (r.getType() != Type.SRV) { continue; } result.add(new DNSServiceRecord(((SRVRecord) r).rdataToString())); } return result; }
private List<InetAddress> resolve(String key) throws UnknownHostException { List<InetAddress> result = new ArrayList<InetAddress>(); List<Record> list = m_records.get(key); if (list != null) for (Record r : list) if (r.getType() == Type.A) result.add(InetAddress.getByName(r.rdataToString())); else if ((r.getType() == Type.CNAME)) { List<Record> cnamelist = m_records.get(r.rdataToString()); for (Record r1 : cnamelist) { result.add(InetAddress.getByName(r1.rdataToString())); } } return result; }
@Override public List<LookupResult> resolve(final String fqdn) { Lookup lookup = lookupFactory.forName(fqdn); Record[] queryResult = lookup.run(); switch (lookup.getResult()) { case Lookup.SUCCESSFUL: return toLookupResults(queryResult); case Lookup.HOST_NOT_FOUND: // fallthrough case Lookup.TYPE_NOT_FOUND: LOG.warn("No results returned for query '{}'; result from XBill: {} - {}", fqdn, lookup.getResult(), lookup.getErrorString()); return ImmutableList.of(); default: throw new DnsException( String.format("Lookup of '%s' failed with code: %d - %s ", fqdn, lookup.getResult(), lookup.getErrorString())); } }
private static List<LookupResult> toLookupResults(Record[] queryResult) { ImmutableList.Builder<LookupResult> builder = ImmutableList.builder(); if (queryResult != null) { for (Record record: queryResult) { if (record instanceof SRVRecord) { SRVRecord srvRecord = (SRVRecord) record; builder.add(LookupResult.create(srvRecord.getTarget().toString(), srvRecord.getPort(), srvRecord.getPriority(), srvRecord.getWeight(), srvRecord.getTTL())); } } } return builder.build(); }
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; }
private static Record[] resolveWildcard(Map<String, Record[]> wildcards, String host, String[] domain) { String host_ = host; Record[] records = wildcards.get(host_); while (records == null) { int dot = host_.indexOf('.'); if (dot < 0) { break; } host_ = host_.substring(dot + 1); if (host_.isEmpty()) { break; } records = wildcards.get(host_); } if (records != null && domain[0] == null) { domain[0] = "*." + host_; } return records; }
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); } }
private String concatenateTxtRecordValues(Record[] records) { if (records == null || records.length == 0) return null; StringBuilder builder = new StringBuilder(); for (Record record : records) { TXTRecord txtRecord = (TXTRecord) record; if (builder.length() != 0) builder.append(EOL); for (Object string : txtRecord.getStrings()) { if (builder.length() != 0) builder.append(EOL); builder.append(string); } } return builder.toString(); }
@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); }
@Test public void testQueryAddressesIpv6() throws SendException { new Expectations() { { lookup.run(); result = new Record[] { new AAAARecord(HOST6_EXAMPLE_COM_NAME, 0, 0, IPV6) }; } }; InetAddress[] addresses = addressLookup.queryAddresses(HOST1_EXAMPLE_COM_NAME); InetAddress[] expected = new InetAddress[] { IPV6 }; assertArrayEquals(expected, addresses); }
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; }
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()]); }
private Message getCached(Message query) { Cache cache = getCache(); if (cache == null) return null; Record question = query.getQuestion(); RRset[] rrsets = cache.findAnyRecords(question.getName(), question.getType()); if (rrsets == null) return null; Message msg = new Message(); for (RRset rrset : rrsets) { @SuppressWarnings("unchecked") Iterator<Record> recordsIter = rrset.rrs(); while (recordsIter.hasNext()) { msg.addRecord(recordsIter.next(), Section.ANSWER); } } return msg; }
private String[] getRoots() { if (ROOTS != null) return ROOTS; try { Master master = new Master(ROOTS_FILE); Record record; ArrayList<Record> records = new ArrayList<Record>(); while ((record = master.nextRecord()) != null) records.add(record); ROOTS = findAddresses(null, records.toArray(new Record[records.size()])); return ROOTS; } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void testDnsJavaWithDnsServer() throws TextParseException, UnknownHostException { final Lookup l = new Lookup("example.com", Type.AAAA); final SimpleResolver resolver = new SimpleResolver("::1"); resolver.setPort(9153); l.setResolver(resolver); l.run(); System.out.println("result: " + l.getResult()); final Record[] answers = l.getAnswers(); assertEquals(answers.length, 1); final Record record = answers[0]; System.err.println(record.getTTL()); if(l.getResult() == Lookup.SUCCESSFUL) { System.out.println(l.getAnswers()[0].rdataToString()); } assertTrue(l.getResult() == Lookup.SUCCESSFUL); }
@Test @JUnitDNSServer(port=9153, zones={}) public void testNoAnswer() throws Exception { final Lookup l = new Lookup("example.com", Type.AAAA); final SimpleResolver resolver = new SimpleResolver("::1"); resolver.setPort(9153); l.setResolver(resolver); l.run(); System.out.println("result: " + l.getResult()); final Record[] answers = l.getAnswers(); assertNotNull(answers); assertEquals(answers.length, 1); final Record record = answers[0]; System.err.println(record.getTTL()); if(l.getResult() == Lookup.SUCCESSFUL) { System.out.println(l.getAnswers()[0].rdataToString()); } assertTrue(l.getResult() == Lookup.SUCCESSFUL); }
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; }
public static List<ForwardLookupResult> getAAAARecord(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.AAAA).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 = ((AAAARecord) record).getAddress().getHostAddress(); foundSubDomain.setIpAddress(ipAddress); foundSubDomain.setLookupType("A"); entries.add(foundSubDomain); } } } } return entries; }
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; }
public static String getDomainFromHost(String host) { String tmpHost = host; if (host.isEmpty()) { return ""; } while (true) { try { if (!tmpHost.startsWith("www.")) { Record[] recs = new Lookup(tmpHost, Type.SOA).run(); if (recs != null) { return tmpHost; } } if (tmpHost.contains(".")) { tmpHost = tmpHost.split("\\.", 2)[1]; } else { break; } } catch (TextParseException ex) { Logger.getLogger("networkTools.getDomainFromHost").log(Level.SEVERE, null, ex); break; } } return ""; }
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; }
@Test public void shouldBuildExpectedCommand() { String id = "id"; Long version = 1L; Set<Record> records = Sets.newHashSet(mock(Record.class), mock(Record.class)); ZoneUpdateResourceRecordsCommand command = new ZoneUpdateResourceRecordsCommand.Builder() .withId(id) .withVersion(version) .withResourceRecords(records) .build(); assertEquals(id, command.getId()); assertEquals(version, command.getVersion()); assertEquals(records, command.getRecords()); }