Java Code Examples for io.netty.handler.codec.dns.DnsRecord#type()

The following examples show how to use io.netty.handler.codec.dns.DnsRecord#type() . 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: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static Map<String, String> buildAliasMap(DnsResponse response) {
    final int answerCount = response.count(DnsSection.ANSWER);
    Map<String, String> cnames = null;
    for (int i = 0; i < answerCount; i ++) {
        final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
        final DnsRecordType type = r.type();
        if (type != DnsRecordType.CNAME) {
            continue;
        }

        if (!(r instanceof DnsRawRecord)) {
            continue;
        }

        final ByteBuf recordContent = ((ByteBufHolder) r).content();
        final String domainName = decodeDomainName(recordContent);
        if (domainName == null) {
            continue;
        }

        if (cnames == null) {
            cnames = new HashMap<String, String>(min(8, answerCount));
        }

        cnames.put(r.name().toLowerCase(Locale.US), domainName.toLowerCase(Locale.US));
    }

    return cnames != null? cnames : Collections.<String, String>emptyMap();
}
 
Example 2
Source File: DnsUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
public static byte[] extractAddressBytes(DnsRecord record, Logger logger, String logPrefix) {
    final DnsRecordType type = record.type();
    final ByteBuf content = ((ByteBufHolder) record).content();
    final int contentLen = content.readableBytes();

    // Skip invalid records.
    if (type == DnsRecordType.A) {
        if (contentLen != 4) {
            warnInvalidRecord(logger, logPrefix, type, content);
            return null;
        }
    } else if (type == DnsRecordType.AAAA) {
        if (contentLen != 16) {
            warnInvalidRecord(logger, logPrefix, type, content);
            return null;
        }
    } else {
        return null;
    }

    final byte[] addrBytes = new byte[contentLen];
    content.getBytes(content.readerIndex(), addrBytes);
    return addrBytes;
}
 
Example 3
Source File: RefreshingAddressResolverTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof DatagramDnsQuery) {
        final DatagramDnsQuery dnsQuery = (DatagramDnsQuery) msg;
        final DnsRecord dnsRecord = dnsQuery.recordAt(DnsSection.QUESTION, 0);
        if (dnsRecord.type() == delayType) {
            ctx.executor().schedule(() -> {
                try {
                    super.channelRead(ctx, msg);
                } catch (Exception ignore) {
                }
            }, 1, TimeUnit.SECONDS);
            return;
        }
    }
    super.channelRead(ctx, msg);
}
 
Example 4
Source File: RefreshingAddressResolverTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof DatagramDnsQuery) {
        final DatagramDnsQuery dnsQuery = (DatagramDnsQuery) msg;
        final DnsRecord dnsRecord = dnsQuery.recordAt(DnsSection.QUESTION, 0);
        if (dnsRecord.type() == A && recordACount++ == 0) {
            // Just release the msg and return so that the client request is timed out.
            ReferenceCountUtil.safeRelease(msg);
            return;
        }
    }
    super.channelRead(ctx, msg);
}
 
Example 5
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * Handles a redirect answer if needed and returns {@code true} if a redirect query has been made.
 */
private boolean handleRedirect(
        DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope,
        final DnsQueryLifecycleObserver queryLifecycleObserver, Promise<T> promise) {
    final DnsResponse res = envelope.content();

    // Check if we have answers, if not this may be an non authority NS and so redirects must be handled.
    if (res.count(DnsSection.ANSWER) == 0) {
        AuthoritativeNameServerList serverNames = extractAuthoritativeNameServers(question.name(), res);

        if (serverNames != null) {
            List<InetSocketAddress> nameServers = new ArrayList<InetSocketAddress>(serverNames.size());
            int additionalCount = res.count(DnsSection.ADDITIONAL);

            for (int i = 0; i < additionalCount; i++) {
                final DnsRecord r = res.recordAt(DnsSection.ADDITIONAL, i);

                if (r.type() == DnsRecordType.A && !parent.supportsARecords() ||
                    r.type() == DnsRecordType.AAAA && !parent.supportsAAAARecords()) {
                    continue;
                }

                final String recordName = r.name();
                AuthoritativeNameServer authoritativeNameServer =
                        serverNames.remove(recordName);

                if (authoritativeNameServer == null) {
                    // Not a server we are interested in.
                    continue;
                }

                InetAddress resolved = parseAddress(r, recordName);
                if (resolved == null) {
                    // Could not parse it, move to the next.
                    continue;
                }

                nameServers.add(new InetSocketAddress(resolved, parent.dnsRedirectPort(resolved)));
                addNameServerToCache(authoritativeNameServer, resolved, r.timeToLive());
            }

            if (!nameServers.isEmpty()) {
                query(parent.uncachedRedirectDnsServerStream(nameServers), 0, question,
                      queryLifecycleObserver.queryRedirected(unmodifiableList(nameServers)), promise, null);
                return true;
            }
        }
    }
    return false;
}
 
