use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project netty by netty.
the class HttpClientCodecTest method testServerCloseSocketInputProvidesData.
@Test
public void testServerCloseSocketInputProvidesData() throws InterruptedException {
ServerBootstrap sb = new ServerBootstrap();
Bootstrap cb = new Bootstrap();
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final CountDownLatch responseReceivedLatch = new CountDownLatch(1);
try {
sb.group(new NioEventLoopGroup(2));
sb.channel(NioServerSocketChannel.class);
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
// Don't use the HttpServerCodec, because we don't want to have content-length or anything added.
ch.pipeline().addLast(new HttpRequestDecoder(4096, 8192, 8192, true));
ch.pipeline().addLast(new HttpObjectAggregator(4096));
ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
// This is just a simple demo...don't block in IO
assertTrue(ctx.channel() instanceof SocketChannel);
final SocketChannel sChannel = (SocketChannel) ctx.channel();
/**
* The point of this test is to not add any content-length or content-encoding headers
* and the client should still handle this.
* See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230, 3.3.3</a>.
*/
sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" + "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" + "Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.writeAndFlush(Unpooled.wrappedBuffer("<html><body>hello half closed!</body></html>\r\n".getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.shutdownOutput();
}
});
}
});
}
});
serverChannelLatch.countDown();
}
});
cb.group(new NioEventLoopGroup(1));
cb.channel(NioSocketChannel.class);
cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true);
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new HttpClientCodec(4096, 8192, 8192, true, true));
ch.pipeline().addLast(new HttpObjectAggregator(4096));
ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
responseReceivedLatch.countDown();
}
});
}
});
Channel serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
assertTrue(ccf.awaitUninterruptibly().isSuccess());
Channel clientChannel = ccf.channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
clientChannel.writeAndFlush(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
assertTrue(responseReceivedLatch.await(5, SECONDS));
} finally {
sb.config().group().shutdownGracefully();
sb.config().childGroup().shutdownGracefully();
cb.config().group().shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project netty by netty.
the class JdkZlibEncoder method close.
@Override
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
}, THREAD_POOL_DELAY_SECONDS, TimeUnit.SECONDS);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project netty by netty.
the class Lz4FrameEncoder method close.
@Override
public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
ChannelFuture f = finishEncode(ctx, ctx.newPromise());
f.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) throws Exception {
ctx.close(promise);
}
});
if (!f.isDone()) {
// Ensure the channel is closed even if the write operation completes in time.
ctx.executor().schedule(new Runnable() {
@Override
public void run() {
ctx.close(promise);
}
}, THREAD_POOL_DELAY_SECONDS, TimeUnit.SECONDS);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project netty by netty.
the class SslHandler method wrapNonAppData.
/**
* This method will not call
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or
* {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}.
* @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
*/
private boolean wrapNonAppData(final ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
ByteBuf out = null;
ByteBufAllocator alloc = ctx.alloc();
try {
// See https://github.com/netty/netty/issues/5860
outer: while (!ctx.isRemoved()) {
if (out == null) {
// As this is called for the handshake we have no real idea how big the buffer needs to be.
// That said 2048 should give us enough room to include everything like ALPN / NPN data.
// If this is not enough we will increase the buffer in wrap(...).
out = allocateOutNetBuf(ctx, 2048, 1);
}
SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);
if (result.bytesProduced() > 0) {
ctx.write(out).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
Throwable cause = future.cause();
if (cause != null) {
setHandshakeFailureTransportFailure(ctx, cause);
}
}
});
if (inUnwrap) {
setState(STATE_NEEDS_FLUSH);
}
out = null;
}
HandshakeStatus status = result.getHandshakeStatus();
switch(status) {
case FINISHED:
// attempt to wrap application data here if any is pending.
if (setHandshakeSuccess() && inUnwrap && !pendingUnencryptedWrites.isEmpty()) {
wrap(ctx, true);
}
return false;
case NEED_TASK:
if (!runDelegatedTasks(inUnwrap)) {
// resume once the task completes.
break outer;
}
break;
case NEED_UNWRAP:
if (inUnwrap || unwrapNonAppData(ctx) <= 0) {
// return) to feed more data to the engine.
return false;
}
break;
case NEED_WRAP:
break;
case NOT_HANDSHAKING:
if (setHandshakeSuccess() && inUnwrap && !pendingUnencryptedWrites.isEmpty()) {
wrap(ctx, true);
}
// https://github.com/netty/netty/issues/1108#issuecomment-14266970
if (!inUnwrap) {
unwrapNonAppData(ctx);
}
return true;
default:
throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus());
}
// a task as last action. It's fine to not produce any data as part of executing a task.
if (result.bytesProduced() == 0 && status != HandshakeStatus.NEED_TASK) {
break;
}
// Fix for Android, where it was encrypting empty buffers even when not handshaking
if (result.bytesConsumed() == 0 && result.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
break;
}
}
} finally {
if (out != null) {
out.release();
}
}
return false;
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener in project netty by netty.
the class SslHandler method safeClose.
private void safeClose(final ChannelHandlerContext ctx, final ChannelFuture flushFuture, final ChannelPromise promise) {
if (!ctx.channel().isActive()) {
ctx.close(promise);
return;
}
final Future<?> timeoutFuture;
if (!flushFuture.isDone()) {
long closeNotifyTimeout = closeNotifyFlushTimeoutMillis;
if (closeNotifyTimeout > 0) {
// Force-close the connection if close_notify is not fully sent in time.
timeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
// May be done in the meantime as cancel(...) is only best effort.
if (!flushFuture.isDone()) {
logger.warn("{} Last write attempt timed out; force-closing the connection.", ctx.channel());
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyTimeout, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
} else {
timeoutFuture = null;
}
// Close the connection if close_notify is sent in time.
flushFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture f) {
if (timeoutFuture != null) {
timeoutFuture.cancel(false);
}
final long closeNotifyReadTimeout = closeNotifyReadTimeoutMillis;
if (closeNotifyReadTimeout <= 0) {
// Trigger the close in all cases to make sure the promise is notified
// See https://github.com/netty/netty/issues/2358
addCloseListener(ctx.close(ctx.newPromise()), promise);
} else {
final Future<?> closeNotifyReadTimeoutFuture;
if (!sslClosePromise.isDone()) {
closeNotifyReadTimeoutFuture = ctx.executor().schedule(new Runnable() {
@Override
public void run() {
if (!sslClosePromise.isDone()) {
logger.debug("{} did not receive close_notify in {}ms; force-closing the connection.", ctx.channel(), closeNotifyReadTimeout);
// Do the close now...
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
}
}, closeNotifyReadTimeout, TimeUnit.MILLISECONDS);
} else {
closeNotifyReadTimeoutFuture = null;
}
// Do the close once the we received the close_notify.
sslClosePromise.addListener(new FutureListener<Channel>() {
@Override
public void operationComplete(Future<Channel> future) throws Exception {
if (closeNotifyReadTimeoutFuture != null) {
closeNotifyReadTimeoutFuture.cancel(false);
}
addCloseListener(ctx.close(ctx.newPromise()), promise);
}
});
}
}
});
}
Aggregations