Search in sources :

Example 1 with DefaultDnsRawRecord

use of io.netty.handler.codec.dns.DefaultDnsRawRecord in project netty by netty.

the class DnsNameResolver method resolveAll.

private Future<List<DnsRecord>> resolveAll(DnsQuestion question, DnsRecord[] additionals, Promise<List<DnsRecord>> promise) {
    checkNotNull(question, "question");
    checkNotNull(promise, "promise");
    // Respect /etc/hosts as well if the record type is A or AAAA.
    final DnsRecordType type = question.type();
    final String hostname = question.name();
    if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
        final List<InetAddress> hostsFileEntries = resolveHostsFileEntries(hostname);
        if (hostsFileEntries != null) {
            List<DnsRecord> result = new ArrayList<DnsRecord>();
            for (InetAddress hostsFileEntry : hostsFileEntries) {
                ByteBuf content = null;
                if (hostsFileEntry instanceof Inet4Address) {
                    if (type == DnsRecordType.A) {
                        content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress());
                    }
                } else if (hostsFileEntry instanceof Inet6Address) {
                    if (type == DnsRecordType.AAAA) {
                        content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress());
                    }
                }
                if (content != null) {
                    // Our current implementation does not support reloading the hosts file,
                    // so use a fairly large TTL (1 day, i.e. 86400 seconds).
                    result.add(new DefaultDnsRawRecord(hostname, type, 86400, content));
                }
            }
            if (!result.isEmpty()) {
                trySuccess(promise, result);
                return promise;
            }
        }
    }
    // It was not A/AAAA question or there was no entry in /etc/hosts.
    final DnsServerAddressStream nameServerAddrs = dnsServerAddressStreamProvider.nameServerAddressStream(hostname);
    new DnsRecordResolveContext(this, promise, question, additionals, nameServerAddrs, maxQueriesPerResolve).resolve(promise);
    return promise;
}
Also used : Inet4Address(java.net.Inet4Address) ArrayList(java.util.ArrayList) DnsRecordType(io.netty.handler.codec.dns.DnsRecordType) Inet6Address(java.net.Inet6Address) ByteBuf(io.netty.buffer.ByteBuf) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) DnsRecord(io.netty.handler.codec.dns.DnsRecord) InetAddress(java.net.InetAddress)

Example 2 with DefaultDnsRawRecord

use of io.netty.handler.codec.dns.DefaultDnsRawRecord in project netty by netty.

the class TcpDnsServer method main.

public static void main(String[] args) throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap().group(new NioEventLoopGroup(1), new NioEventLoopGroup()).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpDnsQueryDecoder(), new TcpDnsResponseEncoder(), new SimpleChannelInboundHandler<DnsQuery>() {

                @Override
                protected void channelRead0(ChannelHandlerContext ctx, DnsQuery msg) throws Exception {
                    DnsQuestion question = msg.recordAt(DnsSection.QUESTION);
                    System.out.println("Query domain: " + question);
                    // always return 192.168.1.1
                    ctx.writeAndFlush(newResponse(msg, question, 600, QUERY_RESULT));
                }

                private DefaultDnsResponse newResponse(DnsQuery query, DnsQuestion question, long ttl, byte[]... addresses) {
                    DefaultDnsResponse response = new DefaultDnsResponse(query.id());
                    response.addRecord(DnsSection.QUESTION, question);
                    for (byte[] address : addresses) {
                        DefaultDnsRawRecord queryAnswer = new DefaultDnsRawRecord(question.name(), DnsRecordType.A, ttl, Unpooled.wrappedBuffer(address));
                        response.addRecord(DnsSection.ANSWER, queryAnswer);
                    }
                    return response;
                }
            });
        }
    });
    final Channel channel = bootstrap.bind(DNS_SERVER_PORT).channel();
    Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() {

        @Override
        public void run() {
            try {
                clientQuery();
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }, 1000, TimeUnit.MILLISECONDS);
    channel.closeFuture().sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) DnsQuestion(io.netty.handler.codec.dns.DnsQuestion) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DefaultDnsResponse(io.netty.handler.codec.dns.DefaultDnsResponse) TcpDnsQueryDecoder(io.netty.handler.codec.dns.TcpDnsQueryDecoder) DefaultDnsQuery(io.netty.handler.codec.dns.DefaultDnsQuery) DnsQuery(io.netty.handler.codec.dns.DnsQuery) TcpDnsResponseEncoder(io.netty.handler.codec.dns.TcpDnsResponseEncoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 3 with DefaultDnsRawRecord

use of io.netty.handler.codec.dns.DefaultDnsRawRecord in project graylog2-server by Graylog2.

the class DnsClient method decodeDnsRecord.

/**
 * Picks out the IP address and TTL from the answer response for each record.
 */
private static ADnsAnswer decodeDnsRecord(DnsRecord dnsRecord, boolean includeIpVersion) {
    if (dnsRecord == null) {
        return null;
    }
    LOG.trace("Attempting to decode DNS record [{}]", dnsRecord);
    /* Read data from DNS record response. The data is a binary representation of the IP address
         * IPv4 address: 32 bits, IPv6 address: 128 bits */
    byte[] ipAddressBytes;
    final DefaultDnsRawRecord dnsRawRecord = (DefaultDnsRawRecord) dnsRecord;
    try {
        final ByteBuf byteBuf = dnsRawRecord.content();
        ipAddressBytes = new byte[byteBuf.readableBytes()];
        int readerIndex = byteBuf.readerIndex();
        byteBuf.getBytes(readerIndex, ipAddressBytes);
    } finally {
        /* Must manually release references on dnsRawRecord object since the DefaultDnsRawRecord class
             * extends ReferenceCounted. This also releases the above ByteBuf, since DefaultDnsRawRecord is
             * the holder for it. */
        dnsRawRecord.release();
    }
    LOG.trace("The IP address has [{}] bytes", ipAddressBytes.length);
    InetAddress ipAddress;
    try {
        // Takes care of correctly creating an IPv4 or IPv6 address.
        ipAddress = InetAddress.getByAddress(ipAddressBytes);
    } catch (UnknownHostException e) {
        // This should not happen.
        LOG.error("Could not extract IP address from DNS entry [{}]. Cause [{}]", dnsRecord.toString(), ExceptionUtils.getRootCauseMessage(e));
        return null;
    }
    LOG.trace("The resulting IP address is [{}]", ipAddress.getHostAddress());
    final ADnsAnswer.Builder builder = ADnsAnswer.builder().ipAddress(ipAddress.getHostAddress()).dnsTTL(dnsRecord.timeToLive());
    if (includeIpVersion) {
        builder.ipVersion(ipAddress instanceof Inet4Address ? IP_4_VERSION : IP_6_VERSION);
    }
    return builder.build();
}
Also used : Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) ByteBuf(io.netty.buffer.ByteBuf) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) InetAddress(java.net.InetAddress)

