Search in sources :

Example 1 with ByteToMessageDecoder

use of io.netty.handler.codec.ByteToMessageDecoder in project cassandra by apache.

the class PipelineConfigurator method encryptionConfig.

protected EncryptionConfig encryptionConfig() {
    final EncryptionOptions encryptionOptions = DatabaseDescriptor.getNativeProtocolEncryptionOptions();
    switch(tlsEncryptionPolicy) {
        case UNENCRYPTED:
            // if encryption is not enabled, no further steps are required after the initial setup
            return channel -> {
            };
        case OPTIONAL:
            // If optional, install a handler which detects whether or not the client is sending
            // encrypted bytes. If so, on receipt of the next bytes, replace that handler with
            // an SSL Handler, otherwise just remove it and proceed with an unencrypted channel.
            logger.debug("Enabling optionally encrypted CQL connections between client and server");
            return channel -> {
                SslContext sslContext = SSLFactory.getOrCreateSslContext(encryptionOptions, encryptionOptions.require_client_auth, ISslContextFactory.SocketType.SERVER);
                channel.pipeline().addFirst(SSL_HANDLER, new ByteToMessageDecoder() {

                    @Override
                    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
                        if (byteBuf.readableBytes() < 5) {
                            // once more bytes a ready.
                            return;
                        }
                        if (SslHandler.isEncrypted(byteBuf)) {
                            // Connection uses SSL/TLS, replace the detection handler with a SslHandler and so use
                            // encryption.
                            SslHandler sslHandler = sslContext.newHandler(channel.alloc());
                            channelHandlerContext.pipeline().replace(SSL_HANDLER, SSL_HANDLER, sslHandler);
                        } else {
                            // Connection use no TLS/SSL encryption, just remove the detection handler and continue without
                            // SslHandler in the pipeline.
                            channelHandlerContext.pipeline().remove(SSL_HANDLER);
                        }
                    }
                });
            };
        case ENCRYPTED:
            logger.debug("Enabling encrypted CQL connections between client and server");
            return channel -> {
                SslContext sslContext = SSLFactory.getOrCreateSslContext(encryptionOptions, encryptionOptions.require_client_auth, ISslContextFactory.SocketType.SERVER);
                channel.pipeline().addFirst(SSL_HANDLER, sslContext.newHandler(channel.alloc()));
            };
        default:
            throw new IllegalStateException("Unrecognized TLS encryption policy: " + this.tlsEncryptionPolicy);
    }
}
Also used : LoggingHandler(io.netty.handler.logging.LoggingHandler) ISslContextFactory(org.apache.cassandra.security.ISslContextFactory) LoggerFactory(org.slf4j.LoggerFactory) EncryptionOptions(org.apache.cassandra.config.EncryptionOptions) Strings(com.google.common.base.Strings) ByteBuf(io.netty.buffer.ByteBuf) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SSLFactory(org.apache.cassandra.security.SSLFactory) Map(java.util.Map) StartupMessage(org.apache.cassandra.transport.messages.StartupMessage) io.netty.channel(io.netty.channel) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Logger(org.slf4j.Logger) IdleStateEvent(io.netty.handler.timeout.IdleStateEvent) SslContext(io.netty.handler.ssl.SslContext) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) TimeUnit(java.util.concurrent.TimeUnit) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Version(io.netty.util.Version) List(java.util.List) LogLevel(io.netty.handler.logging.LogLevel) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) org.apache.cassandra.net(org.apache.cassandra.net) List(java.util.List) EncryptionOptions(org.apache.cassandra.config.EncryptionOptions) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) SslContext(io.netty.handler.ssl.SslContext)

Example 2 with ByteToMessageDecoder

use of io.netty.handler.codec.ByteToMessageDecoder 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 3 with ByteToMessageDecoder

use of io.netty.handler.codec.ByteToMessageDecoder in project netty by netty.

the class SocketChannelNotYetConnectedTest method readMustBePendingUntilChannelIsActive.

@Test
@Timeout(30)
public void readMustBePendingUntilChannelIsActive(TestInfo info) throws Throwable {
    run(info, new Runner<Bootstrap>() {

        @Override
        public void run(Bootstrap bootstrap) throws Throwable {
            NioEventLoopGroup group = new NioEventLoopGroup(1);
            ServerBootstrap sb = new ServerBootstrap().group(group);
            Channel serverChannel = sb.childHandler(new ChannelInboundHandlerAdapter() {

                @Override
                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                    ctx.writeAndFlush(Unpooled.copyInt(42));
                }
            }).channel(NioServerSocketChannel.class).bind(0).sync().channel();
            final CountDownLatch readLatch = new CountDownLatch(1);
            bootstrap.handler(new ByteToMessageDecoder() {

                @Override
                public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
                    assertFalse(ctx.channel().isActive());
                    ctx.read();
                }

                @Override
                protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                    assertThat(in.readableBytes()).isLessThanOrEqualTo(Integer.BYTES);
                    if (in.readableBytes() == Integer.BYTES) {
                        assertThat(in.readInt()).isEqualTo(42);
                        readLatch.countDown();
                    }
                }
            });
            bootstrap.connect(serverChannel.localAddress()).sync();
            readLatch.await();
            group.shutdownGracefully().await();
        }
    });
}
Also used : NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) CountDownLatch(java.util.concurrent.CountDownLatch) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) List(java.util.List) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test) Timeout(org.junit.jupiter.api.Timeout)

Example 4 with ByteToMessageDecoder

use of io.netty.handler.codec.ByteToMessageDecoder in project BRFS by zhangnianli.

the class AsyncFileReaderGroup method createClient.

