package okhttp3.internal.connection;

import c.k;
import c.q.d.j;
import c.q.d.q;
import d.b0;
import d.d;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.net.Socket;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSocketFactory;
import okhttp3.Address;
import okhttp3.Call;
import okhttp3.CertificatePinner;
import okhttp3.Connection;
import okhttp3.EventListener;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.internal.Util;
import okhttp3.internal.http.ExchangeCodec;
import okhttp3.internal.platform.Platform;

/* JADX INFO: compiled from: Transmitter.kt */
/* JADX INFO: loaded from: classes.dex */
public final class Transmitter {
    private final Call call;
    private Object callStackTrace;
    private boolean canceled;
    private final OkHttpClient client;
    private RealConnection connection;
    private final RealConnectionPool connectionPool;
    private final EventListener eventListener;
    private Exchange exchange;
    private ExchangeFinder exchangeFinder;
    private boolean exchangeRequestDone;
    private boolean exchangeResponseDone;
    private boolean noMoreExchanges;
    private Request request;
    private final AnonymousClass1 timeout;
    private boolean timeoutEarlyExit;

    /* JADX INFO: compiled from: Transmitter.kt */
    public static final class TransmitterReference extends WeakReference<Transmitter> {
        private final Object callStackTrace;

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public TransmitterReference(Transmitter transmitter, Object obj) {
            super(transmitter);
            j.c(transmitter, "referent");
            this.callStackTrace = obj;
        }

        public final Object getCallStackTrace() {
            return this.callStackTrace;
        }
    }

    /* JADX WARN: Type inference failed for: r3v6, types: [d.b0, okhttp3.internal.connection.Transmitter$timeout$1] */
    public Transmitter(OkHttpClient okHttpClient, Call call) {
        j.c(okHttpClient, "client");
        j.c(call, "call");
        this.client = okHttpClient;
        this.call = call;
        this.connectionPool = okHttpClient.connectionPool().getDelegate$okhttp();
        this.eventListener = this.client.eventListenerFactory().create(this.call);
        ?? r3 = new d() { // from class: okhttp3.internal.connection.Transmitter.timeout.1
            @Override // d.d
            protected void timedOut() {
                Transmitter.this.cancel();
            }
        };
        r3.timeout(this.client.callTimeoutMillis(), TimeUnit.MILLISECONDS);
        this.timeout = r3;
    }

    private final Address createAddress(HttpUrl httpUrl) {
        SSLSocketFactory sSLSocketFactory;
        HostnameVerifier hostnameVerifier;
        CertificatePinner certificatePinner;
        if (httpUrl.isHttps()) {
            SSLSocketFactory sslSocketFactory = this.client.sslSocketFactory();
            hostnameVerifier = this.client.hostnameVerifier();
            sSLSocketFactory = sslSocketFactory;
            certificatePinner = this.client.certificatePinner();
        } else {
            sSLSocketFactory = null;
            hostnameVerifier = null;
            certificatePinner = null;
        }
        return new Address(httpUrl.host(), httpUrl.port(), this.client.dns(), this.client.socketFactory(), sSLSocketFactory, hostnameVerifier, certificatePinner, this.client.proxyAuthenticator(), this.client.proxy(), this.client.protocols(), this.client.connectionSpecs(), this.client.proxySelector());
    }

    /* JADX WARN: Type inference failed for: r4v3, types: [T, okhttp3.internal.connection.RealConnection] */
    /* JADX WARN: Type inference fix 'apply assigned field type' failed
    java.lang.UnsupportedOperationException: ArgType.getObject(), call class: class jadx.core.dex.instructions.args.ArgType$UnknownArg
    	at jadx.core.dex.instructions.args.ArgType.getObject(ArgType.java:593)
    	at jadx.core.dex.attributes.nodes.ClassTypeVarsAttr.getTypeVarsMapFor(ClassTypeVarsAttr.java:35)
    	at jadx.core.dex.nodes.utils.TypeUtils.replaceClassGenerics(TypeUtils.java:177)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.insertExplicitUseCast(FixTypesVisitor.java:397)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.tryFieldTypeWithNewCasts(FixTypesVisitor.java:359)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.applyFieldType(FixTypesVisitor.java:309)
    	at jadx.core.dex.visitors.typeinference.FixTypesVisitor.visit(FixTypesVisitor.java:94)
     */
    private final <E extends IOException> E maybeReleaseConnection(E e2, boolean z) {
        boolean z2;
        Socket socketReleaseConnectionNoEvents;
        boolean z3;
        q qVar = new q();
        synchronized (this.connectionPool) {
            if (z) {
                try {
                    z2 = this.exchange == null;
                } finally {
                }
            }
            if (!z2) {
                throw new IllegalStateException("cannot release connection while it is in use".toString());
            }
            qVar.f1449b = this.connection;
            socketReleaseConnectionNoEvents = (this.connection != null && this.exchange == null && (z || this.noMoreExchanges)) ? releaseConnectionNoEvents() : null;
            if (this.connection != null) {
                qVar.f1449b = null;
            }
            z3 = this.noMoreExchanges && this.exchange == null;
            c.j jVar = c.j.f1417a;
        }
        if (socketReleaseConnectionNoEvents != null) {
            Util.closeQuietly(socketReleaseConnectionNoEvents);
        }
        T t = qVar.f1449b;
        if (((Connection) t) != null) {
            EventListener eventListener = this.eventListener;
            Call call = this.call;
            Connection connection = (Connection) t;
            if (connection == null) {
                j.g();
                throw null;
            }
            eventListener.connectionReleased(call, connection);
        }
        if (z3) {
            boolean z4 = e2 != null;
            e2 = (E) timeoutExit(e2);
            if (z4) {
                EventListener eventListener2 = this.eventListener;
                Call call2 = this.call;
                if (e2 == null) {
                    j.g();
                    throw null;
                }
                eventListener2.callFailed(call2, e2);
            } else {
                this.eventListener.callEnd(this.call);
            }
        }
        return e2;
    }

