Search in sources :

Example 21 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project cassandra by apache.

the class ProxyHandlerTest method test.

public void test(DoTest test) throws Throwable {
    EventLoopGroup serverGroup = new NioEventLoopGroup(1);
    EventLoopGroup clientGroup = new NioEventLoopGroup(1);
    InboundProxyHandler.Controller controller = new InboundProxyHandler.Controller();
    InboundProxyHandler proxyHandler = new InboundProxyHandler(controller);
    TestHandler testHandler = new TestHandler();
    ServerBootstrap sb = new ServerBootstrap();
    sb.group(serverGroup).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) {
            ch.pipeline().addLast(proxyHandler).addLast(testHandler);
        }
    }).childOption(ChannelOption.AUTO_READ, false);
    Bootstrap cb = new Bootstrap();
    cb.group(clientGroup).channel(LocalChannel.class).handler(new ChannelInitializer<LocalChannel>() {

        @Override
        public void initChannel(LocalChannel ch) throws Exception {
            ch.pipeline().addLast(new LoggingHandler(LogLevel.TRACE));
        }
    });
    final LocalAddress addr = new LocalAddress("test");
    Channel serverChannel = sb.bind(addr).sync().channel();
    Channel clientChannel = cb.connect(addr).sync().channel();
    test.doTest(controller, testHandler, clientChannel);
    clientChannel.close();
    serverChannel.close();
    serverGroup.shutdownGracefully();
    clientGroup.shutdownGracefully();
}
Also used : LoggingHandler(io.netty.handler.logging.LoggingHandler) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 22 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method testHandshakeFailureOnlyFireExceptionOnce.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailureOnlyFireExceptionOnce() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(new X509ExtendedTrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            failVerification();
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            failVerification();
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return EmptyArrays.EMPTY_X509_CERTIFICATES;
        }

        private void failVerification() throws CertificateException {
            throw new CertificateException();
        }
    }).sslProvider(SslProvider.JDK).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    try {
        final Object terminalEvent = new Object();
        final BlockingQueue<Object> errorQueue = new LinkedBlockingQueue<Object>();
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(serverSslHandler);
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(final ChannelHandlerContext ctx, Throwable cause) {
                        errorQueue.add(cause);
                    }

                    @Override
                    public void channelInactive(ChannelHandlerContext ctx) {
                        errorQueue.add(terminalEvent);
                    }
                });
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        final ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(clientSslHandler);
            }
        }).connect(sc.localAddress());
        future.syncUninterruptibly();
        clientSslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {

            @Override
            public void operationComplete(Future<Channel> f) {
                future.channel().close();
            }
        });
        assertFalse(clientSslHandler.handshakeFuture().await().isSuccess());
        assertFalse(serverSslHandler.handshakeFuture().await().isSuccess());
        Object error = errorQueue.take();
        assertThat(error, Matchers.instanceOf(DecoderException.class));
        assertThat(((Throwable) error).getCause(), Matchers.<Throwable>instanceOf(SSLException.class));
        Object terminal = errorQueue.take();
        assertSame(terminalEvent, terminal);
        assertNull(errorQueue.poll(1, TimeUnit.MILLISECONDS));
    } finally {
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
Also used : X509ExtendedTrustManager(javax.net.ssl.X509ExtendedTrustManager) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) SSLEngine(javax.net.ssl.SSLEngine) InetSocketAddress(java.net.InetSocketAddress) CertificateException(java.security.cert.CertificateException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) X509Certificate(java.security.cert.X509Certificate) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Socket(java.net.Socket) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 23 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method newHandler.

private static ChannelHandler newHandler(final SslContext sslCtx, final Promise<Void> promise) {
    return new ChannelInitializer() {

        @Override
        protected void initChannel(final Channel ch) {
            final SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
            sslHandler.setHandshakeTimeoutMillis(1000);
            ch.pipeline().addFirst(sslHandler);
            sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() {

                @Override
                public void operationComplete(final Future<Channel> future) {
                    ch.pipeline().remove(sslHandler);
                    // Schedule the close so removal has time to propagate exception if any.
                    ch.eventLoop().execute(new Runnable() {

                        @Override
                        public void run() {
                            ch.close();
                        }
                    });
                }
            });
            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                    if (cause instanceof CodecException) {
                        cause = cause.getCause();
                    }
                    if (cause instanceof IllegalReferenceCountException) {
                        promise.setFailure(cause);
                    }
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    promise.trySuccess(null);
                }
            });
        }
    };
}
Also used : LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CodecException(io.netty.handler.codec.CodecException) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 24 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method testHandshakeFailureCipherMissmatch.