@Override
public TcpClient<ReadObject, FileContentPart> createClient(AsyncFileReaderCreateConfig config, Executor executor) throws InterruptedException {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(group);
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator());
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.connectTimeoutMillis());
    if (executor == null) {
        executor = new Executor() {

            @Override
            public void execute(Runnable command) {
                command.run();
            }
        };
    }
    FileReadClient reader = new FileReadClient(executor);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new ReadObjectEncoder()).addLast(new ByteToMessageDecoder() {

                private int token;

                private int readingLength = 0;

                @Override
                protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
                    if (readingLength == 0) {
                        if (in.readableBytes() < Integer.BYTES * 2) {
                            return;
                        }
                        token = in.readInt();
                        readingLength = in.readInt();
                        if (readingLength < 0) {
                            reader.handle(token, new FileContentPart(null, true));
                            readingLength = 0;
                            return;
                        }
                        if (readingLength == 0) {
                            reader.handle(token, new FileContentPart(new byte[0], true));
                            return;
                        }
                    }
                    int readableLength = Math.min(readingLength, in.readableBytes());
                    if (readableLength == 0) {
                        return;
                    }
                    byte[] bytes = new byte[readableLength];
                    in.readBytes(bytes);
                    readingLength -= readableLength;
                    reader.handle(token, new FileContentPart(bytes, readingLength == 0));
                }
            });
        }
    });
    ChannelFuture future = bootstrap.connect(config.remoteAddress()).sync();
    if (!future.isSuccess()) {
        return null;
    }
    Channel channel = future.channel();
    channelList.add(channel);
    channel.closeFuture().addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            channelList.remove(channel);
        }
    });
    reader.attach(channel);
    return reader;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) SocketChannel(io.netty.channel.socket.SocketChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) IOException(java.io.IOException) Executor(java.util.concurrent.Executor) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) Bootstrap(io.netty.bootstrap.Bootstrap) ArrayList(java.util.ArrayList) List(java.util.List)

Example 5 with ByteToMessageDecoder

use of io.netty.handler.codec.ByteToMessageDecoder in project rskj by rsksmart.

the class NettyTest method pipelineTest.

@Test
public void pipelineTest() {
    final int[] int2 = new int[1];
    final boolean[] exception = new boolean[1];
    final ByteToMessageDecoder decoder2 = new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int i = in.readInt();
            System.out.println("decoder2 read int (4 bytes): " + Integer.toHexString(i));
            int2[0] = i;
            if (i == 0)
                out.add("aaa");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder2 exception: " + cause);
        }
    };
    final MessageToMessageCodec decoder3 = new MessageToMessageCodec<Object, Object>() {

        @Override
        protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            System.out.println("NettyTest.decode: msg = [" + msg + "]");
            if (msg == "aaa") {
                throw new RuntimeException("Test exception 3");
            }
        }

        @Override
        protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
            throw new RuntimeException("Test exception 4");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder3 exception: " + cause);
            exception[0] = true;
        }
    };
    final ByteToMessageDecoder decoder1 = new ByteToMessageDecoder() {

        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            int i = in.readInt();
            System.out.println("decoder1 read int (4 bytes). Needs no more: " + Integer.toHexString(i));
            ctx.pipeline().addAfter("decoder1", "decoder2", decoder2);
            ctx.pipeline().addAfter("decoder2", "decoder3", decoder3);
            ctx.pipeline().remove(this);
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Decoder1 exception: " + cause);
        }
    };
    ChannelInboundHandlerAdapter initiator = new ChannelInboundHandlerAdapter() {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ctx.pipeline().addFirst("decoder1", decoder1);
            System.out.println("NettyTest.channelActive");
        }
    };
    EmbeddedChannel channel0 = new EmbeddedChannel(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            throw new RuntimeException("Test");
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            System.out.println("Exception caught: " + cause);
        }
    });
    EmbeddedChannel channel = new EmbeddedChannel(initiator);
    ByteBuf buffer = Unpooled.buffer();
    buffer.writeInt(0x12345678);
    buffer.writeInt(0xabcdefff);
    channel.writeInbound(buffer);
    Assert.assertEquals(0xabcdefff, int2[0]);
    channel.writeInbound(Unpooled.buffer().writeInt(0));
    Assert.assertTrue(exception[0]);
// Need the following for the exception in outbound handler to be fired
// ctx.writeAndFlush(msg).addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);
// exception[0] = false;
// channel.writeOutbound("outMsg");
// Assert.assertTrue(exception[0]);
}
Also used : MessageToMessageCodec(io.netty.handler.codec.MessageToMessageCodec) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelOutboundHandlerAdapter(io.netty.channel.ChannelOutboundHandlerAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelPromise(io.netty.channel.ChannelPromise) ByteToMessageDecoder(io.netty.handler.codec.ByteToMessageDecoder) ByteBuf(io.netty.buffer.ByteBuf) List(java.util.List) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ByteToMessageDecoder (io.netty.handler.codec.ByteToMessageDecoder)6 ByteBuf (io.netty.buffer.ByteBuf)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)4 List (java.util.List)4 Bootstrap (io.netty.bootstrap.Bootstrap)3 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Channel (io.netty.channel.Channel)3 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)3 ChannelFuture (io.netty.channel.ChannelFuture)2 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)2 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)2 SocketChannel (io.netty.channel.socket.SocketChannel)2 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)2 Strings (com.google.common.base.Strings)1 io.netty.channel (io.netty.channel)1 AdaptiveRecvByteBufAllocator (io.netty.channel.AdaptiveRecvByteBufAllocator)1 ChannelFutureListener (io.netty.channel.ChannelFutureListener)1 ChannelInitializer (io.netty.channel.ChannelInitializer)1 ChannelOutboundHandlerAdapter (io.netty.channel.ChannelOutboundHandlerAdapter)1 ChannelPromise (io.netty.channel.ChannelPromise)1