Example 6
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
void add(DnsRecord r) {
    if (r.type() != DnsRecordType.NS || !(r instanceof DnsRawRecord)) {
        return;
    }

    // Only include servers that serve the correct domain.
    if (questionName.length() <  r.name().length()) {
        return;
    }

    String recordName = r.name().toLowerCase(Locale.US);

    int dots = 0;
    for (int a = recordName.length() - 1, b = questionName.length() - 1; a >= 0; a--, b--) {
        char c = recordName.charAt(a);
        if (questionName.charAt(b) != c) {
            return;
        }
        if (c == '.') {
            dots++;
        }
    }

    if (head != null && head.dots > dots) {
        // We already have a closer match so ignore this one, no need to parse the domainName etc.
        return;
    }

    final ByteBuf recordContent = ((ByteBufHolder) r).content();
    final String domainName = decodeDomainName(recordContent);
    if (domainName == null) {
        // Could not be parsed, ignore.
        return;
    }

    // We are only interested in preserving the nameservers which are the closest to our qName, so ensure
    // we drop servers that have a smaller dots count.
    if (head == null || head.dots < dots) {
        count = 1;
        head = new AuthoritativeNameServer(dots, recordName, domainName);
    } else if (head.dots == dots) {
        AuthoritativeNameServer serverName = head;
        while (serverName.next != null) {
            serverName = serverName.next;
        }
        serverName.next = new AuthoritativeNameServer(dots, recordName, domainName);
        count++;
    }
}
 
Example 7
Source File: DnsTextEndpointGroup.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.TXT) {
            continue;
        }

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (!content.isReadable()) { // Missing length octet
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        content.markReaderIndex();
        final int txtLen = content.readUnsignedByte();
        if (txtLen == 0) { // Empty content
            continue;
        }

        if (content.readableBytes() != txtLen) { // Mismatching number of octets
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        final byte[] txt = new byte[txtLen];
        content.readBytes(txt);

        final Endpoint endpoint;
        try {
            endpoint = mapping.apply(txt);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.TXT, content);
            continue;
        }

        if (endpoint != null) {
            builder.add(endpoint);
        }
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})",
                       logPrefix(),
                       endpoints.stream().map(Object::toString).collect(Collectors.joining(", ")),
                       ttl);
    }

    return endpoints;
}
 
Example 8
Source File: DnsServiceEndpointGroup.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
ImmutableSortedSet<Endpoint> onDnsRecords(List<DnsRecord> records, int ttl) throws Exception {
    final ImmutableSortedSet.Builder<Endpoint> builder = ImmutableSortedSet.naturalOrder();
    for (DnsRecord r : records) {
        if (!(r instanceof DnsRawRecord) || r.type() != DnsRecordType.SRV) {
            continue;
        }

        final ByteBuf content = ((ByteBufHolder) r).content();
        if (content.readableBytes() <= 6) { // Too few bytes
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        content.markReaderIndex();
        content.skipBytes(2);  // priority unused
        final int weight = content.readUnsignedShort();
        final int port = content.readUnsignedShort();

        final Endpoint endpoint;
        try {
            final String target = stripTrailingDot(DefaultDnsRecordDecoder.decodeName(content));
            endpoint = port > 0 ? Endpoint.of(target, port) : Endpoint.of(target);
        } catch (Exception e) {
            content.resetReaderIndex();
            warnInvalidRecord(DnsRecordType.SRV, content);
            continue;
        }

        builder.add(endpoint.withWeight(weight));
    }

    final ImmutableSortedSet<Endpoint> endpoints = builder.build();
    if (logger().isDebugEnabled()) {
        logger().debug("{} Resolved: {} (TTL: {})",
                       logPrefix(),
                       endpoints.stream()
                                .map(e -> e.authority() + '/' + e.weight())
                                .collect(Collectors.joining(", ")),
                       ttl);
    }

    return endpoints;
}