package okhttp3.internal.ws; import com.google.common.net.HttpHeaders; import java.io.Closeable; import java.io.IOException; import java.net.ProtocolException; import java.net.SocketTimeoutException; import java.util.ArrayDeque; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import o.C14866gag; import o.C14953gcr; import o.C14957gcv; import o.C14973gde; import o.C15155gij; import o.InterfaceC15148gic; import o.InterfaceC15149gid; import o.gdP; import o.gdZ; import o.giE; import okhttp3.Call; import okhttp3.Callback; import okhttp3.EventListener; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.internal.Util; import okhttp3.internal.concurrent.Task; import okhttp3.internal.concurrent.TaskQueue; import okhttp3.internal.concurrent.TaskRunner; import okhttp3.internal.connection.Exchange; import okhttp3.internal.connection.RealCall; import okhttp3.internal.ws.RealWebSocket; import okhttp3.internal.ws.WebSocketReader; import org.bouncycastle.pqc.jcajce.spec.McElieceCCA2KeyGenParameterSpec; /* loaded from: classes6.dex */ public final class RealWebSocket implements WebSocket, WebSocketReader.FrameCallback { private static final long CANCEL_AFTER_CLOSE_MILLIS = 60000; public static final Companion Companion = new Companion(null); public static final long DEFAULT_MINIMUM_DEFLATE_SIZE = 1024; private static final long MAX_QUEUE_SIZE = 16777216; private static final List ONLY_HTTP1; private boolean awaitingPong; private Call call; private boolean enqueuedClose; private WebSocketExtensions extensions; private boolean failed; private final String key; private final WebSocketListener listener; private final ArrayDeque messageAndCloseQueue; private long minimumDeflateSize; private String name; private final Request originalRequest; private final long pingIntervalMillis; private final ArrayDeque pongQueue; private long queueSize; private final Random random; private WebSocketReader reader; private int receivedCloseCode; private String receivedCloseReason; private int receivedPingCount; private int receivedPongCount; private int sentPingCount; private Streams streams; private TaskQueue taskQueue; private WebSocketWriter writer; private Task writerTask; public RealWebSocket(TaskRunner taskRunner, Request request, WebSocketListener webSocketListener, Random random, long j, WebSocketExtensions webSocketExtensions, long j2) { C14957gcv.e(taskRunner, ""); C14957gcv.e(request, ""); C14957gcv.e(webSocketListener, ""); C14957gcv.e(random, ""); this.originalRequest = request; this.listener = webSocketListener; this.random = random; this.pingIntervalMillis = j; this.extensions = webSocketExtensions; this.minimumDeflateSize = j2; this.taskQueue = taskRunner.newQueue(); this.pongQueue = new ArrayDeque<>(); this.messageAndCloseQueue = new ArrayDeque<>(); this.receivedCloseCode = -1; if (!C14957gcv.b((Object) "GET", (Object) request.method())) { throw new IllegalArgumentException(C14957gcv.c("Request must be GET: ", (Object) request.method()).toString()); } C15155gij.LWm lWm = C15155gij.c; byte[] bArr = new byte[16]; random.nextBytes(bArr); C14866gag c14866gag = C14866gag.c; this.key = C15155gij.LWm.b(bArr, giE.d()).e(); } @Override // okhttp3.WebSocket public final long queueSize() { long j; synchronized (this) { j = this.queueSize; } return j; } @Override // okhttp3.WebSocket public final void cancel() { Call call = this.call; C14957gcv.e(call); call.cancel(); } public final void connect(OkHttpClient okHttpClient) { C14957gcv.e(okHttpClient, ""); if (this.originalRequest.header(HttpHeaders.SEC_WEBSOCKET_EXTENSIONS) != null) { failWebSocket(new ProtocolException("Request header not permitted: 'Sec-WebSocket-Extensions'"), null); return; } OkHttpClient build = okHttpClient.newBuilder().eventListener(EventListener.NONE).protocols(ONLY_HTTP1).build(); final Request build2 = this.originalRequest.newBuilder().header(HttpHeaders.UPGRADE, "websocket").header(HttpHeaders.CONNECTION, HttpHeaders.UPGRADE).header(HttpHeaders.SEC_WEBSOCKET_KEY, this.key).header(HttpHeaders.SEC_WEBSOCKET_VERSION, "13").header(HttpHeaders.SEC_WEBSOCKET_EXTENSIONS, "permessage-deflate").build(); RealCall realCall = new RealCall(build, build2, true); this.call = realCall; C14957gcv.e(realCall); realCall.enqueue(new Callback(this, build2) { // from class: okhttp3.internal.ws.RealWebSocket$connect$1 final Request $request; final RealWebSocket this$0; /* JADX INFO: Access modifiers changed from: package-private */ { this.this$0 = this; this.$request = build2; } @Override // okhttp3.Callback public final void onResponse(Call call, Response response) { boolean isValid; ArrayDeque arrayDeque; C14957gcv.e(call, ""); C14957gcv.e(response, ""); Exchange exchange = response.exchange(); try { this.this$0.checkUpgradeSuccess$okhttp(response, exchange); C14957gcv.e(exchange); RealWebSocket.Streams newWebSocketStreams = exchange.newWebSocketStreams(); WebSocketExtensions parse = WebSocketExtensions.Companion.parse(response.headers()); this.this$0.extensions = parse; isValid = this.this$0.isValid(parse); if (!isValid) { RealWebSocket realWebSocket = this.this$0; synchronized (realWebSocket) { arrayDeque = realWebSocket.messageAndCloseQueue; arrayDeque.clear(); realWebSocket.close(1010, "unexpected Sec-WebSocket-Extensions in response header"); } } try { StringBuilder sb = new StringBuilder(); sb.append(Util.okHttpName); sb.append(" WebSocket "); sb.append(this.$request.url().redact()); this.this$0.initReaderAndWriter(sb.toString(), newWebSocketStreams); this.this$0.getListener$okhttp().onOpen(this.this$0, response); this.this$0.loopReader(); } catch (Exception e) { this.this$0.failWebSocket(e, null); } } catch (IOException e2) { if (exchange != null) { exchange.webSocketUpgradeFailed(); } this.this$0.failWebSocket(e2, response); Util.closeQuietly(response); } } @Override // okhttp3.Callback public final void onFailure(Call call, IOException iOException) { C14957gcv.e(call, ""); C14957gcv.e(iOException, ""); this.this$0.failWebSocket(iOException, null); } }); } /* JADX INFO: Access modifiers changed from: private */ public final boolean isValid(WebSocketExtensions webSocketExtensions) { if (webSocketExtensions.unknownValues || webSocketExtensions.clientMaxWindowBits != null) { return false; } if (webSocketExtensions.serverMaxWindowBits == null) { return true; } C14973gde c14973gde = new C14973gde(8, 15); int intValue = webSocketExtensions.serverMaxWindowBits.intValue(); return c14973gde.b <= intValue && intValue <= c14973gde.d; } public final void checkUpgradeSuccess$okhttp(Response response, Exchange exchange) throws IOException { C14957gcv.e(response, ""); if (response.code() != 101) { StringBuilder sb = new StringBuilder("Expected HTTP 101 response but was '"); sb.append(response.code()); sb.append(' '); sb.append(response.message()); sb.append('\''); throw new ProtocolException(sb.toString()); } String header$default = Response.header$default(response, HttpHeaders.CONNECTION, null, 2, null); if (!gdZ.a(HttpHeaders.UPGRADE, header$default, true)) { StringBuilder sb2 = new StringBuilder("Expected 'Connection' header value 'Upgrade' but was '"); sb2.append((Object) header$default); sb2.append('\''); throw new ProtocolException(sb2.toString()); } String header$default2 = Response.header$default(response, HttpHeaders.UPGRADE, null, 2, null); if (!gdZ.a("websocket", header$default2, true)) { StringBuilder sb3 = new StringBuilder("Expected 'Upgrade' header value 'websocket' but was '"); sb3.append((Object) header$default2); sb3.append('\''); throw new ProtocolException(sb3.toString()); } String header$default3 = Response.header$default(response, HttpHeaders.SEC_WEBSOCKET_ACCEPT, null, 2, null); C15155gij.LWm lWm = C15155gij.c; String c = C14957gcv.c(this.key, (Object) WebSocketProtocol.ACCEPT_MAGIC); C14957gcv.e(c, ""); C14957gcv.e(c, ""); byte[] bytes = c.getBytes(gdP.a); C14957gcv.c(bytes, ""); C15155gij c15155gij = new C15155gij(bytes); c15155gij.d = c; String e = c15155gij.b(McElieceCCA2KeyGenParameterSpec.SHA1).e(); if (C14957gcv.b((Object) e, (Object) header$default3)) { if (exchange == null) { throw new ProtocolException("Web Socket exchange missing: bad interceptor?"); } return; } StringBuilder sb4 = new StringBuilder("Expected 'Sec-WebSocket-Accept' header value '"); sb4.append(e); sb4.append("' but was '"); sb4.append((Object) header$default3); sb4.append('\''); throw new ProtocolException(sb4.toString()); } public final void initReaderAndWriter(String str, Streams streams) throws IOException { C14957gcv.e(str, ""); C14957gcv.e(streams, ""); WebSocketExtensions webSocketExtensions = this.extensions; C14957gcv.e(webSocketExtensions); synchronized (this) { this.name = str; this.streams = streams; this.writer = new WebSocketWriter(streams.getClient(), streams.getSink(), this.random, webSocketExtensions.perMessageDeflate, webSocketExtensions.noContextTakeover(streams.getClient()), this.minimumDeflateSize); this.writerTask = new WriterTask(this); if (this.pingIntervalMillis != 0) { final long nanos = TimeUnit.MILLISECONDS.toNanos(this.pingIntervalMillis); TaskQueue taskQueue = this.taskQueue; final String c = C14957gcv.c(str, (Object) " ping"); taskQueue.schedule(new Task(c, this, nanos) { // from class: okhttp3.internal.ws.RealWebSocket$initReaderAndWriter$lambda-3$$inlined$schedule$1 final String $name; final long $pingIntervalNanos$inlined; final RealWebSocket this$0; /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */ { super(c, false, 2, null); this.$name = c; this.this$0 = this; this.$pingIntervalNanos$inlined = nanos; } @Override // okhttp3.internal.concurrent.Task public final long runOnce() { this.this$0.writePingFrame$okhttp(); return this.$pingIntervalNanos$inlined; } }, nanos); } if (!this.messageAndCloseQueue.isEmpty()) { runWriter(); } C14866gag c14866gag = C14866gag.c; } this.reader = new WebSocketReader(streams.getClient(), streams.getSource(), this, webSocketExtensions.perMessageDeflate, webSocketExtensions.noContextTakeover(!streams.getClient())); } public final void loopReader() throws IOException { while (this.receivedCloseCode == -1) { WebSocketReader webSocketReader = this.reader; C14957gcv.e(webSocketReader); webSocketReader.processNextFrame(); } } public final boolean processNextFrame() throws IOException { try { WebSocketReader webSocketReader = this.reader; C14957gcv.e(webSocketReader); webSocketReader.processNextFrame(); } catch (Exception e) { failWebSocket(e, null); } return this.receivedCloseCode == -1; } public final void awaitTermination(long j, TimeUnit timeUnit) throws InterruptedException { C14957gcv.e(timeUnit, ""); this.taskQueue.idleLatch().await(j, timeUnit); } public final void tearDown() throws InterruptedException { this.taskQueue.shutdown(); this.taskQueue.idleLatch().await(10L, TimeUnit.SECONDS); } public final int sentPingCount() { int i; synchronized (this) { i = this.sentPingCount; } return i; } public final int receivedPingCount() { int i; synchronized (this) { i = this.receivedPingCount; } return i; } public final int receivedPongCount() { int i; synchronized (this) { i = this.receivedPongCount; } return i; } @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback public final void onReadMessage(String str) throws IOException { C14957gcv.e(str, ""); this.listener.onMessage(this, str); } @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback public final void onReadMessage(C15155gij c15155gij) throws IOException { C14957gcv.e(c15155gij, ""); this.listener.onMessage(this, c15155gij); } @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback public final void onReadPing(C15155gij c15155gij) { synchronized (this) { C14957gcv.e(c15155gij, ""); if (!this.failed && (!this.enqueuedClose || !this.messageAndCloseQueue.isEmpty())) { this.pongQueue.add(c15155gij); runWriter(); this.receivedPingCount++; } } } @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback public final void onReadPong(C15155gij c15155gij) { synchronized (this) { C14957gcv.e(c15155gij, ""); this.receivedPongCount++; this.awaitingPong = false; } } @Override // okhttp3.internal.ws.WebSocketReader.FrameCallback public final void onReadClose(int i, String str) { Streams streams; WebSocketReader webSocketReader; WebSocketWriter webSocketWriter; C14957gcv.e(str, ""); if (i == -1) { throw new IllegalArgumentException("Failed requirement.".toString()); } synchronized (this) { if (this.receivedCloseCode != -1) { throw new IllegalStateException("already closed".toString()); } this.receivedCloseCode = i; this.receivedCloseReason = str; streams = null; if (this.enqueuedClose && this.messageAndCloseQueue.isEmpty()) { Streams streams2 = this.streams; this.streams = null; webSocketReader = this.reader; this.reader = null; webSocketWriter = this.writer; this.writer = null; this.taskQueue.shutdown(); streams = streams2; } else { webSocketReader = null; webSocketWriter = null; } C14866gag c14866gag = C14866gag.c; } try { this.listener.onClosing(this, i, str); if (streams != null) { this.listener.onClosed(this, i, str); } } finally { if (streams != null) { Util.closeQuietly(streams); } if (webSocketReader != null) { Util.closeQuietly(webSocketReader); } if (webSocketWriter != null) { Util.closeQuietly(webSocketWriter); } } } @Override // okhttp3.WebSocket public final boolean send(String str) { C14957gcv.e(str, ""); C15155gij.LWm lWm = C15155gij.c; C14957gcv.e(str, ""); C14957gcv.e(str, ""); byte[] bytes = str.getBytes(gdP.a); C14957gcv.c(bytes, ""); C15155gij c15155gij = new C15155gij(bytes); c15155gij.d = str; return send(c15155gij, 1); } @Override // okhttp3.WebSocket public final boolean send(C15155gij c15155gij) { C14957gcv.e(c15155gij, ""); return send(c15155gij, 2); } public final boolean pong(C15155gij c15155gij) { synchronized (this) { C14957gcv.e(c15155gij, ""); if (!this.failed && (!this.enqueuedClose || !this.messageAndCloseQueue.isEmpty())) { this.pongQueue.add(c15155gij); runWriter(); return true; } return false; } } @Override // okhttp3.WebSocket public final boolean close(int i, String str) { return close(i, str, CANCEL_AFTER_CLOSE_MILLIS); } public final boolean close(int i, String str, long j) { C15155gij c15155gij; synchronized (this) { WebSocketProtocol.INSTANCE.validateCloseCode(i); if (str != null) { C15155gij.LWm lWm = C15155gij.c; C14957gcv.e(str, ""); C14957gcv.e(str, ""); byte[] bytes = str.getBytes(gdP.a); C14957gcv.c(bytes, ""); c15155gij = new C15155gij(bytes); c15155gij.d = str; if (c15155gij.a() > 123) { throw new IllegalArgumentException(C14957gcv.c("reason.size() > 123: ", (Object) str).toString()); } } else { c15155gij = null; } if (!this.failed && !this.enqueuedClose) { this.enqueuedClose = true; this.messageAndCloseQueue.add(new Close(i, c15155gij, j)); runWriter(); return true; } return false; } } /* JADX WARN: Multi-variable type inference failed */ public final boolean writeOneFrame$okhttp() throws IOException { String str; Streams streams; Closeable closeable; Closeable closeable2; int i; boolean z; boolean z2; synchronized (this) { boolean z3 = this.failed; if (z3) { return false; } WebSocketWriter webSocketWriter = this.writer; C15155gij poll = this.pongQueue.poll(); final boolean z4 = true; Object obj = null; if (poll == null) { Object poll2 = this.messageAndCloseQueue.poll(); if (poll2 instanceof Close) { int i2 = this.receivedCloseCode; str = this.receivedCloseReason; if (i2 != -1) { streams = this.streams; this.streams = null; closeable = this.reader; this.reader = null; closeable2 = this.writer; this.writer = null; this.taskQueue.shutdown(); z2 = i2; obj = poll2; i = z2; } else { long cancelAfterCloseMillis = ((Close) poll2).getCancelAfterCloseMillis(); TaskQueue taskQueue = this.taskQueue; final String c = C14957gcv.c(this.name, (Object) " cancel"); taskQueue.schedule(new Task(c, z4, this) { // from class: okhttp3.internal.ws.RealWebSocket$writeOneFrame$lambda-8$$inlined$execute$default$1 final boolean $cancelable; final String $name; final RealWebSocket this$0; /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */ { super(c, z4); this.$name = c; this.$cancelable = z4; this.this$0 = this; } @Override // okhttp3.internal.concurrent.Task public final long runOnce() { this.this$0.cancel(); return -1L; } }, TimeUnit.MILLISECONDS.toNanos(cancelAfterCloseMillis)); streams = null; z = i2; } } else { if (poll2 == null) { return false; } str = null; streams = null; z = z3; } closeable = streams; closeable2 = closeable; z2 = z; obj = poll2; i = z2; } else { str = null; streams = null; closeable = null; closeable2 = null; i = z3; } C14866gag c14866gag = C14866gag.c; try { if (poll != null) { C14957gcv.e(webSocketWriter); webSocketWriter.writePong(poll); } else if (obj instanceof Message) { Message message = (Message) obj; C14957gcv.e(webSocketWriter); webSocketWriter.writeMessageFrame(message.getFormatOpcode(), message.getData()); synchronized (this) { this.queueSize -= message.getData().a(); C14866gag c14866gag2 = C14866gag.c; } } else if (obj instanceof Close) { Close close = (Close) obj; C14957gcv.e(webSocketWriter); webSocketWriter.writeClose(close.getCode(), close.getReason()); if (streams != null) { C14957gcv.e(str); this.listener.onClosed(this, i, str); } } else { throw new AssertionError(); } return true; } finally { if (streams != null) { Util.closeQuietly(streams); } if (closeable != null) { Util.closeQuietly(closeable); } if (closeable2 != null) { Util.closeQuietly(closeable2); } } } } public final void writePingFrame$okhttp() { synchronized (this) { if (this.failed) { return; } WebSocketWriter webSocketWriter = this.writer; if (webSocketWriter == null) { return; } int i = this.awaitingPong ? this.sentPingCount : -1; this.sentPingCount++; this.awaitingPong = true; C14866gag c14866gag = C14866gag.c; if (i != -1) { StringBuilder sb = new StringBuilder("sent ping but didn't receive pong within "); sb.append(this.pingIntervalMillis); sb.append("ms (after "); sb.append(i - 1); sb.append(" successful ping/pongs)"); failWebSocket(new SocketTimeoutException(sb.toString()), null); return; } try { webSocketWriter.writePing(C15155gij.e); } catch (IOException e) { failWebSocket(e, null); } } } public final void failWebSocket(Exception exc, Response response) { C14957gcv.e(exc, ""); synchronized (this) { if (this.failed) { return; } this.failed = true; Streams streams = this.streams; this.streams = null; WebSocketReader webSocketReader = this.reader; this.reader = null; WebSocketWriter webSocketWriter = this.writer; this.writer = null; this.taskQueue.shutdown(); C14866gag c14866gag = C14866gag.c; try { this.listener.onFailure(this, exc, response); } finally { if (streams != null) { Util.closeQuietly(streams); } if (webSocketReader != null) { Util.closeQuietly(webSocketReader); } if (webSocketWriter != null) { Util.closeQuietly(webSocketWriter); } } } } /* loaded from: classes6.dex */ public static final class Message { private final C15155gij data; private final int formatOpcode; public Message(int i, C15155gij c15155gij) { C14957gcv.e(c15155gij, ""); this.formatOpcode = i; this.data = c15155gij; } public final int getFormatOpcode() { return this.formatOpcode; } public final C15155gij getData() { return this.data; } } /* loaded from: classes6.dex */ public static final class Close { private final long cancelAfterCloseMillis; private final int code; private final C15155gij reason; public Close(int i, C15155gij c15155gij, long j) { this.code = i; this.reason = c15155gij; this.cancelAfterCloseMillis = j; } public final C15155gij getReason() { return this.reason; } public final int getCode() { return this.code; } public final long getCancelAfterCloseMillis() { return this.cancelAfterCloseMillis; } } /* loaded from: classes6.dex */ public static abstract class Streams implements Closeable { private final boolean client; private final InterfaceC15148gic sink; private final InterfaceC15149gid source; public Streams(boolean z, InterfaceC15149gid interfaceC15149gid, InterfaceC15148gic interfaceC15148gic) { C14957gcv.e(interfaceC15149gid, ""); C14957gcv.e(interfaceC15148gic, ""); this.client = z; this.source = interfaceC15149gid; this.sink = interfaceC15148gic; } public final InterfaceC15149gid getSource() { return this.source; } public final InterfaceC15148gic getSink() { return this.sink; } public final boolean getClient() { return this.client; } } /* loaded from: classes6.dex */ final class WriterTask extends Task { final RealWebSocket this$0; /* JADX WARN: 'super' call moved to the top of the method (can break code semantics) */ public WriterTask(RealWebSocket realWebSocket) { super(C14957gcv.c(realWebSocket.name, (Object) " writer"), false, 2, null); C14957gcv.e(realWebSocket, ""); this.this$0 = realWebSocket; } @Override // okhttp3.internal.concurrent.Task public final long runOnce() { try { return this.this$0.writeOneFrame$okhttp() ? 0L : -1L; } catch (IOException e) { this.this$0.failWebSocket(e, null); return -1L; } } } /* loaded from: classes6.dex */ public static final class Companion { private Companion() { } public /* synthetic */ Companion(C14953gcr c14953gcr) { this(); } } static { List singletonList = Collections.singletonList(Protocol.HTTP_1_1); C14957gcv.c(singletonList, ""); ONLY_HTTP1 = singletonList; } private final void runWriter() { if (!Util.assertionsEnabled || Thread.holdsLock(this)) { Task task = this.writerTask; if (task != null) { TaskQueue.schedule$default(this.taskQueue, task, 0L, 2, null); return; } return; } StringBuilder sb = new StringBuilder("Thread "); sb.append((Object) Thread.currentThread().getName()); sb.append(" MUST hold lock on "); sb.append(this); throw new AssertionError(sb.toString()); } private final boolean send(C15155gij c15155gij, int i) { synchronized (this) { if (!this.failed && !this.enqueuedClose) { if (this.queueSize + c15155gij.a() > MAX_QUEUE_SIZE) { close(1001, null); return false; } this.queueSize += c15155gij.a(); this.messageAndCloseQueue.add(new Message(i, c15155gij)); runWriter(); return true; } return false; } } @Override // okhttp3.WebSocket public final Request request() { return this.originalRequest; } public final WebSocketListener getListener$okhttp() { return this.listener; } }