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);
}
}
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();
}
}
}
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();
}
});
}
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;
}
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]);
}
Aggregations