package io.netty.handler.codec.http2;

import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http2.Http2Connection;
import io.netty.handler.codec.http2.Http2Stream;
import io.netty.util.collection.IntObjectHashMap;
import io.netty.util.collection.IntObjectMap;
import io.netty.util.concurrent.Promise;
import io.netty.util.internal.EmptyArrays;
import io.netty.util.internal.ObjectUtil;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;

/* JADX INFO: loaded from: classes.dex */
public class DefaultHttp2Connection implements Http2Connection {
    private static final InternalLogger logger = InternalLoggerFactory.getInstance((Class<?>) DefaultHttp2Connection.class);
    public final ActiveStreams activeStreams;
    public Promise<Void> closePromise;
    public final ConnectionStream connectionStream;
    public final List<Http2Connection.Listener> listeners;
    public final DefaultEndpoint<Http2LocalFlowController> localEndpoint;
    public final PropertyKeyRegistry propertyKeyRegistry;
    public final DefaultEndpoint<Http2RemoteFlowController> remoteEndpoint;
    public final IntObjectMap<Http2Stream> streamMap;

    /* JADX INFO: renamed from: io.netty.handler.codec.http2.DefaultHttp2Connection$3, reason: invalid class name */
    public static /* synthetic */ class AnonymousClass3 {
        public static final /* synthetic */ int[] $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State;

        static {
            Http2Stream.State.values();
            int[] iArr = new int[7];
            $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State = iArr;
            try {
                iArr[Http2Stream.State.IDLE.ordinal()] = 1;
            } catch (NoSuchFieldError unused) {
            }
            try {
                $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State[Http2Stream.State.RESERVED_LOCAL.ordinal()] = 2;
            } catch (NoSuchFieldError unused2) {
            }
            try {
                $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State[Http2Stream.State.RESERVED_REMOTE.ordinal()] = 3;
            } catch (NoSuchFieldError unused3) {
            }
            try {
                $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State[Http2Stream.State.OPEN.ordinal()] = 4;
            } catch (NoSuchFieldError unused4) {
            }
            try {
                $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State[Http2Stream.State.HALF_CLOSED_LOCAL.ordinal()] = 5;
            } catch (NoSuchFieldError unused5) {
            }
            try {
                $SwitchMap$io$netty$handler$codec$http2$Http2Stream$State[Http2Stream.State.HALF_CLOSED_REMOTE.ordinal()] = 6;
            } catch (NoSuchFieldError unused6) {
            }
        }
    }

    public final class ActiveStreams {
        private final List<Http2Connection.Listener> listeners;
        private int pendingIterations;
        private final Queue<Event> pendingEvents = new ArrayDeque(4);
        private final Set<Http2Stream> streams = new LinkedHashSet();

        public ActiveStreams(List<Http2Connection.Listener> list) {
            this.listeners = list;
        }

        public void activate(final DefaultStream defaultStream) {
            if (allowModifications()) {
                addToActiveStreams(defaultStream);
            } else {
                this.pendingEvents.add(new Event() { // from class: io.netty.handler.codec.http2.DefaultHttp2Connection.ActiveStreams.1
                    @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.Event
                    public void process() {
                        ActiveStreams.this.addToActiveStreams(defaultStream);
                    }
                });
            }
        }

        public void addToActiveStreams(DefaultStream defaultStream) {
            if (this.streams.add(defaultStream)) {
                defaultStream.createdBy().numActiveStreams++;
                for (int i2 = 0; i2 < this.listeners.size(); i2++) {
                    try {
                        this.listeners.get(i2).onStreamActive(defaultStream);
                    } catch (Throwable th) {
                        DefaultHttp2Connection.logger.error("Caught Throwable from listener onStreamActive.", th);
                    }
                }
            }
        }

        public boolean allowModifications() {
            return this.pendingIterations == 0;
        }

        public void deactivate(final DefaultStream defaultStream, final Iterator<?> it) {
            if (allowModifications() || it != null) {
                removeFromActiveStreams(defaultStream, it);
            } else {
                this.pendingEvents.add(new Event() { // from class: io.netty.handler.codec.http2.DefaultHttp2Connection.ActiveStreams.2
                    @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.Event
                    public void process() {
                        ActiveStreams.this.removeFromActiveStreams(defaultStream, it);
                    }
                });
            }
        }

