A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix(x11): reject degenerate RFB geometry, bound ZRLE runs, harden audio loop, add decoder reset
ExTv490eab126428
diff --git a/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt b/app/src/main/java/com/excp/podroid/x11/AudioStreamer.ktindex 6225d40..ddeca83 100644--- a/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt+++ b/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt@@ -12,6 +12,7 @@ import android.media.AudioAttributesimport android.media.AudioFormatimport android.media.AudioTrackimport android.util.Log+import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Job@@ -56,11 +57,32 @@ class AudioStreamer(private val host: String = "127.0.0.1") {}private suspend fun runLoop() {- var track = buildTrack()- track.play()+ // Nullable so a failed (re)build leaves no reference to a released track.+ // The write loop only signals "rebuild needed" by nulling this; the actual+ // (re)build happens at the top of each connection attempt, where a throw+ // propagates to the outer catch with `track` already null — the loop can+ // never write to a released AudioTrack, and finally never double-releases.+ var track: AudioTrack? = nulltry {while (coroutineContext.isActive) {try {+ // Ensure a live track before this connection's write loop. If a+ // prior iteration nulled `track` after releasing it, build a fresh+ // one here. Build into a local and only publish to `track` after+ // play() succeeds; if build/play throws, release the half-built+ // local and propagate with `track` still null, so the reconnect+ // path retries cleanly without ever writing to a released track.+ val activeTrack = track ?: run {+ val fresh = buildTrack()+ try {+ fresh.play()+ } catch (e: Throwable) {+ fresh.release()+ throw e+ }+ track = fresh+ fresh+ }Socket().use { s ->socket = ss.connect(InetSocketAddress(host, X11Constants.AUDIO_PORT), 2000)@@ -78,20 +100,33 @@ class AudioStreamer(private val host: String = "127.0.0.1") {// Loop on write: AudioTrack may accept fewer than// BUF_BYTES per call. A negative return is an// ERROR_* (e.g. ERROR_DEAD_OBJECT after a route- // change) → rebuild the track and resume.+ // change) → release this track, null the field so a+ // failed rebuild can't leave a released track in use,+ // and bail to the outer loop, which rebuilds cleanly.+ // A return of exactly 0 is transient (buffer full);+ // back off briefly rather than spinning without advancing.var off = 0+ var zeroRetries = 0while (off < BUF_BYTES) {- val n = track.write(buf, off, BUF_BYTES - off)- if (n < 0) {- Log.v(TAG, "AudioTrack.write error $n; rebuilding")- track.stop(); track.release()- track = buildTrack(); track.play()- break+ val n = activeTrack.write(buf, off, BUF_BYTES - off)+ when {+ n < 0 -> {+ Log.v(TAG, "AudioTrack.write error $n; rebuilding")+ track = null+ activeTrack.stop(); activeTrack.release()+ throw java.io.IOException("AudioTrack.write error $n")+ }+ n == 0 -> {+ if (++zeroRetries > 8) break // give up this chunk+ delay(5)+ }+ else -> { off += n; zeroRetries = 0 }}- off += n}}}+ } catch (e: CancellationException) {+ throw e} catch (e: Exception) {Log.v(TAG, "audio reconnect: ${e.message}")socket = null@@ -100,8 +135,8 @@ class AudioStreamer(private val host: String = "127.0.0.1") {}} finally {socket = null- track.stop()- track.release()+ track?.stop()+ track?.release()}}diff --git a/app/src/main/java/com/excp/podroid/x11/VncClient.kt b/app/src/main/java/com/excp/podroid/x11/VncClient.ktindex e8e5e8c..ad849d8 100644--- a/app/src/main/java/com/excp/podroid/x11/VncClient.kt+++ b/app/src/main/java/com/excp/podroid/x11/VncClient.kt@@ -88,6 +88,7 @@ object VncClient {* No-op for in-range rects.*/private fun requireInBounds(x: Int, y: Int, w: Int, h: Int, stride: Int, size: Int) {+ if (stride <= 0) throw java.io.IOException("RFB: zero or negative stride $stride")val rows = size / strideif (x < 0 || y < 0 || w < 0 || h < 0 || x + w > stride || y + h > rows)throw java.io.IOException("RFB rect out of bounds: x=$x y=$y w=$w h=$h stride=$stride size=$size")@@ -181,6 +182,7 @@ object VncClient {ENC_EXTENDED_DESKTOP_SIZE -> { // -308: w/h are the new fb dimsval screens = din.readUnsignedByte(); skipFully(din, 3)skipFully(din, screens * 16) // we use a single-screen model; dims come from w/h+ if (w <= 0 || h <= 0) throw java.io.IOException("RFB ExtendedDesktopSize: degenerate geometry w=$w h=$h")newSize = VncSize(w, h)}ENC_RAW -> {@@ -213,7 +215,7 @@ object VncClient {zrle.decode(din, x, y, w, h, targetArgb, stride)damage.add(VncRect(x, y, w, h))}- else -> error("unsupported encoding $enc")+ else -> throw java.io.IOException("unsupported encoding $enc")}}return RfbUpdate(newSize, damage)diff --git a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.ktindex 8ed847a..a07f181 100644--- a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt+++ b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt@@ -35,6 +35,13 @@ class ZrleDecoder {private val inflater = Inflater(/*nowrap=*/false)+ companion object {+ // Maximum pixels in a single ZRLE tile (64x64). Run-length accumulators+ // are capped at this value to prevent Int overflow from wrapping the sum+ // to a large negative number that defeats the overrun guard.+ private const val MAX_TILE_PIXELS = 64 * 64+ }+// Scratch buffer for compressed input read from the socket.private var inputScratch = ByteArray(4096)// Decompressed output buffer; re-used across inflate calls within one decode() call.@@ -44,6 +51,24 @@ class ZrleDecoder {private var remaining = 0private var inputStream: DataInputStream? = null+ /**+ * Resets decoder state between RFB sessions.+ *+ * The zlib stream is continuous within a single RFB session, so the [Inflater]+ * must NOT be reset between rects. It MUST be reset on reconnect: a new RFB+ * session starts a fresh zlib stream, and feeding it into a finished or leftover+ * inflater produces corrupt output or a DataFormatException.+ *+ * Call this from the session-level connect path (X11ViewModel.connect()), not+ * from the per-rect decode path. The call site lives in a WS-2 file; this method+ * is intentionally unused after this change and will be wired in a follow-up.+ */+ fun reset() {+ inflater.reset()+ remaining = 0+ inputStream = null+ }+/*** Decodes one ZRLE-encoded rectangle into [target].*@@ -240,12 +265,18 @@ class ZrleDecoder {* Each byte 0xFF contributes 255 and reading continues;* the first byte < 0xFF ends the sequence, contributing its value.* The actual run count = sum + 1.+ *+ * The accumulator is capped at MAX_TILE_PIXELS (4096, the pixel count of+ * the largest possible 64x64 tile) to prevent Int overflow: without the cap,+ * enough 0xFF bytes would wrap the sum to a large negative number, defeating+ * the caller's post-hoc (filled + runLen > total) overrun check.*/fun readRunLength(): Int {var total = 0while (true) {val b = readByte()total += b+ if (total > MAX_TILE_PIXELS) throw IOException("ZRLE: run length $total exceeds max tile size")if (b != 0xFF) break}return total + 1diff --git a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt b/app/src/test/java/com/excp/podroid/x11/VncClientTest.ktindex 2f22529..29eced2 100644--- a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt+++ b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt@@ -157,6 +157,33 @@ class VncClientTest {VncClient.handshake(java.io.ByteArrayInputStream(serverBytes), java.io.ByteArrayOutputStream())}+ // Fix 1: ExtendedDesktopSize with w=0 must throw IOException, not ArithmeticException.+ @Test(expected = java.io.IOException::class)+ fun `ExtendedDesktopSize with width zero throws IOException`() {+ // FramebufferUpdate: type=0, pad, numRects=1; rect x=0 y=0 w=0 h=600 enc=-308;+ // body: screens=1 + pad[3]; screen descriptor (16 bytes).+ val bos = java.io.ByteArrayOutputStream()+ val d = java.io.DataOutputStream(bos)+ d.writeByte(0); d.writeByte(0); d.writeShort(1) // msg, pad, numRects+ d.writeShort(0); d.writeShort(0); d.writeShort(0); d.writeShort(600); d.writeInt(-308) // w=0+ d.writeByte(1); d.writeByte(0); d.writeByte(0); d.writeByte(0) // screens=1 + pad3+ d.writeInt(1); d.writeShort(0); d.writeShort(0); d.writeShort(0); d.writeShort(600); d.writeInt(0)+ val target = IntArray(1280 * 720)+ VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 1280, ZrleDecoder())+ }++ // Fix 2: An unknown encoding type must throw IOException, not IllegalStateException.+ @Test(expected = java.io.IOException::class)+ fun `unsupported encoding throws IOException`() {+ val bos = java.io.ByteArrayOutputStream()+ val d = java.io.DataOutputStream(bos)+ d.writeByte(0); d.writeByte(0); d.writeShort(1) // msg, pad, numRects+ d.writeShort(0); d.writeShort(0); d.writeShort(1); d.writeShort(1) // x=0,y=0,w=1,h=1+ d.writeInt(0x7FFFFFFF) // unknown encoding+ val target = IntArray(1280 * 720)+ VncClient.readFramebufferUpdate(java.io.ByteArrayInputStream(bos.toByteArray()), target, 1280, ZrleDecoder())+ }+@Test fun `ExtendedDesktopSize rect reports new size and writes no pixels`() {// FramebufferUpdate: type=0, pad, numRects=1; rect x=0 y=0 w=800 h=600 enc=-308;// body: screens=1 pad[3]; screen{id=1,x=0,y=0,w=800,h=600,flags=0}diff --git a/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt b/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.ktindex f2b1580..49cf281 100644--- a/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt+++ b/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt@@ -5,9 +5,12 @@package com.excp.podroid.x11import org.junit.Assert.assertEquals+import org.junit.Assert.assertThrows+import org.junit.Assert.assertTrueimport org.junit.Testimport java.io.ByteArrayInputStreamimport java.io.DataInputStream+import java.io.IOExceptionimport java.util.zip.Deflaterclass ZrleDecoderTest {@@ -122,6 +125,35 @@ class ZrleDecoderTest {ZrleDecoder().decode(din, 0, 0, 2, 2, IntArray(4), 2)}+ // Fix 3: a run-length whose accumulated sum exceeds the maximum tile size+ // (4096 pixels for a 64x64 tile) must be rejected inside readRunLength itself,+ // by the explicit accumulator cap, BEFORE the sum can be used. Without the cap+ // a sufficiently long 0xFF run overflows Int and wraps the sum negative,+ // defeating the caller's post-hoc (filled + runLen > total) overrun guard.+ //+ // The fixture (17 x 0xFF + 0x00 → run = 4336) is caught on BOTH paths, so the+ // exception type alone proves nothing: pre-fix the caller's overrun guard fires+ // ("plain RLE run overruns tile"), post-fix the cap fires ("exceeds max tile+ // size"). Asserting on the message pins detection to the cap — RED pre-fix+ // (message mismatch), GREEN post-fix.+ @Test+ fun `ZRLE run length exceeding tile size throws from readRunLength cap`() {+ val plain = java.io.ByteArrayOutputStream()+ plain.write(128) // plain RLE+ plain.write(cpixel(0xFFAABBCC.toInt()))+ // 17 x 0xFF: running sum = 17*255 = 4335, exceeds the 4096-pixel cap.+ repeat(17) { plain.write(0xFF) }+ plain.write(0x00)+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain.toByteArray())))+ val ex = assertThrows(IOException::class.java) {+ ZrleDecoder().decode(din, 0, 0, 64, 64, IntArray(64 * 64), 64)+ }+ assertTrue(+ "expected the readRunLength cap to fire, was: ${ex.message}",+ ex.message?.contains("exceeds max tile size") == true,+ )+ }+/** High: a palette-RLE single-pixel index beyond the palette → IOException, not AIOOBE. */@Test(expected = java.io.IOException::class)fun `palette RLE index out of range throws IOException`() {