A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix: stop host bridge reads and bound request framing
Commiemusclemommieb842567b3e2f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7053fa8..a2124b9 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -111,7 +111,7 @@ On **AVF** there is no QMP and no PL011: the console is captured via `ConsoleFan### Guest → Android host bridge-Lets guest processes call back to Android. Guest side: `podroid-hostd` (multi-call C binary, `build-rootfs/host-bridge/podroid-hostd.c`) owns a guest-local `AF_UNIX` socket `/run/podroid-host.sock`; `argv[0]` dispatch also exposes it as `podroid-notify` and `podroid-forward` (symlinks). The daemon relays one request line / one response line to Android over a backend transport: `/dev/hvc2` on QEMU, `AF_VSOCK:9101` on AVF (chosen by the `podroid.backend=avf` cmdline marker). Android side: `engine/hostbridge/` - `HostRequestServer` reads requests over a `HostTransport` (`QemuHostTransport` via `LocalSocket` to `host.sock`, or `AvfHostTransport` via `connectVsock`), `HostRequestDispatcher` parses them, and routes to `NotificationPoster` (posts via `NotificationManagerCompat`) or `PortForwardRepository` (rules persist and `EngineHolder` applies them live). `PodroidService` starts/stops the server over the VM lifecycle. Free-text fields are base64 (`HostProtocol.kt`) so UTF-8 survives.+Lets guest processes call back to Android. Guest side: `podroid-hostd` (multi-call C binary, `build-rootfs/host-bridge/podroid-hostd.c`) owns a guest-local `AF_UNIX` socket `/run/podroid-host.sock`; `argv[0]` dispatch also exposes it as `podroid-notify` and `podroid-forward` (symlinks). The daemon relays one request line / one response line to Android over a backend transport: `/dev/hvc2` on QEMU, `AF_VSOCK:9101` on AVF (chosen by the `podroid.backend=avf` cmdline marker). Android side: `engine/hostbridge/` - `HostRequestServer` reads requests over a `HostTransport` (`QemuHostTransport` via `LocalSocket` to `host.sock`, or `AvfHostTransport` via `connectVsock`), `HostRequestDispatcher` parses them, and routes to `NotificationPoster` (posts via `NotificationManagerCompat`) or `PortForwardRepository` (rules persist and `EngineHolder` applies them live). `PodroidService` starts/stops the server over the VM lifecycle. Stop or parent cancellation shuts down the active transport to unblock reads; a transport returned by a late native connect is closed without dispatching. Android accepts only complete UTF-8 request lines up to 8191 bytes (matching the guest buffer). Free-text fields are base64 (`HostProtocol.kt`) so UTF-8 survives.> **Gotcha:** `/dev/hvc2` is a virtio-console **TTY** that defaults to echo on. The daemon must `cfmakeraw()` it, or the TTY echoes Android's responses back and the protocol desyncs after the first request. AVF (a raw vsock socket) is unaffected.diff --git a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestServer.kt b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestServer.ktindex 6b2335b..1446001 100644--- a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestServer.kt+++ b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestServer.kt@@ -12,56 +12,172 @@ package com.excp.podroid.engine.hostbridgeimport android.util.Logimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job+import kotlinx.coroutines.awaitCancellation+import kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.isActiveimport kotlinx.coroutines.launch+import java.util.concurrent.atomic.AtomicBoolean+/**+ * Owns one host-bridge generation for the lifetime of [scope]. The synchronous+ * [openTransport] callback may be inside an Android framework/binder connect+ * that cannot be interrupted here; stopping invalidates that generation and+ * closes any transport it eventually returns instead of adding a timeout that+ * could strand a hidden native connect job.+ */class HostRequestServer(private val openTransport: () -> HostTransport?,private val dispatcher: HostRequestDispatcher,private val scope: CoroutineScope,+ private val log: (String, Throwable?) -> Unit = { message, error ->+ if (error == null) Log.d(TAG, message) else Log.w(TAG, message, error)+ },) {companion object {private const val TAG = "HostRequestServer"private const val RETRY_MS = 500L}+ private val lock = Any()private var job: Job? = null+ private var generation = 0L+ private var active: ActiveTransport? = null+ /** Starts one generation. A cancelled old generation cannot revive itself. */fun start() {- if (job?.isActive == true) return- job = scope.launch(Dispatchers.IO) { runLoop() }+ synchronized(lock) {+ if (!scope.isActive || job?.isActive == true) return+ val current = ++generation+ val started = scope.launch(+ context = Dispatchers.IO,+ start = CoroutineStart.LAZY,+ ) { runLoop(current) }+ job = started+ // Assign before starting so a fast run cannot finish and then be+ // overwritten by this stale Job reference.+ started.start()+ // Parent-scope cancellation does not necessarily interrupt a native+ // socket read. The cancellation watcher closes it in that phase;+ // this completion cleanup is only the post-exit safety net. An old+ // job must never tear down a transport from a restart.+ started.invokeOnCompletion {+ val toClose = synchronized(lock) {+ if (generation == current) {+ ++generation+ job = null+ active.also { active = null }+ } else null+ }+ toClose?.close()+ }+ }}+ /**+ * Invalidates the generation before closing its transport. Closing first is+ * what unblocks raw socket reads; cancellation alone is not sufficient for+ * native vsock/LocalSocket reads. If [openTransport] is already in a+ * synchronous framework connect, this does not interrupt that native call;+ * a transport returned later is closed as stale.+ */fun stop() {- job?.cancel()- job = null+ val toClose = synchronized(lock) {+ ++generation+ job?.cancel()+ job = null+ active.also { active = null }+ }+ toClose?.close()}- private suspend fun runLoop() {- while (scope.isActive) {- val transport = openTransport()- if (transport == null) {- delay(RETRY_MS)- continue- }- Log.d(TAG, "host bridge connected")+ private fun isCurrent(current: Long): Boolean = synchronized(lock) {+ generation == current && scope.isActive+ }++ /**+ * Reserves an already-read request against stop(). Once this returns true,+ * stop() cannot cancel the handler itself; the later active check only+ * suppresses its response.+ */+ private fun mayDispatch(current: Long, transport: ActiveTransport): Boolean = synchronized(lock) {+ generation == current && active === transport && scope.isActive+ }++ private suspend fun runLoop(current: Long) = coroutineScope {+ // This child wakes in the cancellation phase, before a blocked read+ // finishes. It belongs to this run only; stopped servers leave no+ // watcher behind in the service scope.+ val cancellationWatcher = launch(Dispatchers.IO, start = CoroutineStart.UNDISPATCHED) {try {- while (scope.isActive) {- val req = transport.readRequest() ?: break- val resp = dispatcher.handle(req)- transport.writeResponse(resp)- }- } catch (c: CancellationException) {- throw c // don't log a stop/swap's cancellation as a loop error- } catch (e: Exception) {- Log.w(TAG, "host bridge loop error: ${e.message}")+ awaitCancellation()} finally {- transport.close()+ val toClose = synchronized(lock) {+ if (generation == current) active.also { active = null } else null+ }+ toClose?.close()}- delay(RETRY_MS) // brief pause before reconnecting+ }+ try {+ while (isCurrent(current)) {+ val opened = openTransport()+ if (opened == null) {+ if (isCurrent(current)) delay(RETRY_MS)+ continue+ }+ val transport = ActiveTransport(opened)+ val accepted = synchronized(lock) {+ if (generation == current && scope.isActive) {+ active = transport+ true+ } else false+ }+ if (!accepted) {+ // stop() won the registration race. No reconnect from this+ // stale generation is allowed.+ transport.close()+ return@coroutineScope+ }++ log("host bridge connected", null)+ try {+ while (isCurrent(current)) {+ val req = transport.value.readRequest() ?: break+ if (!mayDispatch(current, transport)) break+ val resp = dispatcher.handle(req)+ if (!isCurrent(current)) break+ transport.value.writeResponse(resp)+ }+ } catch (c: CancellationException) {+ throw c // don't log a stop/swap's cancellation as a loop error+ } catch (e: Exception) {+ log("host bridge loop error: ${e.message}", e)+ } finally {+ synchronized(lock) {+ if (active === transport) active = null+ }+ transport.close()+ }+ if (isCurrent(current)) delay(RETRY_MS) else return@coroutineScope+ }+ } finally {+ cancellationWatcher.cancel()+ synchronized(lock) {+ // A natural exit (for example, parent-scope cancellation) must+ // not leave a completed Job blocking a later start().+ if (generation == current) job = null+ }+ }+ }++ private class ActiveTransport(val value: HostTransport) {+ private val closed = AtomicBoolean(false)++ fun close() {+ if (closed.compareAndSet(false, true)) runCatching { value.close() }}}}diff --git a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostTransport.kt b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostTransport.ktindex d6291dd..5c0a8d6 100644--- a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostTransport.kt+++ b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostTransport.kt@@ -5,8 +5,9 @@* One open guest<->Android connection carrying the host-bridge line protocol.* Two impls: QEMU connects to a filesystem AF_UNIX socket QEMU created* (-chardev socket,server=on for /dev/hvc2); AVF dials the guest daemon's- * AF_VSOCK listener. The server reads requests (guest-originated) and writes- * one response per request.+ * AF_VSOCK listener. The server reads requests over a bounded line reader+ * (matching the guest daemon's 8192-byte request buffer) and writes one+ * response per request.*/package com.excp.podroid.engine.hostbridge@@ -14,15 +15,60 @@ import android.net.LocalSocketimport android.net.LocalSocketAddressimport android.os.Buildimport android.os.ParcelFileDescriptor+import android.system.Os+import android.system.OsConstantsimport androidx.annotation.RequiresApiimport com.excp.podroid.engine.avf.AvfReflect-import java.io.BufferedReader-import java.io.FileInputStream-import java.io.InputStreamReader+import java.io.BufferedInputStream+import java.io.IOException+import java.io.InputStreamimport java.io.OutputStream+import java.nio.ByteBuffer+import java.nio.charset.CharacterCodingException+import java.nio.charset.CodingErrorAction++/**+ * The guest daemon has `char req[8192]`, so it can carry at most 8191 bytes+ * before its terminating NUL. LF is framing, not part of this limit. A CR+ * immediately before LF is accepted for CRLF-speaking clients and is excluded+ * from the returned request.+ */+internal const val MAX_REQUEST_LINE_BYTES = 8191++internal class RequestLineTooLongException : IOException("host request line exceeds $MAX_REQUEST_LINE_BYTES bytes")++/** Reads exactly one complete UTF-8 request line, or null for EOF. */+internal object HostRequestLineReader {+ fun read(input: InputStream): String? {+ val bytes = ByteArray(MAX_REQUEST_LINE_BYTES)+ var size = 0+ while (true) {+ val value = input.read()+ if (value < 0) {+ // A partial line is not a request. Returning its prefix would+ // let a reconnect turn a truncated command into a valid one.+ return null+ }+ if (value == '\n'.code) {+ val contentSize = if (size > 0 && bytes[size - 1] == '\r'.code.toByte()) size - 1 else size+ return try {+ Charsets.UTF_8.newDecoder()+ .onMalformedInput(CodingErrorAction.REPORT)+ .onUnmappableCharacter(CodingErrorAction.REPORT)+ .decode(ByteBuffer.wrap(bytes, 0, contentSize))+ .toString()+ } catch (e: CharacterCodingException) {+ throw IOException("invalid UTF-8 request", e)+ }+ }+ if (size == bytes.size) throw RequestLineTooLongException()+ bytes[size++] = value.toByte()+ }+ }+}interface HostTransport {- /** Blocks until one LF-terminated request line arrives; null on EOF/error. */+ /** Returns one complete bounded LF-terminated request line, or null on EOF/error. */fun readRequest(): String?/** Writes one response line (a trailing LF is appended). */fun writeResponse(line: String)@@ -36,14 +82,23 @@ interface HostTransport {/** QEMU: client connection to the host.sock that backs guest /dev/hvc2. */class QemuHostTransport private constructor(private val socket: LocalSocket,- private val reader: BufferedReader,+ private val input: BufferedInputStream,private val out: OutputStream,) : HostTransport {- override fun readRequest(): String? = reader.readLine()+ override fun readRequest(): String? = HostRequestLineReader.read(input)override fun writeResponse(line: String) {out.write((line + "\n").toByteArray()); out.flush()}- override fun close() { runCatching { socket.close() } }+ override fun close() {+ // Explicit shutdown is the useful wake-up on Android; close the raw+ // socket before its buffered streams so a blocked native read is not+ // held behind a reader monitor. Both calls are harmless if already shut.+ runCatching { socket.shutdownInput() }+ runCatching { socket.shutdownOutput() }+ runCatching { socket.close() }+ runCatching { input.close() }+ runCatching { out.close() }+ }companion object {/** Returns null if QEMU has not created the socket yet (caller retries). */@@ -51,7 +106,7 @@ class QemuHostTransport private constructor(val s = LocalSocket()try {s.connect(LocalSocketAddress(socketPath, LocalSocketAddress.Namespace.FILESYSTEM))- QemuHostTransport(s, BufferedReader(InputStreamReader(s.inputStream)), s.outputStream)+ QemuHostTransport(s, BufferedInputStream(s.inputStream), s.outputStream)} catch (t: Throwable) {// connect()/stream access failed after the socket was created —// close it so a retry loop doesn't leak one fd per attempt.@@ -65,39 +120,44 @@ class QemuHostTransport private constructor(/** AVF: vsock connection dialed into the guest daemon's :9101 listener. */@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)class AvfHostTransport private constructor(+ // pfd is owned by AutoCloseInputStream(input); it is retained here only so+ // shutdown can run before that stream releases the descriptor.private val pfd: ParcelFileDescriptor,- private val pfdOut: ParcelFileDescriptor,- private val reader: BufferedReader,+ private val input: BufferedInputStream,private val out: OutputStream,) : HostTransport {- override fun readRequest(): String? = reader.readLine()+ override fun readRequest(): String? = HostRequestLineReader.read(input)override fun writeResponse(line: String) {out.write((line + "\n").toByteArray()); out.flush()}override fun close() {- runCatching { reader.close() }+ // Coroutine cancellation does not reliably interrupt a native vsock+ // read. Shutdown the socket while both ParcelFileDescriptors are still+ // valid, then let each AutoClose stream release its one fd owner.+ runCatching { Os.shutdown(pfd.fileDescriptor, OsConstants.SHUT_RDWR) }+ runCatching { input.close() }runCatching { out.close() }- runCatching { pfd.close() }- runCatching { pfdOut.close() }}companion object {/** Returns null if the guest daemon is not listening yet (caller retries). */fun open(vm: Any): AvfHostTransport? = runCatching {- // Read side owns p; write side owns a dup (each AutoClose closes one fd).- var p: ParcelFileDescriptor? = null- var pOut: ParcelFileDescriptor? = null+ val readPfd = AvfReflect.connectVsock(vm, HostTransport.AVF_VSOCK_PORT)try {- p = AvfReflect.connectVsock(vm, HostTransport.AVF_VSOCK_PORT)- pOut = p.dup()- val r = BufferedReader(InputStreamReader(FileInputStream(p.fileDescriptor)))- val o = ParcelFileDescriptor.AutoCloseOutputStream(pOut)- AvfHostTransport(p, pOut, r, o)+ val writePfd = readPfd.dup()+ try {+ val input = BufferedInputStream(ParcelFileDescriptor.AutoCloseInputStream(readPfd))+ val out = ParcelFileDescriptor.AutoCloseOutputStream(writePfd)+ AvfHostTransport(readPfd, input, out)+ } catch (t: Throwable) {+ // The AutoClose streams may already own either descriptor;+ // closing both here is safe and covers construction failure.+ runCatching { writePfd.close() }+ runCatching { readPfd.close() }+ throw t+ }} catch (t: Throwable) {- // dup()/stream construction failed after connectVsock — close the- // fds already opened so a retry loop doesn't leak them.- runCatching { pOut?.close() }- runCatching { p?.close() }+ runCatching { readPfd.close() }throw t}}.getOrNull()diff --git a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.ktnew file mode 100644index 0000000..48043fa--- /dev/null+++ b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt@@ -0,0 +1,191 @@+package com.excp.podroid.engine.hostbridge++import com.excp.podroid.data.repository.AddRuleResult+import com.excp.podroid.data.repository.PortForwardRule+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicInteger+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.joinAll+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class HostRequestServerTest {+ @Test(timeout = 5000) fun stopClosesAReadBlockedTransportExactlyOnce() {+ val scope = testScope()+ try {+ val transport = BlockingTransport()+ val server = HostRequestServer({ transport }, dispatcher(), scope, log = { _, _ -> })+ server.start()+ assertTrue(transport.readStarted.await(1, TimeUnit.SECONDS))++ server.stop()++ assertTrue(transport.closed.await(1, TimeUnit.SECONDS))+ awaitChildren(scope)+ assertEquals(1, transport.closeCount.get())+ } finally {+ scope.cancel()+ }+ }++ @Test(timeout = 5000) fun parentCancellationClosesAndFinishesBlockedReadWithoutStop() {+ val parent = SupervisorJob()+ val scope = CoroutineScope(parent + Dispatchers.Default)+ try {+ val transport = BlockingTransport()+ val server = HostRequestServer({ transport }, dispatcher(), scope, log = { _, _ -> })+ server.start()+ assertTrue(transport.readStarted.await(1, TimeUnit.SECONDS))++ parent.cancel()+ runBlocking { withTimeout(1000) { parent.join() } }++ assertTrue(transport.closed.await(1, TimeUnit.SECONDS))+ assertTrue(transport.readFinished.await(1, TimeUnit.SECONDS))+ assertEquals(1, transport.closeCount.get())+ } finally {+ scope.cancel()+ }+ }++ @Test(timeout = 5000) fun restartUsesANewGenerationAfterStop() {+ val scope = testScope()+ try {+ val first = BlockingTransport()+ val second = OneShotTransport("OPEN ${HostProtocol.enc("https://example.com")}")+ val opens = AtomicInteger(0)+ val handled = CountDownLatch(1)+ val server = HostRequestServer(+ openTransport = { if (opens.getAndIncrement() == 0) first else second },+ dispatcher = dispatcher(openUrl = { handled.countDown(); HostProtocol.ok() }),+ scope = scope,+ log = { _, _ -> },+ )+ server.start()+ assertTrue(first.readStarted.await(1, TimeUnit.SECONDS))+ server.stop()+ server.start()++ assertTrue(handled.await(1, TimeUnit.SECONDS))+ assertEquals(1, first.closeCount.get())+ } finally {+ scope.cancel()+ }+ }++ @Test(timeout = 5000) fun transportOpenedAfterStopIsClosedAndNotReconnected() {+ val scope = testScope()+ try {+ val openEntered = CountDownLatch(1)+ val releaseOpen = CountDownLatch(1)+ val late = OneShotTransport("PING")+ val server = HostRequestServer(+ openTransport = {+ openEntered.countDown()+ releaseOpen.await()+ late+ },+ dispatcher = dispatcher(),+ scope = scope,+ log = { _, _ -> },+ )+ server.start()+ assertTrue(openEntered.await(1, TimeUnit.SECONDS))+ server.stop()+ releaseOpen.countDown()+ awaitChildren(scope)++ assertTrue(late.closed.await(1, TimeUnit.SECONDS))+ assertEquals(1, late.closeCount.get())+ } finally {+ scope.cancel()+ }+ }++ @Test(timeout = 5000) fun requestReleasedByStopIsNotDispatched() {+ val scope = testScope()+ try {+ val transport = BlockingTransport(resultAfterClose = "OPEN ${HostProtocol.enc("https://example.com")}")+ val dispatched = AtomicInteger(0)+ val server = HostRequestServer(+ openTransport = { transport },+ dispatcher = dispatcher(openUrl = { dispatched.incrementAndGet(); HostProtocol.ok() }),+ scope = scope,+ log = { _, _ -> },+ )+ server.start()+ assertTrue(transport.readStarted.await(1, TimeUnit.SECONDS))+ server.stop()++ assertTrue(transport.closed.await(1, TimeUnit.SECONDS))+ assertTrue(transport.readFinished.await(1, TimeUnit.SECONDS))+ awaitChildren(scope)+ assertEquals(0, dispatched.get())+ } finally {+ scope.cancel()+ }+ }++ private fun awaitChildren(scope: CoroutineScope) = runBlocking {+ withTimeout(1000) { scope.coroutineContext[Job]!!.children.toList().joinAll() }+ assertTrue(scope.coroutineContext[Job]!!.children.none())+ }++ private fun testScope() = CoroutineScope(SupervisorJob() + Dispatchers.Default)++ private fun dispatcher(+ openUrl: suspend (String) -> String = { HostProtocol.ok() },+ ) = HostRequestDispatcher(+ notifications = object : NotificationPoster {+ override fun notificationsPermitted() = true+ override fun post(title: String?, body: String, priority: String, id: Int?) = id ?: 1+ },+ addForward = { AddRuleResult.ADDED },+ removeForward = {},+ listForwards = { emptyList<PortForwardRule>() },+ clearForwards = { 0 },+ openUrl = openUrl,+ power = { HostProtocol.ok() },+ setHeadless = { HostProtocol.ok() },+ )++ private class BlockingTransport(private val resultAfterClose: String? = null) : HostTransport {+ val readStarted = CountDownLatch(1)+ val closed = CountDownLatch(1)+ val readFinished = CountDownLatch(1)+ val closeCount = AtomicInteger(0)++ override fun readRequest(): String? {+ readStarted.countDown()+ closed.await(2, TimeUnit.SECONDS)+ readFinished.countDown()+ return resultAfterClose+ }++ override fun writeResponse(line: String) = Unit++ override fun close() {+ if (closeCount.incrementAndGet() == 1) closed.countDown()+ }+ }++ private class OneShotTransport(private val request: String) : HostTransport {+ val closed = CountDownLatch(1)+ val closeCount = AtomicInteger(0)+ private val returned = AtomicInteger(0)++ override fun readRequest(): String? = if (returned.getAndIncrement() == 0) request else null+ override fun writeResponse(line: String) = Unit+ override fun close() {+ if (closeCount.incrementAndGet() == 1) closed.countDown()+ }+ }+}diff --git a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostTransportTest.kt b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostTransportTest.ktnew file mode 100644index 0000000..d2d4d75--- /dev/null+++ b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostTransportTest.kt@@ -0,0 +1,43 @@+package com.excp.podroid.engine.hostbridge++import java.io.ByteArrayInputStream+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test++class HostTransportTest {+ @Test fun acceptsTheGuestBufferBoundary() {+ val line = "x".repeat(MAX_REQUEST_LINE_BYTES)+ assertEquals(line, HostRequestLineReader.read(ByteArrayInputStream("$line\n".toByteArray())))+ }++ @Test fun rejectsAByteBeyondTheGuestBufferBoundary() {+ val line = "x".repeat(MAX_REQUEST_LINE_BYTES + 1)+ try {+ HostRequestLineReader.read(ByteArrayInputStream("$line\n".toByteArray()))+ throw AssertionError("expected overlong line")+ } catch (_: RequestLineTooLongException) {+ // The transport is closed by the server after this exception.+ }+ }++ @Test fun boundsUtf8ByBytesNotKotlinChars() {+ val line = "x".repeat(MAX_REQUEST_LINE_BYTES - 1) + "é"+ try {+ HostRequestLineReader.read(ByteArrayInputStream("$line\n".toByteArray(Charsets.UTF_8)))+ throw AssertionError("expected overlong UTF-8 line")+ } catch (_: RequestLineTooLongException) {+ // Two UTF-8 bytes do not fit in the final byte slot.+ }+ }++ @Test fun partialEofIsNotARequest() {+ assertNull(HostRequestLineReader.read(ByteArrayInputStream("PING".toByteArray())))+ }++ @Test fun acceptsCrLfAndDoesNotExposeTheCarriageReturn() {+ assertEquals("PING", HostRequestLineReader.read(ByteArrayInputStream("PING\r\n".toByteArray())))+ assertTrue(HostRequestLineReader.read(ByteArrayInputStream("\r\n".toByteArray())).isNullOrEmpty())+ }+}