package okhttp3.internal.http1;

import c.q.d.j;
import c.u.n;
import c.u.o;
import d.a0;
import d.b0;
import d.f;
import d.g;
import d.h;
import d.l;
import d.y;
import java.io.EOFException;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
import okhttp3.Address;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.internal.Util;
import okhttp3.internal.connection.RealConnection;
import okhttp3.internal.http.ExchangeCodec;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.http.RequestLine;
import okhttp3.internal.http.StatusLine;

/* JADX INFO: compiled from: Http1ExchangeCodec.kt */
/* JADX INFO: loaded from: classes.dex */
public final class Http1ExchangeCodec implements ExchangeCodec {
    public static final Companion Companion = new Companion(null);
    private static final int HEADER_LIMIT = 262144;
    private static final long NO_CHUNK_YET = -1;
    private static final int STATE_CLOSED = 6;
    private static final int STATE_IDLE = 0;
    private static final int STATE_OPEN_REQUEST_BODY = 1;
    private static final int STATE_OPEN_RESPONSE_BODY = 4;
    private static final int STATE_READING_RESPONSE_BODY = 5;
    private static final int STATE_READ_RESPONSE_HEADERS = 3;
    private static final int STATE_WRITING_REQUEST_BODY = 2;
    private final OkHttpClient client;
    private long headerLimit;
    private final RealConnection realConnection;
    private final g sink;
    private final h source;
    private int state;
    private Headers trailers;

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private abstract class AbstractSource implements a0 {
        private boolean closed;
        private final l timeout;

        public AbstractSource() {
            this.timeout = new l(Http1ExchangeCodec.this.source.timeout());
        }

        @Override // d.a0, java.io.Closeable, java.lang.AutoCloseable
        public abstract /* synthetic */ void close() throws IOException;

        protected final boolean getClosed() {
            return this.closed;
        }

        protected final l getTimeout() {
            return this.timeout;
        }

        @Override // d.a0
        public long read(f fVar, long j) throws IOException {
            j.c(fVar, "sink");
            try {
                return Http1ExchangeCodec.this.source.read(fVar, j);
            } catch (IOException e2) {
                RealConnection realConnection = Http1ExchangeCodec.this.realConnection;
                if (realConnection == null) {
                    j.g();
                    throw null;
                }
                realConnection.noNewExchanges();
                responseBodyComplete$okhttp();
                throw e2;
            }
        }

        public final void responseBodyComplete$okhttp() {
            if (Http1ExchangeCodec.this.state == 6) {
                return;
            }
            if (Http1ExchangeCodec.this.state == 5) {
                Http1ExchangeCodec.this.detachTimeout(this.timeout);
                Http1ExchangeCodec.this.state = 6;
            } else {
                throw new IllegalStateException("state: " + Http1ExchangeCodec.this.state);
            }
        }

        protected final void setClosed(boolean z) {
            this.closed = z;
        }

        @Override // d.a0
        public b0 timeout() {
            return this.timeout;
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private final class ChunkedSink implements y {
        private boolean closed;
        private final l timeout;

        public ChunkedSink() {
            this.timeout = new l(Http1ExchangeCodec.this.sink.timeout());
        }

        @Override // d.y, java.io.Closeable, java.lang.AutoCloseable
        public synchronized void close() {
            if (this.closed) {
                return;
            }
            this.closed = true;
            Http1ExchangeCodec.this.sink.w("0\r\n\r\n");
            Http1ExchangeCodec.this.detachTimeout(this.timeout);
            Http1ExchangeCodec.this.state = 3;
        }

        @Override // d.y, java.io.Flushable
        public synchronized void flush() {
            if (this.closed) {
                return;
            }
            Http1ExchangeCodec.this.sink.flush();
        }

        @Override // d.y
        public b0 timeout() {
            return this.timeout;
        }

        @Override // d.y
        public void write(f fVar, long j) throws IOException {
            j.c(fVar, "source");
            if (!(!this.closed)) {
                throw new IllegalStateException("closed".toString());
            }
            if (j == 0) {
                return;
            }
            Http1ExchangeCodec.this.sink.h(j);
            Http1ExchangeCodec.this.sink.w("\r\n");
            Http1ExchangeCodec.this.sink.write(fVar, j);
            Http1ExchangeCodec.this.sink.w("\r\n");
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private final class ChunkedSource extends AbstractSource {
        private long bytesRemainingInChunk;
        private boolean hasMoreChunks;
        final /* synthetic */ Http1ExchangeCodec this$0;
        private final HttpUrl url;

        /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */
        public ChunkedSource(Http1ExchangeCodec http1ExchangeCodec, HttpUrl httpUrl) {
            super();
            j.c(httpUrl, "url");
            this.this$0 = http1ExchangeCodec;
            this.url = httpUrl;
            this.bytesRemainingInChunk = Http1ExchangeCodec.NO_CHUNK_YET;
            this.hasMoreChunks = true;
        }

        private final void readChunkSize() throws IOException {
            if (this.bytesRemainingInChunk != Http1ExchangeCodec.NO_CHUNK_YET) {
                this.this$0.source.s();
            }
            try {
                this.bytesRemainingInChunk = this.this$0.source.B();
                String strS = this.this$0.source.s();
                if (strS == null) {
                    throw new c.h("null cannot be cast to non-null type kotlin.CharSequence");
                }
                String string = o.g0(strS).toString();
                if (this.bytesRemainingInChunk >= 0) {
                    if (!(string.length() > 0) || n.t(string, ";", false, 2, null)) {
                        if (this.bytesRemainingInChunk == 0) {
                            this.hasMoreChunks = false;
                            Http1ExchangeCodec http1ExchangeCodec = this.this$0;
                            http1ExchangeCodec.trailers = http1ExchangeCodec.readHeaders();
                            OkHttpClient okHttpClient = this.this$0.client;
                            if (okHttpClient == null) {
                                j.g();
                                throw null;
                            }
                            CookieJar cookieJar = okHttpClient.cookieJar();
                            HttpUrl httpUrl = this.url;
                            Headers headers = this.this$0.trailers;
                            if (headers == null) {
                                j.g();
                                throw null;
                            }
                            HttpHeaders.receiveHeaders(cookieJar, httpUrl, headers);
                            responseBodyComplete$okhttp();
                            return;
                        }
                        return;
                    }
                }
                throw new ProtocolException("expected chunk size and optional extensions but was \"" + this.bytesRemainingInChunk + string + '\"');
            } catch (NumberFormatException e2) {
                throw new ProtocolException(e2.getMessage());
            }
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0, java.io.Closeable, java.lang.AutoCloseable
        public void close() {
            if (getClosed()) {
                return;
            }
            if (this.hasMoreChunks && !Util.discard(this, 100, TimeUnit.MILLISECONDS)) {
                RealConnection realConnection = this.this$0.realConnection;
                if (realConnection == null) {
                    j.g();
                    throw null;
                }
                realConnection.noNewExchanges();
                responseBodyComplete$okhttp();
            }
            setClosed(true);
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0
        public long read(f fVar, long j) throws IOException {
            j.c(fVar, "sink");
            if (!(j >= 0)) {
                throw new IllegalArgumentException(("byteCount < 0: " + j).toString());
            }
            if (!(!getClosed())) {
                throw new IllegalStateException("closed".toString());
            }
            if (!this.hasMoreChunks) {
                return Http1ExchangeCodec.NO_CHUNK_YET;
            }
            long j2 = this.bytesRemainingInChunk;
            if (j2 == 0 || j2 == Http1ExchangeCodec.NO_CHUNK_YET) {
                readChunkSize();
                if (!this.hasMoreChunks) {
                    return Http1ExchangeCodec.NO_CHUNK_YET;
                }
            }
            long j3 = super.read(fVar, Math.min(j, this.bytesRemainingInChunk));
            if (j3 != Http1ExchangeCodec.NO_CHUNK_YET) {
                this.bytesRemainingInChunk -= j3;
                return j3;
            }
            RealConnection realConnection = this.this$0.realConnection;
            if (realConnection == null) {
                j.g();
                throw null;
            }
            realConnection.noNewExchanges();
            ProtocolException protocolException = new ProtocolException("unexpected end of stream");
            responseBodyComplete$okhttp();
            throw protocolException;
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    public static final class Companion {
        private Companion() {
        }

        public /* synthetic */ Companion(c.q.d.g gVar) {
            this();
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private final class FixedLengthSource extends AbstractSource {
        private long bytesRemaining;

        public FixedLengthSource(long j) {
            super();
            this.bytesRemaining = j;
            if (j == 0) {
                responseBodyComplete$okhttp();
            }
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0, java.io.Closeable, java.lang.AutoCloseable
        public void close() {
            if (getClosed()) {
                return;
            }
            if (this.bytesRemaining != 0 && !Util.discard(this, 100, TimeUnit.MILLISECONDS)) {
                RealConnection realConnection = Http1ExchangeCodec.this.realConnection;
                if (realConnection == null) {
                    j.g();
                    throw null;
                }
                realConnection.noNewExchanges();
                responseBodyComplete$okhttp();
            }
            setClosed(true);
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0
        public long read(f fVar, long j) throws IOException {
            j.c(fVar, "sink");
            if (!(j >= 0)) {
                throw new IllegalArgumentException(("byteCount < 0: " + j).toString());
            }
            if (!(!getClosed())) {
                throw new IllegalStateException("closed".toString());
            }
            long j2 = this.bytesRemaining;
            if (j2 == 0) {
                return Http1ExchangeCodec.NO_CHUNK_YET;
            }
            long j3 = super.read(fVar, Math.min(j2, j));
            if (j3 != Http1ExchangeCodec.NO_CHUNK_YET) {
                long j4 = this.bytesRemaining - j3;
                this.bytesRemaining = j4;
                if (j4 == 0) {
                    responseBodyComplete$okhttp();
                }
                return j3;
            }
            RealConnection realConnection = Http1ExchangeCodec.this.realConnection;
            if (realConnection == null) {
                j.g();
                throw null;
            }
            realConnection.noNewExchanges();
            ProtocolException protocolException = new ProtocolException("unexpected end of stream");
            responseBodyComplete$okhttp();
            throw protocolException;
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private final class KnownLengthSink implements y {
        private boolean closed;
        private final l timeout;

        public KnownLengthSink() {
            this.timeout = new l(Http1ExchangeCodec.this.sink.timeout());
        }

        @Override // d.y, java.io.Closeable, java.lang.AutoCloseable
        public void close() {
            if (this.closed) {
                return;
            }
            this.closed = true;
            Http1ExchangeCodec.this.detachTimeout(this.timeout);
            Http1ExchangeCodec.this.state = 3;
        }

        @Override // d.y, java.io.Flushable
        public void flush() throws IOException {
            if (this.closed) {
                return;
            }
            Http1ExchangeCodec.this.sink.flush();
        }

        @Override // d.y
        public b0 timeout() {
            return this.timeout;
        }

        @Override // d.y
        public void write(f fVar, long j) throws IOException {
            j.c(fVar, "source");
            if (!(!this.closed)) {
                throw new IllegalStateException("closed".toString());
            }
            Util.checkOffsetAndCount(fVar.b0(), 0L, j);
            Http1ExchangeCodec.this.sink.write(fVar, j);
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    private final class UnknownLengthSource extends AbstractSource {
        private boolean inputExhausted;

        public UnknownLengthSource() {
            super();
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0, java.io.Closeable, java.lang.AutoCloseable
        public void close() {
            if (getClosed()) {
                return;
            }
            if (!this.inputExhausted) {
                responseBodyComplete$okhttp();
            }
            setClosed(true);
        }

        @Override // okhttp3.internal.http1.Http1ExchangeCodec.AbstractSource, d.a0
        public long read(f fVar, long j) throws IOException {
            j.c(fVar, "sink");
            if (!(j >= 0)) {
                throw new IllegalArgumentException(("byteCount < 0: " + j).toString());
            }
            if (!(!getClosed())) {
                throw new IllegalStateException("closed".toString());
            }
            if (this.inputExhausted) {
                return Http1ExchangeCodec.NO_CHUNK_YET;
            }
            long j2 = super.read(fVar, j);
            if (j2 != Http1ExchangeCodec.NO_CHUNK_YET) {
                return j2;
            }
            this.inputExhausted = true;
            responseBodyComplete$okhttp();
            return Http1ExchangeCodec.NO_CHUNK_YET;
        }
    }

    public Http1ExchangeCodec(OkHttpClient okHttpClient, RealConnection realConnection, h hVar, g gVar) {
        j.c(hVar, "source");
        j.c(gVar, "sink");
        this.client = okHttpClient;
        this.realConnection = realConnection;
        this.source = hVar;
        this.sink = gVar;
        this.headerLimit = HEADER_LIMIT;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final void detachTimeout(l lVar) {
        b0 b0VarA = lVar.a();
        lVar.b(b0.NONE);
        b0VarA.clearDeadline();
        b0VarA.clearTimeout();
    }

    private final boolean isChunked(Response response) {
        return n.h("chunked", Response.header$default(response, "Transfer-Encoding", null, 2, null), true);
    }

    private final y newChunkedSink() {
        if (this.state == 1) {
            this.state = 2;
            return new ChunkedSink();
        }
        throw new IllegalStateException(("state: " + this.state).toString());
    }

    private final a0 newChunkedSource(HttpUrl httpUrl) {
        if (this.state == 4) {
            this.state = 5;
            return new ChunkedSource(this, httpUrl);
        }
        throw new IllegalStateException(("state: " + this.state).toString());
    }

    private final a0 newFixedLengthSource(long j) {
        if (this.state == 4) {
            this.state = 5;
            return new FixedLengthSource(j);
        }
        throw new IllegalStateException(("state: " + this.state).toString());
    }

    private final y newKnownLengthSink() {
        if (this.state == 1) {
            this.state = 2;
            return new KnownLengthSink();
        }
        throw new IllegalStateException(("state: " + this.state).toString());
    }

    private final a0 newUnknownLengthSource() {
        if (!(this.state == 4)) {
            throw new IllegalStateException(("state: " + this.state).toString());
        }
        this.state = 5;
        RealConnection realConnection = this.realConnection;
        if (realConnection != null) {
            realConnection.noNewExchanges();
            return new UnknownLengthSource();
        }
        j.g();
        throw null;
    }

    private final String readHeaderLine() throws IOException {
        String strK = this.source.k(this.headerLimit);
        this.headerLimit -= (long) strK.length();
        return strK;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final Headers readHeaders() throws IOException {
        Headers.Builder builder = new Headers.Builder();
        String headerLine = readHeaderLine();
        while (true) {
            if (!(headerLine.length() > 0)) {
                return builder.build();
            }
            builder.addLenient$okhttp(headerLine);
            headerLine = readHeaderLine();
        }
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void cancel() {
        RealConnection realConnection = this.realConnection;
        if (realConnection != null) {
            realConnection.cancel();
        }
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public RealConnection connection() {
        return this.realConnection;
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public y createRequestBody(Request request, long j) throws ProtocolException {
        j.c(request, "request");
        if (request.body() != null && request.body().isDuplex()) {
            throw new ProtocolException("Duplex connections are not supported for HTTP/1");
        }
        if (isChunked(request)) {
            return newChunkedSink();
        }
        if (j != NO_CHUNK_YET) {
            return newKnownLengthSink();
        }
        throw new IllegalStateException("Cannot stream a request body without chunked encoding or a known content length!");
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void finishRequest() {
        this.sink.flush();
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void flushRequest() throws IOException {
        this.sink.flush();
    }

    public final boolean isClosed() {
        return this.state == 6;
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public a0 openResponseBodySource(Response response) {
        j.c(response, "response");
        if (!HttpHeaders.promisesBody(response)) {
            return newFixedLengthSource(0L);
        }
        if (isChunked(response)) {
            return newChunkedSource(response.request().url());
        }
        long jHeadersContentLength = Util.headersContentLength(response);
        return jHeadersContentLength != NO_CHUNK_YET ? newFixedLengthSource(jHeadersContentLength) : newUnknownLengthSource();
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public Response.Builder readResponseHeaders(boolean z) {
        String strRedact;
        Route route;
        Address address;
        HttpUrl httpUrlUrl;
        int i = this.state;
        boolean z2 = true;
        if (i != 1 && i != 3) {
            z2 = false;
        }
        if (!z2) {
            throw new IllegalStateException(("state: " + this.state).toString());
        }
        try {
            StatusLine statusLine = StatusLine.Companion.parse(readHeaderLine());
            Response.Builder builderHeaders = new Response.Builder().protocol(statusLine.protocol).code(statusLine.code).message(statusLine.message).headers(readHeaders());
            if (z && statusLine.code == 100) {
                return null;
            }
            if (statusLine.code == 100) {
                this.state = 3;
                return builderHeaders;
            }
            this.state = 4;
            return builderHeaders;
        } catch (EOFException e2) {
            RealConnection realConnection = this.realConnection;
            if (realConnection == null || (route = realConnection.route()) == null || (address = route.address()) == null || (httpUrlUrl = address.url()) == null || (strRedact = httpUrlUrl.redact()) == null) {
                strRedact = "unknown";
            }
            throw new IOException("unexpected end of stream on " + strRedact, e2);
        }
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public long reportedContentLength(Response response) {
        j.c(response, "response");
        if (HttpHeaders.promisesBody(response)) {
            return isChunked(response) ? NO_CHUNK_YET : Util.headersContentLength(response);
        }
        return 0L;
    }

    public final void skipConnectBody(Response response) {
        j.c(response, "response");
        long jHeadersContentLength = Util.headersContentLength(response);
        if (jHeadersContentLength == NO_CHUNK_YET) {
            return;
        }
        a0 a0VarNewFixedLengthSource = newFixedLengthSource(jHeadersContentLength);
        Util.skipAll(a0VarNewFixedLengthSource, Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
        a0VarNewFixedLengthSource.close();
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public Headers trailers() {
        if (!(this.state == 6)) {
            throw new IllegalStateException("too early; can't read the trailers yet".toString());
        }
        Headers headers = this.trailers;
        return headers != null ? headers : Util.EMPTY_HEADERS;
    }

    public final void writeRequest(Headers headers, String str) {
        j.c(headers, "headers");
        j.c(str, "requestLine");
        if (!(this.state == 0)) {
            throw new IllegalStateException(("state: " + this.state).toString());
        }
        this.sink.w(str).w("\r\n");
        int size = headers.size();
        for (int i = 0; i < size; i++) {
            this.sink.w(headers.name(i)).w(": ").w(headers.value(i)).w("\r\n");
        }
        this.sink.w("\r\n");
        this.state = 1;
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void writeRequestHeaders(Request request) {
        j.c(request, "request");
        RequestLine requestLine = RequestLine.INSTANCE;
        RealConnection realConnection = this.realConnection;
        if (realConnection == null) {
            j.g();
            throw null;
        }
        Proxy.Type type = realConnection.route().proxy().type();
        j.b(type, "realConnection!!.route().proxy.type()");
        writeRequest(request.headers(), requestLine.get(request, type));
    }

    private final boolean isChunked(Request request) {
        return n.h("chunked", request.header("Transfer-Encoding"), true);
    }
}
