Search in sources :

Example 31 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SslHandlerTest method testHandshakeFailBeforeWritePromise.

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeFailBeforeWritePromise() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    final CountDownLatch latch = new CountDownLatch(2);
    final CountDownLatch latch2 = new CountDownLatch(2);
    final BlockingQueue<Object> events = new LinkedBlockingQueue<Object>();
    Channel serverChannel = null;
    Channel clientChannel = null;
    EventLoopGroup group = new DefaultEventLoopGroup();
    try {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(group).channel(LocalServerChannel.class).childHandler(new ChannelInitializer<Channel>() {

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

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) {
                        ByteBuf buf = ctx.alloc().buffer(10);
                        buf.writeZero(buf.capacity());
                        ctx.writeAndFlush(buf).addListener(new ChannelFutureListener() {

                            @Override
                            public void operationComplete(ChannelFuture future) {
                                events.add(future);
                                latch.countDown();
                            }
                        });
                    }

                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                        if (evt instanceof SslCompletionEvent) {
                            events.add(evt);
                            latch.countDown();
                            latch2.countDown();
                        }
                    }
                });
            }
        });
        Bootstrap cb = new Bootstrap();
        cb.group(group).channel(LocalChannel.class).handler(new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) {
                ch.pipeline().addFirst(new ChannelInboundHandlerAdapter() {

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) {
                        ByteBuf buf = ctx.alloc().buffer(1000);
                        buf.writeZero(buf.capacity());
                        ctx.writeAndFlush(buf);
                    }
                });
            }
        });
        serverChannel = sb.bind(new LocalAddress("SslHandlerTest")).sync().channel();
        clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
        latch.await();
        SslCompletionEvent evt = (SslCompletionEvent) events.take();
        assertTrue(evt instanceof SslHandshakeCompletionEvent);
        assertThat(evt.cause(), is(instanceOf(SSLException.class)));
        ChannelFuture future = (ChannelFuture) events.take();
        assertThat(future.cause(), is(instanceOf(SSLException.class)));
        serverChannel.close().sync();
        serverChannel = null;
        clientChannel.close().sync();
        clientChannel = null;
        latch2.await();
        evt = (SslCompletionEvent) events.take();
        assertTrue(evt instanceof SslCloseCompletionEvent);
        assertThat(evt.cause(), is(instanceOf(ClosedChannelException.class)));
        assertTrue(events.isEmpty());
    } finally {
        if (serverChannel != null) {
            serverChannel.close();
        }
        if (clientChannel != null) {
            clientChannel.close();
        }
        group.shutdownGracefully();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) LocalAddress(io.netty.channel.local.LocalAddress) LocalChannel(io.netty.channel.local.LocalChannel) 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) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) ByteBuf(io.netty.buffer.ByteBuf) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) LocalServerChannel(io.netty.channel.local.LocalServerChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 32 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter 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 33 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter 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 34 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SslHandlerTest method testHandshakeAndClosePromiseFailedOnRemoval.

@Test
@Timeout(value = 5000, unit = TimeUnit.MILLISECONDS)
public void testHandshakeAndClosePromiseFailedOnRemoval() throws Exception {
    SSLEngine engine = SSLContext.getDefault().createSSLEngine();
    engine.setUseClientMode(true);
    SslHandler handler = new SslHandler(engine);
    final AtomicReference<Throwable> handshakeRef = new AtomicReference<Throwable>();
    final AtomicReference<Throwable> closeRef = new AtomicReference<Throwable>();
    EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
            if (evt instanceof SslHandshakeCompletionEvent) {
                handshakeRef.set(((SslHandshakeCompletionEvent) evt).cause());
            } else if (evt instanceof SslCloseCompletionEvent) {
                closeRef.set(((SslCloseCompletionEvent) evt).cause());
            }
        }
    });
    assertFalse(handler.handshakeFuture().isDone());
    assertFalse(handler.sslCloseFuture().isDone());
    ch.pipeline().remove(handler);
    try {
        while (!handler.handshakeFuture().isDone() || handshakeRef.get() == null || !handler.sslCloseFuture().isDone() || closeRef.get() == null) {
            Thread.sleep(10);
            // Continue running all pending tasks until we notified for everything.
            ch.runPendingTasks();
        }
        assertSame(handler.handshakeFuture().cause(), handshakeRef.get());
        assertSame(handler.sslCloseFuture().cause(), closeRef.get());
    } finally {
        ch.finishAndReleaseAll();
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 35 with ChannelInboundHandlerAdapter

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelInboundHandlerAdapter in project netty by netty.

the class SniHandlerTest method testServerNameParsing.

@ParameterizedTest(name = "{index}: sslProvider={0}")
@MethodSource("data")
public void testServerNameParsing(SslProvider provider) throws Exception {
    SslContext nettyContext = makeSslContext(provider, false);
    SslContext leanContext = makeSslContext(provider, false);
    SslContext leanContext2 = makeSslContext(provider, false);
    try {
        DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).add("*.netty.io", nettyContext).add("*.LEANCLOUD.CN", leanContext).add("chat4.leancloud.cn", leanContext2).build();
        final AtomicReference<SniCompletionEvent> evtRef = new AtomicReference<SniCompletionEvent>();
        SniHandler handler = new SniHandler(mapping);
        EmbeddedChannel ch = new EmbeddedChannel(handler, new ChannelInboundHandlerAdapter() {

            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                if (evt instanceof SniCompletionEvent) {
                    assertTrue(evtRef.compareAndSet(null, (SniCompletionEvent) evt));
                } else {
                    ctx.fireUserEventTriggered(evt);
                }
            }
        });
        try {
            // hex dump of a client hello packet, which contains hostname "CHAT4.LEANCLOUD.CN"
            String tlsHandshakeMessageHex1 = "16030100";
            // part 2
            String tlsHandshakeMessageHex = "c6010000c20303bb0855d66532c05a0ef784f7c384feeafa68b3" + "b655ac7288650d5eed4aa3fb52000038c02cc030009fcca9cca8ccaac02b" + "c02f009ec024c028006bc023c0270067c00ac0140039c009c0130033009d" + "009c003d003c0035002f00ff010000610000001700150000124348415434" + "2e4c45414e434c4f55442e434e000b000403000102000a000a0008001d00" + "170019001800230000000d0020001e060106020603050105020503040104" + "0204030301030203030201020202030016000000170000";
            ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex1)));
            ch.writeInbound(Unpooled.wrappedBuffer(StringUtil.decodeHexDump(tlsHandshakeMessageHex)));
            // This should produce an alert
            assertTrue(ch.finish());
            assertThat(handler.hostname(), is("chat4.leancloud.cn"));
            assertThat(handler.sslContext(), is(leanContext));
            SniCompletionEvent evt = evtRef.get();
            assertNotNull(evt);
            assertEquals("chat4.leancloud.cn", evt.hostname());
            assertTrue(evt.isSuccess());
            assertNull(evt.cause());
        } finally {
            ch.finishAndReleaseAll();
        }
    } finally {
        releaseAll(leanContext, leanContext2, nettyContext);
    }
}
Also used : EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DecoderException(io.netty.handler.codec.DecoderException) SSLException(javax.net.ssl.SSLException) DomainNameMappingBuilder(io.netty.util.DomainNameMappingBuilder) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)248 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)192 Channel (io.netty.channel.Channel)132 Bootstrap (io.netty.bootstrap.Bootstrap)109 Test (org.junit.jupiter.api.Test)102 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)99 ChannelFuture (io.netty.channel.ChannelFuture)71 CountDownLatch (java.util.concurrent.CountDownLatch)70 InetSocketAddress (java.net.InetSocketAddress)66 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)54 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)53 EventLoopGroup (io.netty.channel.EventLoopGroup)52 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)51 ByteBuf (io.netty.buffer.ByteBuf)47 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)46 ClosedChannelException (java.nio.channels.ClosedChannelException)46 LocalServerChannel (io.netty.channel.local.LocalServerChannel)44 LocalChannel (io.netty.channel.local.LocalChannel)42 SocketChannel (io.netty.channel.socket.SocketChannel)39