A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
feat(usb): pass external USB devices into the QEMU guest
9hm2ff3a59141699
diff --git a/CLAUDE.md b/CLAUDE.mdindex c624d4e..dbc33c8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -68,6 +68,8 @@ The terminal layer uses three QEMU Unix sockets, each with a single role:**`service/PodroidService.kt`** — foreground service that owns the QEMU process. Holds a `WakeLock`, updates the persistent notification with boot stages, and handles graceful stop when the app is swiped from recents.+**`engine/usb/UsbPassthroughManager.kt`** — runtime USB device passthrough into the QEMU guest. An unprivileged Android app cannot open the `/dev/bus/usb` device nodes, so it takes the already-open fd from `UsbManager` / `UsbDeviceConnection.getFileDescriptor()` and streams it to QEMU over `qmp.sock` as SCM_RIGHTS ancillary data (`add-fd`), then hot-plugs it with `device_add usb-host,hostdevice=/dev/fdset/N`. A code-registered `BroadcastReceiver` (no manifest `device_filter.xml`) is live only while the VM is `Running` — `PodroidService` drives `start()`/`stop()` off the VM state. Gated by the `usb_passthrough_enabled` setting, which also makes `buildCommand()` emit `-device qemu-xhci` at boot. Needs a libusb-enabled QEMU build — the `Dockerfile` cross-compiles libusb and configures QEMU `--enable-libusb`.+**`podroid-bridge.c`** — native C binary (compiled to `libpodroid-bridge.so`) that Termux runs as a subprocess. Bidirectionally relays PTY ↔ `terminal.sock`, and writes `RESIZE rows cols\n` to `ctrl.sock` after a 200 ms-debounced SIGWINCH burst (so a single keyboard-slide animation produces one shell prompt redraw, not 25).**`init-podroid`** — minimal initramfs bootstrap (~45 lines). Mounts persistent ext4 (`/dev/vda` → `/mnt/persist`) and read-only Alpine squashfs (`/dev/vdb` → `/mnt/lower`), stacks an overlayfs (lower=squashfs, upper=persist), and `switch_root`s into `/sbin/init` (busybox, which reads `/etc/inittab` and starts OpenRC). All system bringup (cgroup v2, SLIRP networking, devpts/shm/mqueue mounts, ZRAM, sysctl, Podman dirs) lives in three OpenRC services on the squashfs:diff --git a/Dockerfile b/Dockerfileindex 3f8cb4e..468769b 100644--- a/Dockerfile+++ b/Dockerfile@@ -135,7 +135,8 @@ RUN cd linux-${KERNEL_VERSION} \EXT4_FS_SECURITY SQUASHFS_XATTR SQUASHFS_ZSTD \DECOMPRESS_ZSTD ZSTD_DECOMPRESS \IKCONFIG IKCONFIG_PROC BINFMT_MISC \- VSOCKETS VIRTIO_VSOCKETS; do \+ VSOCKETS VIRTIO_VSOCKETS \+ RFKILL LEDS_CLASS CFG80211 MAC80211 RTW88 BT; do \grep -q "^CONFIG_${opt}=y\$" .config \|| { echo "FATAL: CONFIG_${opt} is not =y after merge" >&2; \grep "CONFIG_${opt}" .config >&2; exit 1; }; \@@ -253,6 +254,15 @@ RUN wget -q https://download.savannah.gnu.org/releases/attr/attr-2.5.2.tar.gz &&RUN git clone --depth=1 https://github.com/kaniini/libucontext.git /tmp/libucontext && make -C /tmp/libucontext ARCH=aarch64 CC="${CC}" EXPORT_UNPREFIXED=yes && install -Dm644 /tmp/libucontext/libucontext.a ${PREFIX}/lib/libucontext.a && install -Dm644 /tmp/libucontext/include/libucontext/libucontext.h ${PREFIX}/include/libucontext/libucontext.h && install -Dm644 /tmp/libucontext/arch/common/include/libucontext/bits.h ${PREFIX}/include/libucontext/bits.h \&& printf '#ifndef PODROID_UCONTEXT_SHIM_H\n#define PODROID_UCONTEXT_SHIM_H\n#include_next <ucontext.h>\n#include <libucontext/libucontext.h>\n#define getcontext libucontext_getcontext\n#define makecontext libucontext_makecontext\n#define setcontext libucontext_setcontext\n#define swapcontext libucontext_swapcontext\n#endif\n' > ${PREFIX}/include/ucontext.h+# libusb — required for QEMU's usb-host device. USB passthrough on Android can+# never open /dev/bus/usb itself, so QEMU receives an already-open fd over QMP+# and hands it to libusb_wrap_sys_device(); --disable-udev because Android has+# no udev and we never enumerate (every device arrives as a passed-in fd).+RUN wget -q https://github.com/libusb/libusb/releases/download/v1.0.27/libusb-1.0.27.tar.bz2 \+ && tar xf libusb-1.0.27.tar.bz2 && cd libusb-1.0.27 \+ && ./configure --host=aarch64-linux-android --prefix=${PREFIX} --enable-static --disable-shared --disable-udev CC="${CC}" \+ && make -j$(nproc) install+# QEMU Build (committed flags — no LTO, no -O3 — plus minimal Android compat patches)RUN wget -q https://download.qemu.org/${QEMU_DIR}.tar.xz && tar xf ${QEMU_DIR}.tar.xzRUN sed -i "s/rt = cc.find_library('rt', required: true)/rt = cc.find_library('rt', required: false)/" ${QEMU_DIR}/meson.build@@ -287,7 +297,7 @@ RUN sed -i '1i#include "/opt/qemu_jmp.h"' ${QEMU_DIR}/util/coroutine-ucontext.c&& sed -i 's/\bsigsetjmp(\([^,]*\), *0)/_qemu_setjmp(\1)/g' ${QEMU_DIR}/util/coroutine-ucontext.c \&& sed -i 's/\bsiglongjmp(/_qemu_longjmp(/g' ${QEMU_DIR}/util/coroutine-ucontext.c-RUN cd ${QEMU_DIR} && ./configure --cc="${CC}" --cross-prefix="${LLVM}/bin/llvm-" --extra-cflags="-fPIC -DANDROID -include /opt/shm_shim.h -I${PREFIX}/include -I${PREFIX}/include/glib-2.0 -I${PREFIX}/lib/glib-2.0/include" --extra-ldflags="-L${PREFIX}/lib -Wl,-z,max-page-size=16384 ${PREFIX}/lib/libucontext.a ${PREFIX}/lib/libshm.a ${PREFIX}/lib/libqemujmp.a" --prefix=/opt/qemu-out --target-list=aarch64-softmmu --enable-tcg --enable-slirp --enable-virtfs --enable-pie --disable-docs --disable-gtk --disable-sdl --disable-vnc --disable-vhost-user --disable-plugins --with-coroutine=ucontext && make -j$(nproc) install+RUN cd ${QEMU_DIR} && ./configure --cc="${CC}" --cross-prefix="${LLVM}/bin/llvm-" --extra-cflags="-fPIC -DANDROID -include /opt/shm_shim.h -I${PREFIX}/include -I${PREFIX}/include/glib-2.0 -I${PREFIX}/lib/glib-2.0/include" --extra-ldflags="-L${PREFIX}/lib -Wl,-z,max-page-size=16384 ${PREFIX}/lib/libucontext.a ${PREFIX}/lib/libshm.a ${PREFIX}/lib/libqemujmp.a" --prefix=/opt/qemu-out --target-list=aarch64-softmmu --enable-tcg --enable-slirp --enable-virtfs --enable-libusb --enable-pie --disable-docs --disable-gtk --disable-sdl --disable-vnc --disable-vhost-user --disable-plugins --with-coroutine=ucontext && make -j$(nproc) install# BridgeCOPY podroid-bridge.c /tmp/podroid-bridge.cdiff --git a/README.md b/README.mdindex 6fc972f..3b09d2b 100644--- a/README.md+++ b/README.md@@ -79,6 +79,7 @@ Default login: **root / podroid**.- **Podman, Docker and LXC pre-installed.** Rootless Podman wired up with crun + netavark + slirp4netns; `rc-service docker start` runs the Docker daemon, and `lxc-create -t download` pulls full distro containers (Alpine, Ubuntu, Debian, …) out of the box.- **OpenRC as PID 1.** `apk add` whatever you want, `rc-service ... start`, and it persists across reboots.- **In-app X11 viewer** (Xvnc + PulseAudio): live-resizable display (match-device, or 720p–1440p / custom presets), direct-touch and trackpad pointer modes with scroll, fullscreen, rotation lock, external-keyboard and mouse-wheel support, soft-keyboard input, and PCM audio over loopback.+- **USB device passthrough.** Hot-plug a real USB device — Wi-Fi adapter, storage, serial adapter, audio interface — into the running VM straight from the Android USB stack. No root and no XML device filter: each device asks for permission when attached and is streamed to QEMU over QMP while the app runs.- **Built-in terminal** powered by the Termux engine: xterm-256color, mouse tracking, debounced resize, customizable extra-keys row.- **Persistent ext4 overlay** on a read-only Alpine squashfs. Installs and configs survive every reboot.- **Adaptive Material 3 UI** for phone, tablet and landscape, with dynamic color and a foreground service that keeps the VM alive.@@ -103,6 +104,7 @@ Everything below is editable from **Settings**:- **CPU cores:** 1 · 2 · 4 · 6 · 8- **Persistent storage:** 2 GB to 64 GB (chosen at first setup; reset to change)- **Downloads folder sharing:** toggle on/off; mounted inside the VM at `/mnt/downloads` (virtio-9p on QEMU, AVF `SharedPath` where the backend supports it)+- **USB passthrough:** toggle on/off; hot-plugs attached USB devices into the running VM (QEMU backend only — adds a USB controller at boot, so restart to apply)- **SSH** (Dropbear on host port `9922`): toggle on/off; reachable from the LAN as `ssh root@<phone-ip> -p 9922` once the VM is Ready- **Port forwards:** add/remove host ↔ guest TCP/UDP rules live, no VM restart- **Advanced QEMU args:** full `-cpu` / `-accel` / RNG / device line, editablediff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 24caf2d..208cc99 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -42,6 +42,15 @@<!-- Large heap for QEMU memory allocation --><uses-feature android:name="android.hardware.opengles.aep" android:required="false" />+ <!--+ USB host mode — needed to pass external USB devices into the VM. Per-device+ access is granted at runtime via the system consent dialog; there is no+ manifest <receiver>/device_filter.xml, the attach broadcast is handled by a+ receiver registered in code only while the VM runs. required="false" so the+ APK still installs on devices without USB host support.+ -->+ <uses-feature android:name="android.hardware.usb.host" android:required="false" />+<!--Android Virtualization Framework (AVF / pKVM) opt-in. Both permissionsare signature|*|development and can be granted to a side-loaded APK viadiff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.ktindex 720667d..907eabd 100644--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt@@ -52,6 +52,7 @@ class SettingsRepository @Inject constructor(val KEY_ENGINE_SELECTION = stringPreferencesKey("engine_selection")val KEY_AVF_HINT_DISMISSED = booleanPreferencesKey("avf_hint_dismissed")val KEY_AVF_VERBOSE_LOGGING = booleanPreferencesKey("avf_verbose_logging")+ val KEY_USB_PASSTHROUGH_ENABLED = booleanPreferencesKey("usb_passthrough_enabled")val KEY_X11_RES_MODE = stringPreferencesKey("x11_resolution_mode")val KEY_X11_RES_PRESET = stringPreferencesKey("x11_resolution_preset")@@ -124,6 +125,7 @@ class SettingsRepository @Inject constructor(val dynamicColorEnabled = pref(KEY_DYNAMIC_COLOR_ENABLED, false)val lastBootDurationMs = pref(KEY_LAST_BOOT_DURATION_MS, 0L)val avfHintDismissed = pref(KEY_AVF_HINT_DISMISSED, false)+ val usbPassthroughEnabled = pref(KEY_USB_PASSTHROUGH_ENABLED, false)val avfVerboseLogging: Flow<Boolean> = context.dataStore.data.catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }.map { prefs -> prefs[KEY_AVF_VERBOSE_LOGGING] ?: false }@@ -153,6 +155,7 @@ class SettingsRepository @Inject constructor(suspend fun setEngineSelection(value: EngineSelection) = set(KEY_ENGINE_SELECTION, value.name)suspend fun setAvfHintDismissed(value: Boolean) = set(KEY_AVF_HINT_DISMISSED, value)suspend fun setAvfVerboseLogging(value: Boolean) = set(KEY_AVF_VERBOSE_LOGGING, value)+ suspend fun setUsbPassthroughEnabled(value: Boolean) = set(KEY_USB_PASSTHROUGH_ENABLED, value)val x11Settings: kotlinx.coroutines.flow.Flow<com.excp.podroid.x11.X11Settings> = context.dataStore.data.catch { e -> if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e }@@ -199,4 +202,5 @@ class SettingsRepository @Inject constructor(suspend fun getKernelExtraCmdlineSnapshot() = kernelExtraCmdline.first()suspend fun getEngineSelectionSnapshot() = engineSelection.first()suspend fun getAvfVerboseLoggingSnapshot() = avfVerboseLogging.first()+ suspend fun getUsbPassthroughEnabledSnapshot() = usbPassthroughEnabled.first()}diff --git a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt b/app/src/main/java/com/excp/podroid/engine/QemuEngine.ktindex d222e0d..cf61c9c 100644--- a/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt+++ b/app/src/main/java/com/excp/podroid/engine/QemuEngine.kt@@ -571,6 +571,15 @@ class QemuEngine @Inject constructor(args += "-netdev"; args += netdevArgargs += "-device"; args += "virtio-net-pci,netdev=net0,romfile="+ // USB host controller for hot-plugged passthrough devices. Only emitted+ // when the feature is on — the XHCI model adds emulation overhead that+ // nothing else needs. UsbPassthroughManager streams Android+ // UsbDeviceConnection fds onto this bus at runtime via QMP add-fd ++ // device_add usb-host (needs a libusb-enabled QEMU build).+ if (config.usbPassthroughEnabled) {+ args += "-device"; args += "qemu-xhci,id=usbhc0"+ }+// ── Serial (ttyAMA0) → boot log sink only; kernel msgs + init boot stages ─args += "-serial"; args += "unix:$serialSockPath,server,nowait"diff --git a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt b/app/src/main/java/com/excp/podroid/engine/QmpClient.ktindex d80502f..f98f995 100644--- a/app/src/main/java/com/excp/podroid/engine/QmpClient.kt+++ b/app/src/main/java/com/excp/podroid/engine/QmpClient.kt@@ -3,7 +3,8 @@* Copyright (C) 2024-2026 Podroid contributors** Minimal QMP (QEMU Machine Protocol) client for runtime VM management.- * Used for adding/removing port forwards while the VM is running.+ * Used for adding/removing port forwards and hot-plugging USB passthrough+ * devices while the VM is running.*/package com.excp.podroid.engine@@ -14,8 +15,8 @@ import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport org.json.JSONObjectimport java.io.BufferedReader+import java.io.FileDescriptorimport java.io.InputStreamReader-import java.io.OutputStreamWriterclass QmpClient(private val socketPath: String) {@@ -87,55 +88,66 @@ class QmpClient(private val socketPath: String) {}}- suspend fun execute(command: String, arguments: JSONObject? = null): Result<JSONObject> =- withContext(Dispatchers.IO) {- try {- LocalSocket().use { socket ->- socket.connect(- LocalSocketAddress(socketPath, LocalSocketAddress.Namespace.FILESYSTEM)- )- socket.soTimeout = SOCKET_TIMEOUT_MS-- val reader = BufferedReader(InputStreamReader(socket.inputStream))- val writer = OutputStreamWriter(socket.outputStream)-- // Read QMP greeting (verbose-only: noisy and uninteresting on every command)- val greeting = reader.readLine()- Log.v(TAG, "QMP greeting: $greeting")-- // Send qmp_capabilities to enter command mode- writer.write("{\"execute\":\"qmp_capabilities\"}\n")- writer.flush()- val capResponse = reader.readLine()- Log.v(TAG, "Capabilities response: $capResponse")-- // Send the actual command- val cmd = JSONObject().apply {- put("execute", command)- if (arguments != null) put("arguments", arguments)- }- writer.write(cmd.toString() + "\n")- writer.flush()-- // Read until a terminal reply (return/error). QMP can emit- // async {"event":...} lines at any time — classifyQmpResponse- // returns null for those so we skip them. A null line = EOF.- var result: Result<JSONObject>? = null- while (result == null) {- val response = reader.readLine()- ?: return@withContext Result.failure(- RuntimeException("QMP connection closed before a reply to $command")- )- Log.d(TAG, "Command response: $response")- result = classifyQmpResponse(JSONObject(response))- }- result+ /**+ * Run one QMP command over a fresh connection. When [sendFd] is non-null it+ * is handed to QEMU as SCM_RIGHTS ancillary data on the command write — the+ * mechanism `add-fd` needs to ingest a file descriptor (e.g. an Android+ * UsbDeviceConnection fd for usb-host passthrough).+ */+ private suspend fun exec(+ command: String,+ arguments: JSONObject?,+ sendFd: FileDescriptor? = null,+ ): Result<JSONObject> = withContext(Dispatchers.IO) {+ try {+ LocalSocket().use { socket ->+ socket.connect(+ LocalSocketAddress(socketPath, LocalSocketAddress.Namespace.FILESYSTEM)+ )+ socket.soTimeout = SOCKET_TIMEOUT_MS++ val reader = BufferedReader(InputStreamReader(socket.inputStream))+ val out = socket.outputStream++ // Read QMP greeting, then enter command mode.+ Log.v(TAG, "QMP greeting: ${reader.readLine()}")+ out.write("{\"execute\":\"qmp_capabilities\"}\n".toByteArray())+ out.flush()+ Log.v(TAG, "Capabilities response: ${reader.readLine()}")++ val cmd = JSONObject().apply {+ put("execute", command)+ if (arguments != null) put("arguments", arguments)}- } catch (e: Exception) {- Log.e(TAG, "QMP command failed: $command", e)- Result.failure(e)+ // The fd (if any) must ride on the SAME write that carries the+ // command JSON: QEMU pairs the SCM_RIGHTS payload with the+ // add-fd command currently being parsed.+ if (sendFd != null) socket.setFileDescriptorsForSend(arrayOf(sendFd))+ out.write((cmd.toString() + "\n").toByteArray())+ out.flush()++ // Read until a terminal reply (return/error). QMP can emit+ // async {"event":...} lines at any time — classifyQmpResponse+ // returns null for those so we skip them. A null line = EOF.+ var result: Result<JSONObject>? = null+ while (result == null) {+ val response = reader.readLine()+ ?: return@withContext Result.failure(+ RuntimeException("QMP connection closed before a reply to $command")+ )+ Log.d(TAG, "Command response ($command): $response")+ result = classifyQmpResponse(JSONObject(response))+ }+ result}+ } catch (e: Exception) {+ Log.e(TAG, "QMP command failed: $command", e)+ Result.failure(e)}+ }++ suspend fun execute(command: String, arguments: JSONObject? = null): Result<JSONObject> =+ exec(command, arguments)suspend fun addPortForward(hostPort: Int, guestPort: Int, protocol: String = "tcp"): Result<JSONObject> {val monitorCmd = "hostfwd_add net0 ${protocol}::${hostPort}-:${guestPort}"@@ -152,4 +164,25 @@ class QmpClient(private val socketPath: String) {JSONObject().put("command-line", monitorCmd))}++ /**+ * Pass [fd] to QEMU via SCM_RIGHTS and register it in a freshly-created fd+ * set. Returns the new fdset-id, referenceable from device properties as+ * `/dev/fdset/<id>` — used to hot-plug usb-host devices without QEMU ever+ * needing direct access to /dev/bus/usb (which is unreachable to an+ * unprivileged Android app).+ */+ suspend fun addFd(fd: FileDescriptor): Result<Int> =+ exec("add-fd", null, fd).mapCatching {+ it.getJSONObject("return").getInt("fdset-id")+ }++ suspend fun removeFd(fdSetId: Int): Result<JSONObject> =+ execute("remove-fd", JSONObject().put("fdset-id", fdSetId))++ suspend fun deviceAdd(arguments: JSONObject): Result<JSONObject> =+ execute("device_add", arguments)++ suspend fun deviceDel(id: String): Result<JSONObject> =+ execute("device_del", JSONObject().put("id", id))}diff --git a/app/src/main/java/com/excp/podroid/engine/VmEngine.kt b/app/src/main/java/com/excp/podroid/engine/VmEngine.ktindex 92e1782..818081c 100644--- a/app/src/main/java/com/excp/podroid/engine/VmEngine.kt+++ b/app/src/main/java/com/excp/podroid/engine/VmEngine.kt@@ -83,4 +83,5 @@ data class VmConfig(val kernelExtraCmdline: String = "",val verboseLogging: Boolean = false,val x11Dpi: Int = 96,+ val usbPassthroughEnabled: Boolean = false,)diff --git a/app/src/main/java/com/excp/podroid/engine/usb/UsbPassthroughManager.kt b/app/src/main/java/com/excp/podroid/engine/usb/UsbPassthroughManager.ktnew file mode 100644index 0000000..7fd2f8e--- /dev/null+++ b/app/src/main/java/com/excp/podroid/engine/usb/UsbPassthroughManager.kt@@ -0,0 +1,213 @@+/*+ * Podroid - Rootless Podman for Android+ * Copyright (C) 2024-2026 Podroid contributors+ *+ * USB device passthrough into the QEMU guest.+ *+ * An unprivileged Android app cannot reach the /dev/bus/usb device nodes+ * directly, so QEMU's usb-host backend can never open one itself. Instead this+ * manager goes through the only channel Android offers: UsbManager hands back an+ * already-open file descriptor (UsbDeviceConnection.getFileDescriptor()), and+ * that fd is streamed to QEMU over the QMP control socket as SCM_RIGHTS+ * ancillary data (`add-fd`). QEMU then hot-plugs it with+ * `device_add usb-host,hostdevice=/dev/fdset/<id>`.+ *+ * Everything happens at runtime while the VM is up — there is no manifest+ * <receiver> with a device_filter.xml. The BroadcastReceiver is registered in+ * code only for the duration the VM is Running, so a device can only ever be+ * handed over via a live broadcast while the app itself is running.+ */+package com.excp.podroid.engine.usb++import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.IntentFilter+import android.hardware.usb.UsbDevice+import android.hardware.usb.UsbDeviceConnection+import android.hardware.usb.UsbManager+import android.os.Build+import android.os.ParcelFileDescriptor+import android.util.Log+import androidx.core.content.ContextCompat+import com.excp.podroid.engine.VmEngine+import com.excp.podroid.engine.VmState+import dagger.hilt.android.qualifiers.ApplicationContext+import kotlinx.coroutines.CoroutineExceptionHandler+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import org.json.JSONObject+import java.util.concurrent.ConcurrentHashMap+import javax.inject.Inject++class UsbPassthroughManager @Inject constructor(+ @ApplicationContext private val context: Context,+ private val engine: VmEngine,+) {++ /** A device currently handed over to the guest. */+ private data class Entry(+ val connection: UsbDeviceConnection,+ val fdSetId: Int,+ val qemuId: String,+ )++ private val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager+ private val scope = CoroutineScope(+ SupervisorJob() + Dispatchers.IO ++ CoroutineExceptionHandler { _, e -> Log.e(TAG, "USB passthrough coroutine failed", e) }+ )+ private val mutex = Mutex()++ /** Keyed by UsbDevice.deviceName (the stable /dev/bus/usb/... path). */+ private val active = ConcurrentHashMap<String, Entry>()++ @Volatile private var started = false++ private val receiver = object : BroadcastReceiver() {+ override fun onReceive(ctx: Context, intent: Intent) {+ val device = intent.usbDevice() ?: return+ when (intent.action) {+ ACTION_USB_PERMISSION -> {+ val granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)+ if (granted) {+ scope.launch { attach(device) }+ } else {+ Log.i(TAG, "USB permission denied for ${device.deviceName}")+ }+ }+ UsbManager.ACTION_USB_DEVICE_ATTACHED -> requestAndAttach(device)+ UsbManager.ACTION_USB_DEVICE_DETACHED -> scope.launch { detach(device.deviceName) }+ }+ }+ }++ /**+ * Begin watching for USB devices and pass through anything already plugged+ * in. Called once the VM reaches the Running state. Idempotent.+ */+ fun start() {+ if (started) return+ started = true+ val filter = IntentFilter().apply {+ addAction(ACTION_USB_PERMISSION)+ addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)+ addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)+ }+ ContextCompat.registerReceiver(context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED)+ Log.d(TAG, "USB passthrough armed — scanning ${usbManager.deviceList.size} connected device(s)")+ for (device in usbManager.deviceList.values) requestAndAttach(device)+ }++ /**+ * Stop watching and release every device. Called when the VM leaves the+ * Running state. The QEMU process is being torn down anyway, so the guest+ * side needs no device_del — just unwind the Android-side handles.+ */+ fun stop() {+ if (!started) return+ started = false+ runCatching { context.unregisterReceiver(receiver) }+ val entries = active.values.toList()+ active.clear()+ for (e in entries) runCatching { e.connection.close() }+ scope.cancel()+ Log.d(TAG, "USB passthrough disarmed — released ${entries.size} device(s)")+ }++ private fun requestAndAttach(device: UsbDevice) {+ if (active.containsKey(device.deviceName)) return+ if (usbManager.hasPermission(device)) {+ scope.launch { attach(device) }+ } else {+ // No manifest device filter — we ask for consent explicitly. The+ // result comes back through `receiver` as ACTION_USB_PERMISSION.+ var flags = PendingIntent.FLAG_UPDATE_CURRENT+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ flags = flags or PendingIntent.FLAG_MUTABLE+ }+ val pending = PendingIntent.getBroadcast(+ context,+ 0,+ Intent(ACTION_USB_PERMISSION).setPackage(context.packageName),+ flags,+ )+ usbManager.requestPermission(device, pending)+ }+ }++ private suspend fun attach(device: UsbDevice) {+ mutex.withLock {+ if (!started || engine.state.value !is VmState.Running) return+ if (active.containsKey(device.deviceName)) return++ val qmp = engine.qmpClient+ if (qmp == null) {+ Log.w(TAG, "No QMP client — USB passthrough needs the QEMU backend")+ return+ }+ val connection = usbManager.openDevice(device)+ if (connection == null) {+ Log.w(TAG, "openDevice() failed for ${device.deviceName}")+ return+ }++ // fromFd() dups the descriptor; QEMU receives its own dup via+ // SCM_RIGHTS, so this local copy is closed right after the add-fd write.+ val pfd = ParcelFileDescriptor.fromFd(connection.fileDescriptor)+ try {+ val fdSetId = qmp.addFd(pfd.fileDescriptor).getOrElse { e ->+ Log.w(TAG, "add-fd failed for ${device.deviceName}", e)+ connection.close()+ return+ }+ val qemuId = "podroid_usb_${device.deviceId}"+ val args = JSONObject()+ .put("driver", "usb-host")+ .put("id", qemuId)+ .put("hostdevice", "/dev/fdset/$fdSetId")+ qmp.deviceAdd(args).onFailure { e ->+ Log.w(TAG, "device_add usb-host failed for ${device.deviceName}", e)+ qmp.removeFd(fdSetId)+ connection.close()+ return+ }+ active[device.deviceName] = Entry(connection, fdSetId, qemuId)+ Log.i(TAG, "Passed USB device ${device.deviceName} -> guest ($qemuId)")+ } finally {+ runCatching { pfd.close() }+ }+ }+ }++ private suspend fun detach(deviceName: String) {+ mutex.withLock {+ val entry = active.remove(deviceName) ?: return+ engine.qmpClient?.let { qmp ->+ qmp.deviceDel(entry.qemuId)+ qmp.removeFd(entry.fdSetId)+ }+ runCatching { entry.connection.close() }+ Log.i(TAG, "Released USB device $deviceName from guest")+ }+ }++ @Suppress("DEPRECATION")+ private fun Intent.usbDevice(): UsbDevice? =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ getParcelableExtra(UsbManager.EXTRA_DEVICE, UsbDevice::class.java)+ } else {+ getParcelableExtra(UsbManager.EXTRA_DEVICE)+ }++ companion object {+ private const val TAG = "UsbPassthrough"+ private const val ACTION_USB_PERMISSION = "com.excp.podroid.action.USB_PERMISSION"+ }+}diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.ktindex 03b798f..89b685d 100644--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt@@ -33,6 +33,7 @@ import com.excp.podroid.data.repository.SettingsRepositoryimport com.excp.podroid.engine.VmConfigimport com.excp.podroid.engine.VmEngineimport com.excp.podroid.engine.VmState+import com.excp.podroid.engine.usb.UsbPassthroughManagerimport com.excp.podroid.util.NetworkUtilsimport com.excp.podroid.x11.X11Constantsimport dagger.hilt.android.AndroidEntryPoint@@ -46,6 +47,7 @@ class PodroidService : Service() {@Inject lateinit var engine: VmEngine@Inject lateinit var portForwardRepository: PortForwardRepository@Inject lateinit var settingsRepository: SettingsRepository+ @Inject lateinit var usbPassthroughManager: UsbPassthroughManagerprivate val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)private var notificationJob: Job? = null@@ -128,6 +130,7 @@ class PodroidService : Service() {override fun onDestroy() {super.onDestroy()notificationJob?.cancel()+ usbPassthroughManager.stop()releaseWakeLock()serviceScope.cancel()}@@ -244,6 +247,22 @@ class PodroidService : Service() {}}+ /**+ * Arms USB passthrough once the VM is Running and tears it down when the VM+ * reaches a terminal state. Only launched when the feature is enabled, so+ * the BroadcastReceiver is live strictly while a VM session is up.+ */+ private suspend fun observeStateForUsb() {+ engine.state.collect { state ->+ when (state) {+ is VmState.Running -> usbPassthroughManager.start()+ is VmState.Stopped, is VmState.Idle, is VmState.Error ->+ usbPassthroughManager.stop()+ else -> {}+ }+ }+ }+private fun launchPodroid() {serviceScope.launch {startNotificationUpdates()@@ -283,7 +302,11 @@ class PodroidService : Service() {kernelExtraCmdline = settingsRepository.getKernelExtraCmdlineSnapshot(),verboseLogging = settingsRepository.getAvfVerboseLoggingSnapshot(),x11Dpi = settingsRepository.getX11DpiSnapshot(),+ usbPassthroughEnabled = settingsRepository.getUsbPassthroughEnabledSnapshot(),)+ if (config.usbPassthroughEnabled) {+ serviceScope.launch { observeStateForUsb() }+ }engine.start(rules, config)} catch (e: Exception) {Log.e(TAG, "QEMU failed to start", e)diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.ktindex 5d0857a..bd198cd 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsScreen.kt@@ -294,6 +294,31 @@ fun SettingsScreen(onKernelReset = viewModel::resetKernelExtraCmdline,enabled = vmNotRunning,)++ PodroidSectionLabel("USB passthrough")+ val usbPassthrough by viewModel.usbPassthroughEnabled.collectAsStateWithLifecycle()+ PodroidListRow(+ label = "USB device passthrough",+ rightSlot = {+ PodroidSwitch(+ checked = usbPassthrough,+ onCheckedChange = { viewModel.setUsbPassthroughEnabled(it) },+ enabled = vmNotRunning,+ )+ },+ )+ Text(+ text = "Hot-plugs external USB devices into the running VM. Each device " ++ "asks for permission when attached. Adds a USB controller at boot — " ++ "restart the VM to apply. Requires a libusb-enabled QEMU build.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(+ start = PodroidTokens.Spacing.MD,+ end = PodroidTokens.Spacing.MD,+ bottom = PodroidTokens.Spacing.SM,+ ),+ )}// ── ABOUT ─────────────────────────────────────────────diff --git a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.ktindex 263baf8..d22b2b4 100644--- a/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/excp/podroid/ui/screens/settings/SettingsViewModel.kt@@ -171,6 +171,13 @@ class SettingsViewModel @Inject constructor(viewModelScope.launch { settingsRepository.setAvfVerboseLogging(value) }}+ val usbPassthroughEnabled: StateFlow<Boolean> = settingsRepository.usbPassthroughEnabled+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), false)++ fun setUsbPassthroughEnabled(value: Boolean) {+ viewModelScope.launch { settingsRepository.setUsbPassthroughEnabled(value) }+ }+fun setVmRamMb(value: Int) {viewModelScope.launch { settingsRepository.setVmRamMb(value) }}diff --git a/podroid_kernel.config b/podroid_kernel.configindex 368c2a2..cfd8e3c 100644--- a/podroid_kernel.config+++ b/podroid_kernel.config@@ -181,24 +181,204 @@ CONFIG_CRYPTO_SHA256=yCONFIG_CRYPTO_AES=yCONFIG_CRYPTO_GHASH_ARM64_CE=y-# ── Disable: display / audio / input (no display in -display none) ───────────-# CONFIG_SOUND is not set+# ── Disable: display (headless — QEMU runs with -display none) ───────────────# CONFIG_DRM is not set# CONFIG_FB is not set# CONFIG_FRAMEBUFFER_CONSOLE is not set-# CONFIG_HID is not set-# CONFIG_INPUT_KEYBOARD is not set-# CONFIG_INPUT_MOUSE is not set-# ── Disable: USB / wireless / Bluetooth (not present in QEMU virt) ───────────-# CONFIG_USB_SUPPORT is not set-# CONFIG_WIRELESS is not set-# CONFIG_CFG80211 is not set-# CONFIG_BT is not set+# ──────────────────────────────────────────────────────────────────────────────+# USB host stack + passthrough device drivers+#+# When USB passthrough is enabled, QEMU attaches a qemu-xhci (PCIe XHCI)+# controller and UsbPassthroughManager hot-plugs real Android USB devices into+# the guest at runtime (QMP add-fd + device_add usb-host). The guest kernel+# binds a class driver to whatever is passed through, so every USB device+# class is built in here — storage, input/HID, serial adapters, network+# dongles, audio, webcams, printers, Bluetooth and Wi-Fi. All =y so a device+# can appear before the modprobe-free init has any chance to load a module.+# ──────────────────────────────────────────────────────────────────────────────++# ── Compressed firmware ──────────────────────────────────────────────────────+# Alpine ships /lib/firmware zstd-compressed (e.g. rtw8821a_fw.bin.zst). The+# firmware loader only tries a compressed file as a fallback, and only when+# this is enabled — without it USB Wi-Fi/Bluetooth drivers fail probe with+# -ENOENT even though the firmware package is installed.+CONFIG_FW_LOADER_COMPRESS=y+CONFIG_FW_LOADER_COMPRESS_ZSTD=y++# ── USB core + host controllers ──────────────────────────────────────────────+CONFIG_USB_SUPPORT=y+CONFIG_USB=y+CONFIG_USB_PCI=y+CONFIG_USB_ANNOUNCE_NEW_DEVICES=y+CONFIG_USB_DEFAULT_PERSIST=y+CONFIG_USB_MON=y+CONFIG_USB_XHCI_HCD=y+CONFIG_USB_XHCI_PCI=y+CONFIG_USB_EHCI_HCD=y+CONFIG_USB_EHCI_PCI=y+CONFIG_USB_OHCI_HCD=y+CONFIG_USB_OHCI_HCD_PCI=y+CONFIG_USB_UHCI_HCD=y++# ── Input + HID (keyboards, mice, touchpads, gamepads, tablets) ──────────────+CONFIG_INPUT=y+CONFIG_INPUT_EVDEV=y+CONFIG_INPUT_KEYBOARD=y+CONFIG_INPUT_MOUSE=y+CONFIG_INPUT_JOYDEV=y+CONFIG_INPUT_JOYSTICK=y+CONFIG_INPUT_TABLET=y+CONFIG_INPUT_TOUCHSCREEN=y+CONFIG_INPUT_MISC=y+CONFIG_HID=y+CONFIG_HID_GENERIC=y+CONFIG_HID_MULTITOUCH=y+CONFIG_HIDRAW=y+CONFIG_USB_HID=y+CONFIG_USB_HIDDEV=y++# ── USB mass storage (sits on SCSI) + removable-media filesystems ────────────+CONFIG_SCSI=y+CONFIG_BLK_DEV_SD=y+CONFIG_BLK_DEV_SR=y+CONFIG_CHR_DEV_SG=y+CONFIG_USB_STORAGE=y+CONFIG_USB_UAS=y+CONFIG_FAT_FS=y+CONFIG_VFAT_FS=y+CONFIG_EXFAT_FS=y+CONFIG_NTFS3_FS=y+CONFIG_ISO9660_FS=y+CONFIG_UDF_FS=y+CONFIG_NLS_CODEPAGE_437=y+CONFIG_NLS_ISO8859_1=y+CONFIG_NLS_UTF8=y++# ── USB serial converters (FTDI / Prolific / Silabs / WCH …) + CDC-ACM ───────+CONFIG_USB_ACM=y+CONFIG_USB_SERIAL=y+CONFIG_USB_SERIAL_GENERIC=y+CONFIG_USB_SERIAL_FTDI_SIO=y+CONFIG_USB_SERIAL_PL2303=y+CONFIG_USB_SERIAL_CP210X=y+CONFIG_USB_SERIAL_CH341=y+CONFIG_USB_SERIAL_OPTION=y+CONFIG_USB_SERIAL_QUALCOMM=y+CONFIG_USB_SERIAL_SIERRAWIRELESS=y++# ── Wired USB network adapters ───────────────────────────────────────────────+CONFIG_USB_NET_DRIVERS=y+CONFIG_USB_USBNET=y+CONFIG_USB_NET_AX8817X=y+CONFIG_USB_NET_AX88179_178A=y+CONFIG_USB_NET_CDCETHER=y+CONFIG_USB_NET_CDC_EEM=y+CONFIG_USB_NET_CDC_NCM=y+CONFIG_USB_NET_CDC_MBIM=y+CONFIG_USB_NET_RNDIS_HOST=y+CONFIG_USB_RTL8150=y+CONFIG_USB_RTL8152=y+CONFIG_USB_LAN78XX=y+CONFIG_USB_NET_SMSC75XX=y+CONFIG_USB_NET_SMSC95XX=y+CONFIG_USB_NET_DM9601=y+CONFIG_USB_NET_MCS7830=y+CONFIG_USB_CATC=y+CONFIG_USB_KAWETH=y+CONFIG_USB_PEGASUS=y+CONFIG_USB_IPHETH=y++# ── USB audio / MIDI ─────────────────────────────────────────────────────────+CONFIG_SOUND=y+CONFIG_SND=y+CONFIG_SND_USB=y+CONFIG_SND_USB_AUDIO=y++# ── USB video — UVC webcams ──────────────────────────────────────────────────+CONFIG_MEDIA_SUPPORT=y+CONFIG_MEDIA_USB_SUPPORT=y+CONFIG_MEDIA_CAMERA_SUPPORT=y+CONFIG_VIDEO_DEV=y+CONFIG_USB_VIDEO_CLASS=y++# ── USB printers ─────────────────────────────────────────────────────────────+CONFIG_USB_PRINTER=y++# ── Bluetooth over USB ───────────────────────────────────────────────────────+CONFIG_BT=y+CONFIG_BT_RFCOMM=y+CONFIG_BT_BNEP=y+CONFIG_BT_HIDP=y+CONFIG_BT_HCIBTUSB=y+CONFIG_BT_HCIBTUSB_BCM=y+CONFIG_BT_HCIBTUSB_RTL=y+CONFIG_BT_HCIBTUSB_MTK=y++# ── Wi-Fi over USB — wireless core + common USB dongle families ──────────────+# RFKILL must be =y: cfg80211/mac80211/BT carry `depends on RFKILL || !RFKILL`,+# which evaluates to `m` when RFKILL=m and silently caps the whole wireless ++# Bluetooth stack (and every driver above it) down to a module. Podroid has no+# module-loading path for these, so a demoted driver is a dead driver.+CONFIG_RFKILL=y+CONFIG_WIRELESS=y+CONFIG_CFG80211=y+CONFIG_MAC80211=y+CONFIG_WLAN=y+CONFIG_WLAN_VENDOR_ATH=y+CONFIG_ATH9K_HTC=y+CONFIG_CARL9170=y+CONFIG_AR5523=y+CONFIG_WLAN_VENDOR_BROADCOM=y+CONFIG_BRCMFMAC=y+CONFIG_BRCMFMAC_USB=y+CONFIG_WLAN_VENDOR_INTERSIL=y+CONFIG_P54_COMMON=y+CONFIG_P54_USB=y+CONFIG_WLAN_VENDOR_MARVELL=y+CONFIG_MWIFIEX=y+CONFIG_MWIFIEX_USB=y+CONFIG_LIBERTAS=y+CONFIG_LIBERTAS_USB=y+CONFIG_WLAN_VENDOR_MEDIATEK=y+CONFIG_MT7601U=y+CONFIG_MT76x0U=y+CONFIG_MT76x2U=y+CONFIG_MT7921U=y+CONFIG_WLAN_VENDOR_RALINK=y+CONFIG_RT2X00=y+CONFIG_RT2500USB=y+CONFIG_RT73USB=y+CONFIG_RT2800USB=y+CONFIG_RT2800USB_RT33XX=y+CONFIG_RT2800USB_RT35XX=y+CONFIG_RT2800USB_RT3573=y+CONFIG_RT2800USB_RT53XX=y+CONFIG_RT2800USB_RT55XX=y+CONFIG_RT2800USB_UNKNOWN=y+CONFIG_WLAN_VENDOR_REALTEK=y+CONFIG_RTL8187=y+CONFIG_RTL8XXXU=y+CONFIG_RTL_CARDS=y+CONFIG_RTL8192CU=y+CONFIG_RTW88=y+CONFIG_RTW88_8822BU=y+CONFIG_RTW88_8822CU=y+CONFIG_RTW88_8723DU=y+CONFIG_RTW88_8821CU=y+# AU-series USB adapters (RTL8821AU / RTL8812AU / RTL8814AU) — e.g. the many+# TP-Link Archer T2U/T4U dongles. Separate drivers from the *CU/*BU ones.+CONFIG_RTW88_8821AU=y+CONFIG_RTW88_8812AU=y+CONFIG_RTW88_8814AU=y+CONFIG_WLAN_VENDOR_ZYDAS=y+CONFIG_ZD1211RW=y+CONFIG_WLAN_VENDOR_ATMEL=y+CONFIG_AT76C50X_USB=y+CONFIG_USB_NET_RNDIS_WLAN=y-# ── Disable: storage buses not used (virtio-blk only) ────────────────────────+# ── Disable: storage buses not used (virtio-blk + USB only) ──────────────────# CONFIG_ATA is not set-# CONFIG_SCSI_LOWLEVEL is not set# CONFIG_MMC is not set# CONFIG_MEMSTICK is not set@@ -208,8 +388,11 @@ CONFIG_CRYPTO_GHASH_ARM64_CE=y# CONFIG_CAN is not set# CONFIG_NFC is not set# CONFIG_INFINIBAND is not set-# CONFIG_NEW_LEDS is not set-# CONFIG_LEDS_CLASS is not set+# LED class is built in (=y, not =m): rtl8xxxu carries `depends on LEDS_CLASS`+# and mac80211/rtw88 select it, so a module-level LEDS_CLASS caps those USB+# Wi-Fi drivers down to =m — same dead-driver trap as RFKILL above.+CONFIG_NEW_LEDS=y+CONFIG_LEDS_CLASS=y# CONFIG_EDAC is not set# CONFIG_W1 is not set# CONFIG_PCCARD is not setdiff --git a/skill.md b/skill.mdindex 5e80416..7d099b2 100644--- a/skill.md+++ b/skill.md@@ -479,6 +479,7 @@ adb shell run-as com.excp.podroid.debug cat files/console.log| `storage_access_enabled` | Boolean | false | Downloads sharing via virtio-9p || `setup_done` | Boolean | false | Initial setup completed || `ssh_enabled` | Boolean | false | Dropbear SSH in VM |+| `usb_passthrough_enabled` | Boolean | false | Hot-plug USB devices into the VM (adds `-device qemu-xhci`; QEMU backend only) || `port_forwards` | Set\<String\> | {} | `"tcp:8080:80"` format || `dismissed_update_version` | String | "" | Last dismissed update version |