Search in sources :

Example 41 with ChannelInboundHandlerAdapter

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

the class OcspTest method testClientException.

/**
 * Testing what happens if the {@link OcspClientCallback} throws an {@link Exception}.
 *
 * The exception should bubble up on the client side and the connection should get closed.
 */
private static void testClientException(SslProvider sslProvider) throws Exception {
    final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ChannelInboundHandlerAdapter clientHandler = new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            try {
                causeRef.set(cause);
            } finally {
                latch.countDown();
            }
        }
    };
    final OcspTestException clientException = new OcspTestException("testClientException");
    byte[] response = newOcspResponse();
    OcspClientCallback callback = new OcspClientCallback() {

        @Override
        public boolean verify(byte[] response) throws Exception {
            throw clientException;
        }
    };
    handshake(sslProvider, latch, null, response, clientHandler, callback);
    assertSame(clientException, causeRef.get());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 42 with ChannelInboundHandlerAdapter

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

the class OcspTest method testClientRejectingOcspStaple.

/**
 * The Server provides an OCSP staple and the Client rejects it.
 */
private static void testClientRejectingOcspStaple(SslProvider sslProvider) throws Exception {
    final AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ChannelInboundHandlerAdapter clientHandler = new ChannelInboundHandlerAdapter() {

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            try {
                causeRef.set(cause);
            } finally {
                latch.countDown();
            }
        }
    };
    byte[] response = newOcspResponse();
    TestClientOcspContext callback = new TestClientOcspContext(false);
    handshake(sslProvider, latch, null, response, clientHandler, callback);
    byte[] actual = callback.response();
    assertNotNull(actual);
    assertNotSame(response, actual);
    assertArrayEquals(response, actual);
    Throwable cause = causeRef.get();
    assertThat(cause, CoreMatchers.instanceOf(SSLHandshakeException.class));
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 43 with ChannelInboundHandlerAdapter

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

the class SSLEngineTest method mySetupClientHostnameValidation.

