Search in sources :

Example 1 with DnsMessage

use of org.apache.directory.server.dns.messages.DnsMessage in project netty by netty.

the class DnsNameResolverTest method testFollowNsRedirects.

private void testFollowNsRedirects(DnsCache cache, AuthoritativeDnsServerCache authoritativeDnsServerCache, final boolean invalidNsFirst) throws Exception {
    final String domain = "netty.io";
    final String ns1Name = "ns1." + domain;
    final String ns2Name = "ns2." + domain;
    final InetAddress expected = InetAddress.getByAddress("some.record." + domain, new byte[] { 10, 10, 10, 10 });
    // This is used to simulate a query timeout...
    final DatagramSocket socket = new DatagramSocket(new InetSocketAddress(0));
    final TestDnsServer dnsServerAuthority = new TestDnsServer(new RecordStore() {

        @Override
        public Set<ResourceRecord> getRecords(QuestionRecord question) {
            if (question.getDomainName().equals(expected.getHostName())) {
                return Collections.singleton(newARecord(expected.getHostName(), expected.getHostAddress()));
            }
            return Collections.emptySet();
        }
    });
    dnsServerAuthority.start();
    TestDnsServer redirectServer = new TestDnsServer(new HashSet<String>(asList(expected.getHostName(), ns1Name, ns2Name))) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            for (QuestionRecord record : message.getQuestionRecords()) {
                if (record.getDomainName().equals(expected.getHostName())) {
                    message.getAdditionalRecords().clear();
                    message.getAnswerRecords().clear();
                    if (invalidNsFirst) {
                        message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
                        message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                    } else {
                        message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                        message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
                    }
                    return message;
                }
            }
            return message;
        }
    };
    redirectServer.start();
    EventLoopGroup group = new NioEventLoopGroup(1);
    final DnsNameResolver resolver = new DnsNameResolver(group.next(), new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), cache, authoritativeDnsServerCache, NoopDnsQueryLifecycleObserverFactory.INSTANCE, 2000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(redirectServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {

        @Override
        InetSocketAddress newRedirectServerAddress(InetAddress server) {
            try {
                if (server.getHostName().startsWith(ns1Name)) {
                    return new InetSocketAddress(InetAddress.getByAddress(ns1Name, dnsServerAuthority.localAddress().getAddress().getAddress()), dnsServerAuthority.localAddress().getPort());
                }
                if (server.getHostName().startsWith(ns2Name)) {
                    return new InetSocketAddress(InetAddress.getByAddress(ns2Name, NetUtil.LOCALHOST.getAddress()), socket.getLocalPort());
                }
            } catch (UnknownHostException e) {
                throw new IllegalStateException(e);
            }
            return super.newRedirectServerAddress(server);
        }
    };
    try {
        List<InetAddress> resolved = resolver.resolveAll(expected.getHostName()).syncUninterruptibly().getNow();
        assertEquals(1, resolved.size());
        assertEquals(expected, resolved.get(0));
        List<InetAddress> resolved2 = resolver.resolveAll(expected.getHostName()).syncUninterruptibly().getNow();
        assertEquals(1, resolved2.size());
        assertEquals(expected, resolved2.get(0));
        if (authoritativeDnsServerCache != NoopAuthoritativeDnsServerCache.INSTANCE) {
            DnsServerAddressStream cached = authoritativeDnsServerCache.get(domain + '.');
            assertEquals(2, cached.size());
            InetSocketAddress ns1Address = InetSocketAddress.createUnresolved(ns1Name + '.', DefaultDnsServerAddressStreamProvider.DNS_PORT);
            InetSocketAddress ns2Address = InetSocketAddress.createUnresolved(ns2Name + '.', DefaultDnsServerAddressStreamProvider.DNS_PORT);
            if (invalidNsFirst) {
                assertEquals(ns2Address, cached.next());
                assertEquals(ns1Address, cached.next());
            } else {
                assertEquals(ns1Address, cached.next());
                assertEquals(ns2Address, cached.next());
            }
        }
        if (cache != NoopDnsCache.INSTANCE) {
            List<? extends DnsCacheEntry> ns1Cached = cache.get(ns1Name + '.', null);
            assertEquals(1, ns1Cached.size());
            DnsCacheEntry nsEntry = ns1Cached.get(0);
            assertNotNull(nsEntry.address());
            assertNull(nsEntry.cause());
            List<? extends DnsCacheEntry> ns2Cached = cache.get(ns2Name + '.', null);
            if (invalidNsFirst) {
                assertEquals(1, ns2Cached.size());
                DnsCacheEntry ns2Entry = ns2Cached.get(0);
                assertNotNull(ns2Entry.address());
                assertNull(ns2Entry.cause());
            } else {
                // We should not even have tried to resolve the DNS name so this should be null.
                assertNull(ns2Cached);
            }
            List<? extends DnsCacheEntry> expectedCached = cache.get(expected.getHostName(), null);
            assertEquals(1, expectedCached.size());
            DnsCacheEntry expectedEntry = expectedCached.get(0);
            assertEquals(expected, expectedEntry.address());
            assertNull(expectedEntry.cause());
        }
    } finally {
        resolver.close();
        group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        redirectServer.stop();
        dnsServerAuthority.stop();
        socket.close();
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DatagramSocket(java.net.DatagramSocket) RecordStore(org.apache.directory.server.dns.store.RecordStore) InetAddress(java.net.InetAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 2 with DnsMessage

use of org.apache.directory.server.dns.messages.DnsMessage in project netty by netty.

the class DnsNameResolverTest method testNSRecordsFromCache.

@Test
public void testNSRecordsFromCache() throws Exception {
    final String domain = "netty.io";
    final String hostname = "test.netty.io";
    final String ns0Name = "ns0." + domain + '.';
    final String ns1Name = "ns1." + domain + '.';
    final String ns2Name = "ns2." + domain + '.';
    final InetSocketAddress ns0Address = new InetSocketAddress(InetAddress.getByAddress(ns0Name, new byte[] { 10, 1, 0, 1 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns1Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 1 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns2Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 2 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns3Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 3 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns4Address = new InetSocketAddress(InetAddress.getByAddress(ns1Name, new byte[] { 10, 0, 0, 4 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    final InetSocketAddress ns5Address = new InetSocketAddress(InetAddress.getByAddress(ns2Name, new byte[] { 10, 0, 0, 5 }), DefaultDnsServerAddressStreamProvider.DNS_PORT);
    TestDnsServer redirectServer = new TestDnsServer(new HashSet<String>(asList(hostname, ns1Name))) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            for (QuestionRecord record : message.getQuestionRecords()) {
                if (record.getDomainName().equals(hostname)) {
                    message.getAdditionalRecords().clear();
                    message.getAnswerRecords().clear();
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns0Name));
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
                    message.getAdditionalRecords().add(newARecord(ns0Address));
                    message.getAdditionalRecords().add(newARecord(ns5Address));
                    return message;
                }
            }
            return message;
        }

        private ResourceRecord newARecord(InetSocketAddress address) {
            return newARecord(address.getHostName(), address.getAddress().getHostAddress());
        }
    };
    redirectServer.start();
    EventLoopGroup group = new NioEventLoopGroup(1);
    final List<InetSocketAddress> cached = new CopyOnWriteArrayList<InetSocketAddress>();
    final AuthoritativeDnsServerCache authoritativeDnsServerCache = new AuthoritativeDnsServerCache() {

        @Override
        public DnsServerAddressStream get(String hostname) {
            return null;
        }

        @Override
        public void cache(String hostname, InetSocketAddress address, long originalTtl, EventLoop loop) {
            cached.add(address);
        }

        @Override
        public void clear() {
        // NOOP
        }

        @Override
        public boolean clear(String hostname) {
            return false;
        }
    };
    EventLoop loop = group.next();
    DefaultDnsCache cache = new DefaultDnsCache();
    cache.cache(ns1Name, null, ns1Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns2Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns3Address.getAddress(), 10000, loop);
    cache.cache(ns1Name, null, ns4Address.getAddress(), 10000, loop);
    final AtomicReference<DnsServerAddressStream> redirectedRef = new AtomicReference<DnsServerAddressStream>();
    final DnsNameResolver resolver = new DnsNameResolver(loop, new ReflectiveChannelFactory<DatagramChannel>(NioDatagramChannel.class), cache, authoritativeDnsServerCache, NoopDnsQueryLifecycleObserverFactory.INSTANCE, 2000, ResolvedAddressTypes.IPV4_ONLY, true, 10, true, 4096, false, HostsFileEntriesResolver.DEFAULT, new SingletonDnsServerAddressStreamProvider(redirectServer.localAddress()), DnsNameResolver.DEFAULT_SEARCH_DOMAINS, 0, true) {

        @Override
        protected DnsServerAddressStream newRedirectDnsServerStream(String hostname, List<InetSocketAddress> nameservers) {
            DnsServerAddressStream stream = new SequentialDnsServerAddressStream(nameservers, 0);
            redirectedRef.set(stream);
            return stream;
        }
    };
    try {
        Throwable cause = resolver.resolveAll(hostname).await().cause();
        assertTrue(cause instanceof UnknownHostException);
        DnsServerAddressStream redirected = redirectedRef.get();
        assertNotNull(redirected);
        assertEquals(6, redirected.size());
        assertEquals(3, cached.size());
        // The redirected addresses should have been retrieven from the DnsCache if not resolved, so these are
        // fully resolved.
        assertEquals(ns0Address, redirected.next());
        assertEquals(ns1Address, redirected.next());
        assertEquals(ns2Address, redirected.next());
        assertEquals(ns3Address, redirected.next());
        assertEquals(ns4Address, redirected.next());
        assertEquals(ns5Address, redirected.next());
        // As this address was supplied as ADDITIONAL we should put it resolved into the cache.
        assertEquals(ns0Address, cached.get(0));
        assertEquals(ns5Address, cached.get(1));
        // We should have put the unresolved address in the AuthoritativeDnsServerCache (but only 1 time)
        assertEquals(unresolved(ns1Address), cached.get(2));
    } finally {
        resolver.close();
        group.shutdownGracefully(0, 0, TimeUnit.SECONDS);
        redirectServer.stop();
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) InetSocketAddress(java.net.InetSocketAddress) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) Collections.singletonList(java.util.Collections.singletonList) Arrays.asList(java.util.Arrays.asList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) UnknownHostException(java.net.UnknownHostException) DatagramChannel(io.netty.channel.socket.DatagramChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) EventLoop(io.netty.channel.EventLoop) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Test(org.junit.jupiter.api.Test)

Example 3 with DnsMessage

use of org.apache.directory.server.dns.messages.DnsMessage in project netty by netty.

the class DnsNameResolverTest method testCancelPromise.

@Test
public void testCancelPromise() throws Exception {
    final EventLoop eventLoop = group.next();
    final Promise<InetAddress> promise = eventLoop.newPromise();
    final TestDnsServer dnsServer1 = new TestDnsServer(Collections.<String>emptySet()) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            promise.cancel(true);
            return message;
        }
    };
    dnsServer1.start();
    final AtomicBoolean isQuerySentToSecondServer = new AtomicBoolean();
    final TestDnsServer dnsServer2 = new TestDnsServer(Collections.<String>emptySet()) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            isQuerySentToSecondServer.set(true);
            return message;
        }
    };
    dnsServer2.start();
    DnsServerAddressStreamProvider nameServerProvider = new SequentialDnsServerAddressStreamProvider(dnsServer1.localAddress(), dnsServer2.localAddress());
    final DnsNameResolver resolver = new DnsNameResolverBuilder(group.next()).dnsQueryLifecycleObserverFactory(new TestRecursiveCacheDnsQueryLifecycleObserverFactory()).channelType(NioDatagramChannel.class).optResourceEnabled(false).nameServerProvider(nameServerProvider).build();
    try {
        resolver.resolve("non-existent.netty.io", promise).sync();
        fail();
    } catch (Exception e) {
        assertThat(e, is(instanceOf(CancellationException.class)));
    }
    assertThat(isQuerySentToSecondServer.get(), is(false));
}
Also used : NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) CancellationException(java.util.concurrent.CancellationException) DnsException(org.apache.directory.server.dns.DnsException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) BindException(java.net.BindException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EventLoop(io.netty.channel.EventLoop) CancellationException(java.util.concurrent.CancellationException) InetAddress(java.net.InetAddress) Test(org.junit.jupiter.api.Test)

Example 4 with DnsMessage

use of org.apache.directory.server.dns.messages.DnsMessage in project vert.x by eclipse.

the class DNSTest method testRecursionNotDesired.

@Test
public void testRecursionNotDesired() throws Exception {
    final String ip = "10.0.0.1";
    dnsServer.testResolveA(ip);
    DnsClient dns = prepareDns(new DnsClientOptions().setRecursionDesired(false));
    dns.resolveA("vertx.io", onSuccess(result -> {
        assertFalse(result.isEmpty());
        assertEquals(1, result.size());
        assertEquals(ip, result.get(0));
        DnsMessage msg = dnsServer.pollMessage();
        assertFalse(msg.isRecursionDesired());
        ((DnsClientImpl) dns).inProgressQueries(num -> {
            assertEquals(0, (int) num);
            testComplete();
        });
    }));
    await();
}
Also used : DnsClientOptions(io.vertx.core.dns.DnsClientOptions) VertxException(io.vertx.core.VertxException) DnsException(io.vertx.core.dns.DnsException) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) DnsClientImpl(io.vertx.core.dns.impl.DnsClientImpl) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) Vertx(io.vertx.core.Vertx) DnsClientOptions(io.vertx.core.dns.DnsClientOptions) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) InetSocketAddress(java.net.InetSocketAddress) Function(java.util.function.Function) VertxTestBase(io.vertx.test.core.VertxTestBase) SrvRecord(io.vertx.core.dns.SrvRecord) DnsClient(io.vertx.core.dns.DnsClient) List(java.util.List) TestUtils(io.vertx.test.core.TestUtils) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) DnsResponseCode(io.vertx.core.dns.DnsResponseCode) MxRecord(io.vertx.core.dns.MxRecord) FakeDNSServer(io.vertx.test.fakedns.FakeDNSServer) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DnsClient(io.vertx.core.dns.DnsClient) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage) Test(org.junit.Test)

