package io.netty.handler.codec.http2;

import g.a.a.a.a;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.handler.codec.http.HttpServerUpgradeHandler;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2Exception;
import io.netty.handler.codec.http2.Http2RemoteFlowController;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.handler.codec.http2.HttpConversionUtil;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

/* JADX INFO: loaded from: classes.dex */
public class Http2FrameCodec extends Http2ConnectionHandler {
    public static final /* synthetic */ boolean $assertionsDisabled = false;
    private static final InternalLogger LOG = InternalLoggerFactory.getInstance((Class<?>) Http2FrameCodec.class);
    private ChannelHandlerContext ctx;
    private DefaultHttp2FrameStream frameStreamToInitialize;
    private final Integer initialFlowControlWindowSize;
    private int numBufferedStreams;
    private final Http2Connection.PropertyKey streamKey;
    private final Http2Connection.PropertyKey upgradeKey;

    public final class ConnectionListener extends Http2ConnectionAdapter {
        private ConnectionListener() {
        }

        @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
        public void onStreamActive(Http2Stream http2Stream) {
            Http2FrameCodec.this.onStreamActive0(http2Stream);
        }

        @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
        public void onStreamAdded(Http2Stream http2Stream) {
            if (Http2FrameCodec.this.frameStreamToInitialize == null || http2Stream.id() != Http2FrameCodec.this.frameStreamToInitialize.id()) {
                return;
            }
            Http2FrameCodec.this.frameStreamToInitialize.setStreamAndProperty(Http2FrameCodec.this.streamKey, http2Stream);
            Http2FrameCodec.this.frameStreamToInitialize = null;
        }

        @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
        public void onStreamClosed(Http2Stream http2Stream) {
            DefaultHttp2FrameStream defaultHttp2FrameStream = (DefaultHttp2FrameStream) http2Stream.getProperty(Http2FrameCodec.this.streamKey);
            if (defaultHttp2FrameStream != null) {
                Http2FrameCodec http2FrameCodec = Http2FrameCodec.this;
                http2FrameCodec.onHttp2StreamStateChanged(http2FrameCodec.ctx, defaultHttp2FrameStream);
            }
        }

        @Override // io.netty.handler.codec.http2.Http2ConnectionAdapter, io.netty.handler.codec.http2.Http2Connection.Listener
        public void onStreamHalfClosed(Http2Stream http2Stream) {
            DefaultHttp2FrameStream defaultHttp2FrameStream = (DefaultHttp2FrameStream) http2Stream.getProperty(Http2FrameCodec.this.streamKey);
            if (defaultHttp2FrameStream != null) {
                Http2FrameCodec http2FrameCodec = Http2FrameCodec.this;
                http2FrameCodec.onHttp2StreamStateChanged(http2FrameCodec.ctx, defaultHttp2FrameStream);
            }
        }
    }

    public static class DefaultHttp2FrameStream implements Http2FrameStream {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        private volatile int id = -1;
        public volatile Http2Stream stream;

        @Override // io.netty.handler.codec.http2.Http2FrameStream
        public int id() {
            Http2Stream http2Stream = this.stream;
            return http2Stream == null ? this.id : http2Stream.id();
        }

        public DefaultHttp2FrameStream setStreamAndProperty(Http2Connection.PropertyKey propertyKey, Http2Stream http2Stream) {
            this.stream = http2Stream;
            http2Stream.setProperty(propertyKey, this);
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2FrameStream
        public Http2Stream.State state() {
            Http2Stream http2Stream = this.stream;
            return http2Stream == null ? Http2Stream.State.IDLE : http2Stream.state();
        }

        public String toString() {
            return String.valueOf(id());
        }
    }

    public final class FrameListener implements Http2FrameListener {
        private FrameListener() {
        }

