Example usage for io.netty.handler.codec.dns DnsSection ANSWER

List of usage examples for io.netty.handler.codec.dns DnsSection ANSWER

Introduction

In this page you can find the example usage for io.netty.handler.codec.dns DnsSection ANSWER.

Prototype

DnsSection ANSWER

To view the source code for io.netty.handler.codec.dns DnsSection ANSWER.

Click Source Link

Document

The section that contains the answer DnsRecord s.

Usage

From source file:chat.viska.xmpp.Connection.java

License:Apache License

private static Single<List<DnsRecord>> lookupDnsUsingNetty(final String query, final DnsRecordType type,
        @Nullable final Iterable<String> dns) {
    final NioEventLoopGroup threadPool = new NioEventLoopGroup();
    final DnsNameResolverBuilder builder = new DnsNameResolverBuilder(threadPool.next());
    builder.channelFactory(new ReflectiveChannelFactory<>(NioDatagramChannel.class));
    builder.decodeIdn(true);//from  www  .  j av a2 s. com
    if (dns != null) {
        builder.searchDomains(dns);
    }
    return Single.fromFuture(builder.build().query(new DefaultDnsQuestion(query, type)))
            .map(AddressedEnvelope::content).map(message -> {
                final int recordsSize = message.count(DnsSection.ANSWER);
                final List<DnsRecord> records = new ArrayList<>(recordsSize);
                for (int it = 0; it < recordsSize; ++it) {
                    records.add(message.recordAt(DnsSection.ANSWER, it));
                }
                return records;
            }).doFinally(threadPool::shutdownGracefully);
}

From source file:io.vertx.core.dns.impl.DnsClientImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
private <T> void lookup(String name, Future<List<T>> result, DnsRecordType... types) {
    Objects.requireNonNull(name, "no null name accepted");
    bootstrap.connect(dnsServer).addListener(new RetryChannelFutureListener(result) {
        @Override//w  ww. j  a  va  2  s  . c om
        public void onSuccess(ChannelFuture future) throws Exception {
            DatagramDnsQuery query = new DatagramDnsQuery(null, dnsServer,
                    ThreadLocalRandom.current().nextInt());
            for (DnsRecordType type : types) {
                query.addRecord(DnsSection.QUESTION, new DefaultDnsQuestion(name, type, DnsRecord.CLASS_IN));
            }
            future.channel().writeAndFlush(query).addListener(new RetryChannelFutureListener(result) {
                @Override
                public void onSuccess(ChannelFuture future) throws Exception {
                    future.channel().pipeline().addLast(new SimpleChannelInboundHandler<DnsResponse>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, DnsResponse msg)
                                throws Exception {
                            DnsResponseCode code = DnsResponseCode.valueOf(msg.code().intValue());

                            if (code == DnsResponseCode.NOERROR) {

                                int count = msg.count(DnsSection.ANSWER);

                                List<T> records = new ArrayList<>(count);
                                for (int idx = 0; idx < count; idx++) {
                                    DnsRecord a = msg.recordAt(DnsSection.ANSWER, idx);
                                    T record = RecordDecoder.decode(a);
                                    if (isRequestedType(a.type(), types)) {
                                        records.add(record);
                                    }
                                }

                                if (records.size() > 0 && (records.get(0) instanceof MxRecordImpl
                                        || records.get(0) instanceof SrvRecordImpl)) {
                                    Collections.sort((List) records);
                                }

                                setResult(result, records);
                            } else {
                                setFailure(result, new DnsException(code));
                            }
                            ctx.close();
                        }

                        private boolean isRequestedType(DnsRecordType dnsRecordType, DnsRecordType[] types) {
                            for (DnsRecordType t : types) {
                                if (t.equals(dnsRecordType)) {
                                    return true;
                                }
                            }
                            return false;
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            setFailure(result, cause);
                            ctx.close();
                        }
                    });
                }
            });
        }
    });
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

