Search in sources :

Example 56 with ChannelHandlerContext

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

the class SSLEngineTest method setupHandlers.

protected void setupHandlers(SslContext serverCtx, SslContext clientCtx) throws InterruptedException, SSLException, CertificateException {
    serverSslCtx = serverCtx;
    clientSslCtx = clientCtx;
    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(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(serverReceiver, serverLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    if (cause.getCause() instanceof SSLHandshakeException) {
                        serverException = cause.getCause();
                        serverLatch.countDown();
                    } else {
                        ctx.fireExceptionCaught(cause);
                    }
                }
            });
            serverConnectedChannel = ch;
        }
    });
    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(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientSslCtx.newHandler(ch.alloc()));
            p.addLast(new MessageDelegatorChannelHandler(clientReceiver, clientLatch));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @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(0)).syncUninterruptibly().channel();
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) SSLException(javax.net.ssl.SSLException) ClosedChannelException(java.nio.channels.ClosedChannelException) CertificateException(java.security.cert.CertificateException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 57 with ChannelHandlerContext

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

the class SniHandlerTest method testSniWithApnHandler.

@Test
public void testSniWithApnHandler() throws Exception {
    SslContext nettyContext = makeSslContext(provider, true);
    SslContext sniContext = makeSslContext(provider, true);
    final SslContext clientContext = makeSslClientContext(provider, true);
    try {
        final CountDownLatch serverApnDoneLatch = new CountDownLatch(1);
        final CountDownLatch clientApnDoneLatch = new CountDownLatch(1);
        final DomainNameMapping<SslContext> mapping = new DomainNameMappingBuilder<SslContext>(nettyContext).add("*.netty.io", nettyContext).add("sni.fake.site", sniContext).build();
        final SniHandler handler = new SniHandler(mapping);
        EventLoopGroup group = new NioEventLoopGroup(2);
        Channel serverChannel = null;
        Channel clientChannel = null;
        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(group);
            sb.channel(NioServerSocketChannel.class);
            sb.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    // Server side SNI.
                    p.addLast(handler);
                    // Catch the notification event that APN has completed successfully.
                    p.addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            serverApnDoneLatch.countDown();
                        }
                    });
                }
            });
            Bootstrap cb = new Bootstrap();
            cb.group(group);
            cb.channel(NioSocketChannel.class);
            cb.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ch.pipeline().addLast(new SslHandler(clientContext.newEngine(ch.alloc(), "sni.fake.site", -1)));
                    // Catch the notification event that APN has completed successfully.
                    ch.pipeline().addLast(new ApplicationProtocolNegotiationHandler("foo") {

                        @Override
                        protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                            clientApnDoneLatch.countDown();
                        }
                    });
                }
            });
            serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
            ChannelFuture ccf = cb.connect(serverChannel.localAddress());
            assertTrue(ccf.awaitUninterruptibly().isSuccess());
            clientChannel = ccf.channel();
            assertTrue(serverApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertTrue(clientApnDoneLatch.await(5, TimeUnit.SECONDS));
            assertThat(handler.hostname(), is("sni.fake.site"));
            assertThat(handler.sslContext(), is(sniContext));
        } finally {
            if (serverChannel != null) {
                serverChannel.close().sync();
            }
            if (clientChannel != null) {
                clientChannel.close().sync();
            }
            group.shutdownGracefully(0, 0, TimeUnit.MICROSECONDS);
        }
    } finally {
        releaseAll(clientContext, nettyContext, sniContext);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) LocalServerChannel(io.netty.channel.local.LocalServerChannel) LocalChannel(io.netty.channel.local.LocalChannel) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) DecoderException(io.netty.handler.codec.DecoderException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) DefaultEventLoopGroup(io.netty.channel.DefaultEventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.Test)

Example 58 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project grpc-java by grpc.

the class ProtocolNegotiatorsTest method tlsHandler_userEventTriggeredSslEvent_supportedProtocolGrpcExp.

@Test
public void tlsHandler_userEventTriggeredSslEvent_supportedProtocolGrpcExp() throws Exception {
    SslHandler goodSslHandler = new SslHandler(engine, false) {

        @Override
        public String applicationProtocol() {
            return "grpc-exp";
        }
    };
    ChannelHandler handler = new ServerTlsHandler(sslContext, grpcHandler);
    pipeline.addLast(handler);
    pipeline.replace(SslHandler.class, null, goodSslHandler);
    channelHandlerCtx = pipeline.context(handler);
    Object sslEvent = SslHandshakeCompletionEvent.SUCCESS;
    pipeline.fireUserEventTriggered(sslEvent);
    assertTrue(channel.isOpen());
    ChannelHandlerContext grpcHandlerCtx = pipeline.context(grpcHandler);
    assertNotNull(grpcHandlerCtx);
}
Also used : ServerTlsHandler(io.grpc.netty.ProtocolNegotiators.ServerTlsHandler) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelHandler(io.netty.channel.ChannelHandler) SslHandler(io.netty.handler.ssl.SslHandler) Test(org.junit.Test)

Example 59 with ChannelHandlerContext

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

the class NettyClientRouter method sendMessage.

/**
     * Send a one way message, without adding a completable future.
     *
     * @param ctx     The context to send the message under.
     * @param message The message to send.
     */
public void sendMessage(ChannelHandlerContext ctx, CorfuMsg message) {
    ChannelHandlerContext outContext = context;
    if (ctx == null) {
        if (context == null) {
            // if the router's context is not set, return a failure
            log.warn("Attempting to send on a channel that is not ready.");
            return;
        }
        outContext = context;
    }
    // Get the next request ID.
    final long thisRequest = requestID.getAndIncrement();
    // Set the base fields for this message.
    message.setClientID(clientID);
    message.setRequestID(thisRequest);
    message.setEpoch(epoch);
    // Write this message out on the channel.
    outContext.writeAndFlush(message);
    MetricsUtils.incConditionalCounter(MetricsUtils.isMetricsCollectionEnabled(), counterAsyncOpSent, 1);
    log.trace("Sent one-way message: {}", message);
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext)

Example 60 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project riposte by Nike-Inc.

the class VerifyCornerCasesComponentTest method invalid_http_call_should_result_in_expected_400_error.

@Test
public void invalid_http_call_should_result_in_expected_400_error() throws Exception {
    // given
    // Normal request, but fiddle with the first chunk as it's going out to remove the HTTP version and make it an
    // invalid HTTP call.
    NettyHttpClientRequestBuilder request = request().withMethod(HttpMethod.GET).withUri(BasicEndpoint.MATCHING_PATH).withPipelineAdjuster(p -> p.addFirst(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            String msgAsString = ((ByteBuf) msg).toString(CharsetUtil.UTF_8);
            if (msgAsString.contains("HTTP/1.1")) {
                msg = Unpooled.copiedBuffer(msgAsString.replace("HTTP/1.1", ""), CharsetUtil.UTF_8);
            }
            super.write(ctx, msg, promise);
        }
    }));
    // when
    NettyHttpClientResponse response = request.execute(downstreamServerConfig.endpointsPort(), 3000);
    // then
    verifyErrorReceived(response.payload, response.statusCode, new ApiErrorWithMetadata(SampleCoreApiError.MALFORMED_REQUEST, Pair.of("cause", "Invalid HTTP request")));
}
Also used : ApiErrorWithMetadata(com.nike.backstopper.apierror.ApiErrorWithMetadata) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) NettyHttpClientResponse(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) NettyHttpClientRequestBuilder(com.nike.riposte.server.testutils.ComponentTestUtils.NettyHttpClientRequestBuilder) Test(org.junit.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111