Skip to content

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

feat(avf): share the Downloads folder with the guest over vsock

ExTv04522df88850
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfDownloadsShare.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfDownloadsShare.kt
new file mode 100644
index 0000000..dc1d09c
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfDownloadsShare.kt
@@ -0,0 +1,156 @@
+/*
+ * Podroid - Rootless Podman for Android
+ * Copyright (C) 2024-2026 Podroid contributors
+ *
+ * AVF-only live Downloads share. Serves the real Downloads directory to the guest
+ * by running an in-process 9p2000.L server (Ninep2000LServer) over the vsock
+ * socket the guest mounts via `9p trans=fd`. No subprocess, no native binary.
+ * Non-fatal throughout: any failure here leaves the VM running with
+ * /mnt/downloads simply absent.
+ */
+package com.excp.podroid.engine.avf
+
+import android.os.Build
+import android.os.Environment
+import android.os.ParcelFileDescriptor
+import android.util.Log
+import androidx.annotation.RequiresApi
+import com.excp.podroid.engine.avf.ninep.Ninep2000LServer
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
+class AvfDownloadsShare(
+ private val vm: Any,
+ private val scope: CoroutineScope,
+) {
+ // job is launched from start() and cancelled from stop(), which may run on
+ // different threads (stop() from AvfEngine.cleanup(), the job body on
+ // Dispatchers.IO) - mirrors VsockControlChannel.connectJob.
+ @Volatile private var job: Job? = null
+ // lock guards pfd/pfdOut/stopped together so a stop() that races the
+ // coroutine's post-connect field publish can never miss the fds: either the
+ // coroutine publishes them before stop() sets stopped (stop closes them), or
+ // stop() wins and the coroutine closes its own fds and bails. Mirrors
+ // VsockControlChannel's lock discipline.
+ private val lock = Any()
+ private var pfd: ParcelFileDescriptor? = null // guarded by lock
+ private var pfdOut: ParcelFileDescriptor? = null // guarded by lock
+ private var stopped = false // guarded by lock
+
+ /**
+ * Checks the Downloads directory exists, then launches ONE job on [scope]
+ * that connects to the guest's 9p rendezvous listener (with retry/backoff)
+ * and serves it. Returns immediately - true once the job is launched, false
+ * (never throws) only if the Downloads directory is missing. The actual
+ * connect outcome ("added"/"unavailable") is decided later inside the job
+ * and only logged there, never blocking this call: a racing cleanup() must
+ * always find a job (and, once connected, fds) it can tear down.
+ */
+ fun start(): Boolean {
+ val root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
+ if (!root.isDirectory) {
+ Log.w(TAG, "Downloads dir missing: ${root.absolutePath}")
+ return false
+ }
+ job = scope.launch(Dispatchers.IO) {
+ val p = connectWithRetry(connect = {
+ AvfReflect.connectVsock(vm, DOWNLOADS_VSOCK_PORT.toLong())
+ })
+ if (p == null) {
+ Log.w(TAG, "connectVsock($DOWNLOADS_VSOCK_PORT) failed after $DEFAULT_ATTEMPTS attempts")
+ return@launch
+ }
+ // Read side owns p; write side owns a dup, mirroring
+ // VsockPortForwarder's fd-ownership discipline (each AutoClose
+ // stream closes exactly one descriptor). If dup() fails, close the
+ // already-open p ourselves - nothing else owns it yet.
+ val pOut = runCatching { p.dup() }.getOrElse {
+ Log.w(TAG, "dup() failed after connect", it)
+ runCatching { p.close() }
+ return@launch
+ }
+ // Publish the fds under lock unless stop() already ran; if it did,
+ // we still own p+pOut and must close them here (stop() saw nulls).
+ val proceed = synchronized(lock) {
+ if (stopped) {
+ false
+ } else {
+ pfd = p
+ pfdOut = pOut
+ true
+ }
+ }
+ if (!proceed) {
+ runCatching { p.close() }
+ runCatching { pOut.close() }
+ return@launch
+ }
+ Log.i(TAG, "downloads share added: ${root.absolutePath}")
+ runCatching {
+ ParcelFileDescriptor.AutoCloseInputStream(p).use { input ->
+ ParcelFileDescriptor.AutoCloseOutputStream(pOut).use { output ->
+ Ninep2000LServer(root).serve(input, output)
+ }
+ }
+ }.onFailure { Log.w(TAG, "9p server ended", it) }
+ }
+ return true
+ }
+
+ fun stop() {
+ // Mark stopped and take the fds under lock, so a coroutine still mid
+ // connect either sees stopped and closes its own fds, or has already
+ // published them here for us to close.
+ val (closeIn, closeOut) = synchronized(lock) {
+ stopped = true
+ val a = pfd
+ val b = pfdOut
+ pfd = null
+ pfdOut = null
+ a to b
+ }
+ job?.cancel()
+ job = null
+ // Force-close BOTH sockets so a serve() blocked in a native read()
+ // unblocks; cancelling the coroutine alone cannot interrupt it, and
+ // closing only the read-side pfd leaves the write-side dup open, which
+ // can keep the vsock connection's refcount above zero.
+ runCatching { closeIn?.close() }
+ runCatching { closeOut?.close() }
+ }
+
+ companion object {
+ // Keep == PODROID_DOWNLOADS_VSOCK_PORT in build-rootfs/vsock-agent/podroid-vsock-agent.c
+ const val DOWNLOADS_VSOCK_PORT = 200000
+ private const val TAG = "AvfDownloadsShare"
+ private const val DEFAULT_ATTEMPTS = 30
+ private const val DEFAULT_BACKOFF_MS = 500L
+
+ /**
+ * Retries [connect] up to [attempts] times, suspending on [sleep] between
+ * attempts (not after the last one). Defaults to a real coroutine delay
+ * so the retry loop is cancellable - the caller's job can be cancelled
+ * mid-backoff without a Thread.sleep to wait out. Pure and
+ * unit-testable: a test passes a no-op suspend sleeper so the retry
+ * budget can be exhausted without a real delay. A throwing [connect]
+ * counts as a failed attempt, not a propagated exception. Returns null
+ * once every attempt is spent.
+ */
+ suspend fun <T> connectWithRetry(
+ connect: () -> T?,
+ attempts: Int = DEFAULT_ATTEMPTS,
+ sleep: suspend (Long) -> Unit = { delay(it) },
+ ): T? {
+ repeat(attempts) { attempt ->
+ val result = runCatching { connect() }.getOrNull()
+ if (result != null) return result
+ if (attempt < attempts - 1) sleep(DEFAULT_BACKOFF_MS)
+ }
+ return null
+ }
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
index eb96c76..01dd6f0 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt
@@ -17,7 +17,6 @@ package com.excp.podroid.engine.avf
import android.content.Context
import android.os.Build
-import android.system.Os
import android.util.Log
import androidx.annotation.RequiresApi
import com.excp.podroid.data.repository.PortForwardRule
@@ -179,6 +178,8 @@ class AvfEngine @Inject constructor(
private val maxConsoleSize = 64 * 1024
private var logOut: java.io.FileOutputStream? = null
@Volatile private var control: VsockControlChannel? = null
+ /** Live AVF Downloads share (9p over vsock); started in bringUpControlChannel(), torn down in cleanup(). */
+ @Volatile private var downloadsShare: AvfDownloadsShare? = null
/**
* Initial rules captured from start()'s portForwards arg — includes the
* auto-injected SSH/X11/audio rules that PodroidService adds in-memory
@@ -261,6 +262,18 @@ class AvfEngine @Inject constructor(
// bound; addPortForward logs a one-time warning for that narrow window.
control = ctl
ctl.open()
+ if (lastConfig?.storageAccessEnabled == true) {
+ // Assign `downloadsShare` BEFORE calling start() (mirrors `control =
+ // ctl; ctl.open()` above): start() only launches a non-blocking
+ // connect+serve coroutine now, but a racing cleanup() must always
+ // see a non-null share to stop, even in the instant before that
+ // coroutine's connect attempt completes. The real outcome
+ // ("added"/"unavailable") is logged from inside the coroutine.
+ val share = AvfDownloadsShare(vm, scope)
+ downloadsShare = share
+ Log.i(TAG, "downloadsShare=starting")
+ share.start()
+ }
scope.launch {
// addPortForward now rethrows on failure (for EngineHolder's retry).
// Guard each replay so one failing rule doesn't abort the rest;
@@ -807,6 +820,8 @@ class AvfEngine @Inject constructor(
resizeDebounceJob = null
runCatching { control?.close() }
control = null
+ downloadsShare?.stop()
+ downloadsShare = null
// Close fanout next — drains its coroutines AND closes the console
// streams (it is their single owner). We hold the same references only
// to hand them to the fanout; closing them here too would double-close
@@ -1004,47 +1019,10 @@ class AvfEngine @Inject constructor(
}
AvfReflect.addDisk(cb, storage.absolutePath, writable = true)
AvfReflect.addDisk(cb, squashfs.absolutePath, writable = false)
- var shareSummary = if (config.storageAccessEnabled) "enabled" else "off"
- if (config.storageAccessEnabled) {
- val downloads = android.os.Environment.getExternalStoragePublicDirectory(
- android.os.Environment.DIRECTORY_DOWNLOADS
- ).absolutePath
- // External-storage paths (/storage/emulated/...) live outside the
- // app's SELinux domain. AOSP TerminalApp's ConfigJson.SharedPathJson
- // handles this by passing appDomain=false so crosvm spins up as a
- // child of virtmgr (system domain) instead of inheriting our
- // untrusted_app domain. Without that, crosvm gets EACCES on the
- // first read and the VM dies with reason=4 at start.
- //
- // On AVF revisions that don't ship the 10-param ctor with
- // appDomain, AvfReflect refuses the share (returns false) and we
- // boot without it — better than crashing the VM. The toggle in
- // Settings just becomes a no-op on those devices.
- val ok = runCatching {
- AvfReflect.addSharedPath(
- customBuilder = cb,
- sharedPath = downloads,
- tag = "downloads",
- hostUid = android.os.Process.myUid(),
- hostGid = Os.getgid(),
- guestUid = 1000,
- guestGid = 100,
- mask = 0x0007,
- socket = "downloads",
- socketPath = "",
- appDomain = false,
- )
- }.getOrElse { e ->
- Log.w(TAG, "addSharedPath threw (continuing without share)", e); false
- }
- if (ok) {
- shareSummary = "added"
- Log.i(TAG, "downloads share added: $downloads")
- } else {
- shareSummary = "no-op (unsupported on this AVF revision)"
- Log.i(TAG, "downloads share NOT added — Settings toggle is a no-op on this AVF revision")
- }
- }
+ // The actual share is a post-boot AvfDownloadsShare connecting over vsock
+ // (see bringUpControlChannel()); the real outcome ("added"/"unavailable")
+ // isn't known until then, so this summary just reflects the setting here.
+ val shareSummary = if (config.storageAccessEnabled) "pending" else "off"
AvfReflect.setNetworkSupported(cb, true)
// Declaring a (headless, display-less) GPU forces virtmgr onto the full
// `crosvm` instead of `crosvm_minimal`, which on Pixel's APEX lacks the
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
index d87578a..1e729c9 100644
--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt
@@ -328,136 +328,6 @@ object AvfReflect {
addM.invoke(b, disk)
}
- /**
- * Add a host-filesystem path that the guest can mount via virtio-9p
- * (`mount -t 9p <tag> /mnt/... -o trans=virtio,...`).
- *
- * `appDomain`: true ⇒ crosvm spins up inside the calling app's SELinux
- * domain (`untrusted_app`), which can only see paths under filesDir.
- * false ⇒ crosvm spins up as a child of virtmgr (system domain), which
- * is the only way to share external storage like `/storage/emulated/...`.
- *
- * Returns true if the share was added successfully, false if this AVF
- * revision can't honour the request (e.g. needs `appDomain=false` but
- * this device only ships the older 9-param ctor without that param).
- * Callers should treat false as "share is silently unavailable" — the VM
- * still boots without it. NEVER throws on signature mismatch — the VM
- * starting cleanly is more valuable than the share.
- *
- * Known SharedPath constructor shapes:
- * v3 (AOSP main — has `boolean appDomain`):
- * (String, int, int, int, int, int, String, String, boolean, String)
- * v2 (Pixel 10 mustang beta — 9 params, no appDomain):
- * (String, int, int, int, int, int, String, String, String)
- * v1 (older AOSP — 2 Strings up front):
- * (String, String, int, int, int, int, int, String, String)
- */
- fun addSharedPath(
- customBuilder: Any,
- sharedPath: String,
- tag: String,
- hostUid: Int,
- hostGid: Int,
- guestUid: Int,
- guestGid: Int,
- mask: Int,
- socket: String,
- socketPath: String,
- appDomain: Boolean,
- ): Boolean {
- val spCls = Class.forName("$PKG.VirtualMachineCustomImageConfig\$SharedPath")
- val intT = Int::class.javaPrimitiveType!!
- val boolT = Boolean::class.javaPrimitiveType!!
- val strT = String::class.java
-
- val sp = runCatching {
- buildSharedPath(spCls, intT, boolT, strT,
- sharedPath, tag, socket, socketPath, appDomain,
- hostUid, hostGid, guestUid, guestGid, mask)
- }.getOrElse { e ->
- android.util.Log.w("AvfReflect",
- "addSharedPath: no compatible SharedPath ctor — share for '$sharedPath' " +
- "(tag=$tag) is unavailable on this AVF revision. " +
- "Reason: ${e.message}")
- return false
- } ?: return false
-
- return runCatching {
- val addM = customBuilder.javaClass.getDeclaredMethod("addSharedPath", spCls)
- .apply { isAccessible = true }
- addM.invoke(customBuilder, sp)
- }.fold(
- onSuccess = { true },
- onFailure = { e ->
- android.util.Log.w("AvfReflect",
- "addSharedPath: builder rejected SharedPath for '$sharedPath': ${e.message}")
- false
- }
- )
- }
-
- /**
- * Try each known SharedPath constructor in order.
- *
- * IMPORTANT: when `appDomain=false` is requested, we MUST find a
- * constructor that accepts it (the v3 10-param shape). Older shapes
- * default to in-app-domain and would surface as a VM startup crash
- * later (crosvm can't cross domains to reach the path). Refuse with
- * null in that case so the caller logs a clear "unavailable" instead
- * of letting the VM die with `reason=4`.
- *
- * Returns null if no compatible ctor was found.
- */
- private fun buildSharedPath(
- spCls: Class<*>, intT: Class<*>, boolT: Class<*>, strT: Class<*>,
- sharedPath: String, tag: String, socket: String, socketPath: String, appDomain: Boolean,
- hostUid: Int, hostGid: Int, guestUid: Int, guestGid: Int, mask: Int,
- ): Any? {
- // Shape v3: (String, 5×int, String, String, boolean, String) — AOSP main
- runCatching {
- val c = spCls.getDeclaredConstructor(
- strT, intT, intT, intT, intT, intT, strT, strT, boolT, strT
- ).apply { isAccessible = true }
- return c.newInstance(
- sharedPath, hostUid, hostGid, guestUid, guestGid, mask,
- tag, socket, appDomain, socketPath,
- )!!
- }
- // Older shapes can't honour `appDomain=false`. Refuse so the caller
- // skips the share cleanly instead of crashing the VM at start time.
- if (!appDomain) {
- val shapes = spCls.declaredConstructors.joinToString("; ") { c ->
- c.parameterTypes.joinToString(prefix = "(", postfix = ")") { it.simpleName }
- }
- android.util.Log.w("AvfReflect",
- "buildSharedPath: appDomain=false needed but device has only legacy " +
- "ctors; share would crash VM. Ctors available: $shapes")
- return null
- }
- // Shape v2: (String, 5×int, String, String, String) — Pixel 10 mustang
- runCatching {
- val c = spCls.getDeclaredConstructor(
- strT, intT, intT, intT, intT, intT, strT, strT, strT
- ).apply { isAccessible = true }
- return c.newInstance(
- sharedPath, hostUid, hostGid, guestUid, guestGid, mask,
- tag, socket, socketPath,
- )!!
- }
- // Shape v1: (String, String, 5×int, String, String) — older AOSP
- runCatching {
- val c = spCls.getDeclaredConstructor(
- strT, strT, intT, intT, intT, intT, intT, strT, strT
- ).apply { isAccessible = true }
- return c.newInstance(
- sharedPath, socket,
- hostUid, hostGid, guestUid, guestGid, mask,
- tag, socketPath,
- )!!
- }
- return null
- }
-
fun setNetworkSupported(b: Any, value: Boolean) {
val ok = runCatching { invokeDecl(b, "useNetwork", Boolean::class.javaPrimitiveType!! to value) }.isSuccess
|| runCatching { invokeDecl(b, "setNetworkSupported", Boolean::class.javaPrimitiveType!! to value) }.isSuccess
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServer.kt b/app/src/main/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServer.kt
new file mode 100644
index 0000000..d75ccd5
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServer.kt
@@ -0,0 +1,886 @@
+package com.excp.podroid.engine.avf.ninep
+
+import android.util.Log
+import java.io.ByteArrayOutputStream
+import java.io.EOFException
+import java.io.File
+import java.io.IOException
+import java.io.InputStream
+import java.io.OutputStream
+import java.nio.ByteBuffer
+import java.nio.channels.FileChannel
+import java.nio.file.FileAlreadyExistsException
+import java.nio.file.Files
+import java.nio.file.StandardCopyOption
+import java.nio.file.StandardOpenOption
+import java.nio.file.attribute.BasicFileAttributeView
+import java.nio.file.attribute.FileTime
+import java.nio.file.attribute.PosixFilePermission
+import java.time.Instant
+
+private const val TAG = "Ninep2000LServer"
+
+/** Ceiling for the negotiated msize; the client may ask for less. Matches the codec's
+ * per-frame allocation ceiling so a negotiated msize can never exceed what a single
+ * frame is allowed to declare. */
+private const val MAX_MSIZE = NinepCodec.MAX_FRAME_SIZE.toLong()
+private const val DEFAULT_MSIZE = 8192L
+
+/** qid.type bits, from the 9P2000.L spec. */
+private const val QTDIR = 0x80
+private const val QTSYMLINK = 0x02
+private const val QTFILE = 0x00
+
+/** st_mode format bits (POSIX, same values as android.system.OsConstants). */
+private const val S_IFMT = 0xF000L
+private const val S_IFDIR = 0x4000L
+private const val S_IFLNK = 0xA000L
+
+/** Linux errno values used on the wire for Rlerror (see linux/errno.h). */
+private const val ENOENT = 2
+private const val EIO = 5
+private const val EEXIST = 17
+private const val EOPNOTSUPP = 95
+
+/** P9_GETATTR_BASIC: the field set filled in by Rgetattr below. */
+private const val P9_GETATTR_BASIC = 0x000007ffL
+
+/** Linux open(2) flag bits used to decode Tlopen/Tlcreate's flags[4]. */
+private const val O_ACCMODE = 0x3L
+private const val O_WRONLY = 1L
+private const val O_RDWR = 2L
+private const val O_CREAT = 0x40L
+private const val O_TRUNC = 0x200L
+private const val O_APPEND = 0x400L
+
+/** P9_SETATTR valid-mask bits, from the 9P2000.L spec. */
+private const val SETATTR_MODE = 0x1L
+private const val SETATTR_SIZE = 0x8L
+private const val SETATTR_ATIME = 0x10L
+private const val SETATTR_MTIME = 0x20L
+private const val SETATTR_ATIME_SET = 0x80L
+private const val SETATTR_MTIME_SET = 0x100L
+
+/** dirent d_type values used by Treaddir/Rreaddir, from linux/fs.h (DT_*). */
+private const val DT_REG = 8
+private const val DT_DIR = 4
+private const val DT_LNK = 10
+
+/**
+ * Plain-data stat result, decoupled from android.system.Os so the server is
+ * unit-testable on a plain JVM (Os/StructStat are Android framework classes).
+ */
+data class StatInfo(
+ val ino: Long,
+ val mode: Long,
+ val uid: Long,
+ val gid: Long,
+ val size: Long,
+ val nlink: Long,
+ val rdev: Long,
+ val blksize: Long,
+ val blocks: Long,
+ val atimeSec: Long,
+ val atimeNsec: Long,
+ val mtimeSec: Long,
+ val mtimeNsec: Long,
+ val ctimeSec: Long,
+ val ctimeNsec: Long,
+)
+
+/** Seam over android.system.Os.lstat; production uses [OsStatSource], tests inject a fake. */
+interface StatSource {
+ fun lstat(path: String): StatInfo
+}
+
+/** Production [StatSource] backed by android.system.Os.lstat. */
+object OsStatSource : StatSource {
+ override fun lstat(path: String): StatInfo {
+ val st = android.system.Os.lstat(path)
+ return StatInfo(
+ ino = st.st_ino,
+ mode = st.st_mode.toLong(),
+ uid = st.st_uid.toLong(),
+ gid = st.st_gid.toLong(),
+ size = st.st_size,
+ nlink = st.st_nlink,
+ rdev = st.st_rdev,
+ blksize = st.st_blksize,
+ blocks = st.st_blocks,
+ atimeSec = st.st_atim.tv_sec,
+ atimeNsec = st.st_atim.tv_nsec,
+ mtimeSec = st.st_mtim.tv_sec,
+ mtimeNsec = st.st_mtim.tv_nsec,
+ ctimeSec = st.st_ctim.tv_sec,
+ ctimeNsec = st.st_ctim.tv_nsec,
+ )
+ }
+}
+
+/** A 9p2000.L qid: type[1] version[4] path[8]. */
+data class NinepQid(val type: Int, val version: Long, val path: Long)
+
+private fun NinepCodec.Writer.writeQid(qid: NinepQid) {
+ writeU8(qid.type)
+ writeU32(qid.version)
+ writeU64(qid.path)
+}
+
+/**
+ * Per-fid server state: the path the fid currently refers to, plus an open
+ * [FileChannel] once Tlopen/Tlcreate have opened it (null for a fid that has never
+ * been opened, or that refers to a directory - directories are read via [File.listFiles]
+ * rather than a held handle).
+ */
+private class FidState(var file: File, var channel: FileChannel? = null)
+
+/**
+ * In-process 9p2000.L server. Serves [root] (and everything under it) to a client
+ * driving [serve] over a pair of streams. Backed by [android.system.Os] in production;
+ * tests inject a fake [StatSource] so the session/fid/walk/attr logic runs on a plain JVM.
+ *
+ * This class implements Tversion, Tattach, Twalk, Tgetattr, Tclunk, plus the file and
+ * directory operations Tlopen, Tlcreate, Tread, Twrite, Treaddir, Tsetattr, Tmkdir,
+ * Tunlinkat, Tremove, Trenameat and Tfsync. File content and directory mutation ride
+ * java.nio/java.io (FileChannel positional read/write, Files.createFile/createDirectory/
+ * delete/move) so
+ * they are unit-testable on a plain JVM against a real temp directory; only attribute
+ * lookups (Tgetattr, qids) stay on the [StatSource] seam. Operations with no production
+ * use yet (Tsymlink, Treadlink, Tlink, Txattrwalk, Txattrcreate, Tstatfs, ...) still
+ * reply Rlerror(EOPNOTSUPP).
+ */
+class Ninep2000LServer(
+ private val root: File,
+ private val stat: StatSource = OsStatSource,
+) {
+ private val fids = mutableMapOf<Long, FidState>()
+ private var msize: Long = DEFAULT_MSIZE
+ private var negotiated = false
+
+ /**
+ * Reads and replies to frames from [input] until the client disconnects. Never
+ * throws: a clean EOF ends the loop normally, a truncated frame or a corrupt
+ * (or oversized) size prefix logs a warning and ends the loop, and per-request
+ * failures are reported to the client as Rlerror instead of tearing down the
+ * session. Both catch blocks guard against Throwable, not just Exception, as
+ * defense in depth: a bug that manages to throw an Error (e.g. OutOfMemoryError)
+ * around the read/dispatch boundary must still end the session cleanly rather
+ * than crash the caller.
+ */
+ fun serve(input: InputStream, output: OutputStream) {
+ try {
+ while (true) {
+ // Before Tversion, bound reads by the ceiling; afterwards, by the msize
+ // actually negotiated with this client so no frame can exceed it.
+ val maxSize = if (negotiated) msize.toInt() else NinepCodec.MAX_FRAME_SIZE
+ val frame = try {
+ NinepCodec.readFrame(input, maxSize) ?: break
+ } catch (e: EOFException) {
+ break
+ } catch (e: Throwable) {
+ // Covers IllegalArgumentException (bad or oversized size prefix),
+ // NegativeArraySizeException (size overflow) and, as defense in
+ // depth, any Error a corrupt frame could otherwise trigger. One
+ // corrupt frame ends the session; it must never crash the caller.
+ logWarn("corrupt 9p frame, ending session", e)
+ break
+ }
+
+ try {
+ dispatch(frame, output)
+ } catch (e: IOException) {
+ // The reply could not be written; the peer is gone. Stop serving.
+ logWarn("failed to write 9p reply, ending session", e)
+ break
+ } catch (e: Throwable) {
+ // dispatch() already reports ordinary per-request failures as
+ // Rlerror, so only an unexpected Error reaches here. It must not
+ // crash the caller either.
+ logWarn("unexpected failure handling 9p request, ending session", e)
+ break
+ }
+ }
+ } finally {
+ // However the loop ended, no fid's open handle may outlive the session.
+ closeAllFids()
+ }
+ }
+
+ private fun dispatch(frame: NinepFrame, output: OutputStream) {
+ try {
+ when (frame.type) {
+ Ninep.Tversion -> handleVersion(frame, output)
+ Ninep.Tattach -> handleAttach(frame, output)
+ Ninep.Twalk -> handleWalk(frame, output)
+ Ninep.Tgetattr -> handleGetattr(frame, output)
+ Ninep.Tsetattr -> handleSetattr(frame, output)
+ Ninep.Tlopen -> handleLopen(frame, output)
+ Ninep.Tlcreate -> handleLcreate(frame, output)
+ Ninep.Tread -> handleRead(frame, output)
+ Ninep.Twrite -> handleWrite(frame, output)
+ Ninep.Treaddir -> handleReaddir(frame, output)
+ Ninep.Tmkdir -> handleMkdir(frame, output)
+ Ninep.Tunlinkat -> handleUnlinkat(frame, output)
+ Ninep.Tremove -> handleRemove(frame, output)
+ Ninep.Trenameat -> handleRenameat(frame, output)
+ Ninep.Tfsync -> handleFsync(frame, output)
+ Ninep.Tclunk -> handleClunk(frame, output)
+ else -> replyError(frame.tag, output, EOPNOTSUPP)
+ }
+ } catch (e: IOException) {
+ throw e
+ } catch (e: Exception) {
+ // A malformed request body (short read past the array bounds, etc.) fails
+ // this one request, not the whole session.
+ replyError(frame.tag, output, EIO)
+ }
+ }
+
+ private fun handleVersion(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val clientMsize = r.readU32()
+ val clientVersion = r.readString()
+ val negotiatedVersion = if (clientVersion == "9P2000.L") "9P2000.L" else "unknown"
+ msize = minOf(clientMsize, MAX_MSIZE)
+ negotiated = true
+ writeReply(output, Ninep.Rversion, frame.tag) { w ->
+ w.writeU32(msize)
+ w.writeString(negotiatedVersion)
+ }
+ }
+
+ private fun handleAttach(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ r.readU32() // afid, ignored: no auth support
+ r.readString() // uname
+ r.readString() // aname
+ r.readU32() // n_uname
+
+ val st = statOrNull(root.absolutePath)
+ if (st == null) {
+ replyError(frame.tag, output, ENOENT)
+ return
+ }
+ closeAndReplaceFid(fid, FidState(root))
+ writeReply(output, Ninep.Rattach, frame.tag) { w -> w.writeQid(qidFromStat(st)) }
+ }
+
+ private fun handleWalk(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val newfid = r.readU32()
+ val nwname = r.readU16()
+ val names = (0 until nwname).map { r.readString() }
+
+ val start = fids[fid]
+ if (start == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ if (names.isEmpty()) {
+ // A zero-component walk just clones the fid onto newfid; give the clone
+ // its own FidState so opening one later never aliases the other's handle.
+ if (newfid != fid) {
+ closeAndReplaceFid(newfid, FidState(start.file))
+ }
+ writeReply(output, Ninep.Rwalk, frame.tag) { w -> w.writeU16(0) }
+ return
+ }
+
+ val qids = mutableListOf<NinepQid>()
+ var current: File = start.file
+ for (name in names) {
+ val candidate = when (name) {
+ "." -> current
+ ".." -> parentWithinRoot(current)
+ else -> File(current, name)
+ }
+ if (!isWithinRoot(candidate)) break
+ val st = statOrNull(candidate.absolutePath) ?: break
+ qids += qidFromStat(st)
+ current = candidate
+ }
+
+ if (qids.isEmpty()) {
+ replyError(frame.tag, output, ENOENT)
+ return
+ }
+ if (qids.size == names.size) {
+ closeAndReplaceFid(newfid, FidState(current))
+ }
+ writeReply(output, Ninep.Rwalk, frame.tag) { w ->
+ w.writeU16(qids.size)
+ qids.forEach { w.writeQid(it) }
+ }
+ }
+
+ private fun handleGetattr(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ r.readU64() // request_mask, ignored: we always report the basic field set
+
+ val file = fids[fid]?.file
+ if (file == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val st = statOrNull(file.absolutePath)
+ if (st == null) {
+ replyError(frame.tag, output, ENOENT)
+ return
+ }
+ writeReply(output, Ninep.Rgetattr, frame.tag) { w ->
+ w.writeU64(P9_GETATTR_BASIC)
+ w.writeQid(qidFromStat(st))
+ w.writeU32(st.mode)
+ w.writeU32(st.uid)
+ w.writeU32(st.gid)
+ w.writeU64(st.nlink)
+ w.writeU64(st.rdev)
+ w.writeU64(st.size)
+ w.writeU64(st.blksize)
+ w.writeU64(st.blocks)
+ w.writeU64(st.atimeSec)
+ w.writeU64(st.atimeNsec)
+ w.writeU64(st.mtimeSec)
+ w.writeU64(st.mtimeNsec)
+ w.writeU64(st.ctimeSec)
+ w.writeU64(st.ctimeNsec)
+ w.writeU64(0) // btime_sec: not tracked
+ w.writeU64(0) // btime_nsec
+ w.writeU64(0) // gen
+ w.writeU64(0) // data_version
+ }
+ }
+
+ private fun handleClunk(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ fids.remove(fid)?.channel?.closeQuietly()
+ writeReply(output, Ninep.Rclunk, frame.tag) { }
+ }
+
+ private fun handleLopen(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val flags = r.readU32()
+
+ val state = fids[fid]
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val st = statOrNull(state.file.absolutePath)
+ if (st == null) {
+ replyError(frame.tag, output, ENOENT)
+ return
+ }
+
+ // Directories are served via File.listFiles() in Treaddir, not a held handle,
+ // but Tlopen on a directory fid must still succeed (the client opens it before
+ // Treaddir).
+ val isDir = (st.mode and S_IFMT) == S_IFDIR
+ if (!isDir) {
+ val channel = try {
+ openChannel(state.file, flags)
+ } catch (e: Exception) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ state.channel?.closeQuietly()
+ state.channel = channel
+ }
+ writeReply(output, Ninep.Rlopen, frame.tag) { w ->
+ w.writeQid(qidFromStat(st))
+ w.writeU32(0) // iounit: 0, client falls back to msize
+ }
+ }
+
+ private fun handleLcreate(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val name = r.readString()
+ val flags = r.readU32()
+ val mode = r.readU32()
+ r.readU32() // gid, ignored: no multi-user support
+
+ val state = fids[fid]
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val target = File(state.file, name)
+ if (!isWithinRoot(target)) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ val channel = try {
+ Files.createFile(target.toPath())
+ applyPosixMode(target, mode)
+ openChannel(target, flags)
+ } catch (e: FileAlreadyExistsException) {
+ replyError(frame.tag, output, EEXIST)
+ return
+ } catch (e: Exception) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ // fid now refers to the newly created (and opened) file, per the 9p2000.L spec.
+ state.channel?.closeQuietly()
+ state.file = target
+ state.channel = channel
+
+ val st = statOrNull(target.absolutePath)
+ if (st == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rlcreate, frame.tag) { w ->
+ w.writeQid(qidFromStat(st))
+ w.writeU32(0) // iounit: 0, client falls back to msize
+ }
+ }
+
+ private fun handleRead(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val offset = r.readU64()
+ val count = r.readU32()
+
+ val channel = fids[fid]?.channel
+ if (channel == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ // Rread's own header (size+type+tag+count) costs 11 bytes of the negotiated
+ // msize, so the payload can never exceed msize - 11.
+ val cap = maxOf(0L, minOf(count, msize - 11)).toInt()
+ val buf = ByteBuffer.allocate(cap)
+ val n = try {
+ channel.read(buf, offset)
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val length = if (n < 0) 0 else n
+ writeReply(output, Ninep.Rread, frame.tag) { w ->
+ w.writeU32(length.toLong())
+ w.writeBytes(buf.array().copyOfRange(0, length))
+ }
+ }
+
+ private fun handleWrite(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val offset = r.readU64()
+ val count = r.readU32()
+ val data = r.readBytes(count.toInt())
+
+ val channel = fids[fid]?.channel
+ if (channel == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val n = try {
+ channel.write(ByteBuffer.wrap(data), offset)
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rwrite, frame.tag) { w -> w.writeU32(n.toLong()) }
+ }
+
+ private fun handleReaddir(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val offset = r.readU64()
+ val count = r.readU32()
+
+ val dir = fids[fid]?.file
+ if (dir == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val entries = try {
+ buildDirEntries(dir)
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ // The cookie for the entry at index i is i + 1 ("resume after this entry"), so
+ // resuming from a client-supplied offset means starting at that same index.
+ val startIndex = offset.coerceIn(0L, entries.size.toLong()).toInt()
+ val maxBytes = maxOf(0L, minOf(count, msize - 11))
+ val data = ByteArrayOutputStream()
+ for (i in startIndex until entries.size) {
+ val entry = entries[i]
+ val entryBytes = ByteArrayOutputStream().also { eout ->
+ val w = NinepCodec.Writer(eout)
+ w.writeQid(entry.qid)
+ w.writeU64((i + 1).toLong())
+ w.writeU8(entry.type)
+ w.writeString(entry.name)
+ }.toByteArray()
+ if (data.size() + entryBytes.size > maxBytes) break
+ data.write(entryBytes)
+ }
+
+ writeReply(output, Ninep.Rreaddir, frame.tag) { w ->
+ w.writeU32(data.size().toLong())
+ w.writeBytes(data.toByteArray())
+ }
+ }
+
+ private fun handleSetattr(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ val valid = r.readU32()
+ val mode = r.readU32()
+ r.readU32() // uid, ignored: no multi-user support
+ r.readU32() // gid, ignored: no multi-user support
+ val size = r.readU64()
+ val atimeSec = r.readU64()
+ val atimeNsec = r.readU64()
+ val mtimeSec = r.readU64()
+ val mtimeNsec = r.readU64()
+
+ val state = fids[fid]
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ try {
+ if (valid and SETATTR_MODE != 0L) {
+ applyPosixMode(state.file, mode)
+ }
+ if (valid and SETATTR_SIZE != 0L) {
+ val existing = state.channel
+ if (existing != null) {
+ existing.truncate(size)
+ } else {
+ FileChannel.open(state.file.toPath(), StandardOpenOption.WRITE).use { it.truncate(size) }
+ }
+ }
+ val atimeRequested = valid and SETATTR_ATIME != 0L
+ val mtimeRequested = valid and SETATTR_MTIME != 0L
+ if (atimeRequested || mtimeRequested) {
+ val view = Files.getFileAttributeView(state.file.toPath(), BasicFileAttributeView::class.java)
+ val newMtime = if (mtimeRequested) {
+ if (valid and SETATTR_MTIME_SET != 0L) {
+ FileTime.from(Instant.ofEpochSecond(mtimeSec, mtimeNsec))
+ } else {
+ FileTime.from(Instant.now())
+ }
+ } else {
+ null
+ }
+ val newAtime = if (atimeRequested) {
+ if (valid and SETATTR_ATIME_SET != 0L) {
+ FileTime.from(Instant.ofEpochSecond(atimeSec, atimeNsec))
+ } else {
+ FileTime.from(Instant.now())
+ }
+ } else {
+ null
+ }
+ view.setTimes(newMtime, newAtime, null)
+ }
+ // uid/gid changes are silently ignored (unsupported for an unprivileged app)
+ // rather than erroring, so callers like "cp -p" still succeed overall.
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rsetattr, frame.tag) { }
+ }
+
+ private fun handleMkdir(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val dfid = r.readU32()
+ val name = r.readString()
+ val mode = r.readU32()
+ r.readU32() // gid, ignored: no multi-user support
+
+ val state = fids[dfid]
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val target = File(state.file, name)
+ if (!isWithinRoot(target)) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ try {
+ Files.createDirectory(target.toPath())
+ applyPosixMode(target, mode)
+ } catch (e: FileAlreadyExistsException) {
+ replyError(frame.tag, output, EEXIST)
+ return
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ val st = statOrNull(target.absolutePath)
+ if (st == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rmkdir, frame.tag) { w -> w.writeQid(qidFromStat(st)) }
+ }
+
+ private fun handleUnlinkat(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val dirfid = r.readU32()
+ val name = r.readString()
+ // flags (AT_REMOVEDIR = 0x200) is not needed: Files.delete already removes an
+ // empty directory or a file as appropriate for what "name" actually is.
+ r.readU32()
+
+ val state = fids[dirfid]
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val target = File(state.file, name)
+ if (!isWithinRoot(target)) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ try {
+ if (!Files.deleteIfExists(target.toPath())) {
+ replyError(frame.tag, output, ENOENT)
+ return
+ }
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Runlinkat, frame.tag) { }
+ }
+
+ private fun handleRemove(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+
+ // Tremove removes the fid's file and clunks the fid, even if the removal fails.
+ val state = fids.remove(fid)
+ state?.channel?.closeQuietly()
+ if (state == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ try {
+ Files.deleteIfExists(state.file.toPath())
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rremove, frame.tag) { }
+ }
+
+ private fun handleRenameat(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val olddirfid = r.readU32()
+ val oldname = r.readString()
+ val newdirfid = r.readU32()
+ val newname = r.readString()
+
+ val oldDirState = fids[olddirfid]
+ val newDirState = fids[newdirfid]
+ if (oldDirState == null || newDirState == null) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ val source = File(oldDirState.file, oldname)
+ val target = File(newDirState.file, newname)
+ if (!isWithinRoot(source) || !isWithinRoot(target)) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+
+ try {
+ Files.move(source.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING)
+ } catch (e: IOException) {
+ replyError(frame.tag, output, EIO)
+ return
+ }
+ writeReply(output, Ninep.Rrenameat, frame.tag) { }
+ }
+
+ private fun handleFsync(frame: NinepFrame, output: OutputStream) {
+ val r = NinepCodec.Reader(frame.body)
+ val fid = r.readU32()
+ r.readU32() // datasync, ignored: force() always does a full sync
+
+ try {
+ fids[fid]?.channel?.force(true)
+ } catch (e: IOException) {
+ // An fsync failure must never surface as an error to the client: 9p clients
+ // treat a failed flush as a write failure, and the write itself succeeded.
+ }
+ writeReply(output, Ninep.Rfsync, frame.tag) { }
+ }
+
+ /** Replaces the fid table entry for [fid], closing any handle it previously held. */
+ private fun closeAndReplaceFid(fid: Long, state: FidState) {
+ fids[fid]?.channel?.closeQuietly()
+ fids[fid] = state
+ }
+
+ private fun closeAllFids() {
+ fids.values.forEach { it.channel?.closeQuietly() }
+ fids.clear()
+ }
+
+ private fun FileChannel.closeQuietly() {
+ try {
+ close()
+ } catch (e: IOException) {
+ // ignored: best-effort cleanup, the fid is going away regardless
+ }
+ }
+
+ /** Decodes Linux open(2) flags (Tlopen/Tlcreate's flags[4]) into NIO open options. */
+ private fun openChannel(file: File, flags: Long): FileChannel {
+ val append = flags and O_APPEND != 0L
+ val creat = flags and O_CREAT != 0L
+ val trunc = flags and O_TRUNC != 0L
+
+ val options = mutableSetOf<StandardOpenOption>()
+ if (append) {
+ // APPEND cannot be combined with READ in java.nio; O_APPEND is only ever
+ // meaningful for a writable open, so this matches practice.
+ options += StandardOpenOption.WRITE
+ options += StandardOpenOption.APPEND
+ } else {
+ when (flags and O_ACCMODE) {
+ O_WRONLY -> options += StandardOpenOption.WRITE
+ O_RDWR -> {
+ options += StandardOpenOption.READ
+ options += StandardOpenOption.WRITE
+ }
+ else -> options += StandardOpenOption.READ
+ }
+ }
+ if (creat) options += StandardOpenOption.CREATE
+ if (trunc && !append) options += StandardOpenOption.TRUNCATE_EXISTING
+ return FileChannel.open(file.toPath(), options)
+ }
+
+ /** Best-effort chmod: some filesystems (or, in tests, the JVM's view of them) may
+ * not support POSIX permissions, in which case the mode request is dropped rather
+ * than failing the whole request. */
+ private fun applyPosixMode(file: File, mode: Long) {
+ try {
+ Files.setPosixFilePermissions(file.toPath(), modeToPosixPermissions(mode))
+ } catch (e: Exception) {
+ // ignored: see comment above
+ }
+ }
+
+ private fun modeToPosixPermissions(mode: Long): Set<PosixFilePermission> {
+ val perms = mutableSetOf<PosixFilePermission>()
+ if (mode and 0x100L != 0L) perms += PosixFilePermission.OWNER_READ
+ if (mode and 0x080L != 0L) perms += PosixFilePermission.OWNER_WRITE
+ if (mode and 0x040L != 0L) perms += PosixFilePermission.OWNER_EXECUTE
+ if (mode and 0x020L != 0L) perms += PosixFilePermission.GROUP_READ
+ if (mode and 0x010L != 0L) perms += PosixFilePermission.GROUP_WRITE
+ if (mode and 0x008L != 0L) perms += PosixFilePermission.GROUP_EXECUTE
+ if (mode and 0x004L != 0L) perms += PosixFilePermission.OTHERS_READ
+ if (mode and 0x002L != 0L) perms += PosixFilePermission.OTHERS_WRITE
+ if (mode and 0x001L != 0L) perms += PosixFilePermission.OTHERS_EXECUTE
+ return perms
+ }
+
+ private data class DirEntry(val name: String, val qid: NinepQid, val type: Int)
+
+ /** "." and ".." (bounded at [root], like Twalk's "..") followed by the directory's
+ * children sorted by name, so the ordering (and therefore the offset cookies) is
+ * stable across the multiple Treaddir calls a client may issue. */
+ private fun buildDirEntries(dir: File): List<DirEntry> {
+ val selfStat = statOrNull(dir.absolutePath) ?: throw IOException("cannot stat $dir")
+ val parent = parentWithinRoot(dir)
+ val parentStat = statOrNull(parent.absolutePath) ?: selfStat
+
+ val entries = mutableListOf<DirEntry>()
+ entries += DirEntry(".", qidFromStat(selfStat), direntType(selfStat))
+ entries += DirEntry("..", qidFromStat(parentStat), direntType(parentStat))
+ val children = dir.listFiles()?.sortedBy { it.name } ?: emptyList()
+ for (child in children) {
+ val st = statOrNull(child.absolutePath) ?: continue
+ entries += DirEntry(child.name, qidFromStat(st), direntType(st))
+ }
+ return entries
+ }
+
+ private fun direntType(st: StatInfo): Int = when (st.mode and S_IFMT) {
+ S_IFDIR -> DT_DIR
+ S_IFLNK -> DT_LNK
+ else -> DT_REG
+ }
+
+ /** Walks one ".." step without ever leaving [root]. */
+ private fun parentWithinRoot(current: File): File = try {
+ if (current.canonicalFile == root.canonicalFile) {
+ current
+ } else {
+ current.parentFile ?: current
+ }
+ } catch (e: IOException) {
+ current
+ }
+
+ /** True if [file] canonicalizes to [root] or somewhere under it. */
+ private fun isWithinRoot(file: File): Boolean = try {
+ val rootPath = root.canonicalFile.path
+ val filePath = file.canonicalFile.path
+ filePath == rootPath || filePath.startsWith(rootPath + File.separator)
+ } catch (e: IOException) {
+ false
+ }
+
+ private fun statOrNull(path: String): StatInfo? = try {
+ stat.lstat(path)
+ } catch (e: Exception) {
+ null
+ }
+
+ private fun qidFromStat(st: StatInfo): NinepQid {
+ val type = when (st.mode and S_IFMT) {
+ S_IFDIR -> QTDIR
+ S_IFLNK -> QTSYMLINK
+ else -> QTFILE
+ }
+ return NinepQid(type = type, version = 0L, path = st.ino)
+ }
+
+ private fun replyError(tag: Int, output: OutputStream, errno: Int) {
+ writeReply(output, Ninep.Rlerror, tag) { w -> w.writeU32(errno.toLong()) }
+ }
+
+ private fun writeReply(output: OutputStream, type: Int, tag: Int, write: (NinepCodec.Writer) -> Unit) {
+ val body = ByteArrayOutputStream()
+ write(NinepCodec.Writer(body))
+ NinepCodec.writeFrame(output, type, tag, body.toByteArray())
+ }
+
+ private fun logWarn(message: String, cause: Throwable) {
+ // android.util.Log is a framework stub under plain JVM unit tests and throws
+ // there; a logging failure must never take down the serve loop, so guard it.
+ try {
+ Log.w(TAG, message, cause)
+ } catch (_: Throwable) {
+ // ignored: see comment above
+ }
+ }
+}
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/ninep/NinepCodec.kt b/app/src/main/java/com/excp/podroid/engine/avf/ninep/NinepCodec.kt
new file mode 100644
index 0000000..fbbc6a5
--- /dev/null
+++ b/app/src/main/java/com/excp/podroid/engine/avf/ninep/NinepCodec.kt
@@ -0,0 +1,201 @@
+package com.excp.podroid.engine.avf.ninep
+
+import java.io.ByteArrayOutputStream
+import java.io.EOFException
+import java.io.InputStream
+import java.io.OutputStream
+import java.nio.charset.StandardCharsets
+
+/**
+ * 9p2000.L message type numbers, taken from the 9P2000.L spec / Linux
+ * include/net/9p/9p.h. Wire is little-endian, framed size[4] type[1] tag[2] body.
+ */
+object Ninep {
+ const val Rlerror = 7
+ const val Tlopen = 12
+ const val Rlopen = 13
+ const val Tlcreate = 14
+ const val Rlcreate = 15
+ const val Tgetattr = 24
+ const val Rgetattr = 25
+ const val Tsetattr = 26
+ const val Rsetattr = 27
+ const val Treaddir = 40
+ const val Rreaddir = 41
+ const val Tfsync = 50
+ const val Rfsync = 51
+ const val Tmkdir = 72
+ const val Rmkdir = 73
+ const val Trenameat = 74
+ const val Rrenameat = 75
+ const val Tunlinkat = 76
+ const val Runlinkat = 77
+ const val Tversion = 100
+ const val Rversion = 101
+ const val Tattach = 104
+ const val Rattach = 105
+ const val Twalk = 110
+ const val Rwalk = 111
+ const val Tread = 116
+ const val Rread = 117
+ const val Twrite = 118
+ const val Rwrite = 119
+ const val Tclunk = 120
+ const val Rclunk = 121
+ const val Tremove = 122
+ const val Rremove = 123
+}
+
+/** A decoded 9p message frame: type[1] tag[2] body (size prefix already consumed). */
+data class NinepFrame(val type: Int, val tag: Int, val body: ByteArray)
+
+/**
+ * Little-endian 9p2000.L wire primitives, plus whole-message framing.
+ * Pure Kotlin/java.io, no Android dependency, so it unit-tests under a plain JVM.
+ */
+object NinepCodec {
+
+ /** Minimum frame size: size[4] + type[1] + tag[2]. */
+ private const val HEADER_SIZE = 7
+
+ /**
+ * Hard ceiling for a single frame's declared size, matching the server's msize
+ * ceiling. [readFrame] enforces this before allocating the body array, so a
+ * corrupt or hostile size prefix can never trigger an oversized allocation.
+ */
+ const val MAX_FRAME_SIZE = 262144
+
+ /** Reads little-endian primitives out of an in-memory byte array with a cursor. */
+ class Reader(private val data: ByteArray, private var pos: Int = 0) {
+ fun readU8(): Int {
+ val v = data[pos].toInt() and 0xFF
+ pos += 1
+ return v
+ }
+
+ fun readU16(): Int {
+ val b0 = data[pos].toInt() and 0xFF
+ val b1 = data[pos + 1].toInt() and 0xFF
+ pos += 2
+ return b0 or (b1 shl 8)
+ }
+
+ fun readU32(): Long {
+ val b0 = data[pos].toLong() and 0xFF
+ val b1 = data[pos + 1].toLong() and 0xFF
+ val b2 = data[pos + 2].toLong() and 0xFF
+ val b3 = data[pos + 3].toLong() and 0xFF
+ pos += 4
+ return b0 or (b1 shl 8) or (b2 shl 16) or (b3 shl 24)
+ }
+
+ fun readU64(): Long {
+ var v = 0L
+ for (i in 0 until 8) {
+ v = v or ((data[pos + i].toLong() and 0xFF) shl (8 * i))
+ }
+ pos += 8
+ return v
+ }
+
+ fun readString(): String {
+ val len = readU16()
+ val s = String(data, pos, len, StandardCharsets.UTF_8)
+ pos += len
+ return s
+ }
+
+ fun readBytes(len: Int): ByteArray {
+ val out = data.copyOfRange(pos, pos + len)
+ pos += len
+ return out
+ }
+
+ fun remaining(): Int = data.size - pos
+ }
+
+ /** Writes little-endian primitives to an OutputStream. */
+ class Writer(private val out: OutputStream) {
+ fun writeU8(v: Int) {
+ out.write(v and 0xFF)
+ }
+
+ fun writeU16(v: Int) {
+ out.write(v and 0xFF)
+ out.write((v ushr 8) and 0xFF)
+ }
+
+ fun writeU32(v: Long) {
+ out.write((v and 0xFF).toInt())
+ out.write(((v ushr 8) and 0xFF).toInt())
+ out.write(((v ushr 16) and 0xFF).toInt())
+ out.write(((v ushr 24) and 0xFF).toInt())
+ }
+
+ fun writeU64(v: Long) {
+ for (i in 0 until 8) {
+ out.write(((v ushr (8 * i)) and 0xFF).toInt())
+ }
+ }
+
+ fun writeString(s: String) {
+ val bytes = s.toByteArray(StandardCharsets.UTF_8)
+ writeU16(bytes.size)
+ out.write(bytes)
+ }
+
+ fun writeBytes(b: ByteArray) {
+ out.write(b)
+ }
+ }
+
+ /**
+ * Reads one framed message: size[4] type[1] tag[2] body[size-7].
+ * Returns null on clean EOF (no bytes read before end of stream).
+ *
+ * [maxSize] bounds the declared size and is checked before the body array is
+ * allocated, so an oversized or overflow-prone size prefix fails fast instead
+ * of attempting a huge (or, once truncated to Int, negative) allocation.
+ */
+ fun readFrame(input: InputStream, maxSize: Int = MAX_FRAME_SIZE): NinepFrame? {
+ val sizeBytes = readFully(input, 4) ?: return null
+ val size = (sizeBytes[0].toLong() and 0xFF) or
+ ((sizeBytes[1].toLong() and 0xFF) shl 8) or
+ ((sizeBytes[2].toLong() and 0xFF) shl 16) or
+ ((sizeBytes[3].toLong() and 0xFF) shl 24)
+ require(size >= HEADER_SIZE) { "9p frame size $size smaller than header $HEADER_SIZE" }
+ require(size <= maxSize) { "9p frame size $size exceeds max $maxSize" }
+ val rest = readFully(input, (size - 4).toInt())
+ ?: throw EOFException("9p stream ended mid-frame")
+ val type = rest[0].toInt() and 0xFF
+ val tag = (rest[1].toInt() and 0xFF) or ((rest[2].toInt() and 0xFF) shl 8)
+ val body = rest.copyOfRange(3, rest.size)
+ return NinepFrame(type, tag, body)
+ }
+
+ /** Writes one framed message: size[4] type[1] tag[2] body. */
+ fun writeFrame(out: OutputStream, type: Int, tag: Int, body: ByteArray) {
+ val size = HEADER_SIZE + body.size
+ val header = ByteArrayOutputStream(HEADER_SIZE)
+ val w = Writer(header)
+ w.writeU32(size.toLong())
+ w.writeU8(type)
+ w.writeU16(tag)
+ out.write(header.toByteArray())
+ out.write(body)
+ }
+
+ /** Reads exactly [len] bytes, or returns null if the stream is at clean EOF before any byte. */
+ private fun readFully(input: InputStream, len: Int): ByteArray? {
+ val buf = ByteArray(len)
+ var off = 0
+ while (off < len) {
+ val n = input.read(buf, off, len - off)
+ if (n < 0) {
+ return if (off == 0) null else throw EOFException("9p stream ended mid-read")
+ }
+ off += n
+ }
+ return buf
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/AvfDownloadsShareTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/AvfDownloadsShareTest.kt
new file mode 100644
index 0000000..c43e385
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/AvfDownloadsShareTest.kt
@@ -0,0 +1,62 @@
+package com.excp.podroid.engine.avf
+
+import kotlinx.coroutines.runBlocking
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/**
+ * Unit tests for AvfDownloadsShare.connectWithRetry — the pure retry helper
+ * behind AvfEngine's vsock connect to the guest's 9p rendezvous listener.
+ * These tests never touch a real vsock socket or ParcelFileDescriptor; they
+ * drive the generic retry policy (now suspend, so it is cancellable in
+ * production) with a plain marker object and a no-op suspend sleeper via
+ * runBlocking, so the exhausted-budget case does not really sleep.
+ */
+class AvfDownloadsShareTest {
+
+ @Test fun `succeeds within budget after a couple of failures`() = runBlocking {
+ val marker = Any()
+ var calls = 0
+ var sleeps = 0
+ val result = AvfDownloadsShare.connectWithRetry(
+ connect = { calls++; if (calls < 3) null else marker },
+ attempts = 5,
+ sleep = { sleeps++ },
+ )
+ assertEquals(marker, result)
+ assertEquals(3, calls)
+ assertEquals(2, sleeps) // slept between attempt 1->2 and 2->3, not after success
+ }
+
+ @Test fun `a throwing supplier counts as a failed attempt, not a propagated exception`() = runBlocking {
+ val marker = Any()
+ var calls = 0
+ val result = AvfDownloadsShare.connectWithRetry(
+ connect = { calls++; if (calls == 1) throw RuntimeException("boom") else marker },
+ attempts = 5,
+ sleep = {},
+ )
+ assertEquals(marker, result)
+ assertEquals(2, calls)
+ }
+
+ @Test fun `returns null after exhausting attempts without sleeping in real time`() = runBlocking {
+ var calls = 0
+ var sleeps = 0
+ val startNanos = System.nanoTime()
+ val result = AvfDownloadsShare.connectWithRetry(
+ connect = { calls++; null },
+ attempts = 30,
+ sleep = { sleeps++ }, // no-op suspend sleeper: never calls delay/Thread.sleep
+ )
+ val elapsedMs = (System.nanoTime() - startNanos) / 1_000_000
+ assertNull(result)
+ assertEquals(30, calls)
+ assertEquals(29, sleeps) // between attempts only, never after the last
+ // A real 500ms backoff x 29 gaps would take ~14.5s; the no-op sleeper
+ // keeps this well under a second, proving no real sleep happened.
+ assertTrue("test took ${elapsedMs}ms; sleeper was not a no-op", elapsedMs < 2000)
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServerTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServerTest.kt
new file mode 100644
index 0000000..b46360b
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/ninep/Ninep2000LServerTest.kt
@@ -0,0 +1,623 @@
+package com.excp.podroid.engine.avf.ninep
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.rules.TemporaryFolder
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.io.FileNotFoundException
+
+private const val TEST_S_IFDIR = 0x4000L
+private const val TEST_S_IFREG = 0x8000L
+private const val TEST_EOPNOTSUPP = 95L
+
+/**
+ * Fake StatSource so the server runs on a plain JVM (android.system.Os is unavailable
+ * there). Mode is derived from java.io.File; inode numbers are assigned per absolute
+ * path and stay stable across calls, mirroring real filesystem inode stability.
+ */
+private class FakeStatSource : StatSource {
+ private val inodes = mutableMapOf<String, Long>()
+ private var nextIno = 1L
+
+ override fun lstat(path: String): StatInfo {
+ val f = File(path)
+ if (!f.exists()) throw FileNotFoundException(path)
+ val ino = inodes.getOrPut(path) { nextIno++ }
+ val mode = if (f.isDirectory) TEST_S_IFDIR or 0x1FFL else TEST_S_IFREG or 0x1B4L
+ return StatInfo(
+ ino = ino,
+ mode = mode,
+ uid = 0,
+ gid = 0,
+ size = if (f.isFile) f.length() else 0L,
+ nlink = 1,
+ rdev = 0,
+ blksize = 4096,
+ blocks = 0,
+ atimeSec = 0,
+ atimeNsec = 0,
+ mtimeSec = 0,
+ mtimeNsec = 0,
+ ctimeSec = 0,
+ ctimeNsec = 0,
+ )
+ }
+}
+
+private fun frame(type: Int, tag: Int, body: ByteArray): ByteArray =
+ ByteArrayOutputStream().also { NinepCodec.writeFrame(it, type, tag, body) }.toByteArray()
+
+private fun body(write: (NinepCodec.Writer) -> Unit): ByteArray =
+ ByteArrayOutputStream().also { write(NinepCodec.Writer(it)) }.toByteArray()
+
+private fun readFrames(bytes: ByteArray): List<NinepFrame> {
+ val input = ByteArrayInputStream(bytes)
+ val out = mutableListOf<NinepFrame>()
+ while (true) {
+ val f = NinepCodec.readFrame(input) ?: break
+ out += f
+ }
+ return out
+}
+
+class Ninep2000LServerTest {
+ @get:Rule val tmp = TemporaryFolder()
+
+ private fun versionFrame(tag: Int = 0xFFFF): ByteArray =
+ frame(Ninep.Tversion, tag, body { it.writeU32(8192); it.writeString("9P2000.L") })
+
+ private fun attachFrame(fid: Long, tag: Int): ByteArray =
+ frame(
+ Ninep.Tattach,
+ tag,
+ body { w ->
+ w.writeU32(fid)
+ w.writeU32(0xFFFFFFFFL) // afid = NOFID, no auth
+ w.writeString("user")
+ w.writeString("")
+ w.writeU32(0)
+ },
+ )
+
+ private fun walkFrame(fid: Long, newfid: Long, names: List<String>, tag: Int): ByteArray =
+ frame(
+ Ninep.Twalk,
+ tag,
+ body { w ->
+ w.writeU32(fid)
+ w.writeU32(newfid)
+ w.writeU16(names.size)
+ names.forEach { w.writeString(it) }
+ },
+ )
+
+ private fun getattrFrame(fid: Long, tag: Int): ByteArray =
+ frame(Ninep.Tgetattr, tag, body { w -> w.writeU32(fid); w.writeU64(0x7ffL) })
+
+ private fun clunkFrame(fid: Long, tag: Int): ByteArray =
+ frame(Ninep.Tclunk, tag, body { w -> w.writeU32(fid) })
+
+ private fun lopenFrame(fid: Long, flags: Long, tag: Int): ByteArray =
+ frame(Ninep.Tlopen, tag, body { w -> w.writeU32(fid); w.writeU32(flags) })
+
+ private fun lcreateFrame(fid: Long, name: String, flags: Long, mode: Long, tag: Int): ByteArray =
+ frame(
+ Ninep.Tlcreate,
+ tag,
+ body { w ->
+ w.writeU32(fid)
+ w.writeString(name)
+ w.writeU32(flags)
+ w.writeU32(mode)
+ w.writeU32(0) // gid
+ },
+ )
+
+ private fun treadFrame(fid: Long, offset: Long, count: Long, tag: Int): ByteArray =
+ frame(Ninep.Tread, tag, body { w -> w.writeU32(fid); w.writeU64(offset); w.writeU32(count) })
+
+ private fun twriteFrame(fid: Long, offset: Long, data: ByteArray, tag: Int): ByteArray =
+ frame(
+ Ninep.Twrite,
+ tag,
+ body { w ->
+ w.writeU32(fid)
+ w.writeU64(offset)
+ w.writeU32(data.size.toLong())
+ w.writeBytes(data)
+ },
+ )
+
+ private fun readdirFrame(fid: Long, offset: Long, count: Long, tag: Int): ByteArray =
+ frame(Ninep.Treaddir, tag, body { w -> w.writeU32(fid); w.writeU64(offset); w.writeU32(count) })
+
+ private fun mkdirFrame(dfid: Long, name: String, mode: Long, tag: Int): ByteArray =
+ frame(
+ Ninep.Tmkdir,
+ tag,
+ body { w -> w.writeU32(dfid); w.writeString(name); w.writeU32(mode); w.writeU32(0) },
+ )
+
+ private fun unlinkatFrame(dirfid: Long, name: String, flags: Long, tag: Int): ByteArray =
+ frame(
+ Ninep.Tunlinkat,
+ tag,
+ body { w -> w.writeU32(dirfid); w.writeString(name); w.writeU32(flags) },
+ )
+
+ private fun removeFrame(fid: Long, tag: Int): ByteArray =
+ frame(Ninep.Tremove, tag, body { w -> w.writeU32(fid) })
+
+ private fun renameatFrame(olddirfid: Long, oldname: String, newdirfid: Long, newname: String, tag: Int): ByteArray =
+ frame(
+ Ninep.Trenameat,
+ tag,
+ body { w ->
+ w.writeU32(olddirfid)
+ w.writeString(oldname)
+ w.writeU32(newdirfid)
+ w.writeString(newname)
+ },
+ )
+
+ private fun setattrFrame(
+ fid: Long,
+ valid: Long,
+ tag: Int,
+ mode: Long = 0,
+ size: Long = 0,
+ atimeSec: Long = 0,
+ atimeNsec: Long = 0,
+ mtimeSec: Long = 0,
+ mtimeNsec: Long = 0,
+ ): ByteArray = frame(
+ Ninep.Tsetattr,
+ tag,
+ body { w ->
+ w.writeU32(fid)
+ w.writeU32(valid)
+ w.writeU32(mode)
+ w.writeU32(0) // uid
+ w.writeU32(0) // gid
+ w.writeU64(size)
+ w.writeU64(atimeSec)
+ w.writeU64(atimeNsec)
+ w.writeU64(mtimeSec)
+ w.writeU64(mtimeNsec)
+ },
+ )
+
+ private fun fsyncFrame(fid: Long, tag: Int): ByteArray =
+ frame(Ninep.Tfsync, tag, body { w -> w.writeU32(fid); w.writeU32(0) })
+
+ @Test
+ fun version_negotiates_9p2000L() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(versionFrame()), out)
+
+ val resp = readFrames(out.toByteArray()).single()
+ assertEquals(Ninep.Rversion, resp.type)
+ val r = NinepCodec.Reader(resp.body)
+ r.readU32() // msize, not asserted here
+ assertEquals("9P2000.L", r.readString())
+ }
+
+ @Test
+ fun attach_returns_directory_qid() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() + attachFrame(fid = 0, tag = 1)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val rattach = readFrames(out.toByteArray())[1]
+ assertEquals(Ninep.Rattach, rattach.type)
+ val r = NinepCodec.Reader(rattach.body)
+ val qidType = r.readU8()
+ assertEquals(0x80, qidType)
+ }
+
+ @Test
+ fun walk_to_child_returns_its_qid() {
+ tmp.newFile("marker.txt")
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() + attachFrame(0, 1) + walkFrame(0, 1, listOf("marker.txt"), 2)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val rwalk = readFrames(out.toByteArray())[2]
+ assertEquals(Ninep.Rwalk, rwalk.type)
+ val r = NinepCodec.Reader(rwalk.body)
+ assertEquals(1, r.readU16())
+ assertEquals(0x00, r.readU8()) // regular file qid type
+ }
+
+ @Test
+ fun walk_does_not_escape_above_root() {
+ tmp.newFolder("sub")
+ val stat = FakeStatSource()
+ val rootIno = stat.lstat(tmp.root.absolutePath).ino
+ val server = Ninep2000LServer(tmp.root, stat)
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, listOf("sub"), 2) +
+ walkFrame(1, 2, listOf("..", ".."), 3)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val rwalkUp = readFrames(out.toByteArray())[3]
+ assertEquals(Ninep.Rwalk, rwalkUp.type)
+ val r = NinepCodec.Reader(rwalkUp.body)
+ assertEquals(2, r.readU16())
+ r.readU8(); r.readU32()
+ val firstPath = r.readU64()
+ r.readU8(); r.readU32()
+ val secondPath = r.readU64()
+ // Both ".." hops from an already-root position must resolve back to root,
+ // never to the real filesystem's parent of the temp folder.
+ assertEquals(rootIno, firstPath)
+ assertEquals(rootIno, secondPath)
+ }
+
+ @Test
+ fun getattr_reports_directory_for_root_and_file_for_child() {
+ tmp.newFile("marker.txt")
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ getattrFrame(0, 2) +
+ walkFrame(0, 1, listOf("marker.txt"), 3) +
+ getattrFrame(1, 4)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ val rootAttr = frames[2]
+ val fileAttr = frames[4]
+ assertEquals(Ninep.Rgetattr, rootAttr.type)
+ assertEquals(Ninep.Rgetattr, fileAttr.type)
+
+ val rr = NinepCodec.Reader(rootAttr.body)
+ rr.readU64() // valid mask
+ rr.readU8(); rr.readU32(); rr.readU64() // qid
+ val rootMode = rr.readU32()
+ assertEquals(0x4000L, rootMode and 0xF000L)
+
+ val fr = NinepCodec.Reader(fileAttr.body)
+ fr.readU64()
+ fr.readU8(); fr.readU32(); fr.readU64()
+ val fileMode = fr.readU32()
+ assertEquals(0x8000L, fileMode and 0xF000L)
+ }
+
+ @Test
+ fun clunk_drops_fid() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() + attachFrame(0, 1) + clunkFrame(0, 2) + getattrFrame(0, 3)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rclunk, frames[2].type)
+ assertEquals(Ninep.Rlerror, frames[3].type) // fid 0 no longer valid
+ }
+
+ @Test
+ fun unknown_opcode_returns_rlerror_eopnotsupp() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val bogusType = 250 // not a defined 9p2000.L type
+ val req = frame(bogusType, 9, ByteArray(0))
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val resp = readFrames(out.toByteArray()).single()
+ assertEquals(Ninep.Rlerror, resp.type)
+ val r = NinepCodec.Reader(resp.body)
+ assertEquals(TEST_EOPNOTSUPP, r.readU32())
+ }
+
+ @Test
+ fun truncated_request_stream_ends_loop_cleanly() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val full = versionFrame()
+ val truncated = full.copyOfRange(0, full.size - 3) // cut off mid-frame
+ val out = ByteArrayOutputStream()
+
+ server.serve(ByteArrayInputStream(truncated), out) // must not throw
+
+ assertEquals(0, out.toByteArray().size)
+ }
+
+ @Test
+ fun corrupt_size_prefix_ends_loop_cleanly() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val bogus = byteArrayOf(1, 0, 0, 0) // size = 1, smaller than the 7-byte header
+ val out = ByteArrayOutputStream()
+
+ server.serve(ByteArrayInputStream(bogus), out) // must not throw
+
+ assertTrue(out.toByteArray().isEmpty())
+ }
+
+ @Test
+ fun oversized_size_prefix_ends_loop_cleanly_without_crashing() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ // Little-endian size = 0x20000000 (~536 MB), a plausible allocation size that
+ // would previously have been passed straight to readFully()'s ByteArray(...)
+ // before any bound was checked. The oversized-frame guard must reject it
+ // before that allocation is attempted, so this must not OOM or throw out.
+ val bogus = byteArrayOf(0x00, 0x00, 0x00, 0x20)
+ val out = ByteArrayOutputStream()
+
+ server.serve(ByteArrayInputStream(bogus), out) // must not throw
+
+ assertTrue(out.toByteArray().isEmpty())
+ }
+
+ @Test
+ fun negative_wrap_size_prefix_ends_loop_cleanly() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ // Declared size 0xFFFFFFFF: (size - 4).toInt() would wrap to a negative Int
+ // if it were ever computed. The ceiling check must reject this before that
+ // arithmetic runs, ending the session cleanly instead of throwing out of serve().
+ val bogus = byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte())
+ val out = ByteArrayOutputStream()
+
+ server.serve(ByteArrayInputStream(bogus), out) // must not throw
+
+ assertTrue(out.toByteArray().isEmpty())
+ }
+
+ @Test
+ fun msize_is_clamped_to_ceiling() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = frame(
+ Ninep.Tversion,
+ 0xFFFF,
+ body { it.writeU32(1_000_000); it.writeString("9P2000.L") },
+ )
+ val out = ByteArrayOutputStream()
+
+ server.serve(ByteArrayInputStream(req), out)
+
+ val resp = readFrames(out.toByteArray()).single()
+ assertEquals(Ninep.Rversion, resp.type)
+ val r = NinepCodec.Reader(resp.body)
+ assertEquals(262144L, r.readU32())
+ }
+
+ @Test
+ fun lcreate_write_then_walk_lopen_read_returns_same_bytes() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val data = "hello world".toByteArray()
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ lcreateFrame(0, "hello.txt", flags = 2 /* O_RDWR */, mode = 0x1A4 /* 0644 */, tag = 2) +
+ twriteFrame(0, offset = 0, data = data, tag = 3) +
+ attachFrame(1, 4) +
+ walkFrame(1, 2, listOf("hello.txt"), 5) +
+ lopenFrame(2, flags = 0 /* O_RDONLY */, tag = 6) +
+ treadFrame(2, offset = 0, count = 64, tag = 7)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rlcreate, frames[2].type)
+ assertEquals(Ninep.Rwrite, frames[3].type)
+ val rwrite = NinepCodec.Reader(frames[3].body)
+ assertEquals(data.size.toLong(), rwrite.readU32())
+
+ val rread = NinepCodec.Reader(frames[7].body)
+ val count = rread.readU32()
+ assertEquals(data.size.toLong(), count)
+ assertTrue(data.contentEquals(rread.readBytes(count.toInt())))
+ }
+
+ @Test
+ fun write_at_offset_then_read_range_back() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val initial = "0123456789".toByteArray()
+ val overwrite = "XYZ".toByteArray()
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ lcreateFrame(0, "data.bin", flags = 2, mode = 0x1A4, tag = 2) +
+ twriteFrame(0, offset = 0, data = initial, tag = 3) +
+ twriteFrame(0, offset = 3, data = overwrite, tag = 4) +
+ treadFrame(0, offset = 0, count = 64, tag = 5)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ val rread = NinepCodec.Reader(frames[5].body)
+ val count = rread.readU32()
+ assertEquals("012XYZ6789", String(rread.readBytes(count.toInt())))
+ }
+
+ @Test
+ fun readdir_lists_dot_dotdot_and_children_with_dt_types_and_splits_across_offsets() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ // "." and ".." are always the first two entries with cookies 1 and 2, so the
+ // resume offset for the second page is known ahead of time: no need to run the
+ // server twice to discover it.
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ mkdirFrame(0, "sub", mode = 0x1ED /* 0755 */, tag = 2) +
+ walkFrame(0, 1, emptyList(), 3) + // clone root onto fid 1 without disturbing fid 0
+ lcreateFrame(1, "a.txt", flags = 2, mode = 0x1A4, tag = 4) +
+ readdirFrame(0, offset = 0, count = 4096, tag = 5) +
+ readdirFrame(0, offset = 0, count = 52, tag = 6) +
+ readdirFrame(0, offset = 2, count = 4096, tag = 7)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ val fullEntries = parseReaddirEntries(frames[5].body)
+ assertEquals(listOf(".", "..", "a.txt", "sub"), fullEntries.map { it.name })
+ assertEquals(QTDIR_DT, fullEntries[0].type)
+ assertEquals(QTDIR_DT, fullEntries[1].type)
+ assertEquals(QTREG_DT, fullEntries.first { it.name == "a.txt" }.type)
+ assertEquals(QTDIR_DT, fullEntries.first { it.name == "sub" }.type)
+
+ val firstPage = parseReaddirEntries(frames[6].body)
+ assertEquals(listOf(".", ".."), firstPage.map { it.name })
+ assertEquals(listOf(1L, 2L), firstPage.map { it.offset })
+
+ val secondPage = parseReaddirEntries(frames[7].body)
+ assertEquals(listOf("a.txt", "sub"), secondPage.map { it.name })
+ }
+
+ @Test
+ fun mkdir_then_getattr_shows_directory_and_unlinkat_removes_it() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ mkdirFrame(0, "tempdir", mode = 0x1ED, tag = 2) +
+ walkFrame(0, 2, listOf("tempdir"), 3) +
+ getattrFrame(2, 4) +
+ unlinkatFrame(0, "tempdir", flags = 0x200 /* AT_REMOVEDIR */, tag = 5) +
+ getattrFrame(2, 6)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rmkdir, frames[2].type)
+ val rgetattr = NinepCodec.Reader(frames[4].body)
+ rgetattr.readU64()
+ rgetattr.readU8(); rgetattr.readU32(); rgetattr.readU64()
+ assertEquals(0x4000L, rgetattr.readU32() and 0xF000L)
+ assertEquals(Ninep.Runlinkat, frames[5].type)
+ assertEquals(Ninep.Rlerror, frames[6].type) // directory is gone
+ assertFalse(File(tmp.root, "tempdir").exists())
+ }
+
+ @Test
+ fun renameat_moves_a_file() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, emptyList(), 2) +
+ lcreateFrame(1, "old.txt", flags = 2, mode = 0x1A4, tag = 3) +
+ renameatFrame(0, "old.txt", 0, "new.txt", tag = 4) +
+ walkFrame(0, 2, listOf("old.txt"), 5) +
+ walkFrame(0, 3, listOf("new.txt"), 6)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rrenameat, frames[4].type)
+ assertEquals(Ninep.Rlerror, frames[5].type) // old.txt no longer exists
+ assertEquals(Ninep.Rwalk, frames[6].type) // new.txt exists
+ assertFalse(File(tmp.root, "old.txt").exists())
+ assertTrue(File(tmp.root, "new.txt").exists())
+ }
+
+ @Test
+ fun setattr_size_truncates() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, emptyList(), 2) +
+ lcreateFrame(1, "trunc.txt", flags = 2, mode = 0x1A4, tag = 3) +
+ twriteFrame(1, offset = 0, data = "0123456789".toByteArray(), tag = 4) +
+ setattrFrame(1, valid = 0x8L /* SIZE */, tag = 5, size = 4) +
+ getattrFrame(1, 6)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rsetattr, frames[5].type)
+ val rgetattr = NinepCodec.Reader(frames[6].body)
+ rgetattr.readU64()
+ rgetattr.readU8(); rgetattr.readU32(); rgetattr.readU64() // qid
+ rgetattr.readU32(); rgetattr.readU32(); rgetattr.readU32() // mode, uid, gid
+ rgetattr.readU64() // nlink
+ rgetattr.readU64() // rdev
+ assertEquals(4L, rgetattr.readU64()) // size
+ assertEquals(4L, File(tmp.root, "trunc.txt").length())
+ }
+
+ @Test
+ fun setattr_mtime_sets_mtime() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val mtimeSec = 1_600_000_000L
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, emptyList(), 2) +
+ lcreateFrame(1, "mtime.txt", flags = 2, mode = 0x1A4, tag = 3) +
+ setattrFrame(
+ 1,
+ valid = 0x20L or 0x100L, // MTIME | MTIME_SET
+ tag = 4,
+ mtimeSec = mtimeSec,
+ mtimeNsec = 0,
+ )
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rsetattr, frames[4].type)
+ assertEquals(mtimeSec * 1000L, File(tmp.root, "mtime.txt").lastModified())
+ }
+
+ @Test
+ fun remove_deletes_a_file_and_the_fid_is_gone() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, emptyList(), 2) +
+ lcreateFrame(1, "rm.txt", flags = 2, mode = 0x1A4, tag = 3) +
+ removeFrame(1, tag = 4) +
+ getattrFrame(1, 5)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rremove, frames[4].type)
+ assertEquals(Ninep.Rlerror, frames[5].type) // fid was clunked by Tremove
+ assertFalse(File(tmp.root, "rm.txt").exists())
+ }
+
+ @Test
+ fun fsync_always_replies_success() {
+ val server = Ninep2000LServer(tmp.root, FakeStatSource())
+ val req = versionFrame() +
+ attachFrame(0, 1) +
+ walkFrame(0, 1, emptyList(), 2) +
+ lcreateFrame(1, "fs.txt", flags = 2, mode = 0x1A4, tag = 3) +
+ fsyncFrame(1, tag = 4)
+ val out = ByteArrayOutputStream()
+ server.serve(ByteArrayInputStream(req), out)
+
+ val frames = readFrames(out.toByteArray())
+ assertEquals(Ninep.Rfsync, frames[4].type)
+ }
+
+ private data class ReaddirEntry(val name: String, val offset: Long, val type: Int)
+
+ /** Parses a Rreaddir body (count[4] then count bytes of qid[13] offset[8] type[1]
+ * name[s] entries) back into structured entries for assertions. */
+ private fun parseReaddirEntries(rreaddirBody: ByteArray): List<ReaddirEntry> {
+ val r = NinepCodec.Reader(rreaddirBody)
+ val count = r.readU32()
+ val dataEnd = (rreaddirBody.size - r.remaining()) + count.toInt()
+ val entries = mutableListOf<ReaddirEntry>()
+ while (rreaddirBody.size - r.remaining() < dataEnd) {
+ r.readU8(); r.readU32(); r.readU64() // qid
+ val offset = r.readU64()
+ val type = r.readU8()
+ val name = r.readString()
+ entries += ReaddirEntry(name, offset, type)
+ }
+ return entries
+ }
+
+ companion object {
+ private const val QTDIR_DT = 4
+ private const val QTREG_DT = 8
+ }
+}
diff --git a/app/src/test/java/com/excp/podroid/engine/avf/ninep/NinepCodecTest.kt b/app/src/test/java/com/excp/podroid/engine/avf/ninep/NinepCodecTest.kt
new file mode 100644
index 0000000..825142b
--- /dev/null
+++ b/app/src/test/java/com/excp/podroid/engine/avf/ninep/NinepCodecTest.kt
@@ -0,0 +1,61 @@
+package com.excp.podroid.engine.avf.ninep
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertArrayEquals
+import org.junit.Test
+import java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+
+class NinepCodecTest {
+ @Test fun u32_roundtrip_littleEndian() {
+ val b = ByteArrayOutputStream(); val w = NinepCodec.Writer(b)
+ w.writeU32(0x04030201)
+ assertArrayEquals(byteArrayOf(1, 2, 3, 4), b.toByteArray())
+ val r = NinepCodec.Reader(byteArrayOf(1, 2, 3, 4))
+ assertEquals(0x04030201L, r.readU32())
+ }
+
+ @Test fun string_lengthPrefixed_utf8() {
+ val b = ByteArrayOutputStream(); NinepCodec.Writer(b).writeString("hi")
+ // s[2] = 0x0002 LE, then "hi"
+ assertArrayEquals(byteArrayOf(2, 0, 'h'.code.toByte(), 'i'.code.toByte()), b.toByteArray())
+ }
+
+ @Test fun frame_roundtrip() {
+ val body = byteArrayOf(9, 9, 9)
+ val out = ByteArrayOutputStream()
+ NinepCodec.writeFrame(out, type = Ninep.Rread, tag = 42, body = body)
+ val f = NinepCodec.readFrame(ByteArrayInputStream(out.toByteArray()))!!
+ assertEquals(Ninep.Rread, f.type); assertEquals(42, f.tag)
+ assertArrayEquals(body, f.body)
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun readFrame_rejects_size_over_ceiling_before_allocating_body() {
+ // A declared size just past the ceiling must be rejected by the bounds
+ // check before any body array is allocated, not discovered by attempting
+ // a huge (or, once truncated to Int, negative) readFully.
+ val sizeBytes = ByteArrayOutputStream().also {
+ NinepCodec.Writer(it).writeU32((NinepCodec.MAX_FRAME_SIZE + 1).toLong())
+ }.toByteArray()
+ NinepCodec.readFrame(ByteArrayInputStream(sizeBytes))
+ }
+
+ @Test(expected = IllegalArgumentException::class)
+ fun readFrame_rejects_size_that_would_wrap_negative_when_truncated_to_int() {
+ // 0xFFFFFFFF decoded as an unsigned 32-bit size; (size - 4).toInt() would
+ // wrap to a negative Int if it were ever computed. The ceiling check must
+ // reject this long before that arithmetic runs.
+ val sizeBytes = byteArrayOf(0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte(), 0xFF.toByte())
+ NinepCodec.readFrame(ByteArrayInputStream(sizeBytes))
+ }
+
+ @Test fun readFrame_accepts_custom_maxSize_at_the_boundary() {
+ val body = byteArrayOf(1, 2, 3)
+ val out = ByteArrayOutputStream()
+ NinepCodec.writeFrame(out, type = Ninep.Rread, tag = 1, body = body)
+ val exactSize = out.toByteArray().size
+ val f = NinepCodec.readFrame(ByteArrayInputStream(out.toByteArray()), maxSize = exactSize)!!
+ assertArrayEquals(body, f.body)
+ }
+}
diff --git a/build-rootfs/build-rootfs.sh b/build-rootfs/build-rootfs.sh
index 15246c9..81354df 100755
--- a/build-rootfs/build-rootfs.sh
+++ b/build-rootfs/build-rootfs.sh
@@ -104,6 +104,7 @@ cp /work/files/etc/init.d/podroid-ready "$ROOTFS/etc/init.d/"
cp /work/files/etc/init.d/podroid-x11 "$ROOTFS/etc/init.d/"
cp /work/files/etc/init.d/podroid-vsock "$ROOTFS/etc/init.d/"
cp /work/files/etc/init.d/podroid-hostd "$ROOTFS/etc/init.d/"
+cp /work/files/etc/init.d/podroid-downloads "$ROOTFS/etc/init.d/"
cp /work/files/etc/init.d/podroid-migrate "$ROOTFS/etc/init.d/"
chmod +x "$ROOTFS/etc/init.d/podroid-"*
@@ -187,7 +188,7 @@ mkdir -p "$ROOTFS/etc/runlevels/default" "$ROOTFS/etc/runlevels/boot"
# Guard each link: a dangling symlink (e.g. dnsmasq.lxcbr0, which lxc-bridge
# may ship only as dnsmasq config and not an init script) makes OpenRC log
# an error every boot and stalls podroid-ready's `after *` on a phantom.
-for svc in podroid-migrate podroid-bootstrap podroid-network podroid-resize dropbear docker lxc dnsmasq.lxcbr0 podroid-x11 podroid-vsock podroid-hostd podroid-ready; do
+for svc in podroid-migrate podroid-bootstrap podroid-network podroid-resize dropbear docker lxc dnsmasq.lxcbr0 podroid-x11 podroid-vsock podroid-downloads podroid-hostd podroid-ready; do
if [ -e "$ROOTFS/etc/init.d/$svc" ]; then
ln -sf "/etc/init.d/$svc" "$ROOTFS/etc/runlevels/default/$svc"
else
diff --git a/build-rootfs/files/etc/init.d/podroid-bootstrap b/build-rootfs/files/etc/init.d/podroid-bootstrap
index 96301bb..fc27fac 100644
--- a/build-rootfs/files/etc/init.d/podroid-bootstrap
+++ b/build-rootfs/files/etc/init.d/podroid-bootstrap
@@ -51,18 +51,24 @@ start() {
[ -w "$q" ] && echo mq-deadline > "$q" 2>/dev/null
done
- # Downloads share — self-gating: host only adds the virtio-9p device when
- # the user enables the toggle, so this returns ENODEV and exits silently
- # when off. Foreground so a missing /dev/fuse or kernel feature surfaces
- # in the boot log instead of being swallowed.
+ # Downloads share (QEMU virtio-9p). On AVF, podroid-downloads owns
+ # /mnt/downloads instead (9p over vsock, rendezvous with the Android-side
+ # 9p2000.L server) — skip the virtio-9p attempt there entirely.
+ #
+ # QEMU path: self-gating — host only adds the virtio-9p device when the
+ # user enables the toggle, so this returns ENODEV and exits silently when
+ # off. Foreground so a missing /dev/fuse or kernel feature surfaces in the
+ # boot log instead of being swallowed.
# msize=262144 (256 KB) — well under QEMU's virtio-9p 512 KB ceiling and
# large enough to amortize round-trips for big reads. cache=mmap is the
# next-best after cache=fscache (which requires CONFIG_9P_FSCACHE=y, not
# in this kernel build); mmap still page-caches mapped regions and is
# noticeably better than cache=loose for re-reads.
- mkdir -p /mnt/downloads 2>/dev/null
- mount -t 9p -o trans=virtio,version=9p2000.L,rw,msize=262144,cache=mmap,noatime \
- downloads /mnt/downloads 2>/dev/null
+ if ! grep -q 'podroid\.backend=avf' /proc/cmdline 2>/dev/null; then
+ mkdir -p /mnt/downloads 2>/dev/null
+ mount -t 9p -o trans=virtio,version=9p2000.L,rw,msize=262144,cache=mmap,noatime \
+ downloads /mnt/downloads 2>/dev/null
+ fi
mkdir -p /dev/net 2>/dev/null
[ -c /dev/net/tun ] || mknod /dev/net/tun c 10 200 2>/dev/null
diff --git a/build-rootfs/files/etc/init.d/podroid-downloads b/build-rootfs/files/etc/init.d/podroid-downloads
new file mode 100644
index 0000000..6a1b41b
--- /dev/null
+++ b/build-rootfs/files/etc/init.d/podroid-downloads
@@ -0,0 +1,39 @@
+#!/sbin/openrc-run
+description="Podroid AVF Downloads share (9p over vsock, AVF only)"
+pidfile="/run/podroid-downloads.pid"
+
+depend() {
+ need podroid-bootstrap
+ after podroid-network podroid-vsock
+ before podroid-ready
+}
+
+start() {
+ # AVF-only: QEMU's kernel has no AF_VSOCK and already gets its Downloads
+ # share via virtio-9p in podroid-bootstrap. Skip cleanly via
+ # mark_service_inactive, same idiom podroid-vsock uses.
+ if ! grep -q 'podroid\.backend=avf' /proc/cmdline 2>/dev/null; then
+ einfo "Not an AVF boot - skipping podroid-downloads"
+ mark_service_inactive
+ return 0
+ fi
+ mkdir -p /mnt/downloads 2>/dev/null
+ ebegin "Starting Downloads 9p rendezvous"
+ start-stop-daemon --start --background \
+ --make-pidfile --pidfile "$pidfile" \
+ --stdout /var/log/podroid-downloads.log \
+ --stderr /var/log/podroid-downloads.log \
+ --exec /usr/local/bin/podroid-vsock-agent -- downloads-9p
+ eend $?
+}
+
+stop() {
+ if [ -f "$pidfile" ]; then
+ ebegin "Stopping Downloads 9p rendezvous"
+ start-stop-daemon --stop --pidfile "$pidfile"
+ rm -f "$pidfile"
+ eend $?
+ fi
+ umount /mnt/downloads 2>/dev/null || true
+ return 0
+}
diff --git a/build-rootfs/vsock-agent/podroid-vsock-agent.c b/build-rootfs/vsock-agent/podroid-vsock-agent.c
index ada3538..782bca0 100644
--- a/build-rootfs/vsock-agent/podroid-vsock-agent.c
+++ b/build-rootfs/vsock-agent/podroid-vsock-agent.c
@@ -30,6 +30,11 @@
*
* All TCP listeners bind to AF_VSOCK with CID = VMADDR_CID_ANY (host can reach
* us regardless of the assigned CID).
+ *
+ * Invoked as `podroid-vsock-agent downloads-9p` (argv[1] dispatch, separate
+ * from the config-driven modes above): runs only the Downloads share's 9p
+ * rendezvous listener (see downloads_9p_serve()) instead of the forwards.conf
+ * + ctl loop.
*/
#define _GNU_SOURCE
@@ -40,11 +45,13 @@
#include <linux/vm_sockets.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
+#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/mount.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
@@ -57,6 +64,11 @@
#define TERM_SIZE_PATH "/run/term_size"
#define LOG_TAG "podroid-vsock-agent"
+/* Reserved vsock port for the AVF Downloads share's 9p rendezvous. Keep this
+ * equal to AvfDownloadsShare.DOWNLOADS_VSOCK_PORT in the Android code. */
+#define PODROID_DOWNLOADS_VSOCK_PORT 200000
+#define PODROID_DOWNLOADS_MOUNT "/mnt/downloads"
+
/* ── Logging ─────────────────────────────────────────────────────────────── */
/*
@@ -681,6 +693,88 @@ static void ctl_loop(int fd) {
fclose(out);
}
+/* ── Downloads 9p rendezvous (downloads-9p mode) ────────────────────────────
+ *
+ * Android's AvfDownloadsShare connectVsock()s to this port and runs its own
+ * in-process 9p2000.L server directly against the resulting socket. We are
+ * only the transport rendezvous: accept the one connection, hand its fd to
+ * the guest kernel's 9p client via `mount -t 9p -o trans=fd`, then get out of
+ * the way. The mounted fd carries live 9p protocol traffic between the guest
+ * kernel and Android's server - we must never read() or write() it ourselves,
+ * that would steal or corrupt protocol bytes.
+ *
+ * mount(2) with trans=fd has the kernel take its own reference to rfdno/wfdno
+ * (net/9p/trans_fd.c fgets them), so our own fd stays valid across the call
+ * and keeps working afterwards purely as an observation handle: poll() only
+ * reports readiness, it never consumes data, so it is safe to watch even
+ * though the bytes flowing through the fd belong to the 9p session. POLLHUP/
+ * POLLERR/POLLNVAL are reported by the kernel regardless of the requested
+ * events, so polling with events=0 gives us exactly "the peer went away"
+ * without also waking on ordinary 9p traffic.
+ */
+static void downloads_9p_serve(void) {
+ int s = socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC, 0);
+ if (s < 0) { LOG_E("downloads-9p: vsock socket() failed: %s", strerror(errno)); return; }
+ int one = 1;
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
+ struct sockaddr_vm sa;
+ memset(&sa, 0, sizeof(sa));
+ sa.svm_family = AF_VSOCK;
+ sa.svm_cid = VMADDR_CID_ANY;
+ sa.svm_port = PODROID_DOWNLOADS_VSOCK_PORT;
+ if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
+ LOG_E("downloads-9p: vsock bind(%d) failed: %s", PODROID_DOWNLOADS_VSOCK_PORT, strerror(errno));
+ close(s);
+ return;
+ }
+ if (listen(s, 1) < 0) {
+ LOG_E("downloads-9p: vsock listen(%d) failed: %s", PODROID_DOWNLOADS_VSOCK_PORT, strerror(errno));
+ close(s);
+ return;
+ }
+ LOG_I("downloads-9p: listening on vsock:%d", PODROID_DOWNLOADS_VSOCK_PORT);
+
+ for (;;) {
+ int cfd = accept4(s, NULL, NULL, 0);
+ if (cfd < 0) {
+ if (errno == EINTR) continue;
+ LOG_E("downloads-9p: accept() failed: %s", strerror(errno));
+ break;
+ }
+
+ mkdir(PODROID_DOWNLOADS_MOUNT, 0755);
+ char opts[160];
+ snprintf(opts, sizeof(opts),
+ "trans=fd,rfdno=%d,wfdno=%d,version=9p2000.L,msize=262144,cache=none,access=any",
+ cfd, cfd);
+ if (mount("downloads", PODROID_DOWNLOADS_MOUNT, "9p", 0, opts) < 0) {
+ LOG_W("downloads-9p: mount failed: %s", strerror(errno));
+ close(cfd);
+ continue; // non-fatal - wait for Android to reconnect
+ }
+ LOG_I("downloads-9p: mounted %s", PODROID_DOWNLOADS_MOUNT);
+
+ /* Block until the connection dies (Android side closed, VM stopping,
+ * sharing toggled off), then unmount and go back to accept(). */
+ for (;;) {
+ struct pollfd pfd = { .fd = cfd, .events = 0 };
+ int pr = poll(&pfd, 1, -1);
+ if (pr < 0) {
+ if (errno == EINTR) continue;
+ break;
+ }
+ if (pfd.revents & (POLLHUP | POLLERR | POLLNVAL)) break;
+ }
+
+ LOG_I("downloads-9p: connection ended, unmounting");
+ if (umount2(PODROID_DOWNLOADS_MOUNT, MNT_DETACH) < 0 && errno != EINVAL && errno != ENOENT)
+ LOG_W("downloads-9p: umount2 failed: %s", strerror(errno));
+ close(cfd);
+ // loop back to accept() - best-effort reconnect
+ }
+ close(s);
+}
+
/* ── Main + config bootstrap ────────────────────────────────────────────── */
static int ctl_vport = -1;
@@ -721,15 +815,22 @@ static void reap_children(int signum) {
}
int main(int argc, char **argv) {
- (void)argc; (void)argv;
+ /* Ignore SIGPIPE in every mode - splice_loop's write() and the downloads
+ * 9p rendezvous both prefer EPIPE on a dead peer over the default
+ * SIGPIPE disposition. */
+ signal(SIGPIPE, SIG_IGN);
+
+ if (argc >= 2 && strcmp(argv[1], "downloads-9p") == 0) {
+ downloads_9p_serve();
+ return 0;
+ }
+
/* Reap dead listener children; don't accumulate zombies. */
struct sigaction sa = {0};
sa.sa_handler = reap_children;
sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
sigemptyset(&sa.sa_mask);
sigaction(SIGCHLD, &sa, NULL);
- /* Ignore SIGPIPE — splice_loop's write() will surface the error instead. */
- signal(SIGPIPE, SIG_IGN);
parse_config_and_bootstrap(CONFIG_PATH);