Search in sources :

Example 56 with ChannelFutureListener

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();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) 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) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) PrematureChannelClosureException(io.netty.handler.codec.PrematureChannelClosureException) CodecException(io.netty.handler.codec.CodecException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Test(org.junit.jupiter.api.Test)

Example 57 with ChannelFutureListener

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);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 58 with ChannelFutureListener

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);
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) EncoderException(io.netty.handler.codec.EncoderException) LZ4Exception(net.jpountz.lz4.LZ4Exception)

Example 59 with ChannelFutureListener

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;
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) SSLEngineResult(javax.net.ssl.SSLEngineResult) CompositeByteBuf(io.netty.buffer.CompositeByteBuf) ByteBuf(io.netty.buffer.ByteBuf) ChannelFutureListener(io.netty.channel.ChannelFutureListener) HandshakeStatus(javax.net.ssl.SSLEngineResult.HandshakeStatus)

Example 60 with ChannelFutureListener

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);
                    }
                });
            }
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) FutureListener(io.netty.util.concurrent.FutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Aggregations

ChannelFutureListener (io.netty.channel.ChannelFutureListener)223 ChannelFuture (io.netty.channel.ChannelFuture)208 Channel (io.netty.channel.Channel)70 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)57 ByteBuf (io.netty.buffer.ByteBuf)49 Bootstrap (io.netty.bootstrap.Bootstrap)43 Test (org.junit.jupiter.api.Test)41 CountDownLatch (java.util.concurrent.CountDownLatch)36 IOException (java.io.IOException)35 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)33 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)31 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)31 InetSocketAddress (java.net.InetSocketAddress)27 ClosedChannelException (java.nio.channels.ClosedChannelException)25 ChannelPromise (io.netty.channel.ChannelPromise)21 Logger (org.slf4j.Logger)21 LoggerFactory (org.slf4j.LoggerFactory)21 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)20 EventLoopGroup (io.netty.channel.EventLoopGroup)18 List (java.util.List)17