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