Search in sources :

Example 16 with ChannelInitializer

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

the class SSLEngineTest method clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer.

@Test(timeout = 30000)
public void clientInitiatedRenegotiationWithFatalAlertDoesNotInfiniteLoopServer() throws CertificateException, SSLException, InterruptedException, ExecutionException {
    final SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(sslServerProvider()).build();
    sb = new ServerBootstrap().group(new NioEventLoopGroup(1)).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            p.addLast(serverSslCtx.newHandler(ch.alloc()));
            p.addLast(new ChannelInboundHandlerAdapter() {

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    if (evt instanceof SslHandshakeCompletionEvent && ((SslHandshakeCompletionEvent) evt).isSuccess()) {
                        // This data will be sent to the client before any of the re-negotiation data can be
                        // sent. The client will read this, detect that it is not the response to
                        // renegotiation which was expected, and respond with a fatal alert.
                        ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(100));
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(final ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // The server then attempts to trigger a flush operation once the application data is
                    // received from the client. The flush will encrypt all data and should not result in
                    // deadlock.
                    ctx.channel().eventLoop().schedule(new Runnable() {

                        @Override
                        public void run() {
                            ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(101));
                        }
                    }, 500, TimeUnit.MILLISECONDS);
                }

                @Override
                public void channelInactive(ChannelHandlerContext ctx) {
                    serverLatch.countDown();
                }
            });
            serverConnectedChannel = ch;
        }
    });
    serverChannel = sb.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
    clientSslCtx = SslContextBuilder.forClient().sslProvider(// OpenSslEngine doesn't support renegotiation on client side
    SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    cb = new Bootstrap();
    cb.group(new NioEventLoopGroup(1)).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) {
            ch.config().setAllocator(new TestByteBufAllocator(ch.config().getAllocator(), type));
            ChannelPipeline p = ch.pipeline();
            SslHandler sslHandler = clientSslCtx.newHandler(ch.alloc());
            // The renegotiate is not expected to succeed, so we should stop trying in a timely manner so
            // the unit test can terminate relativley quicly.
            sslHandler.setHandshakeTimeout(1, TimeUnit.SECONDS);
            p.addLast(sslHandler);
            p.addLast(new ChannelInboundHandlerAdapter() {

                private int handshakeCount;

                @Override
                public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
                    // completed the first renegotiation handshake (which is the second handshake).
                    if (evt instanceof SslHandshakeCompletionEvent && ++handshakeCount == 2) {
                        ctx.close();
                        return;
                    }
                    ctx.fireUserEventTriggered(evt);
                }

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                    ReferenceCountUtil.release(msg);
                    // Simulate a request that the server's application logic will think is invalid.
                    ctx.writeAndFlush(ctx.alloc().buffer(1).writeByte(102));
                    ctx.pipeline().get(SslHandler.class).renegotiate();
                }
            });
        }
    });
    ChannelFuture ccf = cb.connect(serverChannel.localAddress());
    assertTrue(ccf.syncUninterruptibly().isSuccess());
    clientChannel = ccf.channel();
    serverLatch.await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SelfSignedCertificate(io.netty.handler.ssl.util.SelfSignedCertificate) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) 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.Test)

Example 17 with ChannelInitializer

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

the class NettyUdpConnectionlessSendTest method createNettyUdpReceiver.

public void createNettyUdpReceiver() {
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioDatagramChannel.class).handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channel.pipeline().addLast(new UdpHandler());
            channel.pipeline().addLast(new ContentHandler());
        }
    }).localAddress(new InetSocketAddress(getPort()));
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 18 with ChannelInitializer

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

the class LumberjackUtil method sendMessages.

static List<Integer> sendMessages(int port, SSLContextParameters sslContextParameters) throws InterruptedException {
    NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        // This list will hold the acknowledgment response sequence numbers
        List<Integer> responses = new ArrayList<>();
        // This initializer configures the SSL and an acknowledgment recorder
        ChannelInitializer<Channel> initializer = new ChannelInitializer<Channel>() {

            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                if (sslContextParameters != null) {
                    SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
                    sslEngine.setUseClientMode(true);
                    pipeline.addLast(new SslHandler(sslEngine));
                }
                // Add the response recorder
                pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
                        assertEquals(msg.readUnsignedByte(), (short) '2');
                        assertEquals(msg.readUnsignedByte(), (short) 'A');
                        synchronized (responses) {
                            responses.add(msg.readInt());
                        }
                    }
                });
            }
        };
        // Connect to the server
        Channel channel = //
        new Bootstrap().group(//
        eventLoopGroup).channel(//
        NioSocketChannel.class).handler(//
        initializer).connect("127.0.0.1", port).sync().channel();
        // Send the 2 window frames
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window10"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.writeAndFlush(readSample("io/window15"));
        TimeUnit.MILLISECONDS.sleep(100);
        channel.close();
        synchronized (responses) {
            return responses;
        }
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ArrayList(java.util.ArrayList) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) IOException(java.io.IOException) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 19 with ChannelInitializer

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

the class NettyHttpClient method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    this.concurrencyLevel = benchmark.concurrencyLevel;
    this.targetBacklog = benchmark.targetBacklog;
    ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (benchmark.tls) {
                SslClient sslClient = SslClient.localhost();
                SSLEngine engine = sslClient.sslContext.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("inflater", new HttpContentDecompressor());
            pipeline.addLast("handler", new HttpChannel(channel));
        }
    };
    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(concurrencyLevel)).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class).handler(channelInitializer);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) SslClient(okhttp3.internal.tls.SslClient) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

ChannelInitializer (io.netty.channel.ChannelInitializer)19 Channel (io.netty.channel.Channel)13 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)12 InetSocketAddress (java.net.InetSocketAddress)12 ChannelPipeline (io.netty.channel.ChannelPipeline)10 Bootstrap (io.netty.bootstrap.Bootstrap)9 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)8 ChannelFuture (io.netty.channel.ChannelFuture)7 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)6 SocketChannel (io.netty.channel.socket.SocketChannel)6 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)6 SslHandler (io.netty.handler.ssl.SslHandler)6 EventLoopGroup (io.netty.channel.EventLoopGroup)5 Map (java.util.Map)5 VertxInternal (io.vertx.core.impl.VertxInternal)4 ByteBuf (io.netty.buffer.ByteBuf)3 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)3 ChannelOption (io.netty.channel.ChannelOption)3 NioDatagramChannel (io.netty.channel.socket.nio.NioDatagramChannel)3