package okhttp3.internal.http1;

import d.b.a.a.a;
import j.b0;
import j.c0;
import j.d;
import j.f;
import j.g;
import j.l;
import j.z;
import java.io.EOFException;
import java.io.IOException;
import java.net.ProtocolException;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
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 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 final RealConnection connection;
    private final HeadersReader headersReader;
    private final f sink;
    private final g source;
    private int state;
    private Headers trailers;

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

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

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

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

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

        @Override // j.b0
        public long read(d dVar, long j2) throws IOException {
            g.h0.c.l.f(dVar, "sink");
            try {
                return Http1ExchangeCodec.this.source.read(dVar, j2);
            } catch (IOException e2) {
                Http1ExchangeCodec.this.getConnection().noNewExchanges$okhttp();
                responseBodyComplete();
                throw e2;
            }
        }

        public final void responseBodyComplete() {
            if (Http1ExchangeCodec.this.state == 6) {
                return;
            }
            if (Http1ExchangeCodec.this.state == 5) {
                Http1ExchangeCodec.this.detachTimeout(this.timeout);
                Http1ExchangeCodec.this.state = 6;
            } else {
                StringBuilder sbB = a.B("state: ");
                sbB.append(Http1ExchangeCodec.this.state);
                throw new IllegalStateException(sbB.toString());
            }
        }

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

        @Override // j.b0
        public c0 timeout() {
            return this.timeout;
        }
    }

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

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

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

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

        @Override // j.z
        public c0 timeout() {
            return this.timeout;
        }

        @Override // j.z
        public void write(d dVar, long j2) throws IOException {
            g.h0.c.l.f(dVar, "source");
            if (!(!this.closed)) {
                throw new IllegalStateException("closed".toString());
            }
            if (j2 == 0) {
                return;
            }
            Http1ExchangeCodec.this.sink.writeHexadecimalUnsignedLong(j2);
            Http1ExchangeCodec.this.sink.writeUtf8("\r\n");
            Http1ExchangeCodec.this.sink.write(dVar, j2);
            Http1ExchangeCodec.this.sink.writeUtf8("\r\n");
        }
    }

    /* JADX INFO: compiled from: Http1ExchangeCodec.kt */
    public final class ChunkedSource extends AbstractSource {
        private long bytesRemainingInChunk;
        private boolean hasMoreChunks;
        public 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();
            g.h0.c.l.f(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.R();
            }
            try {
                this.bytesRemainingInChunk = this.this$0.source.h0();
                String strR = this.this$0.source.R();
                if (strR == null) {
                    throw new NullPointerException("null cannot be cast to non-null type kotlin.CharSequence");
                }
                String string = g.m0.f.R(strR).toString();
                if (this.bytesRemainingInChunk >= 0) {
                    if (!(string.length() > 0) || g.m0.f.J(string, ";", false, 2)) {
                        if (this.bytesRemainingInChunk == 0) {
                            this.hasMoreChunks = false;
                            Http1ExchangeCodec http1ExchangeCodec = this.this$0;
                            http1ExchangeCodec.trailers = http1ExchangeCodec.headersReader.readHeaders();
                            OkHttpClient okHttpClient = this.this$0.client;
                            g.h0.c.l.c(okHttpClient);
                            CookieJar cookieJar = okHttpClient.cookieJar();
                            HttpUrl httpUrl = this.url;
                            Headers headers = this.this$0.trailers;
                            g.h0.c.l.c(headers);
                            HttpHeaders.receiveHeaders(cookieJar, httpUrl, headers);
                            responseBodyComplete();
                            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, j.b0, java.io.Closeable, java.lang.AutoCloseable
        public void close() {
            if (getClosed()) {
                return;
            }
            if (this.hasMoreChunks && !Util.discard(this, 100, TimeUnit.MILLISECONDS)) {
                this.this$0.getConnection().noNewExchanges$okhttp();
                responseBodyComplete();
            }
            setClosed(true);
        }

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

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

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

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

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

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

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

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

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

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

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

        @Override // j.z
        public c0 timeout() {
            return this.timeout;
        }

        @Override // j.z
        public void write(d dVar, long j2) throws IOException {
            g.h0.c.l.f(dVar, "source");
            if (!(!this.closed)) {
                throw new IllegalStateException("closed".toString());
            }
            Util.checkOffsetAndCount(dVar.f4601e, 0L, j2);
            Http1ExchangeCodec.this.sink.write(dVar, j2);
        }
    }

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

        public UnknownLengthSource() {
            super();
        }

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

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

    public Http1ExchangeCodec(OkHttpClient okHttpClient, RealConnection realConnection, g gVar, f fVar) {
        g.h0.c.l.f(realConnection, "connection");
        g.h0.c.l.f(gVar, "source");
        g.h0.c.l.f(fVar, "sink");
        this.client = okHttpClient;
        this.connection = realConnection;
        this.source = gVar;
        this.sink = fVar;
        this.headersReader = new HeadersReader(gVar);
    }

    /* JADX INFO: Access modifiers changed from: private */
    public final void detachTimeout(l lVar) {
        c0 c0Var = lVar.a;
        c0 c0Var2 = c0.NONE;
        g.h0.c.l.f(c0Var2, "delegate");
        lVar.a = c0Var2;
        c0Var.clearDeadline();
        c0Var.clearTimeout();
    }

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

    private final z newChunkedSink() {
        if (this.state == 1) {
            this.state = 2;
            return new ChunkedSink();
        }
        StringBuilder sbB = a.B("state: ");
        sbB.append(this.state);
        throw new IllegalStateException(sbB.toString().toString());
    }

    private final b0 newChunkedSource(HttpUrl httpUrl) {
        if (this.state == 4) {
            this.state = 5;
            return new ChunkedSource(this, httpUrl);
        }
        StringBuilder sbB = a.B("state: ");
        sbB.append(this.state);
        throw new IllegalStateException(sbB.toString().toString());
    }

    private final b0 newFixedLengthSource(long j2) {
        if (this.state == 4) {
            this.state = 5;
            return new FixedLengthSource(j2);
        }
        StringBuilder sbB = a.B("state: ");
        sbB.append(this.state);
        throw new IllegalStateException(sbB.toString().toString());
    }

    private final z newKnownLengthSink() {
        if (this.state == 1) {
            this.state = 2;
            return new KnownLengthSink();
        }
        StringBuilder sbB = a.B("state: ");
        sbB.append(this.state);
        throw new IllegalStateException(sbB.toString().toString());
    }

    private final b0 newUnknownLengthSource() {
        if (this.state == 4) {
            this.state = 5;
            getConnection().noNewExchanges$okhttp();
            return new UnknownLengthSource();
        }
        StringBuilder sbB = a.B("state: ");
        sbB.append(this.state);
        throw new IllegalStateException(sbB.toString().toString());
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void cancel() {
        getConnection().cancel();
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public z createRequestBody(Request request, long j2) throws ProtocolException {
        g.h0.c.l.f(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 (j2 != 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();
    }

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

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

    @Override // okhttp3.internal.http.ExchangeCodec
    public b0 openResponseBodySource(Response response) {
        g.h0.c.l.f(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) {
        int i2 = this.state;
        boolean z2 = true;
        if (i2 != 1 && i2 != 3) {
            z2 = false;
        }
        if (!z2) {
            StringBuilder sbB = a.B("state: ");
            sbB.append(this.state);
            throw new IllegalStateException(sbB.toString().toString());
        }
        try {
            StatusLine statusLine = StatusLine.Companion.parse(this.headersReader.readLine());
            Response.Builder builderHeaders = new Response.Builder().protocol(statusLine.protocol).code(statusLine.code).message(statusLine.message).headers(this.headersReader.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) {
            throw new IOException(a.p("unexpected end of stream on ", getConnection().route().address().url().redact()), e2);
        }
    }

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

    public final void skipConnectBody(Response response) {
        g.h0.c.l.f(response, "response");
        long jHeadersContentLength = Util.headersContentLength(response);
        if (jHeadersContentLength == NO_CHUNK_YET) {
            return;
        }
        b0 b0VarNewFixedLengthSource = newFixedLengthSource(jHeadersContentLength);
        Util.skipAll(b0VarNewFixedLengthSource, Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
        b0VarNewFixedLengthSource.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) {
        g.h0.c.l.f(headers, "headers");
        g.h0.c.l.f(str, "requestLine");
        if (!(this.state == 0)) {
            StringBuilder sbB = a.B("state: ");
            sbB.append(this.state);
            throw new IllegalStateException(sbB.toString().toString());
        }
        this.sink.writeUtf8(str).writeUtf8("\r\n");
        int size = headers.size();
        for (int i2 = 0; i2 < size; i2++) {
            this.sink.writeUtf8(headers.name(i2)).writeUtf8(": ").writeUtf8(headers.value(i2)).writeUtf8("\r\n");
        }
        this.sink.writeUtf8("\r\n");
        this.state = 1;
    }

    @Override // okhttp3.internal.http.ExchangeCodec
    public void writeRequestHeaders(Request request) {
        g.h0.c.l.f(request, "request");
        RequestLine requestLine = RequestLine.INSTANCE;
        Proxy.Type type = getConnection().route().proxy().type();
        g.h0.c.l.e(type, "connection.route().proxy.type()");
        writeRequest(request.headers(), requestLine.get(request, type));
    }

    private final boolean isChunked(Request request) {
        return g.m0.f.e("chunked", request.header("Transfer-Encoding"), true);
    }
}
