io.netty.handler.codec.dns.DnsSection Java Examples

The following examples show how to use io.netty.handler.codec.dns.DnsSection. 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: 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 #3
Source File: DnsQueryContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
void finish(AddressedEnvelope<? extends DnsResponse, InetSocketAddress> envelope) {
    final DnsResponse res = envelope.content();
    if (res.count(DnsSection.QUESTION) != 1) {
        logger.warn("Received a DNS response with invalid number of questions: {}", envelope);
        return;
    }

    if (!question().equals(res.recordAt(DnsSection.QUESTION))) {
        logger.warn("Received a mismatching DNS response: {}", envelope);
        return;
    }

    setSuccess(envelope);
}
 
Example #4
Source File: DnsNameResolverContext.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@code {@link AuthoritativeNameServerList} which were included in {@link DnsSection#AUTHORITY}
 * or {@code null} if non are found.
 */
private static AuthoritativeNameServerList extractAuthoritativeNameServers(String questionName, DnsResponse res) {
    int authorityCount = res.count(DnsSection.AUTHORITY);
    if (authorityCount == 0) {
        return null;
    }

    AuthoritativeNameServerList serverNames = new AuthoritativeNameServerList(questionName);
    for (int i = 0; i < authorityCount; i++) {
        serverNames.add(res.recordAt(DnsSection.AUTHORITY, i));
    }
    return serverNames;
}
 
Example #5
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 #6
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 #7
Source File: TcpClientSession.java    From PacketLib with MIT License 4 votes vote down vote up
private void resolveAddress() {
    boolean debug = getFlag(BuiltinFlags.PRINT_DEBUG, false);

    String name = this.getPacketProtocol().getSRVRecordPrefix() + "._tcp." + this.getHost();
    if(debug) {
        System.out.println("[PacketLib] Attempting SRV lookup for \"" + name + "\".");
    }

    AddressedEnvelope<DnsResponse, InetSocketAddress> envelope = null;
    try(DnsNameResolver resolver = new DnsNameResolverBuilder(this.group.next())
            .channelType(NioDatagramChannel.class)
            .build()) {
        envelope = resolver.query(new DefaultDnsQuestion(name, DnsRecordType.SRV)).get();
        DnsResponse response = envelope.content();
        if(response.count(DnsSection.ANSWER) > 0) {
            DefaultDnsRawRecord record = response.recordAt(DnsSection.ANSWER, 0);
            if(record.type() == DnsRecordType.SRV) {
                ByteBuf buf = record.content();
                buf.skipBytes(4); // Skip priority and weight.

                int port = buf.readUnsignedShort();
                String host = DefaultDnsRecordDecoder.decodeName(buf);
                if(host.endsWith(".")) {
                    host = host.substring(0, host.length() - 1);
                }

                if(debug) {
                    System.out.println("[PacketLib] Found SRV record containing \"" + host + ":" + port + "\".");
                }

                this.host = host;
                this.port = port;
            } else if(debug) {
                System.out.println("[PacketLib] Received non-SRV record in response.");
            }
        } else if(debug) {
            System.out.println("[PacketLib] No SRV record found.");
        }
    } catch(Exception e) {
        if(debug) {
            System.out.println("[PacketLib] Failed to resolve SRV record.");
            e.printStackTrace();
        }
    } finally {
        if(envelope != null) {
            envelope.release();
        }
    }
}