Example 5 with DnsMessage

use of org.apache.directory.server.dns.messages.DnsMessage in project netty by netty.

the class DnsNameResolverTest method testNsLoopFailsResolve.

private void testNsLoopFailsResolve(AuthoritativeDnsServerCache authoritativeDnsServerCache) throws Exception {
    final String domain = "netty.io";
    final String ns1Name = "ns1." + domain;
    final String ns2Name = "ns2." + domain;
    TestDnsServer testDnsServer = new TestDnsServer(new HashSet<String>(Collections.singletonList(domain))) {

        @Override
        protected DnsMessage filterMessage(DnsMessage message) {
            // point.
            for (QuestionRecord record : message.getQuestionRecords()) {
                if (record.getDomainName().equals(domain)) {
                    message.getAdditionalRecords().clear();
                    message.getAnswerRecords().clear();
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns1Name));
                    message.getAuthorityRecords().add(TestDnsServer.newNsRecord(domain, ns2Name));
                }
            }
            return message;
        }
    };
    testDnsServer.start();
    DnsNameResolverBuilder builder = newResolver();
    final DnsNameResolver resolver = builder.resolveCache(NoopDnsCache.INSTANCE).authoritativeDnsServerCache(authoritativeDnsServerCache).nameServerProvider(new SingletonDnsServerAddressStreamProvider(testDnsServer.localAddress())).build();
    try {
        assertThat(resolver.resolve(domain).await().cause(), Matchers.<Throwable>instanceOf(UnknownHostException.class));
        assertThat(resolver.resolveAll(domain).await().cause(), Matchers.<Throwable>instanceOf(UnknownHostException.class));
    } finally {
        resolver.close();
        testDnsServer.stop();
    }
}
Also used : QuestionRecord(org.apache.directory.server.dns.messages.QuestionRecord) UnknownHostException(java.net.UnknownHostException) DnsMessage(org.apache.directory.server.dns.messages.DnsMessage)

Aggregations

DnsMessage (org.apache.directory.server.dns.messages.DnsMessage)10 InetSocketAddress (java.net.InetSocketAddress)7 QuestionRecord (org.apache.directory.server.dns.messages.QuestionRecord)6 UnknownHostException (java.net.UnknownHostException)5 List (java.util.List)5 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)4 EventLoop (io.netty.channel.EventLoop)3 EventLoopGroup (io.netty.channel.EventLoopGroup)3 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 DatagramChannel (io.netty.channel.socket.DatagramChannel)3 AbstractVerticle (io.vertx.core.AbstractVerticle)3 DeploymentOptions (io.vertx.core.DeploymentOptions)3 Vertx (io.vertx.core.Vertx)3 VertxException (io.vertx.core.VertxException)3 VertxOptions (io.vertx.core.VertxOptions)3 DnsClient (io.vertx.core.dns.DnsClient)3 DnsClientOptions (io.vertx.core.dns.DnsClientOptions)3 DnsException (io.vertx.core.dns.DnsException)3 DnsResponseCode (io.vertx.core.dns.DnsResponseCode)3 MxRecord (io.vertx.core.dns.MxRecord)3