private static void testHandshakeFailureCipherMissmatch(SslProvider provider, boolean tls13) throws Exception {
    final String clientCipher;
    final String serverCipher;
    final String protocol;
    if (tls13) {
        clientCipher = "TLS_AES_128_GCM_SHA256";
        serverCipher = "TLS_AES_256_GCM_SHA384";
        protocol = SslProtocols.TLS_v1_3;
    } else {
        clientCipher = "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256";
        serverCipher = "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384";
        protocol = SslProtocols.TLS_v1_2;
    }
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).protocols(protocol).ciphers(Collections.singleton(clientCipher)).sslProvider(provider).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).protocols(protocol).ciphers(Collections.singleton(serverCipher)).sslProvider(provider).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    class SslEventHandler extends ChannelInboundHandlerAdapter {

        private final AtomicReference<SslHandshakeCompletionEvent> ref;

        SslEventHandler(AtomicReference<SslHandshakeCompletionEvent> ref) {
            this.ref = ref;
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt instanceof SslHandshakeCompletionEvent) {
                ref.set((SslHandshakeCompletionEvent) evt);
            }
            super.userEventTriggered(ctx, evt);
        }
    }
    final AtomicReference<SslHandshakeCompletionEvent> clientEvent = new AtomicReference<SslHandshakeCompletionEvent>();
    final AtomicReference<SslHandshakeCompletionEvent> serverEvent = new AtomicReference<SslHandshakeCompletionEvent>();
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ch.pipeline().addLast(serverSslHandler);
                ch.pipeline().addLast(new SslEventHandler(serverEvent));
            }
        }).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(clientSslHandler);
                ch.pipeline().addLast(new SslEventHandler(clientEvent));
            }
        }).connect(sc.localAddress());
        cc = future.syncUninterruptibly().channel();
        Throwable clientCause = clientSslHandler.handshakeFuture().await().cause();
        assertThat(clientCause, CoreMatchers.<Throwable>instanceOf(SSLException.class));
        assertThat(clientCause.getCause(), not(CoreMatchers.<Throwable>instanceOf(ClosedChannelException.class)));
        Throwable serverCause = serverSslHandler.handshakeFuture().await().cause();
        assertThat(serverCause, CoreMatchers.<Throwable>instanceOf(SSLException.class));
        assertThat(serverCause.getCause(), not(CoreMatchers.<Throwable>instanceOf(ClosedChannelException.class)));
        cc.close().syncUninterruptibly();
        sc.close().syncUninterruptibly();
        Throwable eventClientCause = clientEvent.get().cause();
        assertThat(eventClientCause, CoreMatchers.<Throwable>instanceOf(SSLException.class));
        assertThat(eventClientCause.getCause(), not(CoreMatchers.<Throwable>instanceOf(ClosedChannelException.class)));
        Throwable serverEventCause = serverEvent.get().cause();
        assertThat(serverEventCause, CoreMatchers.<Throwable>instanceOf(SSLException.class));
        assertThat(serverEventCause.getCause(), not(CoreMatchers.<Throwable>instanceOf(ClosedChannelException.class)));
    } finally {
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLException(javax.net.ssl.SSLException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) IllegalReferenceCountException(io.netty.util.IllegalReferenceCountException) CodecException(io.netty.handler.codec.CodecException) DecoderException(io.netty.handler.codec.DecoderException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) UnsupportedMessageTypeException(io.netty.handler.codec.UnsupportedMessageTypeException) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 25 with ChannelInitializer

use of io.netty.channel.ChannelInitializer in project netty by netty.

the class SslHandlerTest method testHandshakeTimeoutBecauseExecutorNotExecute.

private static void testHandshakeTimeoutBecauseExecutorNotExecute(final boolean client) throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() {

        @Override
        public void execute(Runnable command) {
            if (!client) {
                command.run();
            }
        // Do nothing to simulate slow execution.
        }
    });
    if (client) {
        clientSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS);
    }
    final SslHandler serverSslHandler = sslServerCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, new Executor() {

        @Override
        public void execute(Runnable command) {
            if (client) {
                command.run();
            }
        // Do nothing to simulate slow execution.
        }
    });
    if (!client) {
        serverSslHandler.setHandshakeTimeout(100, TimeUnit.MILLISECONDS);
    }
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(serverSslHandler).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        ChannelFuture future = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addLast(clientSslHandler);
            }
        }).connect(sc.localAddress());
        cc = future.syncUninterruptibly().channel();
        if (client) {
            Throwable cause = clientSslHandler.handshakeFuture().await().cause();
            assertThat(cause, CoreMatchers.<Throwable>instanceOf(SslHandshakeTimeoutException.class));
            assertFalse(serverSslHandler.handshakeFuture().await().isSuccess());
        } else {
            Throwable cause = serverSslHandler.handshakeFuture().await().cause();
            assertThat(cause, CoreMatchers.<Throwable>instanceOf(SslHandshakeTimeoutException.class));
            assertFalse(clientSslHandler.handshakeFuture().await().isSuccess());
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ImmediateExecutor(io.netty.util.concurrent.ImmediateExecutor) ImmediateEventExecutor(io.netty.util.concurrent.ImmediateEventExecutor) Executor(java.util.concurrent.Executor) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)85 Channel (io.netty.channel.Channel)58 Bootstrap (io.netty.bootstrap.Bootstrap)42 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)39 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)36 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)32 InetSocketAddress (java.net.InetSocketAddress)32 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)31 ChannelFuture (io.netty.channel.ChannelFuture)29 ChannelPipeline (io.netty.channel.ChannelPipeline)26 EventLoopGroup (io.netty.channel.EventLoopGroup)26 LocalServerChannel (io.netty.channel.local.LocalServerChannel)21 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)21 LocalChannel (io.netty.channel.local.LocalChannel)20 SocketChannel (io.netty.channel.socket.SocketChannel)18 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)17 SslHandler (io.netty.handler.ssl.SslHandler)17 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)14 CountDownLatch (java.util.concurrent.CountDownLatch)12 ChannelHandler (io.netty.channel.ChannelHandler)11