Skip to content

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

fix(vnc): RFB bounds-checking, viewer gestures, audio, and ZRLE decoder

ExTvf8ef9374aa03
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
index d1cd2ed..4438470 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11Screen.kt
@@ -55,6 +55,7 @@ import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
@@ -69,6 +70,7 @@ import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type
+import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.PointerType
import androidx.compose.ui.input.pointer.changedToDown
@@ -164,6 +166,11 @@ fun X11Screen(
LaunchedEffect(Unit) { viewModel.connect() }
val activity = LocalContext.current as? Activity
+ // Restore orientation when leaving; without this the lock persists onto
+ // terminal/home until process restart.
+ DisposableEffect(Unit) {
+ onDispose { activity?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED }
+ }
LaunchedEffect(s.rotationLock) {
activity?.requestedOrientation = when (s.rotationLock) {
com.excp.podroid.x11.RotationLock.LANDSCAPE -> ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
@@ -173,7 +180,10 @@ fun X11Screen(
}
val view = LocalView.current
- var fullscreen by remember { mutableStateOf(s.fullscreenDefault) }
+ // Key on s.fullscreenDefault so the setting is picked up once DataStore
+ // delivers its first non-default emission; manual toggles still work because
+ // a toggle changes `fullscreen` without changing the key.
+ var fullscreen by remember(s.fullscreenDefault) { mutableStateOf(s.fullscreenDefault) }
LaunchedEffect(fullscreen) {
val window = activity?.window ?: return@LaunchedEffect
val ctrl = WindowInsetsControllerCompat(window, view)
@@ -192,6 +202,12 @@ fun X11Screen(
activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
onDispose { activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) }
}
+ // Ensure disconnect + heldButtons reset on screen exit even if the ViewModel
+ // lives longer than this nav entry (onCleared would also call it, but that
+ // fires later; the immediate dispose prevents stuck buttons across navigation).
+ DisposableEffect(Unit) {
+ onDispose { viewModel.disconnect() }
+ }
// Back exits fullscreen first (no on-screen exit button); a second Back
// leaves the viewer through normal navigation.
@@ -274,8 +290,9 @@ fun X11Screen(
// pointer handler already sent it to X as button 3, so swallow
// the mouse-sourced Back (both down + up) to stop it exiting
// fullscreen. A real Back (gesture/keyboard) passes through to
- // the BackHandler.
- if (ev.key == Key.Back) {
+ // the BackHandler. Only intercept when fullscreen; in windowed
+ // mode Back should navigate out normally.
+ if (ev.key == Key.Back && fullscreen) {
return@onPreviewKeyEvent (native.source and android.view.InputDevice.SOURCE_MOUSE) ==
android.view.InputDevice.SOURCE_MOUSE
}
@@ -312,7 +329,9 @@ fun X11Screen(
(android.view.KeyEvent.META_SHIFT_ON or android.view.KeyEvent.META_CAPS_LOCK_ON)
)
if (cased == 0) return@onPreviewKeyEvent false
- keysym = cased
+ // X keysyms 0x20-0x7E match ASCII verbatim; non-ASCII Unicode
+ // maps to 0x01000000 | codepoint (X11 protocol extension).
+ keysym = if (cased > 0x7E) 0x01000000 or cased else cased
shiftWrap = false
}
if (shiftWrap) viewModel.sendKey(XK_Shift_L, down = true)
@@ -393,16 +412,27 @@ fun X11Screen(
}
}
X11ConnectionState.Connected -> {
+ // rememberUpdatedState lets the pointerInput lambda always read the
+ // latest layout values without being in the key list, so a resize
+ // during an in-flight gesture updates coordinate mapping rather than
+ // cancelling the gesture coroutine mid-drag.
+ val currentDstX by rememberUpdatedState(dstX)
+ val currentDstY by rememberUpdatedState(dstY)
+ val currentDstW by rememberUpdatedState(dstW)
+ val currentDstH by rememberUpdatedState(dstH)
+ val currentFbW by rememberUpdatedState(fb.w)
+ val currentFbH by rememberUpdatedState(fb.h)
+
AndroidView(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.pointerInput(
- s.touchMode, dstX, dstY, dstW, dstH, fb.w, fb.h,
+ s.touchMode,
s.trackpadSensitivity, s.trackpadAccel,
) {
- fun fbX(px: Float) = ((px - dstX) / dstW.coerceAtLeast(1) * fb.w).toInt().coerceIn(0, fb.w - 1)
- fun fbY(py: Float) = ((py - dstY) / dstH.coerceAtLeast(1) * fb.h).toInt().coerceIn(0, fb.h - 1)
+ fun fbX(px: Float) = ((px - currentDstX) / currentDstW.coerceAtLeast(1) * currentFbW).toInt().coerceIn(0, currentFbW - 1)
+ fun fbY(py: Float) = ((py - currentDstY) / currentDstH.coerceAtLeast(1) * currentFbH).toInt().coerceIn(0, currentFbH - 1)
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
@@ -437,6 +467,9 @@ fun X11Screen(
if (change.type != PointerType.Touch || !change.changedToDown()) continue
viewerFocus.requestFocus()
change.consume()
+ // Pin the primary pointer by ID so finger-order changes
+ // don't jump the cursor to a different finger.
+ val primaryId: PointerId = change.id
val sx = change.position.x; val sy = change.position.y
var lastX = sx; var lastY = sy
var moved = 0f
@@ -465,7 +498,7 @@ fun X11Screen(
val pressed = e.changes.filter { it.pressed }
if (pressed.isEmpty()) { outcome = "tap"; return@withTimeoutOrNull Unit }
if (pressed.size >= 2) { maxPointers = 2; outcome = "multi"; return@withTimeoutOrNull Unit }
- val p = pressed.first().position
+ val p = (pressed.firstOrNull { it.id == primaryId } ?: pressed.first()).position
if (abs(p.x - sx) + abs(p.y - sy) > 16f) {
lastX = p.x; lastY = p.y; outcome = "move"
e.changes.forEach { it.consume() }
@@ -482,36 +515,47 @@ fun X11Screen(
continue
}
- while (true) {
- val e = awaitPointerEvent()
- val pressed = e.changes.filter { it.pressed }
- maxPointers = maxOf(maxPointers, pressed.size)
- if (pressed.isEmpty()) break
- val p = pressed.first().position
- val dx = p.x - lastX; val dy = p.y - lastY
- moved += abs(dx) + abs(dy)
- if (pressed.size >= 2) {
- scrollAcc += dy
- while (abs(scrollAcc) >= 60f) {
- viewModel.scroll(scrollAcc < 0, 1)
- scrollAcc += if (scrollAcc < 0) 60f else -60f
- }
- } else when (s.touchMode) {
- TouchMode.DIRECT -> {
- viewModel.moveTo(fbX(p.x), fbY(p.y))
- if (!leftHeld) { viewModel.press(VncClient.BTN_LEFT); leftHeld = true }
- }
- TouchMode.TRACKPAD -> {
- val accel = if (s.trackpadAccel) (1f + (abs(dx) + abs(dy)) * 0.01f) else 1f
- val c = viewModel.cursor.value
- viewModel.moveTo(
- (c.x + dx * s.trackpadSensitivity * accel).toInt(),
- (c.y + dy * s.trackpadSensitivity * accel).toInt(),
- )
+ try {
+ while (true) {
+ val e = awaitPointerEvent()
+ val pressed = e.changes.filter { it.pressed }
+ maxPointers = maxOf(maxPointers, pressed.size)
+ if (pressed.isEmpty()) break
+ // Track the pinned primary pointer, falling back to
+ // first if it lifted (e.g. swapped fingers).
+ val p = (pressed.firstOrNull { it.id == primaryId } ?: pressed.first()).position
+ val dx = p.x - lastX; val dy = p.y - lastY
+ moved += abs(dx) + abs(dy)
+ if (pressed.size >= 2) {
+ // Transitioning 1→2 fingers: release left if held
+ // so we don't send a left+scroll chord.
+ if (leftHeld) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }
+ scrollAcc += dy
+ while (abs(scrollAcc) >= 60f) {
+ viewModel.scroll(scrollAcc < 0, 1)
+ scrollAcc += if (scrollAcc < 0) 60f else -60f
+ }
+ } else when (s.touchMode) {
+ TouchMode.DIRECT -> {
+ viewModel.moveTo(fbX(p.x), fbY(p.y))
+ if (!leftHeld) { viewModel.press(VncClient.BTN_LEFT); leftHeld = true }
+ }
+ TouchMode.TRACKPAD -> {
+ val accel = if (s.trackpadAccel) (1f + (abs(dx) + abs(dy)) * 0.01f) else 1f
+ val c = viewModel.cursor.value
+ viewModel.moveTo(
+ (c.x + dx * s.trackpadSensitivity * accel).toInt(),
+ (c.y + dy * s.trackpadSensitivity * accel).toInt(),
+ )
+ }
}
+ lastX = p.x; lastY = p.y
+ e.changes.forEach { it.consume() }
}
- lastX = p.x; lastY = p.y
- e.changes.forEach { it.consume() }
+ } finally {
+ // Release left button on cancellation (e.g. settings-change
+ // restarts the pointerInput coroutine mid-drag).
+ if (leftHeld && !dragLocked) { viewModel.release(VncClient.BTN_LEFT); leftHeld = false }
}
if (maxPointers >= 2) {
@@ -528,9 +572,17 @@ fun X11Screen(
holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(h: SurfaceHolder) {}
override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, hh: Int) {
+ // Ignore height-only shrinks caused by the IME appearing;
+ // those don't require a desktop resize (only a layout reflow).
+ // Only send a resolution request when width changes or height
+ // grows (genuine surface resize, not just keyboard insets).
+ val widthChanged = w != svWidth
+ val heightGrew = hh > svHeight
svWidth = w
svHeight = hh
- viewModel.requestResolution(w, hh)
+ if (widthChanged || heightGrew) {
+ viewModel.requestResolution(w, hh)
+ }
}
override fun surfaceDestroyed(h: SurfaceHolder) {}
})
@@ -541,9 +593,9 @@ fun X11Screen(
frameCount
// Lock the IntArray for the copy into Bitmap pixels so
// we never observe a half-written frame from the RFB
- // decoder thread (paired with synchronized(framebuffer)
+ // decoder thread (paired with synchronized(fbLock)
// in X11ViewModel.connect).
- synchronized(viewModel.framebuffer) {
+ synchronized(viewModel.fbLock) {
val src = viewModel.framebuffer
val bw = bitmap.width
val bh = bitmap.height
@@ -595,17 +647,25 @@ fun X11Screen(
BasicTextField(
value = imeBuf,
onValueChange = { new ->
- val added = if (new.text.length > imeBuf.text.length)
- new.text.substring(imeBuf.text.length) else ""
- if ((ctrlActive || altActive) && added.length == 1) {
+ val old = imeBuf
+ // Compute the added text based on the actual old buffer so
+ // deletions (Backspace) are observable as shrinks. Do NOT
+ // reset to empty before the diff — that's what killed Backspace.
+ val addedText = if (new.text.length > old.text.length)
+ new.text.substring(old.text.length) else ""
+ if ((ctrlActive || altActive) && addedText.length == 1) {
// Combine the sticky CTRL/ALT with the typed character
// (e.g. tap CTRL then type L → Ctrl+L to clear the
// terminal). sendWithModifiers clears the one-shot after.
- sendWithModifiers(added[0].code)
+ sendWithModifiers(addedText[0].code)
+ // Reset buffer after ctrl/alt combo to keep it short.
+ imeBuf = TextFieldValue("")
} else {
- forwardImeDiff(imeBuf.text, new.text, viewModel)
+ forwardImeDiff(old.text, new.text, viewModel)
+ // Keep the rolling buffer so future deletions are
+ // observable, but cap it to avoid accumulating without bound.
+ imeBuf = if (new.text.length > 128) TextFieldValue(new.text.takeLast(64)) else new
}
- imeBuf = TextFieldValue("")
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Send),
keyboardActions = KeyboardActions(
@@ -685,6 +745,9 @@ private fun X11KeyButton(
repeatable: Boolean = false,
) {
var pressed by remember { mutableStateOf(false) }
+ // Keyed on pressed/sendKey/repeatable only. (Including onKey here restarted the
+ // repeat coroutine on every recomposition, breaking key-repeat; applying a sticky
+ // modifier across a repeat burst is a deferred minor item.)
LaunchedEffect(pressed, sendKey, repeatable) {
if (!repeatable || !pressed) return@LaunchedEffect
delay(400L)
@@ -728,18 +791,25 @@ private fun X11KeyButton(
/**
* Compares old vs new IME buffer content, fires synthetic X11 key events
- * for the diff. Printable characters use their ASCII code as the keysym
- * (X11 keysyms 0x20–0x7E match ASCII verbatim).
+ * for the diff. ASCII 0x20-0x7E maps to the same keysym value; non-ASCII
+ * Unicode codepoints map to 0x01000000 | codepoint (X11 protocol extension).
+ * Counts by codepoints (not UTF-16 chars) so surrogate pairs count as one.
*/
private fun forwardImeDiff(old: String, new: String, vm: X11ViewModel) {
- if (new.length > old.length) {
- new.substring(old.length).forEach { ch ->
- val keysym = ch.code
+ val oldCp = old.codePointCount(0, old.length)
+ val newCp = new.codePointCount(0, new.length)
+ if (newCp > oldCp) {
+ // Iterate added codepoints (not chars) for correct surrogate handling.
+ var i = old.length
+ while (i < new.length) {
+ val cp = new.codePointAt(i)
+ val keysym = if (cp in 0x20..0x7E) cp else 0x01000000 or cp
vm.sendKey(keysym, down = true)
vm.sendKey(keysym, down = false)
+ i += Character.charCount(cp)
}
- } else if (new.length < old.length) {
- repeat(old.length - new.length) {
+ } else if (newCp < oldCp) {
+ repeat(oldCp - newCp) {
vm.sendKey(XK_BackSpace, down = true)
vm.sendKey(XK_BackSpace, down = false)
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
index a405af7..3a2fa80 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/x11/X11ViewModel.kt
@@ -64,6 +64,8 @@ class X11ViewModel @Inject constructor(
@Volatile private var fbW = X11Constants.FB_WIDTH
@Volatile private var fbH = X11Constants.FB_HEIGHT
@Volatile var framebuffer: IntArray = IntArray(fbW * fbH); private set
+ // Dedicated lock object so synchronized() is never on the reassigned framebuffer field.
+ val fbLock = Any()
@Volatile private var scratch: IntArray = IntArray(fbW * fbH)
private val zrle = ZrleDecoder()
@Volatile private var screenId = 0
@@ -100,7 +102,7 @@ class X11ViewModel @Inject constructor(
if (ns.w != fbW || ns.h != fbH) {
fbW = ns.w; fbH = ns.h
val fresh = IntArray(fbW * fbH)
- synchronized(framebuffer) { framebuffer = fresh }
+ synchronized(fbLock) { framebuffer = fresh }
scratch = IntArray(fbW * fbH)
_fbSize.value = ns
cursor.value = android.graphics.Point(fbW / 2, fbH / 2)
@@ -108,7 +110,7 @@ class X11ViewModel @Inject constructor(
return@let
}
}
- synchronized(framebuffer) {
+ synchronized(fbLock) {
System.arraycopy(scratch, 0, framebuffer, 0, framebuffer.size)
lastDamage = upd.damage
}
@@ -129,6 +131,7 @@ class X11ViewModel @Inject constructor(
}
fun disconnect() {
+ heldButtons = 0
sessionJob?.cancel()
sessionJob = null
}
@@ -219,12 +222,15 @@ class X11ViewModel @Inject constructor(
fun press(button: Int) { heldButtons = heldButtons or button; sendPointer(cursor.value.x, cursor.value.y, heldButtons) }
fun release(button: Int) { heldButtons = heldButtons and button.inv(); sendPointer(cursor.value.x, cursor.value.y, heldButtons) }
fun click(button: Int) { press(button); release(button) }
- /** Physical-mouse update: absolute position + the full button mask in one event. */
+ /** Physical-mouse update: absolute position + the full button mask in one event.
+ * Mouse is authoritative for the button mask (mask=0 on release must clear bits).
+ * A simultaneous touch drag-lock + physical mouse is a rare mixed-input edge left
+ * as-is; OR-ing the mask here would make mouse buttons un-releasable. */
fun mouseUpdate(x: Int, y: Int, mask: Int) {
val nx = x.coerceIn(0, fbW - 1); val ny = y.coerceIn(0, fbH - 1)
cursor.value = android.graphics.Point(nx, ny)
heldButtons = mask
- sendPointer(nx, ny, mask)
+ sendPointer(nx, ny, heldButtons)
}
fun scroll(up: Boolean, ticks: Int = 1) { val b = if (up) VncClient.BTN_WHEEL_UP else VncClient.BTN_WHEEL_DOWN; repeat(ticks) { sendPointer(cursor.value.x, cursor.value.y, heldButtons or b); sendPointer(cursor.value.x, cursor.value.y, heldButtons) } }
diff --git a/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt b/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt
index 9c24f68..6225d40 100644
--- a/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt
+++ b/app/src/main/java/com/excp/podroid/x11/AudioStreamer.kt
@@ -37,6 +37,11 @@ class AudioStreamer(private val host: String = "127.0.0.1") {
}
private var job: Job? = null
+ // Held so stop() can close it: readFully blocks indefinitely when the audio
+ // source is quiet, so cancelling the job alone leaves the socket + thread
+ // leaked on screen exit. Closing the socket unblocks readFully with an
+ // exception, letting the loop observe cancellation and exit.
+ @Volatile private var socket: Socket? = null
fun start(scope: CoroutineScope) {
if (job?.isActive == true) return
@@ -46,15 +51,18 @@ class AudioStreamer(private val host: String = "127.0.0.1") {
fun stop() {
job?.cancel()
job = null
+ try { socket?.close() } catch (_: Exception) {}
+ socket = null
}
private suspend fun runLoop() {
- val track = buildTrack()
+ var track = buildTrack()
track.play()
try {
while (coroutineContext.isActive) {
try {
Socket().use { s ->
+ socket = s
s.connect(InetSocketAddress(host, X11Constants.AUDIO_PORT), 2000)
// Disable Nagle — audio frames are tiny and latency-
// sensitive; coalescing them adds jitter that AudioTrack
@@ -67,15 +75,31 @@ class AudioStreamer(private val host: String = "127.0.0.1") {
// Throws EOFException on socket close → catch outer
// reconnects.
din.readFully(buf, 0, BUF_BYTES)
- track.write(buf, 0, BUF_BYTES)
+ // 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.
+ var off = 0
+ while (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
+ }
+ off += n
+ }
}
}
} catch (e: Exception) {
Log.v(TAG, "audio reconnect: ${e.message}")
+ socket = null
delay(1000)
}
}
} finally {
+ socket = null
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.kt
index 4f67660..e8e5e8c 100644
--- a/app/src/main/java/com/excp/podroid/x11/VncClient.kt
+++ b/app/src/main/java/com/excp/podroid/x11/VncClient.kt
@@ -57,13 +57,42 @@ object VncClient {
// 7. Read ServerInit
val w = din.readUnsignedShort()
val h = din.readUnsignedShort()
- din.skipBytes(16) // pixel format we'll override
+ skipFully(din, 16) // pixel format we'll override
val nameLen = din.readInt()
+ require(nameLen in 0..(1 shl 20)) { "RFB name length $nameLen" }
val name = ByteArray(nameLen).also { din.readFully(it) }.toString(Charsets.UTF_8)
return VncServerInfo(w, h, name)
}
+ /**
+ * Reads and discards exactly [n] bytes from [din]. DataInputStream.skipBytes
+ * may skip fewer than requested over a socket when not all bytes have
+ * arrived; a short skip would leave unconsumed bytes and desync RFB framing.
+ * No behavior change when bytes are already buffered.
+ */
+ private fun skipFully(din: DataInputStream, n: Int) {
+ var left = n
+ val scratch = ByteArray(minOf(n, 4096).coerceAtLeast(1))
+ while (left > 0) {
+ val r = din.read(scratch, 0, minOf(left, scratch.size))
+ if (r < 0) throw java.io.IOException("RFB: EOF skipping $n bytes ($left remaining)")
+ left -= r
+ }
+ }
+
+ /**
+ * Validates a server-supplied rect against the framebuffer before any pixel
+ * access. Reachable on a resolution-change race where the server sends a
+ * rect sized to a different desktop than the client's current buffer.
+ * No-op for in-range rects.
+ */
+ private fun requireInBounds(x: Int, y: Int, w: Int, h: Int, stride: Int, size: Int) {
+ val rows = size / stride
+ if (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")
+ }
+
private const val MSG_FRAMEBUFFER_UPDATE: Int = 0
private const val ENC_RAW: Int = 0
private const val ENC_COPY_RECT: Int = 1
@@ -87,11 +116,12 @@ object VncClient {
out.write(pf)
// SetEncodings (msg=2): CopyRect, Raw, ExtendedDesktopSize(-308).
- // ZRLE is intentionally NOT advertised: the decoder desyncs its
- // continuous zlib stream on complex content (Firefox/xfce send palette/
- // RLE tiles), producing "invalid distance code" which kills the whole
- // VNC session. Raw has no zlib state so it can't desync. Re-enable only
- // after the ZrleDecoder is fixed + verified against real captured tiles.
+ // ZRLE is still NOT advertised, but the historical desync cause is now
+ // fixed: ZrleDecoder fed the inflater in chunks without draining, dropping
+ // all but the last 4 KB of any block >4096 bytes ("invalid distance code").
+ // It now feeds on demand and bounds-checks palette indices and run lengths.
+ // Re-enabling ZRLE changes what the server streams, so it stays gated until
+ // validated on-device against real Firefox/xfce tiles (a separate change).
val se = java.nio.ByteBuffer.allocate(4 + 3 * 4)
se.put(2.toByte()); se.put(0.toByte()); se.putShort(3)
se.putInt(1) // CopyRect
@@ -131,13 +161,13 @@ object VncClient {
msgType = din.readUnsignedByte()
when (msgType) {
MSG_FRAMEBUFFER_UPDATE -> break
- 1 -> { din.skipBytes(1); din.readUnsignedShort(); val n = din.readUnsignedShort(); din.skipBytes(n * 6) }
+ 1 -> { skipFully(din, 1); din.readUnsignedShort(); val n = din.readUnsignedShort(); skipFully(din, n * 6) }
2 -> { }
- 3 -> { din.skipBytes(3); val len = din.readInt(); if (len in 0..(1 shl 20)) din.skipBytes(len) else throw java.io.IOException("ServerCutText absurd length=$len") }
+ 3 -> { skipFully(din, 3); val len = din.readInt(); if (len in 0..(1 shl 20)) skipFully(din, len) else throw java.io.IOException("ServerCutText absurd length=$len") }
else -> throw java.io.IOException("unexpected RFB server msg type $msgType")
}
}
- din.skipBytes(1)
+ skipFully(din, 1)
val numRects = din.readUnsignedShort()
var rowBuf: ByteArray? = null
var newSize: VncSize? = null
@@ -149,11 +179,12 @@ object VncClient {
val enc = din.readInt()
when (enc) {
ENC_EXTENDED_DESKTOP_SIZE -> { // -308: w/h are the new fb dims
- val screens = din.readUnsignedByte(); din.skipBytes(3)
- din.skipBytes(screens * 16) // we use a single-screen model; dims come from w/h
+ val screens = din.readUnsignedByte(); skipFully(din, 3)
+ skipFully(din, screens * 16) // we use a single-screen model; dims come from w/h
newSize = VncSize(w, h)
}
ENC_RAW -> {
+ requireInBounds(x, y, w, h, stride, targetArgb.size)
val needed = w * 4
val rowPixels = rowBuf?.takeIf { it.size >= needed } ?: ByteArray(needed).also { rowBuf = it }
for (row in 0 until h) {
@@ -171,11 +202,14 @@ object VncClient {
}
ENC_COPY_RECT -> {
val srcX = din.readUnsignedShort(); val srcY = din.readUnsignedShort()
+ requireInBounds(x, y, w, h, stride, targetArgb.size)
+ requireInBounds(srcX, srcY, w, h, stride, targetArgb.size)
if (srcY < y) for (row in h - 1 downTo 0) System.arraycopy(targetArgb, (srcY + row) * stride + srcX, targetArgb, (y + row) * stride + x, w)
else for (row in 0 until h) System.arraycopy(targetArgb, (srcY + row) * stride + srcX, targetArgb, (y + row) * stride + x, w)
damage.add(VncRect(x, y, w, h))
}
ENC_ZRLE -> {
+ requireInBounds(x, y, w, h, stride, targetArgb.size)
zrle.decode(din, x, y, w, h, targetArgb, stride)
damage.add(VncRect(x, y, w, h))
}
diff --git a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
index 4d67ed0..8ed847a 100644
--- a/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
+++ b/app/src/main/java/com/excp/podroid/x11/ZrleDecoder.kt
@@ -60,16 +60,14 @@ class ZrleDecoder {
val compLen = din.readInt()
if (compLen < 0 || compLen > 64 * 1024 * 1024) throw IOException("ZRLE: absurd compressed length $compLen")
- // Feed the entire compressed block to the inflater.
- var bytesLeft = compLen
- while (bytesLeft > 0) {
- val chunk = minOf(bytesLeft, inputScratch.size)
- din.readFully(inputScratch, 0, chunk)
- inflater.setInput(inputScratch, 0, chunk)
- bytesLeft -= chunk
- // Drain any output the inflater can produce now so its internal buffer stays free.
- // We don't store it here; ZInput pulls on demand.
- }
+ // Stream the compressed block on demand. setInput() does not copy/append —
+ // it holds inputScratch by reference and is consumed lazily by inflate(),
+ // so pre-loading multiple chunks into one buffer would drop all but the
+ // last. Instead ZInput.fill() reads the next chunk only once the inflater
+ // has consumed the previous one, bounded by `remaining` (this rect's
+ // compLen) so it never crosses the rect boundary.
+ remaining = compLen
+ inputStream = din
// Wrap the inflater so tile-level code just calls readByte()/readBytes().
val zi = ZInput(inflater)
@@ -131,6 +129,9 @@ class ZrleDecoder {
val idx = (accumByte ushr (8 - bitsPerIndex)) and ((1 shl bitsPerIndex) - 1)
accumByte = (accumByte shl bitsPerIndex) and 0xFF
bitsInAccum -= bitsPerIndex
+ // bitsPerIndex rounds up, so the index space can exceed n
+ // when n is not a power of two.
+ if (idx >= n) throw IOException("ZRLE: packed palette index $idx >= $n")
target[base + col] = palette[idx]
col++
}
@@ -145,6 +146,7 @@ class ZrleDecoder {
while (filled < total) {
val color = zi.readCpixel()
val runLen = zi.readRunLength()
+ if (filled + runLen > total) throw IOException("ZRLE: plain RLE run overruns tile ($filled+$runLen > $total)")
repeat(runLen) {
val pos = filled + it
val row = pos / tw; val col = pos % tw
@@ -163,14 +165,18 @@ class ZrleDecoder {
val indexByte = zi.readByte()
if (indexByte and 0x80 == 0) {
// Single pixel.
+ if (indexByte >= n) throw IOException("ZRLE: palette RLE index $indexByte >= $n")
val pos = filled
val row = pos / tw; val col = pos % tw
target[(ty + row) * stride + (tx + col)] = palette[indexByte]
filled++
} else {
// Run of palette[index & 0x7F].
- val color = palette[indexByte and 0x7F]
+ val idx = indexByte and 0x7F
+ if (idx >= n) throw IOException("ZRLE: palette RLE index $idx >= $n")
+ val color = palette[idx]
val runLen = zi.readRunLength()
+ if (filled + runLen > total) throw IOException("ZRLE: palette RLE run overruns tile ($filled+$runLen > $total)")
repeat(runLen) {
val pos = filled + it
val row = pos / tw; val col = pos % tw
@@ -196,11 +202,23 @@ class ZrleDecoder {
private fun fill() {
while (avail == 0) {
if (inf.finished()) throw IOException("ZRLE: inflater finished early")
+ // Feed the next compressed chunk on demand, bounded by this rect's
+ // remaining budget. Each chunk is fully consumed before its buffer
+ // is reused, and we never read past compLen.
+ if (inf.needsInput() && remaining > 0) {
+ val nIn = minOf(remaining, inputScratch.size)
+ inputStream!!.readFully(inputScratch, 0, nIn)
+ inf.setInput(inputScratch, 0, nIn)
+ remaining -= nIn
+ }
val n = inf.inflate(buf)
if (n > 0) { pos = 0; avail = n }
// n == 0 with needsInput means all input was consumed; if finished() is false
// but no output and needsInput, the caller overfed or the stream is malformed.
else if (inf.needsInput()) throw IOException("ZRLE: inflater needs more input but none queued")
+ // n == 0, not finished, not needsInput → needsDictionary or a stuck
+ // stream: bail rather than spin forever.
+ else throw IOException("ZRLE: inflater made no progress")
}
}
diff --git a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
index c212f72..2f22529 100644
--- a/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
+++ b/app/src/test/java/com/excp/podroid/x11/VncClientTest.kt
@@ -94,6 +94,69 @@ class VncClientTest {
assertEquals(7, ((b[8].toInt() and 0xFF) shl 24) or ((b[9].toInt() and 0xFF) shl 16) or ((b[10].toInt() and 0xFF) shl 8) or (b[11].toInt() and 0xFF))
}
+ @Test(expected = java.io.IOException::class)
+ fun `Raw rectangle exceeding framebuffer bounds throws IOException`() {
+ // FramebufferUpdate with a Raw rect at x=0,y=0,w=4,h=1 into a 2-pixel
+ // buffer (stride=2). w*h = 4 pixels would overrun the 2-element array →
+ // must raise IOException (bounds guard), not ArrayIndexOutOfBoundsException.
+ val msg = byteArrayOf(
+ 0x00, 0x00, // msg-type, padding
+ 0x00, 0x01, // num rects
+ 0x00, 0x00, 0x00, 0x00, // x=0, y=0
+ 0x00, 0x04, 0x00, 0x01, // w=4, h=1 (exceeds the 2-pixel buffer)
+ 0x00, 0x00, 0x00, 0x00, // encoding = 0 (Raw)
+ // 4 BGRA pixels of payload so the OOB write is actually reached
+ // (without payload, readFully would EOF before any array access).
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ )
+ VncClient.readFramebufferUpdate(
+ inp = java.io.ByteArrayInputStream(msg),
+ targetArgb = IntArray(2),
+ stride = 2,
+ zrle = ZrleDecoder(),
+ )
+ }
+
+ @Test(expected = java.io.IOException::class)
+ fun `CopyRect with out-of-bounds source throws IOException`() {
+ // CopyRect dst x=0,y=0,w=2,h=1 into a 2-pixel buffer; source srcX=10
+ // is out of range. Must raise IOException, not IndexOutOfBoundsException.
+ val msg = byteArrayOf(
+ 0x00, 0x00, // msg-type, padding
+ 0x00, 0x01, // num rects
+ 0x00, 0x00, 0x00, 0x00, // x=0, y=0
+ 0x00, 0x02, 0x00, 0x01, // w=2, h=1
+ 0x00, 0x00, 0x00, 0x01, // encoding = 1 (CopyRect)
+ 0x00, 0x0A, 0x00, 0x00, // srcX=10, srcY=0 (out of bounds)
+ )
+ VncClient.readFramebufferUpdate(
+ inp = java.io.ByteArrayInputStream(msg),
+ targetArgb = IntArray(2),
+ stride = 2,
+ zrle = ZrleDecoder(),
+ )
+ }
+
+ @Test(expected = Exception::class)
+ fun `ServerInit with absurd name length is rejected without OOM`() {
+ // Up through ServerInit, then nameLen = 0x7FFFFFFF. Must throw (require/
+ // IOException) before allocating ByteArray(nameLen) — no OutOfMemoryError.
+ val serverBytes = byteArrayOf(
+ 'R'.code.toByte(), 'F'.code.toByte(), 'B'.code.toByte(), ' '.code.toByte(),
+ '0'.code.toByte(), '0'.code.toByte(), '3'.code.toByte(), '.'.code.toByte(),
+ '0'.code.toByte(), '0'.code.toByte(), '8'.code.toByte(), '\n'.code.toByte(),
+ 0x01, 0x01, // sec types: count=1, None
+ 0x00, 0x00, 0x00, 0x00, // SecurityResult OK
+ 0x05, 0x00, 0x02, 0xD0.toByte(), // width 1280, height 720
+ 32, 24, 0, 1, // pixel format (16 bytes)
+ 0x00, 0xFF.toByte(), 0x00, 0xFF.toByte(), 0x00, 0xFF.toByte(),
+ 16, 8, 0,
+ 0, 0, 0,
+ 0x7F, 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), // nameLen = 0x7FFFFFFF
+ )
+ VncClient.handshake(java.io.ByteArrayInputStream(serverBytes), java.io.ByteArrayOutputStream())
+ }
+
@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.kt
index 6a88e96..f2b1580 100644
--- a/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt
+++ b/app/src/test/java/com/excp/podroid/x11/ZrleDecoderTest.kt
@@ -46,4 +46,92 @@ class ZrleDecoderTest {
ZrleDecoder().decode(din, 0, 0, 2, 2, target, 2)
assertEquals(a, target[0]); assertEquals(b, target[1]); assertEquals(a, target[2]); assertEquals(b, target[3])
}
+
+ /**
+ * Marquee fix A: a rect whose compressed zlib block exceeds the 4096-byte
+ * inputScratch must decode correctly. High-entropy raw tiles across a wide
+ * rect compress to >4 KB, so the old pre-load loop dropped all but the last
+ * 4 KB chunk and zlib reported "invalid distance code".
+ */
+ @Test fun `wide rect with compressed block over 4KB decodes correctly`() {
+ // 320x64 rect = 5 raw tiles of 64x64. Pseudo-random colors so zlib can't
+ // shrink it below 4096 bytes compressed.
+ val w = 320; val h = 64
+ val src = IntArray(w * h)
+ var seed = 0x12345678
+ for (i in src.indices) {
+ // xorshift PRNG → high-entropy, deterministic
+ seed = seed xor (seed shl 13); seed = seed xor (seed ushr 17); seed = seed xor (seed shl 5)
+ src[i] = (0xFF shl 24) or (seed and 0xFFFFFF)
+ }
+ // Build the ZRLE tile stream: row-major 64x64 raw tiles.
+ val plain = java.io.ByteArrayOutputStream()
+ var ty = 0
+ while (ty < h) {
+ val th = minOf(64, h - ty)
+ var tx = 0
+ while (tx < w) {
+ val tw = minOf(64, w - tx)
+ plain.write(0) // subencoding 0 = raw
+ for (row in 0 until th) for (col in 0 until tw) {
+ plain.write(cpixel(src[(ty + row) * w + (tx + col)]))
+ }
+ tx += 64
+ }
+ ty += 64
+ }
+ val rect = zrleRect(plain.toByteArray())
+ // Sanity: the compressed block must actually exceed inputScratch (4096).
+ val compLen = java.nio.ByteBuffer.wrap(rect, 0, 4).int
+ org.junit.Assert.assertTrue("compressed block must exceed 4096 (was $compLen)", compLen > 4096)
+
+ val din = DataInputStream(ByteArrayInputStream(rect))
+ val target = IntArray(w * h)
+ ZrleDecoder().decode(din, 0, 0, w, h, target, w)
+ org.junit.Assert.assertArrayEquals(src, target)
+ }
+
+ /** High: a packed-palette tile whose index exceeds the palette size → IOException, not AIOOBE. */
+ @Test(expected = java.io.IOException::class)
+ fun `packed palette index out of range throws IOException`() {
+ // Palette of 2 entries (subenc 2, 1 bit/index). Feed a row byte 0b1000_0000:
+ // first index = 1 (valid). Use a 1-entry palette via subenc would not be 2..16;
+ // instead force overflow with n=2 but a single-color palette is fine — to
+ // overflow we use n that makes idx exceed: build subenc=3 (n=3, 2 bits/idx),
+ // so idx can be 0..3 but palette only has 3 entries; idx=3 overflows.
+ val n = 3
+ val plain = java.io.ByteArrayOutputStream()
+ plain.write(n) // subencoding 3 = packed palette, 3 entries
+ repeat(n) { plain.write(cpixel(0xFF000000.toInt() or it)) }
+ // 1x1 tile: one packed byte. 2 bits/index, top 2 bits = 0b11 = idx 3 (out of range).
+ plain.write(0b1100_0000)
+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain.toByteArray())))
+ ZrleDecoder().decode(din, 0, 0, 1, 1, IntArray(1), 1)
+ }
+
+ /** High: a plain-RLE run that overruns the tile total → IOException, not AIOOBE. */
+ @Test(expected = java.io.IOException::class)
+ fun `plain RLE run overrun throws IOException`() {
+ // 2x2 tile (total=4). One run of length 5 (> 4) must be rejected.
+ val plain = java.io.ByteArrayOutputStream()
+ plain.write(128) // plain RLE
+ plain.write(cpixel(0xFFAABBCC.toInt()))
+ // run-length encoding: sum-of-bytes + 1 == 5 → sum 4 → single byte 0x04
+ plain.write(0x04)
+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain.toByteArray())))
+ ZrleDecoder().decode(din, 0, 0, 2, 2, IntArray(4), 2)
+ }
+
+ /** 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`() {
+ // Palette of 2 entries (subenc 130). A single-pixel index byte 0x05 (bit7=0,
+ // index 5) exceeds the 2-entry palette.
+ val plain = java.io.ByteArrayOutputStream()
+ plain.write(130) // palette RLE, n = 2
+ plain.write(cpixel(0xFF111111.toInt())); plain.write(cpixel(0xFF222222.toInt()))
+ plain.write(0x05) // single pixel, index 5 → out of range
+ val din = DataInputStream(ByteArrayInputStream(zrleRect(plain.toByteArray())))
+ ZrleDecoder().decode(din, 0, 0, 2, 2, IntArray(4), 2)
+ }
}