Example 4 with DefaultDnsRawRecord

use of io.netty.handler.codec.dns.DefaultDnsRawRecord in project crate by crate.

the class SrvUnicastHostsProvider method parseRecords.

List<TransportAddress> parseRecords(List<DnsRecord> records) {
    List<TransportAddress> addresses = new ArrayList<>(records.size());
    for (DnsRecord record : records) {
        if (record instanceof DefaultDnsRawRecord) {
            DefaultDnsRawRecord rawRecord = (DefaultDnsRawRecord) record;
            ByteBuf content = rawRecord.content();
            // first is "priority", we don't use it
            content.readUnsignedShort();
            // second is "weight", we don't use it
            content.readUnsignedShort();
            int port = content.readUnsignedShort();
            String hostname = DefaultDnsRecordDecoder.decodeName(content).replaceFirst("\\.$", "");
            String address = hostname + ":" + port;
            try {
                for (TransportAddress transportAddress : transportService.addressesFromString(address)) {
                    if (LOGGER.isTraceEnabled()) {
                        LOGGER.trace("adding {}, transport_address {}", address, transportAddress);
                    }
                    addresses.add(transportAddress);
                }
            } catch (Exception e) {
                LOGGER.warn("failed to add " + address, e);
            }
        }
    }
    return addresses;
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) ArrayList(java.util.ArrayList) DnsRecord(io.netty.handler.codec.dns.DnsRecord) ByteBuf(io.netty.buffer.ByteBuf) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException)

Example 5 with DefaultDnsRawRecord

use of io.netty.handler.codec.dns.DefaultDnsRawRecord in project crate by crate.

the class SrvUnicastHostsProviderTest method testParseRecords.

@Test
public void testParseRecords() {
    ByteBuf buf = Unpooled.buffer();
    // priority
    buf.writeShort(0);
    // weight
    buf.writeShort(0);
    // port
    buf.writeShort(993);
    encodeName("localhost.", buf);
    DnsRecord record = new DefaultDnsRawRecord("_myprotocol._tcp.crate.io.", DnsRecordType.SRV, 30, buf);
    List<TransportAddress> addresses = srvUnicastHostsProvider.parseRecords(Collections.singletonList(record));
    assertThat(addresses.get(0).getAddress(), is("127.0.0.1"));
    assertThat(addresses.get(0).getPort(), is(993));
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) ByteBuf(io.netty.buffer.ByteBuf) DnsRecord(io.netty.handler.codec.dns.DnsRecord) DefaultDnsRawRecord(io.netty.handler.codec.dns.DefaultDnsRawRecord) Test(org.junit.Test)

Aggregations

DefaultDnsRawRecord (io.netty.handler.codec.dns.DefaultDnsRawRecord)6 ByteBuf (io.netty.buffer.ByteBuf)4 DnsRecord (io.netty.handler.codec.dns.DnsRecord)4 ArrayList (java.util.ArrayList)3 DefaultDnsQuestion (io.netty.handler.codec.dns.DefaultDnsQuestion)2 Inet4Address (java.net.Inet4Address)2 InetAddress (java.net.InetAddress)2 ExecutionException (java.util.concurrent.ExecutionException)2 TimeoutException (java.util.concurrent.TimeoutException)2 TransportAddress (org.elasticsearch.common.transport.TransportAddress)2 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)1 Channel (io.netty.channel.Channel)1 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)1 SimpleChannelInboundHandler (io.netty.channel.SimpleChannelInboundHandler)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 DefaultDnsQuery (io.netty.handler.codec.dns.DefaultDnsQuery)1 DefaultDnsResponse (io.netty.handler.codec.dns.DefaultDnsResponse)1