Skip to content

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

fix: validate QMP capabilities reply before sending commands

Commiemusclemommiece1c672ba861
diff --git a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
index 012b1a1..7bff079 100644
--- a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
@@ -73,6 +73,29 @@ class QmpClient(private val socketPath: String) {
is QmpVerdict.SkipEvent -> null
}
+ /**
+ * Read through asynchronous events until the next terminal QMP reply.
+ * A failure (including EOF) is returned to the caller so it can stop
+ * before sending any subsequent command.
+ */
+ internal fun readQmpResponse(reader: BufferedReader, operation: String): Result<JSONObject> =
+ readQmpResponse(reader, operation) { line -> classifyQmpResponse(JSONObject(line)) }
+
+ internal fun <T> readQmpResponse(
+ reader: BufferedReader,
+ operation: String,
+ classifyResponse: (String) -> Result<T>?,
+ ): Result<T> {
+ while (true) {
+ val line = reader.readLine()
+ ?: return Result.failure(
+ RuntimeException("QMP connection closed before a reply to $operation")
+ )
+ val result = classifyResponse(line)
+ if (result != null) return result
+ }
+ }
+
/**
* human-monitor-command (hostfwd_add/remove) reports failures as plain
* text in the `"return"` field. Match the QEMU SLIRP/hostfwd error
@@ -114,7 +137,9 @@ class QmpClient(private val socketPath: String) {
Log.v(TAG, "QMP greeting: ${reader.readLine()}")
out.write("{\"execute\":\"qmp_capabilities\"}\n".toByteArray())
out.flush()
- Log.v(TAG, "Capabilities response: ${reader.readLine()}")
+ val capabilities = readQmpResponse(reader, "qmp_capabilities")
+ if (capabilities.isFailure) return@withContext capabilities
+ Log.v(TAG, "Capabilities response: ${capabilities.getOrThrow()}")
val cmd = JSONObject().apply {
put("execute", command)
@@ -127,18 +152,10 @@ class QmpClient(private val socketPath: String) {
out.write((cmd.toString() + "\n").toByteArray())
out.flush()
- // Read until a terminal reply (return/error). QMP can emit
- // async {"event":...} lines at any time — classifyQmpResponse
- // returns null for those so we skip them. A null line = EOF.
- var result: Result<JSONObject>? = null
- while (result == null) {
- val response = reader.readLine()
- ?: return@withContext Result.failure(
- RuntimeException("QMP connection closed before a reply to $command")
- )
- Log.d(TAG, "Command response ($command): $response")
- result = classifyQmpResponse(JSONObject(response))
- }
+ // Read until a terminal reply (return/error), skipping any
+ // async {"event":...} lines that interleave with it.
+ val result = readQmpResponse(reader, command)
+ Log.d(TAG, "Command response ($command): $result")
result
}
} catch (e: CancellationException) {
diff --git a/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt b/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt
index 2d71536..42f8aa6 100644
--- a/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt
+++ b/app/src/test/java/com/excp/podroid/engine/QmpClientTest.kt
@@ -6,9 +6,12 @@ package com.excp.podroid.engine
import com.excp.podroid.engine.QmpClient.Companion.QmpVerdict
import com.excp.podroid.engine.QmpClient.Companion.classifyQmpFields
+import com.excp.podroid.engine.QmpClient.Companion.readQmpResponse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
+import java.io.BufferedReader
+import java.io.StringReader
/**
* Pins QMP response classification. Port-forward commands run via
@@ -16,12 +19,52 @@ import org.junit.Test
* envelope (no QMP-level error, no exception), so a naive
* Result.success(JSONObject(line)) reports a failed forward as applied.
*
- * Tests target the pure [classifyQmpFields] (no org.json) so they run as plain
- * JVM unit tests; the thin classifyQmpResponse(JSONObject) adapter just maps its
- * verdict onto Result/null.
+ * The reader tests use plain string classifiers so they run as JVM unit tests;
+ * the pure [classifyQmpFields] tests cover the protocol classification rules.
*/
class QmpClientTest {
+ /** Keep reader tests on the plain JVM; field classification is covered below. */
+ private fun classifyTestResponse(line: String): Result<String>? = when {
+ line.contains("\"event\"") -> null
+ line.contains("\"error\"") -> Result.failure(RuntimeException("QMP error"))
+ else -> Result.success(line)
+ }
+
+ @Test
+ fun `reader skips events for capability and command replies`() {
+ val reader = BufferedReader(StringReader(
+ """
+ {"event":"RESET"}
+ {"return":{}}
+ {"event":"RESUME"}
+ {"return":{"ok":true}}
+ """.trimIndent()
+ ))
+
+ val capabilities = readQmpResponse(reader, "qmp_capabilities", ::classifyTestResponse)
+ val command = readQmpResponse(reader, "test-command", ::classifyTestResponse)
+
+ assertEquals("{\"return\":{}}", capabilities.getOrThrow())
+ assertEquals("{\"return\":{\"ok\":true}}", command.getOrThrow())
+ }
+
+ @Test
+ fun `capability ack is consumed separately from following command error`() {
+ val reader = BufferedReader(StringReader(
+ """
+ {"return":{}}
+ {"error":{"class":"GenericError","desc":"bad command"}}
+ """.trimIndent()
+ ))
+
+ assertTrue(readQmpResponse(reader, "qmp_capabilities", ::classifyTestResponse).isSuccess)
+ val command = readQmpResponse(reader, "test-command", ::classifyTestResponse)
+
+ assertTrue(command.isFailure)
+ assertEquals("QMP error", command.exceptionOrNull()?.message)
+ }
+
@Test
fun `top-level error envelope is a failure`() {
// {"error":{"class":"GenericError","desc":"bad command"}}
@@ -84,6 +127,28 @@ class QmpClientTest {
assertEquals(QmpVerdict.Success, verdict)
}
+ @Test
+ fun `reader returns capability error without consuming next line`() {
+ val reader = BufferedReader(StringReader(
+ "{" +
+ "\"error\":{\"class\":\"GenericError\",\"desc\":\"capabilities rejected\"}}\n" +
+ "{\"return\":{}}\n"
+ ))
+
+ assertTrue(readQmpResponse(reader, "qmp_capabilities", ::classifyTestResponse).isFailure)
+ assertTrue(readQmpResponse(reader, "test-command", ::classifyTestResponse).isSuccess)
+ }
+
+ @Test
+ fun `reader returns failure on EOF after events`() {
+ val reader = BufferedReader(StringReader("{\"event\":\"RESET\"}\n"))
+
+ val result = readQmpResponse(reader, "test-command", ::classifyTestResponse)
+
+ assertTrue(result.isFailure)
+ assertTrue(result.exceptionOrNull()?.message?.contains("connection closed") == true)
+ }
+
@Test
fun `event takes precedence is not consulted when error present`() {
// Defensive: an error envelope is terminal even if an event key co-occurs.