        private Http2FrameStream requireStream(int i2) {
            Http2FrameStream http2FrameStream = (Http2FrameStream) Http2FrameCodec.this.connection().stream(i2).getProperty(Http2FrameCodec.this.streamKey);
            if (http2FrameStream != null) {
                return http2FrameStream;
            }
            throw new IllegalStateException(a.l("Stream object required for identifier: ", i2));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public int onDataRead(ChannelHandlerContext channelHandlerContext, int i2, ByteBuf byteBuf, int i3, boolean z2) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2DataFrame(byteBuf, z2, i3).stream(requireStream(i2)).retain());
            return 0;
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onGoAwayRead(ChannelHandlerContext channelHandlerContext, int i2, long j2, ByteBuf byteBuf) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2GoAwayFrame(i2, j2, byteBuf).retain());
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onHeadersRead(ChannelHandlerContext channelHandlerContext, int i2, Http2Headers http2Headers, int i3, short s2, boolean z2, int i4, boolean z3) {
            onHeadersRead(channelHandlerContext, i2, http2Headers, i4, z3);
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onHeadersRead(ChannelHandlerContext channelHandlerContext, int i2, Http2Headers http2Headers, int i3, boolean z2) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2HeadersFrame(http2Headers, z2, i3).stream(requireStream(i2)));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onPingAckRead(ChannelHandlerContext channelHandlerContext, long j2) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2PingFrame(j2, true));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onPingRead(ChannelHandlerContext channelHandlerContext, long j2) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2PingFrame(j2, false));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onPriorityRead(ChannelHandlerContext channelHandlerContext, int i2, int i3, short s2, boolean z2) {
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onPushPromiseRead(ChannelHandlerContext channelHandlerContext, int i2, int i3, Http2Headers http2Headers, int i4) {
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onRstStreamRead(ChannelHandlerContext channelHandlerContext, int i2, long j2) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2ResetFrame(j2).stream(requireStream(i2)));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onSettingsAckRead(ChannelHandlerContext channelHandlerContext) {
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onSettingsRead(ChannelHandlerContext channelHandlerContext, Http2Settings http2Settings) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2SettingsFrame(http2Settings));
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onUnknownFrame(ChannelHandlerContext channelHandlerContext, byte b2, int i2, Http2Flags http2Flags, ByteBuf byteBuf) {
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2UnknownFrame(b2, http2Flags, byteBuf).stream(requireStream(i2)).retain());
        }

        @Override // io.netty.handler.codec.http2.Http2FrameListener
        public void onWindowUpdateRead(ChannelHandlerContext channelHandlerContext, int i2, int i3) {
            if (i2 == 0) {
                return;
            }
            Http2FrameCodec.this.onHttp2Frame(channelHandlerContext, new DefaultHttp2WindowUpdateFrame(i3).stream(requireStream(i2)));
        }
    }

    public final class Http2RemoteFlowControllerListener implements Http2RemoteFlowController.Listener {
        private Http2RemoteFlowControllerListener() {
        }

        @Override // io.netty.handler.codec.http2.Http2RemoteFlowController.Listener
        public void writabilityChanged(Http2Stream http2Stream) {
            Http2FrameStream http2FrameStream = (Http2FrameStream) http2Stream.getProperty(Http2FrameCodec.this.streamKey);
            if (http2FrameStream == null) {
                return;
            }
            Http2FrameCodec http2FrameCodec = Http2FrameCodec.this;
            http2FrameCodec.onHttp2StreamWritabilityChanged(http2FrameCodec.ctx, http2FrameStream, ((Http2RemoteFlowController) Http2FrameCodec.this.connection().remote().flowController()).isWritable(http2Stream));
        }
    }

    public Http2FrameCodec(Http2ConnectionEncoder http2ConnectionEncoder, Http2ConnectionDecoder http2ConnectionDecoder, Http2Settings http2Settings) {
        super(http2ConnectionDecoder, http2ConnectionEncoder, http2Settings);
        http2ConnectionDecoder.frameListener(new FrameListener());
        connection().addListener(new ConnectionListener());
        ((Http2RemoteFlowController) connection().remote().flowController()).listener(new Http2RemoteFlowControllerListener());
        this.streamKey = connection().newKey();
        this.upgradeKey = connection().newKey();
        this.initialFlowControlWindowSize = http2Settings.initialWindowSize();
    }

    public static /* synthetic */ int access$610(Http2FrameCodec http2FrameCodec) {
        int i2 = http2FrameCodec.numBufferedStreams;
        http2FrameCodec.numBufferedStreams = i2 - 1;
        return i2;
    }

    private void increaseInitialConnectionWindow(int i2) {
        ((Http2LocalFlowController) connection().local().flowController()).incrementWindowSize(connection().connectionStream(), i2);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public static void notifyHeaderWritePromise(ChannelFuture channelFuture, ChannelPromise channelPromise) {
        Throwable thCause = channelFuture.cause();
        if (thCause == null) {
            channelPromise.setSuccess();
        } else {
            channelPromise.setFailure(thCause);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void onStreamActive0(Http2Stream http2Stream) {
        if (connection().local().isValidStreamId(http2Stream.id())) {
            return;
        }
        onHttp2StreamStateChanged(this.ctx, newStream().setStreamAndProperty(this.streamKey, http2Stream));
    }

    private void tryExpandConnectionFlowControlWindow(Http2Connection http2Connection) {
        if (this.initialFlowControlWindowSize != null) {
            Http2Stream http2StreamConnectionStream = http2Connection.connectionStream();
            Http2LocalFlowController http2LocalFlowController = (Http2LocalFlowController) http2Connection.local().flowController();
            int iIntValue = this.initialFlowControlWindowSize.intValue() - http2LocalFlowController.initialWindowSize(http2StreamConnectionStream);
            if (iIntValue > 0) {
                http2LocalFlowController.incrementWindowSize(http2StreamConnectionStream, Math.max(iIntValue << 1, iIntValue));
                flush(this.ctx);
            }
        }
    }

    private void writeGoAwayFrame(ChannelHandlerContext channelHandlerContext, Http2GoAwayFrame http2GoAwayFrame, ChannelPromise channelPromise) {
        if (http2GoAwayFrame.lastStreamId() > -1) {
            http2GoAwayFrame.release();
            throw new IllegalArgumentException("Last stream id must not be set on GOAWAY frame");
        }
        long jExtraStreamIds = (((long) http2GoAwayFrame.extraStreamIds()) * 2) + ((long) connection().remote().lastStreamCreated());
        if (jExtraStreamIds > 2147483647L) {
            jExtraStreamIds = 2147483647L;
        }
        goAway(channelHandlerContext, (int) jExtraStreamIds, http2GoAwayFrame.errorCode(), http2GoAwayFrame.content(), channelPromise);
    }

    private void writeHeadersFrame(ChannelHandlerContext channelHandlerContext, Http2HeadersFrame http2HeadersFrame, final ChannelPromise channelPromise) {
        if (Http2CodecUtil.isStreamIdValid(http2HeadersFrame.stream().id())) {
            encoder().writeHeaders(channelHandlerContext, http2HeadersFrame.stream().id(), http2HeadersFrame.headers(), http2HeadersFrame.padding(), http2HeadersFrame.isEndStream(), channelPromise);
            return;
        }
        DefaultHttp2FrameStream defaultHttp2FrameStream = (DefaultHttp2FrameStream) http2HeadersFrame.stream();
        int iIncrementAndGetNextStreamId = connection().local().incrementAndGetNextStreamId();
        if (iIncrementAndGetNextStreamId < 0) {
            channelPromise.setFailure((Throwable) new Http2NoMoreStreamIdsException());
            return;
        }
        defaultHttp2FrameStream.id = iIncrementAndGetNextStreamId;
        this.frameStreamToInitialize = defaultHttp2FrameStream;
        ChannelPromise channelPromiseNewPromise = channelHandlerContext.newPromise();
        encoder().writeHeaders(channelHandlerContext, iIncrementAndGetNextStreamId, http2HeadersFrame.headers(), http2HeadersFrame.padding(), http2HeadersFrame.isEndStream(), channelPromiseNewPromise);
        if (channelPromiseNewPromise.isDone()) {
            notifyHeaderWritePromise(channelPromiseNewPromise, channelPromise);
        } else {
            this.numBufferedStreams++;
            channelPromiseNewPromise.addListener((GenericFutureListener<? extends Future<? super Void>>) new ChannelFutureListener() { // from class: io.netty.handler.codec.http2.Http2FrameCodec.2
                @Override // io.netty.util.concurrent.GenericFutureListener
                public void operationComplete(ChannelFuture channelFuture) {
                    Http2FrameCodec.access$610(Http2FrameCodec.this);
                    Http2FrameCodec.notifyHeaderWritePromise(channelFuture, channelPromise);
                }
            });
        }
    }

    public final boolean consumeBytes(int i2, int i3) {
        Http2Stream http2StreamStream = connection().stream(i2);
        if (i2 == 1) {
            if (Boolean.TRUE.equals((Boolean) http2StreamStream.getProperty(this.upgradeKey))) {
                return false;
            }
        }
        return ((Http2LocalFlowController) connection().local().flowController()).consumeBytes(http2StreamStream, i3);
    }

    public final void forEachActiveStream(final Http2FrameStreamVisitor http2FrameStreamVisitor) {
        connection().forEachActiveStream(new Http2StreamVisitor() { // from class: io.netty.handler.codec.http2.Http2FrameCodec.1
            @Override // io.netty.handler.codec.http2.Http2StreamVisitor
            public boolean visit(Http2Stream http2Stream) {
                try {
                    return http2FrameStreamVisitor.visit((Http2FrameStream) http2Stream.getProperty(Http2FrameCodec.this.streamKey));
                } catch (Throwable th) {
                    Http2FrameCodec http2FrameCodec = Http2FrameCodec.this;
                    http2FrameCodec.onError(http2FrameCodec.ctx, false, th);
                    return false;
                }
            }
        });
    }

    @Override // io.netty.handler.codec.http2.Http2ConnectionHandler, io.netty.channel.ChannelHandlerAdapter, io.netty.channel.ChannelHandler
    public final void handlerAdded(ChannelHandlerContext channelHandlerContext) {
        this.ctx = channelHandlerContext;
        super.handlerAdded(channelHandlerContext);
        handlerAdded0(channelHandlerContext);
        Http2Connection http2ConnectionConnection = connection();
        if (http2ConnectionConnection.isServer()) {
            tryExpandConnectionFlowControlWindow(http2ConnectionConnection);
        }
    }

    public void handlerAdded0(ChannelHandlerContext channelHandlerContext) {
    }

    @Override // io.netty.handler.codec.http2.Http2ConnectionHandler
    public final boolean isGracefulShutdownComplete() {
        return super.isGracefulShutdownComplete() && this.numBufferedStreams == 0;
    }

    public final boolean isWritable(DefaultHttp2FrameStream defaultHttp2FrameStream) {
        Http2Stream http2Stream = defaultHttp2FrameStream.stream;
        return http2Stream != null && ((Http2RemoteFlowController) connection().remote().flowController()).isWritable(http2Stream);
    }

    public DefaultHttp2FrameStream newStream() {
        return new DefaultHttp2FrameStream();
    }

    @Override // io.netty.handler.codec.http2.Http2ConnectionHandler
    public void onConnectionError(ChannelHandlerContext channelHandlerContext, boolean z2, Throwable th, Http2Exception http2Exception) {
        if (!z2) {
            channelHandlerContext.fireExceptionCaught(th);
        }
        super.onConnectionError(channelHandlerContext, z2, th, http2Exception);
    }

    public void onHttp2Frame(ChannelHandlerContext channelHandlerContext, Http2Frame http2Frame) {
        channelHandlerContext.fireChannelRead((Object) http2Frame);
    }

    public void onHttp2FrameStreamException(ChannelHandlerContext channelHandlerContext, Http2FrameStreamException http2FrameStreamException) {
        channelHandlerContext.fireExceptionCaught((Throwable) http2FrameStreamException);
    }

    public void onHttp2StreamStateChanged(ChannelHandlerContext channelHandlerContext, Http2FrameStream http2FrameStream) {
        channelHandlerContext.fireUserEventTriggered((Object) Http2FrameStreamEvent.stateChanged(http2FrameStream));
    }

    public void onHttp2StreamWritabilityChanged(ChannelHandlerContext channelHandlerContext, Http2FrameStream http2FrameStream, boolean z2) {
        channelHandlerContext.fireUserEventTriggered((Object) Http2FrameStreamEvent.writabilityChanged(http2FrameStream));
    }

    public void onHttp2UnknownStreamError(ChannelHandlerContext channelHandlerContext, Throwable th, Http2Exception.StreamException streamException) {
        LOG.warn("Stream exception thrown for unkown stream {}.", Integer.valueOf(streamException.streamId()), th);
    }

    @Override // io.netty.handler.codec.http2.Http2ConnectionHandler
    public final void onStreamError(ChannelHandlerContext channelHandlerContext, boolean z2, Throwable th, Http2Exception.StreamException streamException) {
        Http2Stream http2StreamStream = connection().stream(streamException.streamId());
        if (http2StreamStream == null) {
            onHttp2UnknownStreamError(channelHandlerContext, th, streamException);
        } else {
            Http2FrameStream http2FrameStream = (Http2FrameStream) http2StreamStream.getProperty(this.streamKey);
            if (http2FrameStream != null) {
                if (z2) {
                    return;
                }
                onHttp2FrameStreamException(channelHandlerContext, new Http2FrameStreamException(http2FrameStream, streamException.error(), th));
                return;
            }
            LOG.warn("Stream exception thrown without stream object attached.", th);
        }
        super.onStreamError(channelHandlerContext, z2, th, streamException);
    }

    public void onUpgradeEvent(ChannelHandlerContext channelHandlerContext, HttpServerUpgradeHandler.UpgradeEvent upgradeEvent) {
        channelHandlerContext.fireUserEventTriggered((Object) upgradeEvent);
    }

    @Override // io.netty.handler.codec.ByteToMessageDecoder, io.netty.channel.ChannelInboundHandlerAdapter, io.netty.channel.ChannelInboundHandler
    public final void userEventTriggered(ChannelHandlerContext channelHandlerContext, Object obj) {
        if (obj == Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE) {
            tryExpandConnectionFlowControlWindow(connection());
        } else if (obj instanceof HttpServerUpgradeHandler.UpgradeEvent) {
            HttpServerUpgradeHandler.UpgradeEvent upgradeEvent = (HttpServerUpgradeHandler.UpgradeEvent) obj;
            try {
                onUpgradeEvent(channelHandlerContext, upgradeEvent.retain());
                Http2Stream http2StreamStream = connection().stream(1);
                if (http2StreamStream.getProperty(this.streamKey) == null) {
                    onStreamActive0(http2StreamStream);
                }
                upgradeEvent.upgradeRequest().headers().setInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(), 1);
                http2StreamStream.setProperty(this.upgradeKey, Boolean.TRUE);
                InboundHttpToHttp2Adapter.handle(channelHandlerContext, connection(), decoder().frameListener(), upgradeEvent.upgradeRequest().retain());
                return;
            } finally {
                upgradeEvent.release();
            }
        }
        super.userEventTriggered(channelHandlerContext, obj);
    }

    @Override // io.netty.handler.codec.http2.Http2ConnectionHandler, io.netty.channel.ChannelOutboundHandler
    public void write(ChannelHandlerContext channelHandlerContext, Object obj, ChannelPromise channelPromise) {
        if (obj instanceof Http2DataFrame) {
            Http2DataFrame http2DataFrame = (Http2DataFrame) obj;
            encoder().writeData(channelHandlerContext, http2DataFrame.stream().id(), http2DataFrame.content(), http2DataFrame.padding(), http2DataFrame.isEndStream(), channelPromise);
            return;
        }
        if (obj instanceof Http2HeadersFrame) {
            writeHeadersFrame(channelHandlerContext, (Http2HeadersFrame) obj, channelPromise);
            return;
        }
        if (obj instanceof Http2WindowUpdateFrame) {
            Http2WindowUpdateFrame http2WindowUpdateFrame = (Http2WindowUpdateFrame) obj;
            Http2FrameStream http2FrameStreamStream = http2WindowUpdateFrame.stream();
            try {
                if (http2FrameStreamStream == null) {
                    increaseInitialConnectionWindow(http2WindowUpdateFrame.windowSizeIncrement());
                } else {
                    consumeBytes(http2FrameStreamStream.id(), http2WindowUpdateFrame.windowSizeIncrement());
                }
                channelPromise.setSuccess();
                return;
            } catch (Throwable th) {
                channelPromise.setFailure(th);
                return;
            }
        }
        if (obj instanceof Http2ResetFrame) {
            Http2ResetFrame http2ResetFrame = (Http2ResetFrame) obj;
            encoder().writeRstStream(channelHandlerContext, http2ResetFrame.stream().id(), http2ResetFrame.errorCode(), channelPromise);
            return;
        }
        if (obj instanceof Http2PingFrame) {
            Http2PingFrame http2PingFrame = (Http2PingFrame) obj;
            encoder().writePing(channelHandlerContext, http2PingFrame.ack(), http2PingFrame.content(), channelPromise);
        } else {
            if (obj instanceof Http2SettingsFrame) {
                encoder().writeSettings(channelHandlerContext, ((Http2SettingsFrame) obj).settings(), channelPromise);
                return;
            }
            if (obj instanceof Http2GoAwayFrame) {
                writeGoAwayFrame(channelHandlerContext, (Http2GoAwayFrame) obj, channelPromise);
            } else {
                if (obj instanceof Http2Frame) {
                    ReferenceCountUtil.release(obj);
                    throw new UnsupportedMessageTypeException(obj, (Class<?>[]) new Class[0]);
                }
                channelHandlerContext.write(obj, channelPromise);
            }
        }
    }
}