        public void decrementPendingIterations() {
            this.pendingIterations--;
            if (!allowModifications()) {
                return;
            }
            while (true) {
                Event eventPoll = this.pendingEvents.poll();
                if (eventPoll == null) {
                    return;
                }
                try {
                    eventPoll.process();
                } catch (Throwable th) {
                    DefaultHttp2Connection.logger.error("Caught Throwable while processing pending ActiveStreams$Event.", th);
                }
            }
        }

        public Http2Stream forEachActiveStream(Http2StreamVisitor http2StreamVisitor) {
            incrementPendingIterations();
            try {
                for (Http2Stream http2Stream : this.streams) {
                    if (!http2StreamVisitor.visit(http2Stream)) {
                        return http2Stream;
                    }
                }
                return null;
            } finally {
                decrementPendingIterations();
            }
        }

        public void incrementPendingIterations() {
            this.pendingIterations++;
        }

        public void removeFromActiveStreams(DefaultStream defaultStream, Iterator<?> it) {
            if (this.streams.remove(defaultStream)) {
                DefaultEndpoint<? extends Http2FlowController> defaultEndpointCreatedBy = defaultStream.createdBy();
                defaultEndpointCreatedBy.numActiveStreams--;
                DefaultHttp2Connection.this.notifyClosed(defaultStream);
            }
            DefaultHttp2Connection.this.removeStream(defaultStream, it);
        }

        public int size() {
            return this.streams.size();
        }
    }

