Skip to content

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

fix(engine): surface port-forward failures and fix stop/wakelock ordering

ExTvbf91edce072d
diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
index f6a9541..1baec78 100644
--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt
@@ -210,10 +210,19 @@ class QemuEngine @Inject constructor(
override fun createTerminalSession(client: TerminalSessionClient): TerminalSession {
sessionClientDelegate = client
- // Session already auto-started during boot — just return it
- if (_terminalSession != null) {
+ // Reuse the boot-time session ONLY if it's still alive. A finished
+ // session (bridge died while the VM kept running) must not be handed
+ // back — re-entering the terminal screen would otherwise show the dead
+ // "[Process completed]" buffer forever. Drop it and fall through to
+ // spawn a fresh bridge against the still-running VM.
+ val cached = _terminalSession
+ if (cached != null && cached.isRunning) {
Log.d(TAG, "Returning pre-started terminal session")
- return _terminalSession!!
+ return cached
+ }
+ if (cached != null) {
+ Log.d(TAG, "Cached terminal session is dead — recreating against the running VM")
+ _terminalSession = null
}
// Fallback: create session now
@@ -446,15 +455,22 @@ class QemuEngine @Inject constructor(
override suspend fun addPortForward(rule: PortForwardRule) {
if (_state.value !is VmState.Running) return
val qmp = qmpClient ?: return
- runCatching { qmp.addPortForward(rule.hostPort, rule.guestPort, rule.protocol) }
+ // QmpClient returns Result and never throws, so the failure lives INSIDE
+ // the returned Result — unwrap it. getOrThrow rethrows so EngineHolder
+ // records this rule as not-applied and retries on the next diff (a
+ // host-port-already-bound failure would otherwise be permanently dropped
+ // and silently recorded as live).
+ qmp.addPortForward(rule.hostPort, rule.guestPort, rule.protocol, rule.loopbackOnly)
.onFailure { Log.w(TAG, "QMP addPortForward failed for $rule", it) }
+ .getOrThrow()
}
override suspend fun removePortForward(rule: PortForwardRule) {
if (_state.value !is VmState.Running) return
val qmp = qmpClient ?: return
- runCatching { qmp.removePortForward(rule.hostPort, rule.protocol) }
+ qmp.removePortForward(rule.hostPort, rule.protocol, rule.loopbackOnly)
.onFailure { Log.w(TAG, "QMP removePortForward failed for $rule", it) }
+ .getOrThrow()
}
@Synchronized
@@ -570,7 +586,11 @@ class QemuEngine @Inject constructor(
val netdevArg = buildString {
append("user,id=net0,ipv6=off")
for (rule in portForwards) {
- append(",hostfwd=${rule.protocol}::${rule.hostPort}-:${rule.guestPort}")
+ // hostfwd hostaddr: empty = 0.0.0.0 (LAN-reachable, user rules);
+ // 127.0.0.1 for loopbackOnly rules (implicit VNC/audio) so they
+ // aren't exposed to the network.
+ val hostAddr = if (rule.loopbackOnly) "127.0.0.1" else ""
+ append(",hostfwd=${rule.protocol}:$hostAddr:${rule.hostPort}-:${rule.guestPort}")
}
}
args += "-netdev"; args += netdevArg
@@ -626,9 +646,28 @@ class QemuEngine @Inject constructor(
val desiredBytes = storageSizeGb.toLong() * 1024L * 1024L * 1024L
if (storageFile.exists()) {
- if (storageFile.length() == desiredBytes) return
- Log.d(TAG, "storage.img size mismatch — recreating")
- storageFile.delete()
+ val current = storageFile.length()
+ when {
+ current == desiredBytes -> return
+ // NEVER delete: storage.img is the persistent ext4 overlay (every
+ // apk add, container, user file). Deleting on mismatch could wipe
+ // all guest data if the size ever changes (a corrupted DataStore
+ // falling back to the 2GB default, or a future resize UI). Grow in
+ // place when larger — the guest's first-boot resize2fs claims the
+ // new space; truncating to shrink would corrupt the filesystem.
+ desiredBytes > current -> {
+ runCatching {
+ java.io.RandomAccessFile(storageFile, "rw").use { it.setLength(desiredBytes) }
+ }.onSuccess {
+ Log.i(TAG, "storage.img grown ${current / (1024 * 1024)}MB → ${storageSizeGb}GB (guest resize2fs on next boot)")
+ }.onFailure { Log.e(TAG, "Failed to grow storage.img", it) }
+ return
+ }
+ else -> {
+ Log.w(TAG, "storage.img (${current / (1024 * 1024)}MB) larger than requested ${storageSizeGb}GB; keeping existing image (shrink would corrupt the filesystem)")
+ return
+ }
+ }
}
try {
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 326218e..012b1a1 100644
--- a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
+++ b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt
@@ -152,16 +152,26 @@ class QmpClient(private val socketPath: String) {
suspend fun execute(command: String, arguments: JSONObject? = null): Result<JSONObject> =
exec(command, arguments)
- suspend fun addPortForward(hostPort: Int, guestPort: Int, protocol: String = "tcp"): Result<JSONObject> {
- val monitorCmd = "hostfwd_add net0 ${protocol}::${hostPort}-:${guestPort}"
+ suspend fun addPortForward(
+ hostPort: Int,
+ guestPort: Int,
+ protocol: String = "tcp",
+ loopbackOnly: Boolean = false,
+ ): Result<JSONObject> {
+ // hostaddr empty = 0.0.0.0; 127.0.0.1 keeps a loopback-only rule off the
+ // network even when applied live (matches the static buildCommand path).
+ val hostAddr = if (loopbackOnly) "127.0.0.1" else ""
+ val monitorCmd = "hostfwd_add net0 ${protocol}:${hostAddr}:${hostPort}-:${guestPort}"
return execute(
"human-monitor-command",
JSONObject().put("command-line", monitorCmd)
)
}
- suspend fun removePortForward(hostPort: Int, protocol: String = "tcp"): Result<JSONObject> {
- val monitorCmd = "hostfwd_remove net0 ${protocol}::${hostPort}"
+ suspend fun removePortForward(hostPort: Int, protocol: String = "tcp", loopbackOnly: Boolean = false): Result<JSONObject> {
+ // hostfwd_remove must match the hostaddr used at add time.
+ val hostAddr = if (loopbackOnly) "127.0.0.1" else ""
+ val monitorCmd = "hostfwd_remove net0 ${protocol}:${hostAddr}:${hostPort}"
return execute(
"human-monitor-command",
JSONObject().put("command-line", monitorCmd)
diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
index f458e48..1b55eb7 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -110,15 +110,26 @@ class PodroidService : Service() {
}
}
ACTION_STOP -> {
- // engine.stop() is a no-op if nothing is running. Either way the
- // shutdown observer only fires after an active state, so on the
- // "stop while idle" path (e.g. PodroidService.stop() spinning up a
- // fresh service) we must release + stop here so this doesn't
- // linger as a started-but-never-foregrounded orphan.
+ val wasActive = engine.state.value is VmState.Starting ||
+ engine.state.value is VmState.Running
engine.stop()
- releaseWakeLock()
- stopForegroundCompat()
- stopSelf()
+ if (wasActive) {
+ // engine.stop() kicks off an async best-effort guest flush
+ // (AVF syncAndWait, up to 8s) on the engine's own scope and
+ // returns immediately. Releasing the partial WakeLock here
+ // would let the CPU suspend mid-flush with the screen off,
+ // defeating the deliberate ext4 sync. Keep it held; the
+ // shutdown observer runs teardown() (release + stopSelf) once
+ // the engine reaches Stopped/Error.
+ Log.d(TAG, "ACTION_STOP: VM active — deferring teardown to state observer")
+ } else {
+ // Stop while idle (e.g. a fresh service spun up only to stop):
+ // no terminal transition will arrive, so release + stop now so
+ // this doesn't linger as a started-but-never-foregrounded orphan.
+ releaseWakeLock()
+ stopForegroundCompat()
+ stopSelf()
+ }
}
else -> {
// Null/unrecognized action (e.g. a system redelivery): we never
@@ -322,11 +333,14 @@ class PodroidService : Service() {
// Always-on X11 viewer forwards. These are implicit, not user-managed —
// they back the in-app screen toggle and never appear in the PortForward UI.
+ // loopbackOnly = bind 127.0.0.1: the in-app viewer dials loopback, and
+ // Xvnc runs with no auth + PulseAudio streams raw PCM, so binding 0.0.0.0
+ // would hand any device on the same Wi-Fi a no-password root X session.
if (rules.none { it.hostPort == X11Constants.VNC_PORT }) {
- rules.add(com.excp.podroid.data.repository.PortForwardRule(X11Constants.VNC_PORT, X11Constants.VNC_PORT, "tcp"))
+ rules.add(com.excp.podroid.data.repository.PortForwardRule(X11Constants.VNC_PORT, X11Constants.VNC_PORT, "tcp", loopbackOnly = true))
}
if (rules.none { it.hostPort == X11Constants.AUDIO_PORT }) {
- rules.add(com.excp.podroid.data.repository.PortForwardRule(X11Constants.AUDIO_PORT, X11Constants.AUDIO_PORT, "tcp"))
+ rules.add(com.excp.podroid.data.repository.PortForwardRule(X11Constants.AUDIO_PORT, X11Constants.AUDIO_PORT, "tcp", loopbackOnly = true))
}
val config = VmConfig(