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..07cf9b291e25 --- /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") + .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 260c5c17ec43..26efc5bf6263 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/connection/ConnectPlan.kt @@ -419,7 +419,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 fa0732811ded..c80a22f2fa8f 100644 --- a/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt +++ b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Connection.kt @@ -85,6 +85,19 @@ 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() + + /** + * 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() @@ -147,7 +160,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 +174,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 +499,41 @@ 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 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. + // + // 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, e) + } + + // 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) } @@ -1050,5 +1098,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/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt b/okhttp/src/commonJvmAndroid/kotlin/okhttp3/internal/http2/Http2Stream.kt index cfb42ea36fa4..c8a52ac46a92 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 cae668c3d806..385fd0cfb880 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 @@ -30,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 @@ -43,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 @@ -673,6 +677,116 @@ class Http2ConnectionTest { } } + /** + * 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) + } + + /** + * 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) + } + + /** + * 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())