private Future<Void> mySetupClientHostnameValidation(final SSLEngineTestParam param, File serverCrtFile, File serverKeyFile, File clientTrustCrtFile, final boolean failureExpected) throws SSLException, InterruptedException {
    final String expectedHost = "localhost";
    serverSslCtx = wrapContext(param, SslContextBuilder.forServer(serverCrtFile, serverKeyFile, null).sslProvider(sslServerProvider()).protocols(param.protocols()).ciphers(param.ciphers()).sslContextProvider(serverSslContextProvider()).trustManager(InsecureTrustManagerFactory.INSTANCE).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build());
    clientSslCtx = wrapContext(param, SslContextBuilder.forClient().sslProvider(sslClientProvider()).protocols(param.protocols()).ciphers(param.ciphers()).sslContextProvider(clientSslContextProvider()).trustManager(clientTrustCrtFile).ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0).build());
    serverConnectedChannel = null;
    sb = new ServerBootstrap();
    cb = new Bootstrap();
    sb.group(new NioEventLoopGroup(), new NioEventLoopGroup());
    sb.channel(NioServerSocketChannel.class);
    sb.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), param.type));
            ChannelPipeline p = ch.pipeline();
            SslHandler handler = !param.delegate ? serverSslCtx.newHandler(ch.alloc()) : serverSslCtx.newHandler(ch.alloc(), delegatingExecutor);
            p.addLast(handler);
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            serverException = new IllegalStateException("handshake complete. expected failure");
                        }
                        serverLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        serverException = ((SslHandshakeCompletionEvent) evt).cause();
                        serverLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        serverException = cause.getCause();
                        serverLatch.countDown();
                    } else {
                        serverException = cause;
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    });
    final Promise<Void> clientWritePromise = ImmediateEventExecutor.INSTANCE.newPromise();
    cb.group(new NioEventLoopGroup());
    cb.channel(NioSocketChannel.class);
    cb.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), param.type));
            ChannelPipeline p = ch.pipeline();
            InetSocketAddress remoteAddress = (InetSocketAddress) serverChannel.localAddress();
            SslHandler sslHandler = !param.delegate ? clientSslCtx.newHandler(ch.alloc(), expectedHost, 0) : clientSslCtx.newHandler(ch.alloc(), expectedHost, 0, delegatingExecutor);
            SSLParameters parameters = sslHandler.engine().getSSLParameters();
            if (SslUtils.isValidHostNameForSNI(expectedHost)) {
                assertEquals(1, parameters.getServerNames().size());
                assertEquals(new SNIHostName(expectedHost), parameters.getServerNames().get(0));
            }
            parameters.setEndpointIdentificationAlgorithm("HTTPS");
            sslHandler.engine().setSSLParameters(parameters);
            p.addLast(sslHandler);
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void handlerAdded(ChannelHandlerContext ctx) {
                    // about verifying the payload and releasing the content on the server side.
                    if (failureExpected) {
                        ChannelFuture f = ctx.write(ctx.alloc().buffer(1).writeByte(1));
                        PromiseNotifier.cascade(f, clientWritePromise);
                    }
                }

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                    if (evt == SslHandshakeCompletionEvent.SUCCESS) {
                        if (failureExpected) {
                            clientException = new IllegalStateException("handshake complete. expected failure");
                        }
                        clientLatch.countDown();
                    } else if (evt instanceof SslHandshakeCompletionEvent) {
                        clientException = ((SslHandshakeCompletionEvent) evt).cause();
                        clientLatch.countDown();
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        clientException = cause.getCause();
                        clientLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(expectedHost, 0)).sync().channel();
    final int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    ChannelFuture ccf = cb.connect(new InetSocketAddress(expectedHost, port));
    assertTrue(ccf.awaitUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    return clientWritePromise;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLParameters(javax.net.ssl.SSLParameters) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) KeyStoreException(java.security.KeyStoreException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ChannelPipeline(io.netty.channel.ChannelPipeline) SNIHostName(javax.net.ssl.SNIHostName) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 44 with ChannelInboundHandlerAdapter

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

the class IdleStateHandlerTest method anyIdle.

private static void anyIdle(TestableIdleStateHandler idleStateHandler, Object... expected) throws Exception {
    assertThat(expected.length, greaterThanOrEqualTo(1));
    final List<Object> events = new ArrayList<Object>();
    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            events.add(evt);
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(idleStateHandler, handler);
    try {
        // or read anything from the channel.
        for (int i = 0; i < expected.length; i++) {
            idleStateHandler.tickRun();
        }
        assertEquals(expected.length, events.size());
        // Compare the expected with the actual IdleStateEvents
        for (int i = 0; i < expected.length; i++) {
            Object evt = events.get(i);
            assertSame(expected[i], evt, "Element " + i + " is not matching");
        }
    } finally {
        channel.finishAndReleaseAll();
    }
}
Also used : ArrayList(java.util.ArrayList) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 45 with ChannelInboundHandlerAdapter

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

the class IdleStateHandlerTest method anyNotIdle.

private static void anyNotIdle(TestableIdleStateHandler idleStateHandler, Action action, Object expected) throws Exception {
    final List<Object> events = new ArrayList<Object>();
    ChannelInboundHandlerAdapter handler = new ChannelInboundHandlerAdapter() {

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            events.add(evt);
        }
    };
    EmbeddedChannel channel = new EmbeddedChannel(idleStateHandler, handler);
    try {
        idleStateHandler.tick(1L, TimeUnit.NANOSECONDS);
        action.run(channel);
        // Advance the ticker by some fraction and run() the task.
        // There shouldn't be an IdleStateEvent getting fired because
        // we've just performed an action on the channel that is meant
        // to reset the idle task.
        long delayInNanos = idleStateHandler.delay(TimeUnit.NANOSECONDS);
        assertNotEquals(0L, delayInNanos);
        idleStateHandler.tickRun(delayInNanos / 2L, TimeUnit.NANOSECONDS);
        assertEquals(0, events.size());
        // Advance the ticker by the full amount and it should yield
        // in an IdleStateEvent.
        idleStateHandler.tickRun();
        assertEquals(1, events.size());
        assertSame(expected, events.get(0));
    } finally {
        channel.finishAndReleaseAll();
    }
}
Also used : ArrayList(java.util.ArrayList) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

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