Search in sources :

Example 26 with ChannelInitializer

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

the class SslHandlerTest method testHandshakeWithExecutor.

private static void testHandshakeWithExecutor(Executor executor, SslProvider provider, boolean mtls) throws Throwable {
    final SelfSignedCertificate cert = new SelfSignedCertificate();
    final SslContext sslClientCtx;
    final SslContext sslServerCtx;
    if (mtls) {
        sslClientCtx = SslContextBuilder.forClient().protocols(SslProtocols.TLS_v1_2).trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(cert.key(), cert.cert()).sslProvider(provider).build();
        sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).protocols(SslProtocols.TLS_v1_2).trustManager(InsecureTrustManagerFactory.INSTANCE).clientAuth(ClientAuth.REQUIRE).sslProvider(provider).build();
    } else {
        sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(provider).build();
        sslServerCtx = SslContextBuilder.forServer(cert.key(), cert.cert()).sslProvider(provider).build();
    }
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final SslHandler clientSslHandler = new SslHandler(sslClientCtx.newEngine(UnpooledByteBufAllocator.DEFAULT), executor);
    final SslHandler serverSslHandler = new SslHandler(sslServerCtx.newEngine(UnpooledByteBufAllocator.DEFAULT), executor);
    final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    try {
        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(ChannelHandlerContext ctx, Throwable cause) {
                        causeRef.compareAndSet(null, cause);
                    }
                });
            }
        }).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 ChannelInboundHandlerAdapter() {

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        causeRef.compareAndSet(null, cause);
                    }
                });
            }
        }).connect(sc.localAddress());
        cc = future.syncUninterruptibly().channel();
        assertTrue(clientSslHandler.handshakeFuture().await().isSuccess());
        assertTrue(serverSslHandler.handshakeFuture().await().isSuccess());
        Throwable cause = causeRef.get();
        if (cause != null) {
            throw cause;
        }
    } 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 27 with ChannelInitializer

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

the class SslHandlerTest method testSessionTickets.

private static void testSessionTickets(InetSocketAddress serverAddress, EventLoopGroup group, SslContext sslClientCtx, final byte[] bytes, boolean isReused) throws Throwable {
    Channel cc = null;
    final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>();
    try {
        final SslHandler clientSslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT, serverAddress.getAddress().getHostAddress(), serverAddress.getPort());
        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 ByteToMessageDecoder() {

                    @Override
                    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
                        if (in.readableBytes() == bytes.length) {
                            queue.add(in.readBytes(bytes.length));
                        }
                    }

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                        queue.add(cause);
                    }
                });
            }
        }).connect(serverAddress);
        cc = future.syncUninterruptibly().channel();
        assertTrue(clientSslHandler.handshakeFuture().sync().isSuccess());
        ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) clientSslHandler.engine();
        // See https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_sess_set_get_cb.html
        if (!SslProtocols.TLS_v1_3.equals(engine.getSession().getProtocol())) {
            assertEquals(isReused, engine.isSessionReused());
        }
        Object obj = queue.take();
        if (obj instanceof ByteBuf) {
            ByteBuf buffer = (ByteBuf) obj;
            ByteBuf expected = Unpooled.wrappedBuffer(bytes);
            try {
                assertEquals(expected, buffer);
            } finally {
                expected.release();
                buffer.release();
            }
        } else {
            throw (Throwable) obj;
        }
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) 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) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer)

Example 28 with ChannelInitializer

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

the class SslHandlerTest method testHandshakeFailedByWriteBeforeChannelActive.

@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailedByWriteBeforeChannelActive() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().protocols(SslProtocols.SSL_v3).trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    final CountDownLatch activeLatch = new CountDownLatch(1);
    final AtomicReference<AssertionError> errorRef = new AtomicReference<AssertionError>();
    final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

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

                    @Override
                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                        if (cause instanceof AssertionError) {
                            errorRef.set((AssertionError) cause);
                        }
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        activeLatch.countDown();
                    }
                });
            }
        }).connect(sc.localAddress()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // Write something to trigger the handshake before fireChannelActive is called.
                future.channel().writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }));
            }
        }).syncUninterruptibly().channel();
        // Ensure there is no AssertionError thrown by having the handshake failed by the writeAndFlush(...) before
        // channelActive(...) was called. Let's first wait for the activeLatch countdown to happen and after this
        // check if we saw and AssertionError (even if we timed out waiting).
        activeLatch.await(5, TimeUnit.SECONDS);
        AssertionError error = errorRef.get();
        if (error != null) {
            throw error;
        }
        assertThat(sslHandler.handshakeFuture().await().cause(), CoreMatchers.<Throwable>instanceOf(SSLException.class));
    } 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) 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) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SSLException(javax.net.ssl.SSLException) 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) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 29 with ChannelInitializer

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

the class NettyBlockHoundIntegrationTest method testHandshake.

private static void testHandshake(SslContext sslClientCtx, SslHandler clientSslHandler, SslHandler serverSslHandler) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    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).addLast(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).cause() != null) {
                            ((SslHandshakeCompletionEvent) evt).cause().printStackTrace();
                        }
                        ctx.fireUserEventTriggered(evt);
                    }
                });
            }
        }).connect(sc.localAddress());
        cc = future.syncUninterruptibly().channel();
        clientSslHandler.handshakeFuture().await().sync();
        serverSslHandler.handshakeFuture().await().sync();
    } 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) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 30 with ChannelInitializer

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

the class NettyBlockHoundIntegrationTest method testSslHandlerWrapAllowsBlockingCalls.

@Test
public void testSslHandlerWrapAllowsBlockingCalls() throws Exception {
    final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).sslProvider(SslProvider.JDK).build();
    final SslHandler sslHandler = sslClientCtx.newHandler(UnpooledByteBufAllocator.DEFAULT);
    final EventLoopGroup group = new NioEventLoopGroup();
    final CountDownLatch activeLatch = new CountDownLatch(1);
    final AtomicReference<Throwable> error = new AtomicReference<>();
    Channel sc = null;
    Channel cc = null;
    try {
        sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInboundHandlerAdapter()).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {

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

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) {
                        activeLatch.countDown();
                    }

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).cause() != null) {
                            Throwable cause = ((SslHandshakeCompletionEvent) evt).cause();
                            cause.printStackTrace();
                            error.set(cause);
                        }
                        ctx.fireUserEventTriggered(evt);
                    }
                });
            }
        }).connect(sc.localAddress()).addListener((ChannelFutureListener) future -> future.channel().writeAndFlush(wrappedBuffer(new byte[] { 1, 2, 3, 4 }))).syncUninterruptibly().channel();
        assertTrue(activeLatch.await(5, TimeUnit.SECONDS));
        assertNull(error.get());
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
        ReferenceCountUtil.release(sslClientCtx);
    }
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SslHandshakeCompletionEvent(io.netty.handler.ssl.SslHandshakeCompletionEvent) InetSocketAddress(java.net.InetSocketAddress) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelFutureListener(io.netty.channel.ChannelFutureListener) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

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