    private final <E extends IOException> E timeoutExit(E e2) {
        if (this.timeoutEarlyExit || !exit()) {
            return e2;
        }
        InterruptedIOException interruptedIOException = new InterruptedIOException("timeout");
        if (e2 != null) {
            interruptedIOException.initCause(e2);
        }
        return interruptedIOException;
    }

    public final void acquireConnectionNoEvents(RealConnection realConnection) {
        j.c(realConnection, "connection");
        boolean zHoldsLock = Thread.holdsLock(this.connectionPool);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        if (!(this.connection == null)) {
            throw new IllegalStateException("Check failed.".toString());
        }
        this.connection = realConnection;
        realConnection.getTransmitters().add(new TransmitterReference(this, this.callStackTrace));
    }

    public final void callStart() {
        this.callStackTrace = Platform.Companion.get().getStackTraceForCloseable("response.body().close()");
        this.eventListener.callStart(this.call);
    }

    public final boolean canRetry() {
        ExchangeFinder exchangeFinder = this.exchangeFinder;
        if (exchangeFinder == null) {
            j.g();
            throw null;
        }
        if (exchangeFinder.hasStreamFailure()) {
            ExchangeFinder exchangeFinder2 = this.exchangeFinder;
            if (exchangeFinder2 == null) {
                j.g();
                throw null;
            }
            if (exchangeFinder2.hasRouteToTry()) {
                return true;
            }
        }
        return false;
    }

    public final void cancel() {
        Exchange exchange;
        RealConnection realConnectionConnectingConnection;
        synchronized (this.connectionPool) {
            this.canceled = true;
            exchange = this.exchange;
            ExchangeFinder exchangeFinder = this.exchangeFinder;
            if (exchangeFinder == null || (realConnectionConnectingConnection = exchangeFinder.connectingConnection()) == null) {
                realConnectionConnectingConnection = this.connection;
            }
            c.j jVar = c.j.f1417a;
        }
        if (exchange != null) {
            exchange.cancel();
        } else if (realConnectionConnectingConnection != null) {
            realConnectionConnectingConnection.cancel();
        }
    }

    public final void exchangeDoneDueToException() {
        synchronized (this.connectionPool) {
            if (!(!this.noMoreExchanges)) {
                throw new IllegalStateException("Check failed.".toString());
            }
            this.exchange = null;
            c.j jVar = c.j.f1417a;
        }
    }

    public final <E extends IOException> E exchangeMessageDone$okhttp(Exchange exchange, boolean z, boolean z2, E e2) {
        boolean z3;
        j.c(exchange, "exchange");
        synchronized (this.connectionPool) {
            boolean z4 = true;
            if (!j.a(exchange, this.exchange)) {
                return e2;
            }
            if (z) {
                z3 = !this.exchangeRequestDone;
                this.exchangeRequestDone = true;
            } else {
                z3 = false;
            }
            if (z2) {
                if (!this.exchangeResponseDone) {
                    z3 = true;
                }
                this.exchangeResponseDone = true;
            }
            if (this.exchangeRequestDone && this.exchangeResponseDone && z3) {
                Exchange exchange2 = this.exchange;
                if (exchange2 == null) {
                    j.g();
                    throw null;
                }
                RealConnection realConnectionConnection = exchange2.connection();
                if (realConnectionConnection == null) {
                    j.g();
                    throw null;
                }
                realConnectionConnection.setSuccessCount$okhttp(realConnectionConnection.getSuccessCount$okhttp() + 1);
                this.exchange = null;
            } else {
                z4 = false;
            }
            c.j jVar = c.j.f1417a;
            return z4 ? (E) maybeReleaseConnection(e2, false) : e2;
        }
    }

