From 792dcdca44df65d13eea06b98c214fdd61c9db0e Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Fri, 15 May 2026 16:05:40 -0500 Subject: [PATCH 1/6] Recover HTTP2 connection from half-open socket using pingInterval. A stateful firewall *CAN* silently kill a pooled HTTP2 connection at L3 (no RST, no FIN). When this happens with okhttp, the next frame write that fills the kernel TCP send buffer blocks indefinitely. pingInterval is documented to detect exactly this, but three issues prevented it from firing: * The ping watchdog ran on writerQueue, so it queued behind the wedged frame write and never ticked. Moved to its own pingQueue; the ping write itself is fire-and-forget onto writerQueue. * failConnection -> close -> shutdown -> writer.goAway() deadlocked on writer.lock held by the wedged write. failConnection now cancels the socket first to unblock the writer. * SSLSocket.close() can block for many seconds attempting to send close_notify on a half-open connection. ConnectPlan now closes the raw TCP socket before the SSL layer on cancel. This PR adds a container-tests repro using socat amd an iptables DROP to simulate such a firewall drop. It asserts the failure within 3x pingInterval. --- .../java/okhttp3/containers/DeadSocketTest.kt | 211 ++++++++++++++++++ .../internal/connection/ConnectPlan.kt | 12 +- .../okhttp3/internal/http2/Http2Connection.kt | 21 +- 3 files changed, 241 insertions(+), 3 deletions(-) create mode 100644 container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt diff --git a/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt b/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt new file mode 100644 index 000000000000..ef54813f2597 --- /dev/null +++ b/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2026 OkHttp Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package okhttp3.containers + +import assertk.assertFailure +import assertk.assertThat +import assertk.assertions.isInstanceOf +import assertk.assertions.isLessThan +import com.github.dockerjava.api.model.Capability +import java.io.IOException +import java.time.Duration +import java.util.concurrent.TimeUnit +import mockwebserver3.Dispatcher +import mockwebserver3.MockResponse +import mockwebserver3.MockWebServer +import mockwebserver3.RecordedRequest +import okhttp3.MediaType +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Protocol +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.Response +import okhttp3.tls.HandshakeCertificates +import okhttp3.tls.HeldCertificate +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.Timeout +import org.junit.jupiter.api.parallel.Isolated +import org.testcontainers.Testcontainers +import org.testcontainers.containers.GenericContainer +import org.testcontainers.containers.wait.strategy.Wait +import org.testcontainers.images.builder.ImageFromDockerfile + +/** + * Reproduces a stateful firewall silently killing a pooled HTTP/2 connection at L3 (no RST, no FIN) + * while a new stream is being written. A socat tunnel in an Alpine container with `NET_ADMIN` + * engages `iptables -j DROP` mid-test, after which the next HEADERS write fills the kernel TCP + * send buffer and blocks indefinitely waiting for ACKs that will never arrive. + * + * Asserts the design intent of [OkHttpClient.Builder.pingInterval]: a configured ping interval + * detects the dead connection and fails the call within a small multiple of the interval. + * + * Requires Docker with the `NET_ADMIN` capability (for `iptables -j DROP`). + */ +@Isolated +@Timeout(value = 30, unit = TimeUnit.SECONDS) +class DeadSocketTest { + private lateinit var rootCa: HeldCertificate + private lateinit var mockWebServer: MockWebServer + private lateinit var tunnel: GenericContainer<*> + private lateinit var client: OkHttpClient + + @BeforeEach + fun setUp() { + rootCa = + HeldCertificate + .Builder() + .certificateAuthority(0) + .build() + + val serverCert = + HeldCertificate + .Builder() + .addSubjectAlternativeName("localhost") + .signedBy(rootCa) + .build() + + val serverHandshakeCerts = + HandshakeCertificates + .Builder() + .heldCertificate(serverCert) + .build() + + mockWebServer = MockWebServer() + mockWebServer.useHttps(serverHandshakeCerts.sslSocketFactory()) + mockWebServer.protocols = listOf(Protocol.HTTP_2, Protocol.HTTP_1_1) + mockWebServer.dispatcher = + object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = + MockResponse + .Builder() + .code(200) + .body("ok") + .build() + } + mockWebServer.start() + + Testcontainers.exposeHostPorts(mockWebServer.port) + + tunnel = + GenericContainer( + ImageFromDockerfile() + .withDockerfileFromBuilder { builder -> + builder + .from("alpine:3.19") + .run("apk add --no-cache socat iptables") + .build() + }, + ).withCreateContainerCmdModifier { cmd -> + cmd.hostConfig!!.withCapAdd(Capability.NET_ADMIN) + }.withExposedPorts(TUNNEL_PORT) + .withCommand( + "socat", + "TCP-LISTEN:$TUNNEL_PORT,fork,reuseaddr", + "TCP:host.testcontainers.internal:${mockWebServer.port}", + ).waitingFor(Wait.forListeningPort()) + tunnel.start() + + val clientCerts = + HandshakeCertificates + .Builder() + .addTrustedCertificate(rootCa.certificate) + .build() + + client = + OkHttpClient + .Builder() + .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)) + .pingInterval(Duration.ofSeconds(1)) + // Isolate pingInterval detection latency from connect-retry latency: with retry on, the + // retry's new TCP+TLS handshake races against connectTimeout through the still-dead tunnel + // and would dominate the measured elapsed time. + .retryOnConnectionFailure(false) + .sslSocketFactory(clientCerts.sslSocketFactory(), clientCerts.trustManager) + .hostnameVerifier { hostname, _ -> hostname == "localhost" } + .build() + } + + @AfterEach + fun tearDown() { + client.connectionPool.evictAll() + client.dispatcher.executorService.shutdown() + mockWebServer.close() + tunnel.stop() + } + + /** + * Warms up a pooled HTTP/2 connection through a socat tunnel, then engages `iptables -j DROP` to + * silently kill the connection at L3. The next request carries oversized headers so the HEADERS + * write overflows the TCP send buffer and blocks. The 1s pingInterval should detect the dead + * connection within a few intervals. + */ + @Test + fun pingIntervalBoundsFailureOnDeadConnection() { + repeat(3) { i -> + sendPost("warmup-$i").use { response -> + check(response.code == 200) { "warm-up $i failed: ${response.code}" } + response.body.string() + } + } + + execInTunnel("iptables", "-I", "INPUT", "-p", "tcp", "--dport", "$TUNNEL_PORT", "-j", "DROP") + execInTunnel("iptables", "-I", "OUTPUT", "-p", "tcp", "--sport", "$TUNNEL_PORT", "-j", "DROP") + + val startNanos = System.nanoTime() + assertFailure { + sendPostWithLargeHeaders().use { it.body.string() } + }.isInstanceOf() + val elapsedSeconds = (System.nanoTime() - startNanos) / 1_000_000_000.0 + + // pingInterval is 1s; design intent is failure within a small multiple of the interval. + assertThat(elapsedSeconds).isLessThan(3.0) + } + + private fun sendPost(body: String): Response = + client + .newCall( + Request + .Builder() + .url("https://localhost:${tunnel.getMappedPort(TUNNEL_PORT)}/echo") + .post(body.toRequestBody(JSON)) + .build(), + ).execute() + + private fun sendPostWithLargeHeaders(): Response = + client + .newCall( + Request + .Builder() + .url("https://localhost:${tunnel.getMappedPort(TUNNEL_PORT)}/echo") + .post("hello".toRequestBody(JSON)) + .header("X-Padding", "X".repeat(LARGE_HEADER_SIZE)) + .build(), + ).execute() + + private fun execInTunnel(vararg command: String) { + val result = tunnel.execInContainer(*command) + check(result.exitCode == 0) { "container exec failed: ${result.stderr}" } + } + + companion object { + private const val TUNNEL_PORT = 8443 + private const val LARGE_HEADER_SIZE = 8 * 1024 * 1024 + private val JSON: MediaType = "application/json".toMediaType() + } +} diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt index e90421ccdc44..f84c868c586d 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt @@ -402,7 +402,17 @@ class ConnectPlan internal constructor( null } javaNetSocket = sslSocket - socket = sslSocket.asBufferedSocket() + val rawSocket = requireNotNull(rawSocket) { "TCP not connected" } + val sslBuffered = sslSocket.asBufferedSocket() + // Close the raw TCP socket before the SSL layer: SSLSocket.close() may block for many + // seconds attempting to send close_notify on a half-open connection. + socket = + object : BufferedSocket by sslBuffered { + override fun cancel() { + rawSocket.closeQuietly() + sslBuffered.cancel() + } + } protocol = if (maybeProtocol != null) Protocol.get(maybeProtocol) else Protocol.HTTP_1_1 success = true } finally { diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt index b79401a79f64..60a8f78a1cd2 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -85,6 +85,12 @@ class Http2Connection internal constructor( /** Asynchronously writes frames to the outgoing socket. */ private val writerQueue = taskRunner.newQueue() + /** + * Runs the periodic pingInterval watchdog. Separate from [writerQueue] so missing-pong detection + * still fires when the writer is wedged on a frame write to a half-open connection. + */ + private val pingQueue = taskRunner.newQueue() + /** Ensures push promise callbacks events are sent in order per stream. */ private val pushQueue = taskRunner.newQueue() @@ -147,7 +153,7 @@ class Http2Connection internal constructor( init { if (builder.pingIntervalMillis != 0) { val pingIntervalNanos = TimeUnit.MILLISECONDS.toNanos(builder.pingIntervalMillis.toLong()) - writerQueue.schedule("$connectionName ping", pingIntervalNanos) { + pingQueue.schedule("$connectionName ping", pingIntervalNanos) { val failDueToMissingPong = withLock { if (intervalPongsReceived < intervalPingsSent) { @@ -161,7 +167,12 @@ class Http2Connection internal constructor( failConnection(null) return@schedule -1L } else { - writePing(false, INTERVAL_PING, 0) + // Fire-and-forget the ping write so the watchdog returns promptly. If writer.lock is + // held by a wedged frame write, the ping queues behind it; the next tick sees + // pongs < pings and fails the connection, which cancels the socket and unblocks the writer. + writerQueue.execute("$connectionName ping write") { + writePing(false, INTERVAL_PING, 0) + } return@schedule pingIntervalNanos } } @@ -481,11 +492,17 @@ class Http2Connection internal constructor( // Release the threads. writerQueue.shutdown() + pingQueue.shutdown() pushQueue.shutdown() settingsListenerQueue.shutdown() } private fun failConnection(e: IOException?) { + // Cancel the socket before close() so any thread blocked on writer.lock unblocks first; + // otherwise close() -> shutdown() -> writer.goAway() would deadlock on the same lock. + ignoreIoExceptions { + socket.cancel() + } close(ErrorCode.PROTOCOL_ERROR, ErrorCode.PROTOCOL_ERROR, e) } From 333d1ad8f27079b3ad85f8b71108f6c839071398 Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Fri, 15 May 2026 17:15:24 -0500 Subject: [PATCH 2/6] Pin alpine to 3 3.19 is gone --- .../src/test/java/okhttp3/containers/DeadSocketTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt b/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt index ef54813f2597..07cf9b291e25 100644 --- a/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt +++ b/container-tests/src/test/java/okhttp3/containers/DeadSocketTest.kt @@ -107,7 +107,7 @@ class DeadSocketTest { ImageFromDockerfile() .withDockerfileFromBuilder { builder -> builder - .from("alpine:3.19") + .from("alpine:3") .run("apk add --no-cache socat iptables") .build() }, From f6a48860c91f5d5510eb6d89d36a29af00a8e874 Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Fri, 15 May 2026 18:04:17 -0500 Subject: [PATCH 3/6] Preserve StreamResetException(PROTOCOL_ERROR) when pingInterval fails the connection. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restores the contract asserted by HttpOverHttp2Test.missingPongsFailsConnection. The earlier dead-socket fix made failConnection() cancel the socket before calling close(), to unblock a writer stuck on a half-open TCP send. That ordering also surfaced SocketException("Socket closed") to in-flight callers instead of the StreamResetException(PROTOCOL_ERROR) they previously saw, because the reader thread's socket read returns SocketException before close() -> stream.close() has a chance to set errorCode on Http2Stream. So: mark active streams with closeLater(PROTOCOL_ERROR) up front, before cancelling the socket. closeLater enqueues the RST_STREAM via writerQueue rather than writing it synchronously under writer.lock — that lock is held by the stuck frame write, so close()'s synchronous RST_STREAM path would itself block. With errorCode set then Http2Stream.closeInternal returns early on subseqent calls and a racing failConnection from the reader thread can not overwrite the callers StreamResetException with the SocketException it caught. --- .../okhttp3/internal/http2/Http2Connection.kt | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt index 60a8f78a1cd2..5b3751afd7ad 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -498,8 +498,22 @@ class Http2Connection internal constructor( } private fun failConnection(e: IOException?) { - // Cancel the socket before close() so any thread blocked on writer.lock unblocks first; - // otherwise close() -> shutdown() -> writer.goAway() would deadlock on the same lock. + // Mark active streams with PROTOCOL_ERROR before socket.cancel() so the caller surfaces + // StreamResetException(PROTOCOL_ERROR) on its waiting read or write. + // + // Note that if we cancel first: the reader thread's blocked socket read returns SocketException, + // which can reach the caller before close() -> stream.close() sets errorCode in Http2Stream.closeInternal. + // + // We use closeLater() (which enqueues RST_STREAM via writerQueue) rather than close(): the latter + // writes RST_STREAM synchronously under writer.lock, and that lock is already held by the + // frame write that's blocked on the half-open socket. See pingQueue. + val streamsToClose: Array? = + withLock { + if (streams.isNotEmpty()) streams.values.toTypedArray() else null + } + streamsToClose?.forEach { stream -> + stream.closeLater(ErrorCode.PROTOCOL_ERROR) + } ignoreIoExceptions { socket.cancel() } From 966e1743ba778766630695e5aa2ccc255af0baa4 Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Wed, 18 Nov 2026 12:54:56 -0600 Subject: [PATCH 4/6] keep the caused-by exception when failConnection closes streams --- .../okhttp3/internal/http2/Http2Connection.kt | 2 +- .../okhttp3/internal/http2/Http2Stream.kt | 8 +++-- .../internal/http2/Http2ConnectionTest.kt | 32 +++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt index 5b3751afd7ad..f28954f1433d 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -512,7 +512,7 @@ class Http2Connection internal constructor( if (streams.isNotEmpty()) streams.values.toTypedArray() else null } streamsToClose?.forEach { stream -> - stream.closeLater(ErrorCode.PROTOCOL_ERROR) + stream.closeLater(ErrorCode.PROTOCOL_ERROR, e) } ignoreIoExceptions { socket.cancel() diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt index 2c1b1779023a..eda0c3bb0cd8 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt @@ -256,9 +256,13 @@ class Http2Stream internal constructor( /** * Abnormally terminate this stream. This enqueues a `RST_STREAM` frame and returns immediately. + * When not null, [errorException] is what callers blocked on this stream will throw. */ - fun closeLater(errorCode: ErrorCode) { - if (!closeInternal(errorCode, null)) { + fun closeLater( + errorCode: ErrorCode, + errorException: IOException? = null, + ) { + if (!closeInternal(errorCode, errorException)) { return // Already closed. } connection.writeSynResetLater(id, errorCode) diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt index a073f1d41b61..dd2decc83c69 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt @@ -23,6 +23,7 @@ import assertk.assertions.isEqualTo import assertk.assertions.isFalse import assertk.assertions.isGreaterThan import assertk.assertions.isLessThan +import assertk.assertions.isNotInstanceOf import assertk.assertions.isNull import assertk.assertions.isTrue import java.io.EOFException @@ -510,6 +511,37 @@ class Http2ConnectionTest { connection.newStream(headerEntries("b", longString), false) } } + /** + * When a write fails with an IOException, a stream that is waiting on the connection must + * surface that very exception. A StreamResetException would hide the actual cause of the + * failure. + */ + @Test fun failedWriteSurfacesCauseToWaitingStream() { + peer.sendFrame().settings(Settings()) + peer.acceptFrame() // ACK + peer.acceptFrame() // SYN_STREAM + peer.play() + val socket = peer.openSocket() + val connection = + Http2Connection + .Builder(true, TaskRunner.INSTANCE) + .socket(socket.asBufferedSocket(), "peer") + .pushObserver(IGNORE) + .build() + connection.start(sendConnectionPreface = false) + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_SETTINGS) + val stream = connection.newStream(headerEntries("b", "banana"), false) + + // The next write fails with an IOException, which then fails the connection. + socket.shutdownOutput() + connection.writePing(false, 1, 2) + + val expected = + assertFailsWith { + stream.takeHeaders() + } + assertThat(expected).isNotInstanceOf(StreamResetException::class.java) + } @Test fun clientCreatesStreamAndServerReplies() { // Write the mocking script. From abef912840af8fbb709ac56a6a5d99b34e7333e2 Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Wed, 18 Nov 2026 12:57:37 -0600 Subject: [PATCH 5/6] in failConnection, send GOAWAY before cancelling the socket --- .../okhttp3/internal/http2/Http2Connection.kt | 26 ++++++++++++++++--- .../internal/http2/Http2ConnectionTest.kt | 26 +++++++++++++++++++ 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt index f28954f1433d..bd131b76c0b1 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -91,6 +91,13 @@ class Http2Connection internal constructor( */ private val pingQueue = taskRunner.newQueue() + /** + * Runs the fallback that cancels the socket when a failed connection could not be closed + * gracefully. Separate from [pingQueue] and [writerQueue] because the thread that fails the + * connection can be one of their threads, and it blocks while it waits for the writer. + */ + private val cancelQueue = taskRunner.newQueue() + /** Ensures push promise callbacks events are sent in order per stream. */ private val pushQueue = taskRunner.newQueue() @@ -493,13 +500,14 @@ class Http2Connection internal constructor( // Release the threads. writerQueue.shutdown() pingQueue.shutdown() + cancelQueue.shutdown() pushQueue.shutdown() settingsListenerQueue.shutdown() } private fun failConnection(e: IOException?) { - // Mark active streams with PROTOCOL_ERROR before socket.cancel() so the caller surfaces - // StreamResetException(PROTOCOL_ERROR) on its waiting read or write. + // Mark active streams with PROTOCOL_ERROR before the socket is cancelled so the caller surfaces + // StreamResetException(PROTOCOL_ERROR), or [e], on its waiting read or write. // // Note that if we cancel first: the reader thread's blocked socket read returns SocketException, // which can reach the caller before close() -> stream.close() sets errorCode in Http2Stream.closeInternal. @@ -514,8 +522,17 @@ class Http2Connection internal constructor( streamsToClose?.forEach { stream -> stream.closeLater(ErrorCode.PROTOCOL_ERROR, e) } - ignoreIoExceptions { - socket.cancel() + + // close() sends the peer a GOAWAY frame, and it does so while holding writer.lock. If another + // thread is blocked writing to a half-open socket, that thread holds the lock and the GOAWAY + // cannot be sent. So arrange for the socket to be cancelled after a short delay: the blocked + // write then fails and releases the lock. If close() finishes first, it shuts down cancelQueue + // and the cancel never runs. + cancelQueue.schedule("$connectionName cancel socket", FAIL_CONNECTION_CANCEL_DELAY_NS) { + ignoreIoExceptions { + socket.cancel() + } + return@schedule -1L } close(ErrorCode.PROTOCOL_ERROR, ErrorCode.PROTOCOL_ERROR, e) } @@ -1073,5 +1090,6 @@ class Http2Connection internal constructor( const val DEGRADED_PING = 2 const val AWAIT_PING = 3 const val DEGRADED_PONG_TIMEOUT_NS = 1_000_000_000 // 1 second. + const val FAIL_CONNECTION_CANCEL_DELAY_NS = 500_000_000L // 0.5 seconds. } } diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt index dd2decc83c69..0889d931faf3 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt @@ -542,6 +542,32 @@ class Http2ConnectionTest { } assertThat(expected).isNotInstanceOf(StreamResetException::class.java) } + /** + * When the connection fails because the peer never answers a ping, the peer is told with a + * `GOAWAY` frame, as long as the socket can still carry it. + */ + @Test fun missingPongSendsGoAwayToPeer() { + peer.sendFrame().settings(Settings()) + peer.acceptFrame() // ACK + peer.acceptFrame() // PING + peer.acceptFrame() // GOAWAY + peer.play() + val connection = + Http2Connection + .Builder(true, TaskRunner.INSTANCE) + .socket(peer.openSocket().asBufferedSocket(), "peer") + .pushObserver(IGNORE) + .pingIntervalMillis(50) + .build() + connection.start(sendConnectionPreface = false) + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_SETTINGS) + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_PING) + + // The peer never answers the ping, so the next interval fails the connection. + val goAway = peer.takeFrame() + assertThat(goAway.type).isEqualTo(Http2.TYPE_GOAWAY) + assertThat(goAway.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR) + } @Test fun clientCreatesStreamAndServerReplies() { // Write the mocking script. From f6f8ec74f8b59c86cc84be3eeeb4d26ec5390c39 Mon Sep 17 00:00:00 2001 From: Joel Caplin Date: Wed, 18 Nov 2026 12:59:42 -0600 Subject: [PATCH 6/6] gap - test that the ping interval unblocks a write stuck on a half-open socket --- .../internal/http2/Http2ConnectionTest.kt | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt index 0889d931faf3..e155c2a110c3 100644 --- a/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt +++ b/okhttp/src/jvmTest/kotlin/okhttp3/internal/http2/Http2ConnectionTest.kt @@ -31,6 +31,7 @@ import java.io.IOException import java.io.InterruptedIOException import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlin.test.assertFailsWith import okhttp3.Headers @@ -44,10 +45,12 @@ import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.concurrent.notifyAll import okhttp3.internal.concurrent.wait import okhttp3.internal.concurrent.withLock +import okhttp3.internal.connection.BufferedSocket import okhttp3.internal.connection.asBufferedSocket import okio.AsyncTimeout import okio.Buffer import okio.BufferedSource +import okio.ForwardingSink import okio.Source import okio.buffer import org.junit.jupiter.api.AfterEach @@ -511,6 +514,7 @@ class Http2ConnectionTest { connection.newStream(headerEntries("b", longString), false) } } + /** * When a write fails with an IOException, a stream that is waiting on the connection must * surface that very exception. A StreamResetException would hide the actual cause of the @@ -542,6 +546,7 @@ class Http2ConnectionTest { } assertThat(expected).isNotInstanceOf(StreamResetException::class.java) } + /** * When the connection fails because the peer never answers a ping, the peer is told with a * `GOAWAY` frame, as long as the socket can still carry it. @@ -569,6 +574,57 @@ class Http2ConnectionTest { assertThat(goAway.errorCode).isEqualTo(ErrorCode.PROTOCOL_ERROR) } + /** + * A frame write that blocks on a half-open socket holds the writer lock. The ping interval must + * still notice the missing pong and fail the connection, which SHOULD unblock the stuck write. + */ + @Test fun missingPongUnblocksWriteStuckOnHalfOpenSocket() { + peer.sendFrame().settings(Settings()) + peer.acceptFrame() // ACK + peer.play() + val realSocket = peer.openSocket().asBufferedSocket() + val halfOpen = AtomicBoolean() + val cancelled = CountDownLatch(1) + val socket = + object : BufferedSocket { + override val source = realSocket.source + override val sink = + object : ForwardingSink(realSocket.sink) { + override fun write( + source: Buffer, + byteCount: Long, + ) { + if (halfOpen.get()) { + cancelled.await() + throw IOException("socket cancelled") + } + super.write(source, byteCount) + } + }.buffer() + + override fun cancel() { + realSocket.cancel() + cancelled.countDown() + } + } + val connection = + Http2Connection + .Builder(true, TaskRunner.INSTANCE) + .socket(socket, "peer") + .pushObserver(IGNORE) + .pingIntervalMillis(50) + .build() + connection.start(sendConnectionPreface = false) + assertThat(peer.takeFrame().type).isEqualTo(Http2.TYPE_SETTINGS) + + // The socket accepts no more bytes and never answers, so this write blocks forever, unless the + // connection is failed. + halfOpen.set(true) + assertFailsWith { + connection.newStream(headerEntries("b", "banana"), false) + } + } + @Test fun clientCreatesStreamAndServerReplies() { // Write the mocking script. peer.sendFrame().settings(Settings())