void onResponse(final DnsQuestion question, AddressedEnvelope<DnsResponse, InetSocketAddress> envelope) {
    try {/*w w  w.  jav  a2 s. c  o  m*/
        final DnsResponse res = envelope.content();
        final DnsResponseCode code = res.code();
        if (code == DnsResponseCode.NOERROR) {
            final DnsRecordType type = question.type();
            if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
                onResponseAorAAAA(type, question, envelope);
            } else if (type == DnsRecordType.CNAME) {
                onResponseCNAME(question, envelope);
            }
            return;
        }

        if (traceEnabled) {
            addTrace(envelope.sender(), "response code: " + code + " with " + res.count(DnsSection.ANSWER)
                    + " answer(s) and " + res.count(DnsSection.AUTHORITY) + " authority resource(s)");
        }

        // Retry with the next server if the server did not tell us that the domain does not exist.
        if (code != DnsResponseCode.NXDOMAIN) {
            query(nameServerAddrs.next(), question);
        }
    } finally {
        ReferenceCountUtil.safeRelease(envelope);
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

private void onResponseAorAAAA(DnsRecordType qType, DnsQuestion question,
        AddressedEnvelope<DnsResponse, InetSocketAddress> envelope) {

    // We often get a bunch of CNAMES as well when we asked for A/AAAA.
    final DnsResponse response = envelope.content();
    final Map<String, String> cnames = buildAliasMap(response);
    final int answerCount = response.count(DnsSection.ANSWER);

    boolean found = false;
    for (int i = 0; i < answerCount; i++) {
        final DnsRecord r = response.recordAt(DnsSection.ANSWER, i);
        final DnsRecordType type = r.type();
        if (type != DnsRecordType.A && type != DnsRecordType.AAAA) {
            continue;
        }//from  w w w.j  av  a  2  s  .c om

        final String qName = question.name().toLowerCase(Locale.US);
        final String rName = r.name().toLowerCase(Locale.US);

        // Make sure the record is for the questioned domain.
        if (!rName.equals(qName)) {
            // Even if the record's name is not exactly same, it might be an alias defined in the CNAME records.
            String resolved = qName;
            do {
                resolved = cnames.get(resolved);
                if (rName.equals(resolved)) {
                    break;
                }
            } while (resolved != null);

            if (resolved == null) {
                continue;
            }
        }

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

        final ByteBuf content = ((ByteBufHolder) r).content();
        final int contentLen = content.readableBytes();
        if (contentLen != INADDRSZ4 && contentLen != INADDRSZ6) {
            continue;
        }

        final byte[] addrBytes = new byte[contentLen];
        content.getBytes(content.readerIndex(), addrBytes);

        final InetAddress resolved;
        try {
            resolved = InetAddress.getByAddress(hostname, addrBytes);
        } catch (UnknownHostException e) {
            // Should never reach here.
            throw new Error(e);
        }

        if (resolvedEntries == null) {
            resolvedEntries = new ArrayList<DnsCacheEntry>(8);
        }

        final DnsCacheEntry e = new DnsCacheEntry(hostname, resolved);
        resolveCache.cache(hostname, resolved, r.timeToLive(), parent.ch.eventLoop());
        resolvedEntries.add(e);
        found = true;

        // Note that we do not break from the loop here, so we decode/cache all A/AAAA records.
    }

    if (found) {
        return;
    }

    if (traceEnabled) {
        addTrace(envelope.sender(), "no matching " + qType + " record found");
    }

    // We aked for A/AAAA but we got only CNAME.
    if (!cnames.isEmpty()) {
        onResponseCNAME(question, envelope, cnames, false);
    }
}

From source file:io.vertx.core.dns.impl.fix.DnsNameResolverContext.java

License:Apache License

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;
        }/*from ww w.  ja  va 2  s  .com*/

        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>();
        }

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

    return cnames != null ? cnames : Collections.<String, String>emptyMap();
}