    public final RealConnection getConnection() {
        return this.connection;
    }

    public final boolean hasExchange() {
        boolean z;
        synchronized (this.connectionPool) {
            z = this.exchange != null;
        }
        return z;
    }

    public final boolean isCanceled() {
        boolean z;
        synchronized (this.connectionPool) {
            z = this.canceled;
        }
        return z;
    }

    public final Exchange newExchange$okhttp(Interceptor.Chain chain, boolean z) {
        j.c(chain, "chain");
        synchronized (this.connectionPool) {
            boolean z2 = true;
            if (!(!this.noMoreExchanges)) {
                throw new IllegalStateException("released".toString());
            }
            if (this.exchange != null) {
                z2 = false;
            }
            if (!z2) {
                throw new IllegalStateException("cannot make a new request because the previous response is still open: please call response.close()".toString());
            }
            c.j jVar = c.j.f1417a;
        }
        ExchangeFinder exchangeFinder = this.exchangeFinder;
        if (exchangeFinder == null) {
            j.g();
            throw null;
        }
        ExchangeCodec exchangeCodecFind = exchangeFinder.find(this.client, chain, z);
        Call call = this.call;
        EventListener eventListener = this.eventListener;
        ExchangeFinder exchangeFinder2 = this.exchangeFinder;
        if (exchangeFinder2 == null) {
            j.g();
            throw null;
        }
        Exchange exchange = new Exchange(this, call, eventListener, exchangeFinder2, exchangeCodecFind);
        synchronized (this.connectionPool) {
            this.exchange = exchange;
            this.exchangeRequestDone = false;
            this.exchangeResponseDone = false;
        }
        return exchange;
    }

    public final IOException noMoreExchanges(IOException iOException) {
        synchronized (this.connectionPool) {
            this.noMoreExchanges = true;
            c.j jVar = c.j.f1417a;
        }
        return maybeReleaseConnection(iOException, false);
    }

    public final void prepareToConnect(Request request) {
        j.c(request, "request");
        Request request2 = this.request;
        if (request2 != null) {
            if (request2 == null) {
                j.g();
                throw null;
            }
            if (Util.canReuseConnectionFor(request2.url(), request.url())) {
                ExchangeFinder exchangeFinder = this.exchangeFinder;
                if (exchangeFinder == null) {
                    j.g();
                    throw null;
                }
                if (exchangeFinder.hasRouteToTry()) {
                    return;
                }
            }
            if (!(this.exchange == null)) {
                throw new IllegalStateException("Check failed.".toString());
            }
            if (this.exchangeFinder != null) {
                maybeReleaseConnection(null, true);
                this.exchangeFinder = null;
            }
        }
        this.request = request;
        this.exchangeFinder = new ExchangeFinder(this, this.connectionPool, createAddress(request.url()), this.call, this.eventListener);
    }

    public final Socket releaseConnectionNoEvents() {
        boolean zHoldsLock = Thread.holdsLock(this.connectionPool);
        if (k.f1418a && !zHoldsLock) {
            throw new AssertionError("Assertion failed");
        }
        RealConnection realConnection = this.connection;
        if (realConnection == null) {
            j.g();
            throw null;
        }
        Iterator<Reference<Transmitter>> it = realConnection.getTransmitters().iterator();
        int i = 0;
        while (true) {
            if (!it.hasNext()) {
                i = -1;
                break;
            }
            if (j.a(it.next().get(), this)) {
                break;
            }
            i++;
        }
        if (!(i != -1)) {
            throw new IllegalStateException("Check failed.".toString());
        }
        RealConnection realConnection2 = this.connection;
        if (realConnection2 == null) {
            j.g();
            throw null;
        }
        realConnection2.getTransmitters().remove(i);
        this.connection = null;
        if (realConnection2.getTransmitters().isEmpty()) {
            realConnection2.setIdleAtNanos$okhttp(System.nanoTime());
            if (this.connectionPool.connectionBecameIdle(realConnection2)) {
                return realConnection2.socket();
            }
        }
        return null;
    }

    public final void setConnection(RealConnection realConnection) {
        this.connection = realConnection;
    }

    public final b0 timeout() {
        return this.timeout;
    }

    public final void timeoutEarlyExit() {
        if (!(!this.timeoutEarlyExit)) {
            throw new IllegalStateException("Check failed.".toString());
        }
        this.timeoutEarlyExit = true;
        exit();
    }

    public final void timeoutEnter() {
        enter();
    }
}
