Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

fix: preserve half-close in AVF TCP forwarding

Commiemusclemommie96deddec79f6
diff --git a/CLAUDE.md b/CLAUDE.md
index 4520333..b24605e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -222,7 +222,7 @@ In `QemuEngine.buildCommand()`: `tcg,thread=multi`, larger `tb-size` for ≥2GB
- **`CONFIG_DEVTMPFS_MOUNT=y` pre-mounts `/dev` before `/init` runs.** `init-podroid` must use `mount ... || true` for the devtmpfs line — the kernel's pre-populated `/dev` is sufficient and a second `mount(2)` returns EBUSY. Also: `size=` is not valid for devtmpfs in kernels where it is ramfs-backed (causes EINVAL). Either failure exits util-linux with `MNT_EX_FAIL=32`; `set -e` propagates `exit(32)`, encoded as `exitcode=0x00002000` ("Attempted to kill init!"). Always keep the `|| true`.
- **util-linux `mount` stops option parsing at the first non-option argument** when `POSIXLY_CORRECT` is set. Put `-o` flags *before* device and mountpoint (`mount -t proc -o noexec,nosuid,nodev proc /proc`), not after. Options placed after the mountpoint are silently dropped, causing `mount(2)` to be called with `flags=0` and returning EPERM — which util-linux prints as "must be superuser to use mount" even for root.
- **`Dockerfile` heredoc gotcha.** Docker BuildKit's parser treats `[section]` lines inside `RUN ... << 'EOF'` heredocs as unknown Dockerfile instructions and aborts the parse. Instead of using shell heredocs in `RUN` for multi-line config files, use `COPY build-tools/<file>` from the build context. The Meson cross-compilation config lives in `build-tools/cross-android-aarch64.ini` for this reason.
-- **Backend asymmetry is the #1 source of bugs.** QEMU = SLIRP + QMP + virtio-console (TTY); AVF = DHCP + vsock (raw sockets). Test both. The host bridge's `cfmakeraw` on hvc2 (above) is a concrete example.
+- **Backend asymmetry is the #1 source of bugs.** QEMU = SLIRP + QMP + virtio-console (TTY); AVF = DHCP + vsock (raw sockets). Test both. The host bridge's `cfmakeraw` on hvc2 (above) is a concrete example. AVF TCP forwarding preserves half-close: EOF shuts down only the destination output; failures/cancellation abort both endpoints, with raw-vsock `Os.shutdown` serialized before descriptor closure.
- **Boot detection** scans a rolling buffer, not per-read chunks (fast devices split markers).
- **Bridge stderr is silenced** (`dup2(/dev/null, STDERR)`): it runs as a `TerminalSession` subprocess whose stderr IS the PTY. Never add `fprintf(stderr, ...)` to `podroid-bridge.c`.
- **`forceUpdateSizeFromView` must not multiply by scaledDensity** - `TerminalView` passes the raw int textSize to `Paint`; mismatched math renders TUI apps in the wrong grid.
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfTcpRelay.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfTcpRelay.kt
new file mode 100644
index 0000000..4b34325
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfTcpRelay.kt
@@ -0,0 +1,274 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * Bidirectional stream relay used by the AVF TCP forwarder. The endpoint
+ * contract deliberately keeps half-close separate from abort: EOF on one
+ * input shuts down only the other endpoint's output, while failures and
+ * cancellation tear down both directions.
+ */
+package com.excp.podroid.engine.avf
+
+import android.os.ParcelFileDescriptor
+import android.system.Os
+import android.system.OsConstants
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.joinAll
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.NonCancellable
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.net.Socket
+import java.util.concurrent.atomic.AtomicBoolean
+
+/** The small ownership boundary needed by [BidirectionalRelay]. */
+internal interface RelayEndpoint {
+ val input: InputStream
+ val output: OutputStream
+
+ /** Propagate a clean input EOF without closing the input half. */
+ fun shutdownOutput()
+
+ /** Interrupt blocked native I/O and release all endpoint resources. */
+ fun abort()
+
+ /** Release resources after both directions have completed cleanly. */
+ fun close()
+}
+
+/**
+ * Relays two connected stream endpoints while preserving TCP-style half-close.
+ * Exactly two IO pump coroutines are used for the data paths. The short-lived
+ * cancellation watcher is per relay, so cancellation can wake blocking native
+ * reads without registering a permanent watcher on the forwarder's scope.
+ */
+internal class BidirectionalRelay(
+ private val source: RelayEndpoint,
+) {
+ private val lock = Any()
+ private var destination: RelayEndpoint? = null
+ private var started = false
+ private var aborted = false
+
+ /** Attaches the second endpoint, or aborts it if close won the race. */
+ fun attach(endpoint: RelayEndpoint): Boolean {
+ val accepted = synchronized(lock) {
+ if (aborted || started || destination != null) {
+ false
+ } else {
+ destination = endpoint
+ true
+ }
+ }
+ if (!accepted) endpoint.abort()
+ return accepted
+ }
+
+ /** Idempotently interrupts both endpoints, including a late attachment. */
+ fun abort() {
+ val endpoints = synchronized(lock) {
+ if (aborted) return
+ aborted = true
+ listOfNotNull(source, destination)
+ }
+ endpoints.forEach { runCatching { it.abort() } }
+ }
+
+ suspend fun run() {
+ val peer = synchronized(lock) {
+ if (aborted) null else destination?.also { started = true }
+ }
+ if (peer == null) {
+ closeEndpoints()
+ return
+ }
+
+ var completed = false
+ try {
+ runPumps(peer)
+ completed = true
+ } finally {
+ if (!completed) abort()
+ closeEndpoints()
+ }
+ }
+
+ private suspend fun runPumps(peer: RelayEndpoint) = coroutineScope {
+ val completed = AtomicBoolean(false)
+ // Coroutine cancellation does not reliably interrupt a blocking read
+ // on a native socket. This watcher exists only for this relay run and
+ // aborts the endpoints before structured cancellation waits on pumps.
+ val cancellationWatcher = launch(
+ Dispatchers.IO,
+ start = CoroutineStart.UNDISPATCHED,
+ ) {
+ try {
+ awaitCancellation()
+ } finally {
+ if (!completed.get()) abort()
+ }
+ }
+
+ try {
+ val leftToRight = launch(Dispatchers.IO) { pump(source, peer) }
+ val rightToLeft = launch(Dispatchers.IO) { pump(peer, source) }
+ joinAll(leftToRight, rightToLeft)
+ completed.set(true)
+ } finally {
+ if (!completed.get()) abort()
+ withContext(NonCancellable) {
+ cancellationWatcher.cancelAndJoin()
+ }
+ }
+ }
+
+ private fun pump(from: RelayEndpoint, to: RelayEndpoint) {
+ val buffer = ByteArray(16 * 1024)
+ try {
+ while (true) {
+ val count = from.input.read(buffer)
+ if (count <= 0) {
+ to.shutdownOutput()
+ return
+ }
+ to.output.write(buffer, 0, count)
+ to.output.flush()
+ }
+ } catch (e: CancellationException) {
+ abort()
+ throw e
+ } catch (_: IOException) {
+ abort()
+ } catch (_: Exception) {
+ // Android's Os methods report some native I/O failures as an
+ // exception other than IOException. They are still hard relay
+ // failures and must not leave the opposite pump blocked.
+ abort()
+ }
+ }
+
+ private fun closeEndpoints() {
+ val endpoints = synchronized(lock) { listOfNotNull(source, destination) }
+ endpoints.forEach { runCatching { it.close() } }
+ }
+}
+
+/** TCP endpoint whose clean output shutdown preserves its input half. */
+internal class SocketRelayEndpoint(
+ private val socket: Socket,
+) : RelayEndpoint {
+ private val lock = Any()
+ private var outputShutdown = false
+ private var closed = false
+
+ override val input: InputStream = socket.getInputStream()
+ override val output: OutputStream = socket.getOutputStream()
+
+ override fun shutdownOutput() {
+ synchronized(lock) {
+ if (closed || outputShutdown) return
+ socket.shutdownOutput()
+ outputShutdown = true
+ }
+ }
+
+ override fun abort() {
+ synchronized(lock) {
+ if (closed) return
+ closed = true
+ runCatching { socket.shutdownInput() }
+ runCatching { socket.shutdownOutput() }
+ runCatching { socket.close() }
+ }
+ }
+
+ override fun close() {
+ synchronized(lock) {
+ if (closed) return
+ closed = true
+ runCatching { socket.close() }
+ }
+ }
+}
+
+/**
+ * Raw AF_VSOCK endpoint. Each AutoClose stream owns a distinct descriptor;
+ * shutdown/close are serialized so a reused descriptor cannot be shut down by
+ * a late operation from an older connection.
+ */
+internal class VsockRelayEndpoint private constructor(
+ private val inputPfd: ParcelFileDescriptor,
+ private val outputPfd: ParcelFileDescriptor,
+ override val input: InputStream,
+ override val output: OutputStream,
+) : RelayEndpoint {
+ private val lock = Any()
+ private var outputShutdown = false
+ private var closed = false
+
+ companion object {
+ fun open(pfd: ParcelFileDescriptor): VsockRelayEndpoint {
+ val outputPfd = try {
+ pfd.dup()
+ } catch (t: Throwable) {
+ runCatching { pfd.close() }
+ throw t
+ }
+ val input = try {
+ ParcelFileDescriptor.AutoCloseInputStream(pfd)
+ } catch (t: Throwable) {
+ runCatching { outputPfd.close() }
+ runCatching { pfd.close() }
+ throw t
+ }
+ val output = try {
+ ParcelFileDescriptor.AutoCloseOutputStream(outputPfd)
+ } catch (t: Throwable) {
+ runCatching { input.close() }
+ runCatching { outputPfd.close() }
+ throw t
+ }
+ return VsockRelayEndpoint(pfd, outputPfd, input, output)
+ }
+ }
+
+ override fun shutdownOutput() {
+ synchronized(lock) {
+ if (closed || outputShutdown) return
+ try {
+ Os.shutdown(outputPfd.fileDescriptor, OsConstants.SHUT_WR)
+ outputShutdown = true
+ } catch (e: Exception) {
+ throw IOException("vsock shutdown(SHUT_WR) failed", e)
+ }
+ }
+ }
+
+ override fun abort() {
+ synchronized(lock) {
+ if (closed) return
+ closed = true
+ // The native shutdown must happen before either AutoClose stream
+ // closes its descriptor. This is also the wakeup for blocked reads.
+ runCatching { Os.shutdown(inputPfd.fileDescriptor, OsConstants.SHUT_RDWR) }
+ runCatching { input.close() }
+ runCatching { output.close() }
+ }
+ }
+
+ override fun close() {
+ synchronized(lock) {
+ if (closed) return
+ closed = true
+ runCatching { input.close() }
+ runCatching { output.close() }
+ }
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt b/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt
index 69d279b..e40491b 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt
@@ -18,21 +18,51 @@ import android.os.Build
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.annotation.RequiresApi
+import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
-import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
+import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.launch
-import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Semaphore
-import java.io.InputStream
-import java.io.OutputStream
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.net.SocketException
+import java.util.concurrent.atomic.AtomicBoolean
+
+/**
+ * Owns the resources acquired for one accepted connection until its coroutine
+ * completes, including the case where cancellation wins before the body starts.
+ */
+internal class RelayJobCompletion(
+ private val abort: () -> Unit,
+ private val remove: () -> Unit,
+ private val release: () -> Unit,
+) {
+ private val completed = AtomicBoolean(false)
+
+ fun attach(job: Job) {
+ job.invokeOnCompletion { cleanup() }
+ }
+
+ fun cleanup() {
+ if (!completed.compareAndSet(false, true)) return
+ try {
+ abort()
+ } finally {
+ try {
+ remove()
+ } finally {
+ release()
+ }
+ }
+ }
+}
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
class VsockPortForwarder(
@@ -60,14 +90,17 @@ class VsockPortForwarder(
}
private var server: ServerSocket? = null
+ private var acceptCancellationWatcher: Job? = null
// Parent of every per-connection coroutine so close() cancels them all at
// once and completed connections don't accumulate Job references for the
// forwarder's lifetime (the old plain list never removed finished jobs).
- private val connections = SupervisorJob()
+ private val connections = SupervisorJob(scope.coroutineContext[Job])
private var acceptJob: Job? = null
- // Live client sockets — force-closed in close() so a pump blocked in a
- // native read() unblocks (cancel() alone can't interrupt a blocking read).
- private val openSockets = java.util.Collections.synchronizedSet(mutableSetOf<Socket>())
+ // Registration happens before the synchronous framework connectVsock call.
+ // A close can therefore abort the TCP side immediately and reject a raw
+ // vsock endpoint returned after that call races with close().
+ private val lifecycleLock = Any()
+ private val activeRelays = mutableSetOf<BidirectionalRelay>()
// Caps concurrent in-flight proxy() coroutines so an accept burst can't
// exhaust fds/coroutines. tryAcquire (non-suspending) keeps the accept loop
// hot: when the cap is hit we drop the new connection immediately rather than
@@ -77,76 +110,118 @@ class VsockPortForwarder(
override fun start() {
val s = ServerSocket(hostPort, /* backlog */ 16, InetAddress.getByName(bindAddress))
- server = s
- Log.d(TAG, "listening on $bindAddress:$hostPort → vsock:$guestVsockPort")
- // The accept loop blocks on ServerSocket.accept() for the forwarder's
- // whole lifetime, so it runs on the shared AvfForwarderDispatcher
- // rather than the 64-thread-capped Dispatchers.IO (see its doc).
- acceptJob = AvfForwarderDispatcher.launch(scope) {
- while (!closed) {
- val client = try { s.accept() } catch (_: SocketException) { break }
- if (!inflight.tryAcquire()) {
- Log.w(TAG, "inflight cap ($MAX_INFLIGHT) reached on :$hostPort; dropping connection")
- runCatching { client.close() }
- continue
+ synchronized(lifecycleLock) {
+ if (closed) {
+ runCatching { s.close() }
+ return
+ }
+ // Publish the listener under the same lock close() uses. Otherwise
+ // close() can observe null, return, and leave this socket behind.
+ server = s
+ Log.d(TAG, "listening on $bindAddress:$hostPort → vsock:$guestVsockPort")
+ // The accept loop blocks on ServerSocket.accept() for the forwarder's
+ // whole lifetime, so it runs on the shared AvfForwarderDispatcher
+ // rather than the 64-thread-capped Dispatchers.IO (see its doc).
+ val accept = AvfForwarderDispatcher.launch(scope) {
+ while (!closed) {
+ currentCoroutineContext().ensureActive()
+ val client = try { s.accept() } catch (_: SocketException) { break }
+ try {
+ currentCoroutineContext().ensureActive()
+ } catch (e: CancellationException) {
+ runCatching { client.close() }
+ throw e
+ }
+ if (!inflight.tryAcquire()) {
+ Log.w(TAG, "inflight cap ($MAX_INFLIGHT) reached on :$hostPort; dropping connection")
+ runCatching { client.close() }
+ continue
+ }
+
+ val relay = BidirectionalRelay(SocketRelayEndpoint(client))
+ val registered = synchronized(lifecycleLock) {
+ if (closed) {
+ false
+ } else {
+ activeRelays.add(relay)
+ true
+ }
+ }
+ if (!registered) {
+ relay.abort()
+ inflight.release()
+ continue
+ }
+ val completion = RelayJobCompletion(
+ abort = relay::abort,
+ remove = { synchronized(lifecycleLock) { activeRelays.remove(relay) } },
+ release = inflight::release,
+ )
+ val connection = try {
+ // Lazy start closes the registration window: the
+ // completion handler is installed before any body can
+ // run, while still handling a parent already cancelled.
+ scope.launch(Dispatchers.IO + connections, start = CoroutineStart.LAZY) {
+ proxy(relay)
+ }
+ } catch (t: Throwable) {
+ completion.cleanup()
+ throw t
+ }
+ completion.attach(connection)
+ connection.start()
}
- openSockets.add(client)
- scope.launch(Dispatchers.IO + connections) {
- try { proxy(client) } finally { inflight.release() }
+ }
+ acceptJob = accept
+ // Coroutine cancellation does not interrupt a native accept(). This
+ // watcher is scoped to this listener run; it closes the endpoint
+ // when the owning scope is cancelled, and is cancelled by close().
+ acceptCancellationWatcher = scope.launch(Dispatchers.IO, start = CoroutineStart.UNDISPATCHED) {
+ try {
+ accept.join()
+ } finally {
+ close()
}
}
}
}
- private suspend fun proxy(tcp: Socket) = coroutineScope {
- val pfd = connectVsockWithRetry()
- if (pfd == null) {
- openSockets.remove(tcp)
- runCatching { tcp.close() }
- return@coroutineScope
- }
- // FD ownership: the read side owns `pfd`; the write side owns a dup of
- // it. Each AutoClose stream closes exactly ONE descriptor, and there is
- // no explicit pfd.close() in the finally. The previous code wrapped the
- // SAME pfd in both an AutoCloseInputStream and an AutoCloseOutputStream
- // AND closed it again in finally — three closers of one descriptor, a
- // classic double-close / FD-reuse cross-talk hazard.
- val pfdOut = runCatching { pfd.dup() }.getOrNull()
- if (pfdOut == null) {
- openSockets.remove(tcp)
- runCatching { pfd.close() }
- runCatching { tcp.close() }
- return@coroutineScope
- }
- val vsockIn = ParcelFileDescriptor.AutoCloseInputStream(pfd)
- val vsockOut = ParcelFileDescriptor.AutoCloseOutputStream(pfdOut)
- val tcpIn = tcp.getInputStream()
- val tcpOut = tcp.getOutputStream()
- try {
- val a = launch(Dispatchers.IO) { copyUntilEof(tcpIn, vsockOut) }
- val b = launch(Dispatchers.IO) { copyUntilEof(vsockIn, tcpOut) }
- // Whichever direction EOFs first cancels its sibling so the
- // socket closes cleanly on both halves.
- select<Unit> {
- a.onJoin { b.cancel() }
- b.onJoin { a.cancel() }
- }
- } finally {
- openSockets.remove(tcp)
- runCatching { tcp.close() }
- // Close both stream owners; each owns a distinct fd (pfd / its dup).
- runCatching { vsockIn.close() }
- runCatching { vsockOut.close() }
- }
+ private suspend fun proxy(relay: BidirectionalRelay) {
+ val pfd = connectVsockWithRetry() ?: return
+ val vsock = runCatching { VsockRelayEndpoint.open(pfd) }.getOrNull() ?: return
+ if (!relay.attach(vsock)) return
+ relay.run()
}
private suspend fun connectVsockWithRetry(): ParcelFileDescriptor? {
var lastCause: Throwable? = null
repeat(CONNECT_ATTEMPTS) { attempt ->
if (closed) return null
- val pfd = runCatching { AvfReflect.connectVsock(vm, guestVsockPort.toLong()) }
- .getOrElse { lastCause = it.cause ?: it; null }
- if (pfd != null) return pfd
+ val pfd = try {
+ AvfReflect.connectVsock(vm, guestVsockPort.toLong())
+ } catch (e: CancellationException) {
+ throw e
+ } catch (t: Throwable) {
+ lastCause = t.cause ?: t
+ null
+ }
+ if (pfd != null) {
+ // Android's synchronous framework connect cannot be made
+ // cancellable cheaply. Invalidate the result if cancellation or
+ // forwarder close won while it was blocked; relay.attach() also
+ // rejects and closes a descriptor returned in that close window.
+ try {
+ currentCoroutineContext().ensureActive()
+ } catch (e: CancellationException) {
+ runCatching { pfd.close() }
+ throw e
+ }
+ if (closed) {
+ runCatching { pfd.close() }
+ return null
+ }
+ return pfd
+ }
if (attempt < CONNECT_ATTEMPTS - 1) delay(CONNECT_RETRY_MS)
}
// Surface the underlying ErrnoException class — e.message alone is null
@@ -158,28 +233,31 @@ class VsockPortForwarder(
return null
}
- private fun copyUntilEof(src: InputStream, dst: OutputStream) {
- val buf = ByteArray(16 * 1024)
- try {
- while (true) {
- val n = src.read(buf)
- if (n <= 0) break
- dst.write(buf, 0, n); dst.flush()
- }
- } catch (_: java.io.IOException) { /* peer closed — normal exit */ }
- }
-
override fun close() {
- if (closed) return
- closed = true
- runCatching { server?.close() } // unblocks accept()
- runCatching { acceptJob?.cancel() }
- // Force-close live sockets so pumps blocked in native read() throw + exit;
- // cancelling the coroutines alone wouldn't interrupt a blocking read.
- synchronized(openSockets) {
- openSockets.forEach { runCatching { it.close() } }
- openSockets.clear()
+ val relays: List<BidirectionalRelay>
+ val listener: ServerSocket?
+ val accept: Job?
+ val watcher: Job?
+ synchronized(lifecycleLock) {
+ if (closed) return
+ closed = true
+ // Mark every relay aborted before releasing the lock: a late
+ // connect cannot attach a raw endpoint and start pumps after close.
+ relays = activeRelays.toList()
+ activeRelays.clear()
+ relays.forEach { it.abort() }
+ listener = server
+ server = null
+ accept = acceptJob
+ acceptJob = null
+ watcher = acceptCancellationWatcher
+ acceptCancellationWatcher = null
}
+ runCatching { listener?.close() } // unblocks native accept()
+ runCatching { accept?.cancel() }
+ runCatching { watcher?.cancel() }
+ // Abort both TCP and raw-vsock endpoints so native reads wake; cancelling
+ // coroutines alone cannot interrupt a blocking read.
runCatching { connections.cancel() }
}
}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/AvfTcpRelayTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/AvfTcpRelayTest.kt
new file mode 100644
index 0000000..f05fadf
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/AvfTcpRelayTest.kt
@@ -0,0 +1,174 @@
+package com.excp.podroid.engine.avf
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeout
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.InputStream
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.Socket
+
+class AvfTcpRelayTest {
+ @Test
+ fun request_half_close_still_delivers_delayed_reply() = runBlocking {
+ val pair = RelaySockets.open()
+ val relay = BidirectionalRelay(
+ SocketRelayEndpoint(pair.left.endpoint),
+ )
+ val right = SocketRelayEndpoint(pair.right.endpoint)
+ assertTrue(relay.attach(right))
+ val job = launch(Dispatchers.Default) { relay.run() }
+ try {
+ pair.left.peer.outputStream.apply {
+ write("request".toByteArray())
+ flush()
+ }
+ pair.left.peer.shutdownOutput()
+
+ withContext(Dispatchers.IO) {
+ assertArrayEquals("request".toByteArray(), pair.right.peer.inputStream.readExactly(7))
+ assertEquals(-1, pair.right.peer.inputStream.read())
+ pair.right.peer.outputStream.apply {
+ write("delayed reply".toByteArray())
+ flush()
+ }
+ pair.right.peer.shutdownOutput()
+ }
+
+ withContext(Dispatchers.IO) {
+ assertArrayEquals("delayed reply".toByteArray(), pair.left.peer.inputStream.readExactly(13))
+ assertEquals(-1, pair.left.peer.inputStream.read())
+ }
+ withTimeout(3_000) { job.join() }
+ } finally {
+ relay.abort()
+ job.cancelAndJoin()
+ pair.close()
+ }
+ }
+
+ @Test
+ fun both_directions_can_half_close_symmetrically() = runBlocking {
+ val pair = RelaySockets.open()
+ val relay = BidirectionalRelay(SocketRelayEndpoint(pair.left.endpoint))
+ assertTrue(relay.attach(SocketRelayEndpoint(pair.right.endpoint)))
+ val job = launch(Dispatchers.Default) { relay.run() }
+ try {
+ withContext(Dispatchers.IO) {
+ pair.left.peer.outputStream.apply { write("left".toByteArray()); flush() }
+ pair.left.peer.shutdownOutput()
+ pair.right.peer.outputStream.apply { write("right".toByteArray()); flush() }
+ pair.right.peer.shutdownOutput()
+
+ assertArrayEquals("left".toByteArray(), pair.right.peer.inputStream.readExactly(4))
+ assertEquals(-1, pair.right.peer.inputStream.read())
+ assertArrayEquals("right".toByteArray(), pair.left.peer.inputStream.readExactly(5))
+ assertEquals(-1, pair.left.peer.inputStream.read())
+ }
+ withTimeout(3_000) { job.join() }
+ } finally {
+ relay.abort()
+ job.cancelAndJoin()
+ pair.close()
+ }
+ }
+
+ @Test
+ fun external_abort_closes_both_idle_sockets() = runBlocking {
+ val pair = RelaySockets.open()
+ val relay = BidirectionalRelay(SocketRelayEndpoint(pair.left.endpoint))
+ assertTrue(relay.attach(SocketRelayEndpoint(pair.right.endpoint)))
+ val job = launch(Dispatchers.Default) { relay.run() }
+ try {
+ relay.abort()
+ withTimeout(3_000) { job.join() }
+ assertTrue(pair.left.endpoint.isClosed)
+ assertTrue(pair.right.endpoint.isClosed)
+ } finally {
+ relay.abort()
+ job.cancelAndJoin()
+ pair.close()
+ }
+ }
+
+ @Test
+ fun cancellation_closes_both_idle_sockets() = runBlocking {
+ val pair = RelaySockets.open()
+ val relay = BidirectionalRelay(SocketRelayEndpoint(pair.left.endpoint))
+ assertTrue(relay.attach(SocketRelayEndpoint(pair.right.endpoint)))
+ val job = launch(Dispatchers.Default) { relay.run() }
+ try {
+ withTimeout(3_000) { job.cancelAndJoin() }
+ assertTrue(pair.left.endpoint.isClosed)
+ assertTrue(pair.right.endpoint.isClosed)
+ } finally {
+ relay.abort()
+ job.cancelAndJoin()
+ pair.close()
+ }
+ }
+
+ @Test
+ fun hard_peer_error_aborts_the_other_side() = runBlocking {
+ val pair = RelaySockets.open()
+ val relay = BidirectionalRelay(SocketRelayEndpoint(pair.left.endpoint))
+ assertTrue(relay.attach(SocketRelayEndpoint(pair.right.endpoint)))
+ val job = launch(Dispatchers.Default) { relay.run() }
+ try {
+ pair.right.peer.setSoLinger(true, 0)
+ pair.right.peer.close()
+ withTimeout(3_000) { job.join() }
+ assertTrue(pair.left.endpoint.isClosed)
+ assertTrue(pair.right.endpoint.isClosed)
+ } finally {
+ relay.abort()
+ job.cancelAndJoin()
+ pair.close()
+ }
+ }
+
+ private data class RelaySocket(val endpoint: Socket, val peer: Socket)
+
+ private class RelaySockets(
+ val left: RelaySocket,
+ val right: RelaySocket,
+ ) {
+ fun close() {
+ listOf(left.endpoint, left.peer, right.endpoint, right.peer).forEach {
+ runCatching { it.close() }
+ }
+ }
+
+ companion object {
+ fun open(): RelaySockets = RelaySockets(openPair(), openPair())
+
+ private fun openPair(): RelaySocket {
+ ServerSocket(0, 1, InetAddress.getLoopbackAddress()).use { listener ->
+ val peer = Socket(InetAddress.getLoopbackAddress(), listener.localPort)
+ val endpoint = listener.accept()
+ endpoint.soTimeout = 2_000
+ peer.soTimeout = 2_000
+ return RelaySocket(endpoint, peer)
+ }
+ }
+ }
+ }
+}
+
+private fun InputStream.readExactly(length: Int): ByteArray {
+ val result = ByteArray(length)
+ var offset = 0
+ while (offset < length) {
+ val count = read(result, offset, length - offset)
+ if (count < 0) error("unexpected EOF after $offset bytes")
+ offset += count
+ }
+ return result
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/VsockPortForwarderTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/VsockPortForwarderTest.kt
new file mode 100644
index 0000000..fde44b3
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/VsockPortForwarderTest.kt
@@ -0,0 +1,38 @@
+package com.excp.podroid.engine.avf
+
+import kotlinx.coroutines.CoroutineStart
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.launch
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Test
+import java.util.concurrent.atomic.AtomicBoolean
+
+class VsockPortForwarderTest {
+ @Test
+ fun cancellation_before_connection_body_starts_releases_ownership_once() = runBlocking {
+ var aborts = 0
+ var removals = 0
+ var releases = 0
+ val bodyStarted = AtomicBoolean(false)
+ val connection: Job = launch(start = CoroutineStart.LAZY) {
+ bodyStarted.set(true)
+ }
+ val completion = RelayJobCompletion(
+ abort = { aborts++ },
+ remove = { removals++ },
+ release = { releases++ },
+ )
+
+ completion.attach(connection)
+ connection.cancel()
+ connection.join()
+ completion.cleanup()
+
+ assertFalse(bodyStarted.get())
+ assertEquals(1, aborts)
+ assertEquals(1, removals)
+ assertEquals(1, releases)
+ }
+}