    public final class ConnectionStream extends DefaultStream {
        public ConnectionStream() {
            super(0, Http2Stream.State.IDLE);
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream close() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream closeLocalSide() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream closeRemoteSide() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream
        public DefaultEndpoint<? extends Http2FlowController> createdBy() {
            return null;
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream headersSent(boolean z2) {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public boolean isHeadersSent() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public boolean isPushPromiseSent() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public boolean isResetSent() {
            return false;
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream open(boolean z2) {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream pushPromiseSent() {
            throw new UnsupportedOperationException();
        }

        @Override // io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream, io.netty.handler.codec.http2.Http2Stream
        public Http2Stream resetSent() {
            throw new UnsupportedOperationException();
        }
    }

    public final class DefaultEndpoint<F extends Http2FlowController> implements Http2Connection.Endpoint<F> {
        public static final /* synthetic */ boolean $assertionsDisabled = false;
        private F flowController;
        private int lastStreamKnownByPeer = -1;
        private int maxActiveStreams;
        private final int maxReservedStreams;
        private int maxStreams;
        private int nextReservationStreamId;
        private int nextStreamIdToCreate;
        public int numActiveStreams;
        public int numStreams;
        private boolean pushToAllowed;
        private final boolean server;

        public DefaultEndpoint(boolean z2, int i2) {
            this.pushToAllowed = true;
            this.server = z2;
            if (z2) {
                this.nextStreamIdToCreate = 2;
                this.nextReservationStreamId = 0;
            } else {
                this.nextStreamIdToCreate = 1;
                this.nextReservationStreamId = 1;
            }
            this.pushToAllowed = true ^ z2;
            this.maxActiveStreams = Integer.MAX_VALUE;
            this.maxReservedStreams = ObjectUtil.checkPositiveOrZero(i2, "maxReservedStreams");
            updateMaxStreams();
        }

        private void addStream(DefaultStream defaultStream) {
            DefaultHttp2Connection.this.streamMap.put(defaultStream.id(), defaultStream);
            for (int i2 = 0; i2 < DefaultHttp2Connection.this.listeners.size(); i2++) {
                try {
                    DefaultHttp2Connection.this.listeners.get(i2).onStreamAdded(defaultStream);
                } catch (Throwable th) {
                    DefaultHttp2Connection.logger.error("Caught Throwable from listener onStreamAdded.", th);
                }
            }
        }

        private void checkNewStreamAllowed(int i2, Http2Stream.State state) throws Http2Exception {
            if (DefaultHttp2Connection.this.goAwayReceived() && i2 > DefaultHttp2Connection.this.localEndpoint.lastStreamKnownByPeer()) {
                throw Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Cannot create stream %d since this endpoint has received a GOAWAY frame with last stream id %d.", Integer.valueOf(i2), Integer.valueOf(DefaultHttp2Connection.this.localEndpoint.lastStreamKnownByPeer()));
            }
            if (!isValidStreamId(i2)) {
                if (i2 < 0) {
                    throw new Http2NoMoreStreamIdsException();
                }
                Http2Error http2Error = Http2Error.PROTOCOL_ERROR;
                Object[] objArr = new Object[2];
                objArr[0] = Integer.valueOf(i2);
                objArr[1] = this.server ? "server" : "client";
                throw Http2Exception.connectionError(http2Error, "Request stream %d is not correct for %s connection", objArr);
            }
            int i3 = this.nextStreamIdToCreate;
            if (i2 < i3) {
                throw Http2Exception.closedStreamError(Http2Error.PROTOCOL_ERROR, "Request stream %d is behind the next expected stream %d", Integer.valueOf(i2), Integer.valueOf(this.nextStreamIdToCreate));
            }
            if (i3 <= 0) {
                throw Http2Exception.connectionError(Http2Error.REFUSED_STREAM, "Stream IDs are exhausted for this endpoint.", new Object[0]);
            }
            boolean z2 = state == Http2Stream.State.RESERVED_LOCAL || state == Http2Stream.State.RESERVED_REMOTE;
            if ((!z2 && !canOpenStream()) || (z2 && this.numStreams >= this.maxStreams)) {
                throw Http2Exception.streamError(i2, Http2Error.REFUSED_STREAM, "Maximum active streams violated for this endpoint.", new Object[0]);
            }
            if (DefaultHttp2Connection.this.isClosed()) {
                throw Http2Exception.connectionError(Http2Error.INTERNAL_ERROR, "Attempted to create stream id %d after connection was closed", Integer.valueOf(i2));
            }
        }

        private void incrementExpectedStreamId(int i2) {
            int i3 = this.nextReservationStreamId;
            if (i2 > i3 && i3 >= 0) {
                this.nextReservationStreamId = i2;
            }
            this.nextStreamIdToCreate = i2 + 2;
            this.numStreams++;
        }

        private boolean isLocal() {
            return this == DefaultHttp2Connection.this.localEndpoint;
        }

        /* JADX INFO: Access modifiers changed from: private */
        public void lastStreamKnownByPeer(int i2) {
            this.lastStreamKnownByPeer = i2;
        }

        private void updateMaxStreams() {
            this.maxStreams = (int) Math.min(2147483647L, ((long) this.maxActiveStreams) + ((long) this.maxReservedStreams));
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public void allowPushTo(boolean z2) {
            if (z2 && this.server) {
                throw new IllegalArgumentException("Servers do not allow push");
            }
            this.pushToAllowed = z2;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean allowPushTo() {
            return this.pushToAllowed;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean canOpenStream() {
            return this.numActiveStreams < this.maxActiveStreams;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public DefaultStream createStream(int i2, boolean z2) throws Http2Exception {
            Http2Stream.State stateActiveState = DefaultHttp2Connection.activeState(i2, Http2Stream.State.IDLE, isLocal(), z2);
            checkNewStreamAllowed(i2, stateActiveState);
            DefaultStream defaultStream = DefaultHttp2Connection.this.new DefaultStream(i2, stateActiveState);
            incrementExpectedStreamId(i2);
            addStream(defaultStream);
            defaultStream.activate();
            return defaultStream;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean created(Http2Stream http2Stream) {
            return (http2Stream instanceof DefaultStream) && ((DefaultStream) http2Stream).createdBy() == this;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public F flowController() {
            return this.flowController;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public void flowController(F f2) {
            this.flowController = (F) ObjectUtil.checkNotNull(f2, "flowController");
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public int incrementAndGetNextStreamId() {
            int i2 = this.nextReservationStreamId;
            if (i2 < 0) {
                return i2;
            }
            int i3 = i2 + 2;
            this.nextReservationStreamId = i3;
            return i3;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean isServer() {
            return this.server;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean isValidStreamId(int i2) {
            if (i2 > 0) {
                return this.server == ((i2 & 1) == 0);
            }
            return false;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public int lastStreamCreated() {
            int i2 = this.nextStreamIdToCreate;
            if (i2 > 1) {
                return i2 - 2;
            }
            return 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public int lastStreamKnownByPeer() {
            return this.lastStreamKnownByPeer;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public int maxActiveStreams() {
            return this.maxActiveStreams;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public void maxActiveStreams(int i2) {
            this.maxActiveStreams = i2;
            updateMaxStreams();
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public boolean mayHaveCreatedStream(int i2) {
            return isValidStreamId(i2) && i2 <= lastStreamCreated();
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public int numActiveStreams() {
            return this.numActiveStreams;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public Http2Connection.Endpoint<? extends Http2FlowController> opposite() {
            return isLocal() ? DefaultHttp2Connection.this.remoteEndpoint : DefaultHttp2Connection.this.localEndpoint;
        }

        @Override // io.netty.handler.codec.http2.Http2Connection.Endpoint
        public DefaultStream reservePushStream(int i2, Http2Stream http2Stream) throws Http2Exception {
            if (http2Stream == null) {
                throw Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Parent stream missing", new Object[0]);
            }
            if (!isLocal() ? http2Stream.state().remoteSideOpen() : http2Stream.state().localSideOpen()) {
                throw Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Stream %d is not open for sending push promise", Integer.valueOf(http2Stream.id()));
            }
            if (!opposite().allowPushTo()) {
                throw Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Server push not allowed to opposite endpoint", new Object[0]);
            }
            Http2Stream.State state = isLocal() ? Http2Stream.State.RESERVED_LOCAL : Http2Stream.State.RESERVED_REMOTE;
            checkNewStreamAllowed(i2, state);
            DefaultStream defaultStream = DefaultHttp2Connection.this.new DefaultStream(i2, state);
            incrementExpectedStreamId(i2);
            addStream(defaultStream);
            return defaultStream;
        }
    }

    public final class DefaultPropertyKey implements Http2Connection.PropertyKey {
        public final int index;

        public DefaultPropertyKey(int i2) {
            this.index = i2;
        }

        public DefaultPropertyKey verifyConnection(Http2Connection http2Connection) {
            if (http2Connection == DefaultHttp2Connection.this) {
                return this;
            }
            throw new IllegalArgumentException("Using a key that was not created by this connection");
        }
    }

    public class DefaultStream implements Http2Stream {
        private static final byte META_STATE_RECV_HEADERS = 16;
        private static final byte META_STATE_RECV_TRAILERS = 32;
        private static final byte META_STATE_SENT_HEADERS = 2;
        private static final byte META_STATE_SENT_PUSHPROMISE = 8;
        private static final byte META_STATE_SENT_RST = 1;
        private static final byte META_STATE_SENT_TRAILERS = 4;
        private final int id;
        private byte metaState;
        private final PropertyMap properties = new PropertyMap();
        private Http2Stream.State state;

        public class PropertyMap {
            public Object[] values;

            private PropertyMap() {
                this.values = EmptyArrays.EMPTY_OBJECTS;
            }

            public <V> V add(DefaultPropertyKey defaultPropertyKey, V v2) {
                resizeIfNecessary(defaultPropertyKey.index);
                Object[] objArr = this.values;
                int i2 = defaultPropertyKey.index;
                V v3 = (V) objArr[i2];
                objArr[i2] = v2;
                return v3;
            }

            public <V> V get(DefaultPropertyKey defaultPropertyKey) {
                int i2 = defaultPropertyKey.index;
                Object[] objArr = this.values;
                if (i2 >= objArr.length) {
                    return null;
                }
                return (V) objArr[i2];
            }

            public <V> V remove(DefaultPropertyKey defaultPropertyKey) {
                int i2 = defaultPropertyKey.index;
                Object[] objArr = this.values;
                if (i2 >= objArr.length) {
                    return null;
                }
                V v2 = (V) objArr[i2];
                objArr[i2] = null;
                return v2;
            }

            public void resizeIfNecessary(int i2) {
                Object[] objArr = this.values;
                if (i2 >= objArr.length) {
                    this.values = Arrays.copyOf(objArr, DefaultHttp2Connection.this.propertyKeyRegistry.size());
                }
            }
        }

        public DefaultStream(int i2, Http2Stream.State state) {
            this.id = i2;
            this.state = state;
        }

        public void activate() {
            DefaultHttp2Connection.this.activeStreams.activate(this);
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream close() {
            return close(null);
        }

        public Http2Stream close(Iterator<?> it) {
            Http2Stream.State state = this.state;
            Http2Stream.State state2 = Http2Stream.State.CLOSED;
            if (state == state2) {
                return this;
            }
            this.state = state2;
            DefaultEndpoint<? extends Http2FlowController> defaultEndpointCreatedBy = createdBy();
            defaultEndpointCreatedBy.numStreams--;
            DefaultHttp2Connection.this.activeStreams.deactivate(this, it);
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream closeLocalSide() {
            int iOrdinal = this.state.ordinal();
            if (iOrdinal == 3) {
                this.state = Http2Stream.State.HALF_CLOSED_LOCAL;
                DefaultHttp2Connection.this.notifyHalfClosed(this);
            } else if (iOrdinal != 4) {
                close();
            }
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream closeRemoteSide() {
            int iOrdinal = this.state.ordinal();
            if (iOrdinal == 3) {
                this.state = Http2Stream.State.HALF_CLOSED_REMOTE;
                DefaultHttp2Connection.this.notifyHalfClosed(this);
            } else if (iOrdinal != 5) {
                close();
            }
            return this;
        }

        public DefaultEndpoint<? extends Http2FlowController> createdBy() {
            return DefaultHttp2Connection.this.localEndpoint.isValidStreamId(this.id) ? DefaultHttp2Connection.this.localEndpoint : DefaultHttp2Connection.this.remoteEndpoint;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public final <V> V getProperty(Http2Connection.PropertyKey propertyKey) {
            return (V) this.properties.get(DefaultHttp2Connection.this.verifyKey(propertyKey));
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream headersReceived(boolean z2) {
            if (!z2) {
                this.metaState = (byte) (this.metaState | (isHeadersReceived() ? (byte) 32 : (byte) 16));
            }
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream headersSent(boolean z2) {
            if (!z2) {
                this.metaState = (byte) (this.metaState | (isHeadersSent() ? (byte) 4 : (byte) 2));
            }
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public final int id() {
            return this.id;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isHeadersReceived() {
            return (this.metaState & 16) != 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isHeadersSent() {
            return (this.metaState & 2) != 0;
        }

        public final boolean isLocal() {
            return DefaultHttp2Connection.this.localEndpoint.isValidStreamId(this.id);
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isPushPromiseSent() {
            return (this.metaState & 8) != 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isResetSent() {
            return (this.metaState & 1) != 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isTrailersReceived() {
            return (this.metaState & 32) != 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public boolean isTrailersSent() {
            return (this.metaState & 4) != 0;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream open(boolean z2) throws Http2Exception {
            this.state = DefaultHttp2Connection.activeState(this.id, this.state, isLocal(), z2);
            if (!createdBy().canOpenStream()) {
                throw Http2Exception.connectionError(Http2Error.PROTOCOL_ERROR, "Maximum active streams violated for this endpoint.", new Object[0]);
            }
            activate();
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream pushPromiseSent() {
            this.metaState = (byte) (this.metaState | 8);
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public final <V> V removeProperty(Http2Connection.PropertyKey propertyKey) {
            return (V) this.properties.remove(DefaultHttp2Connection.this.verifyKey(propertyKey));
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public Http2Stream resetSent() {
            this.metaState = (byte) (this.metaState | 1);
            return this;
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public final <V> V setProperty(Http2Connection.PropertyKey propertyKey, V v2) {
            return (V) this.properties.add(DefaultHttp2Connection.this.verifyKey(propertyKey), v2);
        }

        @Override // io.netty.handler.codec.http2.Http2Stream
        public final Http2Stream.State state() {
            return this.state;
        }
    }

    public interface Event {
        void process();
    }

    public final class PropertyKeyRegistry {
        public final List<DefaultPropertyKey> keys;

        private PropertyKeyRegistry() {
            this.keys = new ArrayList(4);
        }

        public DefaultPropertyKey newKey() {
            DefaultPropertyKey defaultPropertyKey = DefaultHttp2Connection.this.new DefaultPropertyKey(this.keys.size());
            this.keys.add(defaultPropertyKey);
            return defaultPropertyKey;
        }

        public int size() {
            return this.keys.size();
        }
    }

    public DefaultHttp2Connection(boolean z2) {
        this(z2, 100);
    }

    public DefaultHttp2Connection(boolean z2, int i2) {
        IntObjectHashMap intObjectHashMap = new IntObjectHashMap();
        this.streamMap = intObjectHashMap;
        this.propertyKeyRegistry = new PropertyKeyRegistry();
        ConnectionStream connectionStream = new ConnectionStream();
        this.connectionStream = connectionStream;
        ArrayList arrayList = new ArrayList(4);
        this.listeners = arrayList;
        this.activeStreams = new ActiveStreams(arrayList);
        this.localEndpoint = new DefaultEndpoint<>(z2, z2 ? Integer.MAX_VALUE : i2);
        this.remoteEndpoint = new DefaultEndpoint<>(!z2, i2);
        intObjectHashMap.put(connectionStream.id(), connectionStream);
    }

    public static Http2Stream.State activeState(int i2, Http2Stream.State state, boolean z2, boolean z3) throws Http2Exception {
        int iOrdinal = state.ordinal();
        if (iOrdinal == 0) {
            return z3 ? z2 ? Http2Stream.State.HALF_CLOSED_LOCAL : Http2Stream.State.HALF_CLOSED_REMOTE : Http2Stream.State.OPEN;
        }
        if (iOrdinal == 1) {
            return Http2Stream.State.HALF_CLOSED_REMOTE;
        }
        if (iOrdinal == 2) {
            return Http2Stream.State.HALF_CLOSED_LOCAL;
        }
        throw Http2Exception.streamError(i2, Http2Error.PROTOCOL_ERROR, "Attempting to open a stream in an invalid state: " + state, new Object[0]);
    }

    private boolean isStreamMapEmpty() {
        return this.streamMap.size() == 1;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public void addListener(Http2Connection.Listener listener) {
        this.listeners.add(listener);
    }

    /* JADX WARN: Removed duplicated region for block: B:12:0x0024  */
    @Override // io.netty.handler.codec.http2.Http2Connection
    /*
        Code decompiled incorrectly, please refer to instructions dump.
        To view partially-correct add '--show-bad-code' argument
    */
    public io.netty.util.concurrent.Future<java.lang.Void> close(io.netty.util.concurrent.Promise<java.lang.Void> r3) {
        /*
            r2 = this;
            java.lang.String r0 = "promise"
            io.netty.util.internal.ObjectUtil.checkNotNull(r3, r0)
            io.netty.util.concurrent.Promise<java.lang.Void> r0 = r2.closePromise
            if (r0 == 0) goto L24
            if (r0 != r3) goto Lc
            goto L26
        Lc:
            boolean r1 = r3 instanceof io.netty.channel.ChannelPromise
            if (r1 == 0) goto L19
            io.netty.channel.ChannelPromise r0 = (io.netty.channel.ChannelPromise) r0
            boolean r0 = r0.isVoid()
            if (r0 == 0) goto L19
            goto L24
        L19:
            io.netty.util.concurrent.Promise<java.lang.Void> r0 = r2.closePromise
            io.netty.util.concurrent.UnaryPromiseNotifier r1 = new io.netty.util.concurrent.UnaryPromiseNotifier
            r1.<init>(r3)
            r0.addListener(r1)
            goto L26
        L24:
            r2.closePromise = r3
        L26:
            boolean r0 = r2.isStreamMapEmpty()
            if (r0 == 0) goto L31
            r0 = 0
            r3.trySuccess(r0)
            return r3
        L31:
            io.netty.util.collection.IntObjectMap<io.netty.handler.codec.http2.Http2Stream> r3 = r2.streamMap
            java.lang.Iterable r3 = r3.entries()
            java.util.Iterator r3 = r3.iterator()
            io.netty.handler.codec.http2.DefaultHttp2Connection$ActiveStreams r0 = r2.activeStreams
            boolean r0 = r0.allowModifications()
            if (r0 == 0) goto L71
            io.netty.handler.codec.http2.DefaultHttp2Connection$ActiveStreams r0 = r2.activeStreams
            r0.incrementPendingIterations()
        L48:
            boolean r0 = r3.hasNext()     // Catch: java.lang.Throwable -> L6a
            if (r0 == 0) goto L64
            java.lang.Object r0 = r3.next()     // Catch: java.lang.Throwable -> L6a
            io.netty.util.collection.IntObjectMap$PrimitiveEntry r0 = (io.netty.util.collection.IntObjectMap.PrimitiveEntry) r0     // Catch: java.lang.Throwable -> L6a
            java.lang.Object r0 = r0.value()     // Catch: java.lang.Throwable -> L6a
            io.netty.handler.codec.http2.DefaultHttp2Connection$DefaultStream r0 = (io.netty.handler.codec.http2.DefaultHttp2Connection.DefaultStream) r0     // Catch: java.lang.Throwable -> L6a
            int r1 = r0.id()     // Catch: java.lang.Throwable -> L6a
            if (r1 == 0) goto L48
            r0.close(r3)     // Catch: java.lang.Throwable -> L6a
            goto L48
        L64:
            io.netty.handler.codec.http2.DefaultHttp2Connection$ActiveStreams r3 = r2.activeStreams
            r3.decrementPendingIterations()
            goto L8d
        L6a:
            r3 = move-exception
            io.netty.handler.codec.http2.DefaultHttp2Connection$ActiveStreams r0 = r2.activeStreams
            r0.decrementPendingIterations()
            throw r3
        L71:
            boolean r0 = r3.hasNext()
            if (r0 == 0) goto L8d
            java.lang.Object r0 = r3.next()
            io.netty.util.collection.IntObjectMap$PrimitiveEntry r0 = (io.netty.util.collection.IntObjectMap.PrimitiveEntry) r0
            java.lang.Object r0 = r0.value()
            io.netty.handler.codec.http2.Http2Stream r0 = (io.netty.handler.codec.http2.Http2Stream) r0
            int r1 = r0.id()
            if (r1 == 0) goto L71
            r0.close()
            goto L71
        L8d:
            io.netty.util.concurrent.Promise<java.lang.Void> r3 = r2.closePromise
            return r3
        */
        throw new UnsupportedOperationException("Method not decompiled: io.netty.handler.codec.http2.DefaultHttp2Connection.close(io.netty.util.concurrent.Promise):io.netty.util.concurrent.Future");
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Stream connectionStream() {
        return this.connectionStream;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Stream forEachActiveStream(Http2StreamVisitor http2StreamVisitor) {
        return this.activeStreams.forEachActiveStream(http2StreamVisitor);
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public void goAwayReceived(final int i2, long j2, ByteBuf byteBuf) {
        this.localEndpoint.lastStreamKnownByPeer(i2);
        for (int i3 = 0; i3 < this.listeners.size(); i3++) {
            try {
                this.listeners.get(i3).onGoAwayReceived(i2, j2, byteBuf);
            } catch (Throwable th) {
                logger.error("Caught Throwable from listener onGoAwayReceived.", th);
            }
        }
        try {
            forEachActiveStream(new Http2StreamVisitor() { // from class: io.netty.handler.codec.http2.DefaultHttp2Connection.1
                @Override // io.netty.handler.codec.http2.Http2StreamVisitor
                public boolean visit(Http2Stream http2Stream) {
                    if (http2Stream.id() <= i2 || !DefaultHttp2Connection.this.localEndpoint.isValidStreamId(http2Stream.id())) {
                        return true;
                    }
                    http2Stream.close();
                    return true;
                }
            });
        } catch (Http2Exception e2) {
            PlatformDependent.throwException(e2);
        }
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public boolean goAwayReceived() {
        return ((DefaultEndpoint) this.localEndpoint).lastStreamKnownByPeer >= 0;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public void goAwaySent(final int i2, long j2, ByteBuf byteBuf) {
        this.remoteEndpoint.lastStreamKnownByPeer(i2);
        for (int i3 = 0; i3 < this.listeners.size(); i3++) {
            try {
                this.listeners.get(i3).onGoAwaySent(i2, j2, byteBuf);
            } catch (Throwable th) {
                logger.error("Caught Throwable from listener onGoAwaySent.", th);
            }
        }
        try {
            forEachActiveStream(new Http2StreamVisitor() { // from class: io.netty.handler.codec.http2.DefaultHttp2Connection.2
                @Override // io.netty.handler.codec.http2.Http2StreamVisitor
                public boolean visit(Http2Stream http2Stream) {
                    if (http2Stream.id() <= i2 || !DefaultHttp2Connection.this.remoteEndpoint.isValidStreamId(http2Stream.id())) {
                        return true;
                    }
                    http2Stream.close();
                    return true;
                }
            });
        } catch (Http2Exception e2) {
            PlatformDependent.throwException(e2);
        }
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public boolean goAwaySent() {
        return ((DefaultEndpoint) this.remoteEndpoint).lastStreamKnownByPeer >= 0;
    }

    public final boolean isClosed() {
        return this.closePromise != null;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public boolean isServer() {
        return this.localEndpoint.isServer();
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Connection.Endpoint<Http2LocalFlowController> local() {
        return this.localEndpoint;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Connection.PropertyKey newKey() {
        return this.propertyKeyRegistry.newKey();
    }

    public void notifyClosed(Http2Stream http2Stream) {
        for (int i2 = 0; i2 < this.listeners.size(); i2++) {
            try {
                this.listeners.get(i2).onStreamClosed(http2Stream);
            } catch (Throwable th) {
                logger.error("Caught Throwable from listener onStreamClosed.", th);
            }
        }
    }

    public void notifyHalfClosed(Http2Stream http2Stream) {
        for (int i2 = 0; i2 < this.listeners.size(); i2++) {
            try {
                this.listeners.get(i2).onStreamHalfClosed(http2Stream);
            } catch (Throwable th) {
                logger.error("Caught Throwable from listener onStreamHalfClosed.", th);
            }
        }
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public int numActiveStreams() {
        return this.activeStreams.size();
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Connection.Endpoint<Http2RemoteFlowController> remote() {
        return this.remoteEndpoint;
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public void removeListener(Http2Connection.Listener listener) {
        this.listeners.remove(listener);
    }

    public void removeStream(DefaultStream defaultStream, Iterator<?> it) {
        boolean z2 = true;
        if (it != null) {
            it.remove();
        } else if (this.streamMap.remove(defaultStream.id()) == null) {
            z2 = false;
        }
        if (z2) {
            for (int i2 = 0; i2 < this.listeners.size(); i2++) {
                try {
                    this.listeners.get(i2).onStreamRemoved(defaultStream);
                } catch (Throwable th) {
                    logger.error("Caught Throwable from listener onStreamRemoved.", th);
                }
            }
            if (this.closePromise == null || !isStreamMapEmpty()) {
                return;
            }
            this.closePromise.trySuccess(null);
        }
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public Http2Stream stream(int i2) {
        return this.streamMap.get(i2);
    }

    @Override // io.netty.handler.codec.http2.Http2Connection
    public boolean streamMayHaveExisted(int i2) {
        return this.remoteEndpoint.mayHaveCreatedStream(i2) || this.localEndpoint.mayHaveCreatedStream(i2);
    }

    public final DefaultPropertyKey verifyKey(Http2Connection.PropertyKey propertyKey) {
        return ((DefaultPropertyKey) ObjectUtil.checkNotNull((DefaultPropertyKey) propertyKey, "key")).verifyConnection(this);
    }
}
