From f1b51523547fa139ee4c22be3b2d405d7f34dde0 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:39:15 +0530 Subject: [PATCH 01/17] feat: automatic usb sessions (enable once) `lfa usb enable -i NAME` now also turns on automatic mode. The launchers (`lfa shell` via terminal-linux and `lfa desktop` via start-linux) call lfa-usb-auto before doing anything: it takes the real descriptor from Termux:API, prepares the synthetic sysfs tree once per device (later sessions reuse it), and re-runs the launcher with the proot binds and the guest preload exported. No attach, no manual scp, no DISPLAY juggling: GUI programs started from the desktop inherit the same device view. Sessions still start normally when nothing is plugged in, when the preload cannot be built, or when the instance is not the one enabled. `lfa usb disable` turns the mode off and removes lfa-usb-auto. Also extracts the attach descriptor prep into lfa_usb_prep_sysfs so the attach and automatic paths share one implementation. --- CHANGELOG.md | 9 ++ README.md | 4 +- docs/TEST-REPORT.md | 4 +- docs/USB.md | 35 +++++- install_linux.sh | 254 ++++++++++++++++++++++++++++++++++++-------- tests/test-all.sh | 26 +++++ tracker.md | 4 +- 7 files changed, 283 insertions(+), 53 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb9e898..dbefc6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,15 @@ tag names, define the order. See the table at the bottom. ### Added +- USB automatic mode. `lfa usb enable -i NAME` now makes every later session + that LFA starts (`lfa shell`, `lfa desktop`, the Terminal shortcut) open + with the plugged-in device already available: the launchers call + `lfa-usb-auto`, which takes the real descriptor from Termux:API, prepares + the synthetic sysfs tree once per device, and re-runs the launcher with + `--bind` flags and the guest preload exported. No `lfa usb attach`, no + environment variables, and GUI programs inherit the same view. Sessions + still start normally when nothing is plugged in; `lfa usb disable` turns + the mode off again. - `lfa appimage` (alias `lfa app`) adds first-class AppImage support. `add` extracts an AppImage once into `~/.local/opt/appimages`, writes a launcher in `~/.local/bin`, and adds a desktop entry; `list`, `run`, and `remove` diff --git a/README.md b/README.md index 52a8352..3f0d9f3 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `811` checks with 0 failures. The same suite runs on the +> The test suite runs `826` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=811 FAIL=0 +./tests/test-all.sh # expect: PASS=826 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index 662877c..a8970b4 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=811 FAIL=0`. +> Current development suite: `PASS=826 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=811 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=826 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 32c534d..131ab66 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -93,6 +93,39 @@ lfa usb flash write 0x0 /sdcard/firmware.bin shell) inside the guest. `lfa usb list` still works without any session: it reads the published bridge and needs no permission dialog. +## Automatic mode: enable once + +`lfa usb enable -i NAME` also turns on automatic mode. After that, every +session LFA starts — `lfa shell`, `lfa desktop` (and the Terminal shortcut, +which use the same launchers) — is opened with the device already inside: +no `lfa usb attach`, no `lfa usb scan`, no environment variables. + +```bash +lfa usb enable -i ubuntu-5623 # once +lfa desktop -i ubuntu-5623 # lsusb, PyUSB, esptool: already there +lfa shell -i ubuntu-5623 # same +``` + +How it works: the launchers call `lfa-usb-auto`, which asks Termux:API for +the descriptor, prepares the synthetic sysfs tree once per device (it is +reused by later sessions), and re-runs the launcher with `--bind` flags and +the guest preload exported. If no device is plugged in, the session starts +normally. GUI programs inherit the same view, so a serial tool opened from +the desktop menu sees `/dev/bus/usb/...` like any other process in that +session. + +Limits of automatic mode: + +- Android still asks for permission per device and connection. Tick "always + allow for this app" to stop the repeat dialogs; LFA cannot bypass them. +- Only sessions started through LFA get the view. A bare + `proot-distro login` is untouched. +- One device per session, as everywhere else in this bridge. Automatic + mode follows the instance you enabled; a session for a different distro + starts without it. +- `lfa usb disable -i NAME` turns automatic mode off again and removes + `lfa-usb-auto`. + ## Commands ``` @@ -101,7 +134,7 @@ lfa usb list [--json] live devices; descriptors when already cached lfa usb refresh re-read `termux-usb -l` and rewrite the guest view lfa usb scan [DEV...] request permission and read real descriptors lfa usb watch [--interval N] poll for hotplug, print add/remove events -lfa usb enable [-i NAME] install helpers, preload, and the tty bridge +lfa usb enable [-i NAME] install helpers, preload, tty bridge, auto mode lfa usb disable [-i NAME] remove those helpers lfa usb attach [DEV] [-- CMD] session with /dev/bus/usb/BBB/DDD and sysfs lfa usb tty [DEV] [-- CMD] session with /dev/ttyUSB0 diff --git a/install_linux.sh b/install_linux.sh index 4709bb0..ba0dbde 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2752,7 +2752,7 @@ Usage: lfa usb [options] scan [DEV...] request permission and read real descriptors watch [--interval N] [--count N] poll for hotplug and print add/remove events - enable [-i NAME] install the guest helpers, libusb preload, tty bridge + enable [-i NAME] install helpers, preload, tty bridge, auto mode disable [-i NAME] remove those guest helpers attach [DEV] [-- CMD...] open a guest session with /dev/bus/usb/BBB/DDD tty [DEV] [-- CMD...] open a session with /dev/ttyUSB0 (serial bridge) @@ -2767,7 +2767,8 @@ Examples: lfa usb status lfa usb refresh lfa usb scan - lfa usb enable -i ubuntu + lfa usb enable -i ubuntu # once: helpers and automatic mode + lfa desktop -i ubuntu-5623 # USB already inside; no attach needed lfa usb attach # shell with a real /dev/bus/usb + sysfs lfa usb attach 001/002 -- lsusb -v lfa usb tty # shell with /dev/ttyUSB0 @@ -2918,6 +2919,7 @@ lfa_usb_status() { echo " live refresh: $_refresh" echo " bridge directory: $LFA_USB_BRIDGE" echo " guest helpers: $_shims" + echo " automatic mode: $(lfa_usb_conf_get USB_AUTO | grep -qx 1 && echo "on (sessions get the device)" || echo "off")" echo " libusb preload: $_preload" echo " last scan: $_last" echo " USB fd in this shell: $_fd_now" @@ -3139,6 +3141,8 @@ lfa_usb_enable() { echo "[!] Rootfs missing for $_id." >&2 return 1 fi + lfa_usb_conf_set USB_AUTO "1" + lfa_usb_write_auto_wrapper || true mkdir -p "$_root/usr/local/bin" "$_root/usr/local/libexec" 2>/dev/null || true lfa_usb_shim_safe "$_root/usr/local/bin/lsusb" || return 1 lfa_usb_shim_safe "$_root/usr/local/bin/lfa-usb" || return 1 @@ -3488,6 +3492,10 @@ LFAUSB echo " Serial: lfa usb tty (real /dev/ttyUSB0)" echo " Flash: lfa usb flash --install" echo " Raw fd: lfa usb exec 001/002 -- lfa-usb desc" + echo "" + echo "[*] Automatic mode is on: lfa shell and lfa desktop now start with" + echo " the plugged-in device already inside. Plug it in, then open a" + echo " session; no lfa usb attach needed. Off: lfa usb disable -i $_id" } lfa_usb_disable() { @@ -3504,6 +3512,8 @@ lfa_usb_disable() { return 1 fi _id="$INSTANCE_NAME" + lfa_usb_conf_set USB_AUTO "0" + rm -f "$PREFIX/bin/lfa-usb-auto" 2>/dev/null || true _root="$(pd_rootfs "$_id")" for _f in "usr/local/bin/lsusb" "usr/local/bin/lfa-usb"; do if [ -f "$_root/$_f" ] && grep -q 'LFA USB bridge' "$_root/$_f" 2>/dev/null; then @@ -3932,6 +3942,144 @@ lfa_usb_install_esptool() { # $1 = optional instance return 0 } +lfa_usb_sys_bind() { # print the /sys/bus bind spec when the tree is ready + if [ -d "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" ] && \ + [ -n "$(ls -A "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" 2>/dev/null)" ]; then + mkdir -p "$LFA_USB_BRIDGE/sysroot/class" 2>/dev/null || true + printf '%s/bus:/sys/bus\n' "$LFA_USB_BRIDGE/sysroot" + fi +} + +lfa_usb_prep_sysfs() { # instance user bus dev path speed + local _id="$1" _user="$2" _bus="$3" _devn="$4" _dev="$5" _speed="$6" + local _prep_rc=0 + rm -rf "$LFA_USB_BRIDGE/sysroot" 2>/dev/null || true + rm -f "$LFA_USB_BRIDGE/prep-$_bus-$_devn.json" \ + "$LFA_USB_BRIDGE/prep-$_bus-$_devn.tsv" \ + "$LFA_USB_BRIDGE/prep-$_bus-$_devn.bin" 2>/dev/null || true + ( + export LFA_USB_MODE=prep + export LFA_USB_INSTANCE="$_id" + export LFA_USB_USER="$_user" + LFA_USB_PD_FLAGS="$(pd_login_flags)" + export LFA_USB_PD_FLAGS + export LFA_USB_OUT="/tmp/lfa-usb/prep-$_bus-$_devn.json" + export LFA_USB_TSV="/tmp/lfa-usb/prep-$_bus-$_devn.tsv" + export LFA_USB_BLOB="/tmp/lfa-usb/prep-$_bus-$_devn.bin" + export LFA_USB_SYSFS_OUT="/tmp/lfa-usb/sysroot/bus/usb/devices" + export LFA_USB_BUS="$_bus" + export LFA_USB_DEV="$_devn" + export LFA_USB_PATH="$_dev" + export LFA_USB_SPEED="$_speed" + lfa_android_timeout 120 termux-usb -r -E -e "$LFA_USB_CALLBACK" "$_dev" + ) > "$LFA_USB_BRIDGE/prep.log" 2>&1 || _prep_rc=$? + [ -n "$(lfa_usb_sys_bind)" ] && return 0 + echo "[!] Descriptors could not be read; libusb will not see the device." >&2 + if [ -s "$LFA_USB_BRIDGE/prep.log" ]; then + sed 's/^/ /' "$LFA_USB_BRIDGE/prep.log" >&2 + fi + return 1 +} + +lfa_usb_write_auto_wrapper() { + mkdir -p "$PREFIX/bin" 2>/dev/null || return 1 + cat > "$PREFIX/bin/lfa-usb-auto" </dev/null || true +} + +lfa_usb_write_auto_script() { # dst preload bind devbind BBB/DDD -- command... + local _dst="$1" _preload="$2" _bind="$3" _devbind="$4" _map="$5" + shift 5 + [ $# -gt 0 ] || return 1 + { + printf '#!/bin/bash\n' + printf '# Generated by lfa usb auto; deleted when the session ends.\n' + # termux-usb captures the callback's stdout, so keep the session on + # the terminal unless both streams are redirected by the caller. + printf 'if [ ! -t 1 ] && [ -t 2 ]; then exec >&2; fi\n' + printf 'export LFA_USB_AUTO_DONE=1\n' + lfa_usb_fd_prelude + printf 'export LFA_USB_MAP="%s=$TERMUX_USB_FD"\n' "$_map" + [ -n "$_preload" ] && printf 'export LFA_USB_PRELOAD=%q\n' "$_preload" + [ -n "$_bind" ] && printf 'export LFA_USB_BIND=%q\n' "$_bind" + [ -n "$_devbind" ] && printf 'export LFA_USB_DEVBIND=%q\n' "$_devbind" + printf 'exec' + printf ' %q' "$@" + printf '\n' + } > "$_dst" 2>/dev/null || return 1 + chmod 700 "$_dst" 2>/dev/null || true +} + +lfa_usb_auto() { # -- COMMAND... : session entrypoint used by the launchers + local _inst _dev _bd _bus _devn _root _user _shim _preload="" _speed + local _bind="" _devbind="" _script_host + while [ $# -gt 0 ]; do + case "$1" in + -h|--help) echo "Usage: lfa usb auto -- COMMAND..." >&2; return 0 ;; + --) shift; break ;; + *) break ;; + esac + done + [ $# -gt 0 ] || return 2 + # Anything that cannot be prepared must still start the session: a + # missing device is not an error for a desktop or a shell. + if [ "${LFA_USB_AUTO_DONE:-}" = "1" ] || \ + [ "$(lfa_usb_conf_get USB_AUTO)" != "1" ]; then + LFA_USB_AUTO_DONE=1 exec "$@" + fi + _inst="$(lfa_usb_conf_instance)" + _dev="$(lfa_usb_default_dev)" + if [ -z "$_inst" ] || [ -z "$_dev" ] || ! lfa_usb_api_ok || ! lfa_usb_export_ok; then + LFA_USB_AUTO_DONE=1 exec "$@" + fi + _dev="$(lfa_usb_normalize_dev "$_dev")" + _bd="$(lfa_usb_bus_dev "$_dev")" + _root="$(pd_rootfs "$_inst" 2>/dev/null || true)" + if [ -z "$_bd" ] || [ -z "$_root" ] || [ ! -d "$_root" ]; then + LFA_USB_AUTO_DONE=1 exec "$@" + fi + _bus="$(lfa_usb_pad3 "${_bd%% *}")" + _devn="$(lfa_usb_pad3 "${_bd##* }")" + _user="$(lfa_appimage_user "$_inst" 2>/dev/null || echo user)" + lfa_usb_stage_desc "$_root" 2>/dev/null || true + lfa_usb_stage_tty "$_root" 2>/dev/null || true + _shim="$(lfa_usb_build_shim "$_root" 2>/dev/null || true)" + if [ -n "$_shim" ] && lfa_usb_stage_shim "$_root" "$_shim"; then + _preload="$LFA_USB_SHIM_GUEST" + fi + lfa_usb_write_callback 2>/dev/null || true + mkdir -p "$LFA_USB_BRIDGE" 2>/dev/null || true + lfa_usb_prepare_nodes "$_root" "$_bus" "$_devn" 0 + [ -f "$LFA_USB_BRIDGE/dev/bus/usb/$_bus/$_devn" ] && \ + _devbind="$LFA_USB_BRIDGE/dev/bus/usb:/dev/bus/usb" + _speed="$(cat "$LFA_USB_BRIDGE/sys/${_bus}-${_devn}/speed" 2>/dev/null || true)" + case "$_speed" in ''|*[!0-9]*) _speed=480 ;; esac + if [ -n "$_preload" ]; then + # Reuse the tree from an earlier session when it already describes + # this device: the descriptor prep costs a whole guest login. + if [ -d "$LFA_USB_BRIDGE/sysroot/bus/usb/devices/$_bus-$_devn" ]; then + _bind="$(lfa_usb_sys_bind)" + elif lfa_usb_prep_sysfs "$_inst" "$_user" "$_bus" "$_devn" "$_dev" "$_speed"; then + _bind="$(lfa_usb_sys_bind)" + fi + [ -n "$_bind" ] && \ + _devbind="${_devbind:+$_devbind;}$LFA_USB_BRIDGE/sysroot/class:/sys/class" + fi + if [ -z "$_preload" ] || [ -z "$_bind" ]; then + LFA_USB_AUTO_DONE=1 exec "$@" + fi + _script_host="$LFA_USB_BRIDGE/auto-$$.sh" + lfa_usb_write_auto_script "$_script_host" "$_preload" "$_bind" "$_devbind" \ + "$_bus/$_devn" "$@" || { LFA_USB_AUTO_DONE=1 exec "$@"; } + echo "[*] USB: $_bus/$_devn available in this session (auto mode)" + exec termux-usb -r -E -e "$_script_host" "$_dev" +} + lfa_usb_attach() { local _inst="" _user="" _root _id _dev="" _cwd="" _perm=1 _sysfs=1 _rc=0 local _devbind="" @@ -4033,41 +4181,8 @@ lfa_usb_attach() { case "$_speed" in ''|*[!0-9]*) _speed=480 ;; esac if [ "$_sysfs" = 1 ] && [ -n "$_preload" ]; then - rm -rf "$LFA_USB_BRIDGE/sysroot" 2>/dev/null || true - rm -f "$LFA_USB_BRIDGE/prep-$_bus-$_devn.json" \ - "$LFA_USB_BRIDGE/prep-$_bus-$_devn.tsv" \ - "$LFA_USB_BRIDGE/prep-$_bus-$_devn.bin" 2>/dev/null || true - ( - export LFA_USB_MODE=prep - export LFA_USB_INSTANCE="$_id" - export LFA_USB_USER="$_user" - LFA_USB_PD_FLAGS="$(pd_login_flags)" - export LFA_USB_PD_FLAGS - export LFA_USB_OUT="/tmp/lfa-usb/prep-$_bus-$_devn.json" - export LFA_USB_TSV="/tmp/lfa-usb/prep-$_bus-$_devn.tsv" - export LFA_USB_BLOB="/tmp/lfa-usb/prep-$_bus-$_devn.bin" - export LFA_USB_SYSFS_OUT="/tmp/lfa-usb/sysroot/bus/usb/devices" - export LFA_USB_BUS="$_bus" - export LFA_USB_DEV="$_devn" - export LFA_USB_PATH="$_dev" - export LFA_USB_SPEED="$_speed" - lfa_android_timeout 120 termux-usb -r -E -e "$LFA_USB_CALLBACK" "$_dev" - ) > "$LFA_USB_BRIDGE/prep.log" 2>&1 || _prep_rc=$? - # libudev enumerates /sys/bus and /sys/class before it looks at - # /sys/bus/usb/devices, and Android's /sys is not readable for an - # app, so a bind of the devices dir alone fails with EACCES. Bind a - # small readable /sys/bus (which contains our usb/devices tree) and - # an empty /sys/class instead. - if [ -d "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" ] && \ - [ -n "$(ls -A "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" 2>/dev/null)" ]; then - mkdir -p "$LFA_USB_BRIDGE/sysroot/class" 2>/dev/null || true - _bind="$LFA_USB_BRIDGE/sysroot/bus:/sys/bus" - else - echo "[!] Descriptors could not be read; libusb will not see the device." >&2 - if [ -s "$LFA_USB_BRIDGE/prep.log" ]; then - sed 's/^/ /' "$LFA_USB_BRIDGE/prep.log" >&2 - fi - fi + lfa_usb_prep_sysfs "$_id" "$_user" "$_bus" "$_devn" "$_dev" "$_speed" || true + _bind="$(lfa_usb_sys_bind)" fi if [ -n "$_bind" ] && [ -d "$LFA_USB_BRIDGE/sysroot/class" ]; then @@ -4386,6 +4501,7 @@ lfa_cli_usb() { watch|monitor) lfa_usb_watch "$@" ;; enable|install) lfa_usb_enable "$@" ;; disable|remove) lfa_usb_disable "$@" ;; + auto) lfa_usb_auto "$@" ;; exec|run) lfa_usb_exec "$@" ;; attach|shell) lfa_usb_attach "$@" ;; tty|serial) lfa_usb_tty "$@" ;; @@ -7291,6 +7407,26 @@ if ! proot --help 2>&1 | grep -q "sysvipc"; then fi fi +# USB auto mode: `lfa usb enable` is enough. When it is on, lfa-usb-auto +# prepares the device view and re-runs this launcher with the bindings +# exported; without a device it just runs the launcher. +if [ "${LFA_USB_AUTO_DONE:-}" != "1" ] && [ -x "$PREFIX/bin/lfa-usb-auto" ]; then + exec "$PREFIX/bin/lfa-usb-auto" -- "$0" "$@" +fi +USB_BIND=() +[ -n "${LFA_USB_BIND:-}" ] && USB_BIND+=(--bind "$LFA_USB_BIND") +if [ -n "${LFA_USB_DEVBIND:-}" ]; then + _ub_ifs="$IFS"; IFS=';' + for _ub in $LFA_USB_DEVBIND; do [ -n "$_ub" ] && USB_BIND+=(--bind "$_ub"); done + IFS="$_ub_ifs"; unset _ub_ifs _ub +fi +USB_WRAP="" +if [ -n "${LFA_USB_PRELOAD:-}" ] && [ -n "${LFA_USB_MAP:-}" ]; then + USB_WRAP="export LD_PRELOAD=$LFA_USB_PRELOAD; export LFA_USB_MAP=$LFA_USB_MAP; " +fi + +pd_login() { proot-distro login "${USB_BIND[@]}" "$@"; } + # GUI installs can boot the full desktop or drop straight to a shell. # CLI-only installs go directly to a root terminal. LAST_SERVER_FILE="$HOME/.config/linux-for-android/last-server-$INSTANCE_NAME" @@ -7401,10 +7537,10 @@ if [ "$SERVER_MODE" = "both" ] && [ "$MODE" == "desktop" ]; then fi if [ "$MODE" == "root" ]; then - proot-distro login $NO_SYSVIPC $DISTRO --shared-tmp -- /bin/bash -l + pd_login $NO_SYSVIPC $DISTRO --shared-tmp -- /bin/bash -l exit 0 elif [ "$MODE" == "user" ]; then - proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- /bin/bash -l + pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- /bin/bash -l exit 0 fi @@ -7498,15 +7634,15 @@ if [ "$SERVER" == "x11" ]; then # visible instead of hidden. echo "Starting $DISTRO desktop as '$X11_USER' (session log: ~/start-linux-session.log)..." if [ "$DE" == "xfce4" ]; then - nohup proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startxfce4 > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startxfce4 > \$HOME/start-linux-session.log 2>&1; else startxfce4 > \$HOME/start-linux-session.log 2>&1; fi" & + nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startxfce4 > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startxfce4 > \$HOME/start-linux-session.log 2>&1; else startxfce4 > \$HOME/start-linux-session.log 2>&1; fi" & elif [ "$DE" == "lxde" ]; then - nohup proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startlxde > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startlxde > \$HOME/start-linux-session.log 2>&1; else startlxde > \$HOME/start-linux-session.log 2>&1; fi" & + nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- startlxde > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session startlxde > \$HOME/start-linux-session.log 2>&1; else startlxde > \$HOME/start-linux-session.log 2>&1; fi" & elif [ "$DE" == "mate" ]; then - nohup proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- mate-session > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session mate-session > \$HOME/start-linux-session.log 2>&1; else mate-session > \$HOME/start-linux-session.log 2>&1; fi" & + nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export LANG=\${LANG:-C.UTF-8}; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- mate-session > \$HOME/start-linux-session.log 2>&1; elif command -v dbus-launch >/dev/null 2>&1; then dbus-launch --exit-with-session mate-session > \$HOME/start-linux-session.log 2>&1; else mate-session > \$HOME/start-linux-session.log 2>&1; fi" & elif [ "$DE" == "gnome" ]; then # Experimental: gnome-session is skipped (no systemd/logind in proot); # start-gnome-session runs lfa-set-wallpaper then `gnome-shell --x11`. - nohup proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; else /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; fi" & + nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}mkdir -p /tmp/.X11-unix; chmod 1777 /tmp/.X11-unix; export XDG_RUNTIME_DIR=/tmp/xdg-\$USER-$DISTRO; mkdir -p "\$XDG_RUNTIME_DIR"; chmod 700 "\$XDG_RUNTIME_DIR"; export PULSE_SERVER=127.0.0.1; export DISPLAY=:1; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; $VIRGL_ENV if command -v dbus-run-session >/dev/null 2>&1; then dbus-run-session -- /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; else /usr/local/bin/start-gnome-session > \$HOME/start-linux-session.log 2>&1; fi" & fi echo "If the screen stays on the X cursor, the desktop failed to start:" echo " cat ~/start-linux-session.log (inside the distro) for the reason." @@ -7539,7 +7675,7 @@ elif [ "$SERVER" == "vnc" ]; then [ "$DE" = "lxde" ] && VNC_SES="startlxde" [ "$DE" = "mate" ] && VNC_SES="mate-session" [ "$DE" = "gnome" ] && VNC_SES="/usr/local/bin/start-gnome-session" - nohup proot-distro login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "export PULSE_SERVER=127.0.0.1; mkdir -p \$HOME/.vnc \$HOME/.config/tigervnc; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.vnc/config; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.config/tigervnc/config; if command -v vncserver >/dev/null 2>&1; then $VIRGL_ENV vncserver :1; rc=\$?; [ \$rc -eq 0 ] || exit \$rc; else $VIRGL_ENV Xvnc :1 -geometry $RESOLUTION -depth 24 -rfbauth \$HOME/.config/tigervnc/passwd -SecurityTypes VncAuth > \$HOME/.vnc-xvnc.log 2>&1 & sleep 2; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; DISPLAY=:1 dbus-run-session -- $VNC_SES > \$HOME/start-linux-session.log 2>&1; fi; exec sleep 2147483647" > "$VNC_LOG" 2>&1 & + nohup pd_login $NO_SYSVIPC $DISTRO --user "$X11_USER" --shared-tmp -- bash -c "${USB_WRAP}export PULSE_SERVER=127.0.0.1; mkdir -p \$HOME/.vnc \$HOME/.config/tigervnc; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.vnc/config; printf 'geometry=%s\n' '$RESOLUTION' > \$HOME/.config/tigervnc/config; if command -v vncserver >/dev/null 2>&1; then $VIRGL_ENV vncserver :1; rc=\$?; [ \$rc -eq 0 ] || exit \$rc; else $VIRGL_ENV Xvnc :1 -geometry $RESOLUTION -depth 24 -rfbauth \$HOME/.config/tigervnc/passwd -SecurityTypes VncAuth > \$HOME/.vnc-xvnc.log 2>&1 & sleep 2; export XCURSOR_THEME=Adwaita; export XCURSOR_SIZE=24; DISPLAY=:1 dbus-run-session -- $VNC_SES > \$HOME/start-linux-session.log 2>&1; fi; exec sleep 2147483647" > "$VNC_LOG" 2>&1 & echo $! > "$VNC_PIDFILE" printf 'Waiting for VNC on port 5901' for _i in $(seq 1 20); do @@ -7759,6 +7895,24 @@ else lfa_clear_stale_x1() { local _p=999999; [ -f "$PREFIX/tmp/.X1-lock" ] && _p=$(tr -dc '0-9' < "$PREFIX/tmp/.X1-lock" 2>/dev/null); [ -n "$_p" ] && kill -0 "$_p" 2>/dev/null && return 0; rm -f "$PREFIX/tmp/.X11-unix/X1" "$PREFIX/tmp/.X1-lock" 2>/dev/null; } fi +# USB auto mode: `lfa usb enable` is enough. When it is on, lfa-usb-auto +# prepares the device view and re-runs this launcher with the bindings +# exported; without a device it just runs the launcher. +if [ "${LFA_USB_AUTO_DONE:-}" != "1" ] && [ -x "$PREFIX/bin/lfa-usb-auto" ]; then + exec "$PREFIX/bin/lfa-usb-auto" -- "$0" "$@" +fi +USB_BIND=() +[ -n "${LFA_USB_BIND:-}" ] && USB_BIND+=(--bind "$LFA_USB_BIND") +if [ -n "${LFA_USB_DEVBIND:-}" ]; then + _ub_ifs="$IFS"; IFS=';' + for _ub in $LFA_USB_DEVBIND; do [ -n "$_ub" ] && USB_BIND+=(--bind "$_ub"); done + IFS="$_ub_ifs"; unset _ub_ifs _ub +fi +USB_WRAP="" +if [ -n "${LFA_USB_PRELOAD:-}" ] && [ -n "${LFA_USB_MAP:-}" ]; then + USB_WRAP="export LD_PRELOAD=$LFA_USB_PRELOAD; export LFA_USB_MAP=$LFA_USB_MAP; " +fi + TERM_MODE="" EXPLICIT_INSTANCE=0 PRESELECT_INSTANCE="" @@ -7839,9 +7993,17 @@ else read -p "Select [1-2, default 1]: " TERM_CHOICE fi if [ "$TERM_CHOICE" == "2" ]; then - proot-distro login $NO_SYSVIPC $DISTRO --user "$TERM_USER" --shared-tmp -- /bin/bash -l + if [ -n "$USB_WRAP" ]; then + proot-distro login $NO_SYSVIPC "${USB_BIND[@]}" $DISTRO --user "$TERM_USER" --shared-tmp -- bash -c "${USB_WRAP}exec /bin/bash -l" + else + proot-distro login $NO_SYSVIPC "${USB_BIND[@]}" $DISTRO --user "$TERM_USER" --shared-tmp -- /bin/bash -l + fi else - proot-distro login $NO_SYSVIPC $DISTRO --shared-tmp -- /bin/bash -l + if [ -n "$USB_WRAP" ]; then + proot-distro login $NO_SYSVIPC "${USB_BIND[@]}" $DISTRO --shared-tmp -- bash -c "${USB_WRAP}exec /bin/bash -l" + else + proot-distro login $NO_SYSVIPC "${USB_BIND[@]}" $DISTRO --shared-tmp -- /bin/bash -l + fi fi EOF chmod +x $PREFIX/bin/terminal-linux diff --git a/tests/test-all.sh b/tests/test-all.sh index 42f232f..d2ac41f 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -1974,6 +1974,32 @@ timeout 60 python3 "$REPO/tests/usb-tty-plumbing.py" > "$T/y11-tty-plumb.log" 2> [ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y11 tty plumbing exit $rc"; } check "Y11 tty plumbing relay" 'plumbing: ok' "$T/y11-tty-plumb.log" +# Automatic mode: `lfa usb enable` is enough; the launchers ask for the +# device themselves and inject the binds. +"$LFA" usb enable -i debian > "$T/y11-auto-enable.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y11 auto enable exit $rc"; } +check "Y11 auto conf" 'USB_AUTO="1"' "$T/home/.config/linux-for-android/usb.conf" +[ -x "$T/prefix/bin/lfa-usb-auto" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 auto wrapper not installed"; } +"$LFA" usb auto -- sh -c 'echo "bind=${LFA_USB_BIND:-}"; echo "devbind=${LFA_USB_DEVBIND:-}"; echo "map=${LFA_USB_MAP:-}"; echo "preload=${LFA_USB_PRELOAD:-}"' \ + > "$T/y11-auto.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y11 auto exit $rc"; } +check "Y11 auto announced" 'available in this session (auto mode)' "$T/y11-auto.log" +check "Y11 auto sysfs bind" '/lfa-usb/sysroot/bus:/sys/bus' "$T/y11-auto.log" +check "Y11 auto dev bind" 'dev/bus/usb:/dev/bus/usb' "$T/y11-auto.log" +# The fake termux-usb sets TERMUX_USB_FD=9 without opening it, so the map +# keeps that number; a real session re-dups to a free fd first. +check "Y11 auto map" 'map=001/002=9' "$T/y11-auto.log" +check "Y11 auto preload" 'preload=/usr/local/lib/lfa-usb-node.so' "$T/y11-auto.log" +check "Y11 auto terminal hook" 'lfa-usb-auto' "$T/prefix/bin/terminal-linux" +check "Y11 auto terminal binds" 'USB_BIND+=(--bind "$LFA_USB_BIND")' "$T/prefix/bin/terminal-linux" +check "Y11 auto desktop helper" 'pd_login() { proot-distro login "${USB_BIND[@]}" "$@"' "$T/prefix/bin/start-linux" +check "Y11 auto desktop wrap" '${USB_WRAP}mkdir' "$T/prefix/bin/start-linux" +"$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 +check "Y11 auto off" 'USB_AUTO="0"' "$T/home/.config/linux-for-android/usb.conf" +[ ! -e "$T/prefix/bin/lfa-usb-auto" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 auto wrapper survived disable"; } + # The sysfs tree must carry the interface and endpoint directories that # libusb walks, not just the device files. python3 - "$REPO/lib/usb-desc.py" "$T/usb-sysfs" > "$T/y11-sysfs-build.log" 2>&1 <<'PY'; rc=$? diff --git a/tracker.md b/tracker.md index ad82323..9a42a77 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=811 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=826 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=811 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=826 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From cc78d494c1714e3d55e56d5532df46d59adcafe0 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 10:38:02 +0530 Subject: [PATCH 02/17] feat: expose storage cards to sessions `lfa usb storage` lists the volumes Android mounts for apps under /storage/ (the FUSE view), with filesystem, size, free space and a real read/write probe. Sessions started by LFA bind the first card at /mnt/sdcard, further cards at /mnt/, and internal storage at /sdcard, with mount points created inside the rootfs. The binds are exported before every auto-mode exit path, so a card is available even when no USB device (or no preload) is present. The block device itself stays out of reach: Android's usb-storage owns the reader's interface and proot has no block layer, which the docs now state plainly along with the termux-storage-get fallback. Also pins LFA_USB_SYSFS in the suite so a real device on the build host cannot shadow the fake scan cache. --- CHANGELOG.md | 7 ++ README.md | 4 +- docs/TEST-REPORT.md | 4 +- docs/USB.md | 44 ++++++++++++ install_linux.sh | 171 +++++++++++++++++++++++++++++++++++++++++++- tests/test-all.sh | 25 ++++++- tracker.md | 4 +- 7 files changed, 251 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbefc6b..3bd7f77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,13 @@ tag names, define the order. See the table at the bottom. ### Added +- `lfa usb storage` lists the storage cards Android mounts for apps + (`/storage/`), with filesystem, size, free space and a real + read/write probe. Sessions started by LFA bind the first card at + `/mnt/sdcard`, further cards at `/mnt/`, and internal storage at + `/sdcard`, so a card reader behaves like a normal directory in the guest. + Mounting the block device itself stays impossible without root: Android's + `usb-storage` driver owns the interface and proot has no block layer. - USB automatic mode. `lfa usb enable -i NAME` now makes every later session that LFA starts (`lfa shell`, `lfa desktop`, the Terminal shortcut) open with the plugged-in device already available: the launchers call diff --git a/README.md b/README.md index 3f0d9f3..7cbecae 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `826` checks with 0 failures. The same suite runs on the +> The test suite runs `837` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=826 FAIL=0 +./tests/test-all.sh # expect: PASS=837 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index a8970b4..d9fd83e 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=826 FAIL=0`. +> Current development suite: `PASS=837 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=826 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=837 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 131ab66..130dd07 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -133,6 +133,7 @@ lfa usb status Termux:API, host feature, bridge, preload state lfa usb list [--json] live devices; descriptors when already cached lfa usb refresh re-read `termux-usb -l` and rewrite the guest view lfa usb scan [DEV...] request permission and read real descriptors +lfa usb storage [--json] list storage cards Android exposes to apps lfa usb watch [--interval N] poll for hotplug, print add/remove events lfa usb enable [-i NAME] install helpers, preload, tty bridge, auto mode lfa usb disable [-i NAME] remove those helpers @@ -259,6 +260,49 @@ devices and `usb-storage` for mass storage). A userspace claim then fails with this clearly. Native-USB ESP32 bootloaders and CP210x/CH340 boards normally have no bound driver, which is why they work. +## Storage cards (SD, card readers, USB sticks) + +A mass-storage device is the one thing this bridge cannot turn into +`/dev/sdb1`. Android's own `usb-storage` driver claims the reader's +interface and mounts the card at the kernel level; proot has no block +layer, cannot create block nodes, and the guest has no kernel of its own. +Bulk transfers to a claimed interface fail with `EBUSY`, so a userspace +reader cannot reach the files either without root. + +What does work: Android already mounted the card, and on Android 11+ +the FUSE view under `/storage/` is often readable by Termux. +LFA uses that path: + +```bash +lfa usb storage +# VOLUME SIZE FREE FS MODE PATH +# CABC-1701 7.4G 7.4G vfat rw /storage/CABC-1701 + +lfa shell -i ubuntu-5623 +# [*] storage: CABC-1701 -> /mnt/sdcard (rw) +ls /mnt/sdcard +``` + +Sessions started by LFA bind: + +| Path | Contents | +|---|---| +| `/mnt/sdcard` | first storage card Android exposes | +| `/mnt/` | any further cards | +| `/sdcard` | internal phone storage (`/storage/emulated/0`) | + +`lfa usb storage --json` prints the same data for scripts. If +`/storage/` is readable but not writable, the mode column says +`ro`; proot cannot enforce read-only binds, so LFA warns instead of +pretending. Unplugging the card removes the directory contents, exactly +as on a desktop. + +If `/storage/` is denied (some Android builds restrict it), +there is no filesystem path for the app to bind. Use `termux-storage-get +FILE` (opens Android's picker and copies one file into Termux) or copy +with the Files app to internal storage, then bind that. `/mnt/media_rw` +is root/media_rw-only and unusable from Termux. + ## Raw descriptor mode: `lfa usb exec` If the preload cannot be built for a guest, or you want the smallest possible diff --git a/install_linux.sh b/install_linux.sh index ba0dbde..e796eb1 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2750,6 +2750,7 @@ Usage: lfa usb [options] list [--json] list real devices visible through Termux:API refresh re-read `termux-usb -l` and rebuild the guest view scan [DEV...] request permission and read real descriptors + storage [--json] list storage cards Android exposes to apps watch [--interval N] [--count N] poll for hotplug and print add/remove events enable [-i NAME] install helpers, preload, tty bridge, auto mode @@ -2920,6 +2921,12 @@ lfa_usb_status() { echo " bridge directory: $LFA_USB_BRIDGE" echo " guest helpers: $_shims" echo " automatic mode: $(lfa_usb_conf_get USB_AUTO | grep -qx 1 && echo "on (sessions get the device)" || echo "off")" + _vols="$(lfa_usb_storage_rows 2>/dev/null)" + if [ -n "$_vols" ]; then + echo " storage cards: $(printf '%s\n' "$_vols" | awk -F '\t' '{ printf "%s%s (%s, %s)", (n++ ? ", " : ""), $1, $3, $6 }') -> /mnt/sdcard" + else + echo " storage cards: none mounted for apps" + fi echo " libusb preload: $_preload" echo " last scan: $_last" echo " USB fd in this shell: $_fd_now" @@ -3942,6 +3949,118 @@ lfa_usb_install_esptool() { # $1 = optional instance return 0 } +lfa_usb_storage_root() { # where Android exposes volumes to apps + printf '%s\n' "${LFA_STORAGE_ROOT:-/storage}" +} + +lfa_usb_storage_ids() { # volume ids Android exposes under the storage root + local _root _id + _root="$(lfa_usb_storage_root)" + if [ -n "${LFA_STORAGE_ROOT:-}" ]; then + # Tests (and unusual setups) point this at a plain directory. + for _id in "$_root"/*; do + [ -d "$_id" ] || continue + _id="${_id##*/}" + case "$_id" in emulated|self) continue ;; esac + printf '%s\n' "$_id" + done + return 0 + fi + # `/storage` itself is not listable for an app, so read the mount table. + awk -v root="$_root/" 'index($2, root) == 1 { + id = substr($2, length(root) + 1) + sub("/.*", "", id) + if (id != "" && id != "emulated" && id != "self") print id + }' /proc/mounts 2>/dev/null | awk '!seen[$0]++' +} + +lfa_usb_size_h() { # $1 KiB -> short human size + awk -v k="${1:-0}" 'BEGIN { + if (k >= 1048576) printf "%.1fG", k / 1048576 + else if (k >= 1024) printf "%.1fM", k / 1024 + else printf "%dK", k + }' +} + +lfa_usb_storage_rows() { # idpathfssize_kavail_krw + local _root _id _path _fs _size _avail _rw _probe + _root="$(lfa_usb_storage_root)" + lfa_usb_storage_ids | while IFS= read -r _id; do + [ -n "$_id" ] || continue + _path="$_root/$_id" + [ -d "$_path" ] || continue + _fs="$(awk -v p="$_path" '$2 == p { print $3; exit }' /proc/mounts 2>/dev/null)" + [ -n "$_fs" ] || _fs="?" + _size=""; _avail="" + read -r _size _avail </dev/null | awk 'NR == 2 { print $2, $4 }') +EOF + case "$_size" in ''|*[!0-9]*) _size=0 ;; esac + case "$_avail" in ''|*[!0-9]*) _avail=0 ;; esac + # FUSE ignores the mode bits, so probe with a real write. + _rw="ro" + _probe="$_path/.lfa-write-$$" + if ( : > "$_probe" ) 2>/dev/null; then + _rw="rw" + rm -f "$_probe" 2>/dev/null || true + fi + printf '%s\t%s\t%s\t%s\t%s\t%s\n' "$_id" "$_path" "$_fs" "$_size" "$_avail" "$_rw" + done +} + +lfa_usb_storage() { # [--json] + local _json=0 _rows _id _path _fs _size _avail _rw + while [ $# -gt 0 ]; do + case "$1" in + --json) _json=1; shift ;; + -h|--help) echo "Usage: lfa usb storage [--json]" >&2; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + _rows="$(lfa_usb_storage_rows)" + if [ "$_json" = "1" ]; then + printf '%s\n' "$_rows" | awk -F '\t' ' + BEGIN { printf "[" } + NF { printf "%s{\"id\":\"%s\",\"path\":\"%s\",\"fs\":\"%s\",\"size_kb\":%s,\"avail_kb\":%s,\"writable\":%s}", + (n++ ? "," : ""), $1, $2, $3, $4, $5, ($6 == "rw" ? "true" : "false") } + END { print "]" }' + return 0 + fi + if [ -z "$_rows" ]; then + echo "No storage card is mounted for apps." + echo "Plug an OTG reader or card; Android must mount it first." + return 0 + fi + printf '%-12s %8s %8s %-5s %-4s %s\n' VOLUME SIZE FREE FS MODE PATH + printf '%s\n' "$_rows" | while IFS="$(printf '\t')" read -r _id _path _fs _size _avail _rw; do + printf '%-12s %8s %8s %-5s %-4s %s\n' \ + "$_id" "$(lfa_usb_size_h "$_size")" "$(lfa_usb_size_h "$_avail")" \ + "$_fs" "$_rw" "$_path" + done + echo "" + echo "Sessions started by lfa bind the first card at /mnt/sdcard," + echo "internal storage at /sdcard." +} + +lfa_usb_storage_binds() { # host:guest bind specs, ';' separated + local _root _id _guest _n=0 _out="" _ids + _root="$(lfa_usb_storage_root)" + _ids="$(lfa_usb_storage_ids)" + while IFS= read -r _id; do + [ -n "$_id" ] || continue + _n=$((_n + 1)) + if [ "$_n" = "1" ]; then _guest="/mnt/sdcard"; else _guest="/mnt/$_id"; fi + _out="${_out:+$_out;}$_root/$_id:$_guest" + done </dev/null)" ]; then @@ -4026,6 +4145,21 @@ lfa_usb_auto() { # -- COMMAND... : session entrypoint used by the launchers esac done [ $# -gt 0 ] || return 2 + # Storage binds do not need a USB descriptor, so they are exported before + # any of the early exits below: a session always sees a mounted card. + LFA_STORAGE_BIND="$(lfa_usb_storage_binds 2>/dev/null || true)" + [ -n "$LFA_STORAGE_BIND" ] && export LFA_STORAGE_BIND + if [ -n "$LFA_STORAGE_BIND" ]; then + _str_root="$(pd_rootfs "$(lfa_usb_conf_instance)" 2>/dev/null || true)" + if [ -n "$_str_root" ] && [ -d "$_str_root" ]; then + _str_ifs="$IFS"; IFS=';' + for _str_spec in $LFA_STORAGE_BIND; do + [ -n "$_str_spec" ] && mkdir -p "$_str_root${_str_spec##*:}" 2>/dev/null || true + done + IFS="$_str_ifs"; unset _str_ifs _str_spec + fi + unset _str_root + fi # Anything that cannot be prepared must still start the session: a # missing device is not an error for a desktop or a shell. if [ "${LFA_USB_AUTO_DONE:-}" = "1" ] || \ @@ -4501,6 +4635,7 @@ lfa_cli_usb() { watch|monitor) lfa_usb_watch "$@" ;; enable|install) lfa_usb_enable "$@" ;; disable|remove) lfa_usb_disable "$@" ;; + storage|sdcard) lfa_usb_storage "$@" ;; auto) lfa_usb_auto "$@" ;; exec|run) lfa_usb_exec "$@" ;; attach|shell) lfa_usb_attach "$@" ;; @@ -7420,12 +7555,30 @@ if [ -n "${LFA_USB_DEVBIND:-}" ]; then for _ub in $LFA_USB_DEVBIND; do [ -n "$_ub" ] && USB_BIND+=(--bind "$_ub"); done IFS="$_ub_ifs"; unset _ub_ifs _ub fi +if [ -n "${LFA_STORAGE_BIND:-}" ]; then + _st_ifs="$IFS"; IFS=';' + for _st in $LFA_STORAGE_BIND; do [ -n "$_st" ] && USB_BIND+=(--bind "$_st"); done + IFS="$_st_ifs"; unset _st_ifs _st +fi USB_WRAP="" if [ -n "${LFA_USB_PRELOAD:-}" ] && [ -n "${LFA_USB_MAP:-}" ]; then USB_WRAP="export LD_PRELOAD=$LFA_USB_PRELOAD; export LFA_USB_MAP=$LFA_USB_MAP; " fi -pd_login() { proot-distro login "${USB_BIND[@]}" "$@"; } +pd_login() { + if [ -n "${LFA_STORAGE_BIND:-}" ]; then + _st_rfs="$(lfa_rootfs "$DISTRO" 2>/dev/null || true)" + if [ -n "$_st_rfs" ]; then + _st_ifs="$IFS"; IFS=';' + for _st in $LFA_STORAGE_BIND; do + [ -n "$_st" ] && mkdir -p "$_st_rfs${_st##*:}" 2>/dev/null || true + done + IFS="$_st_ifs"; unset _st_ifs _st + fi + unset _st_rfs + fi + proot-distro login "${USB_BIND[@]}" "$@" +} # GUI installs can boot the full desktop or drop straight to a shell. # CLI-only installs go directly to a root terminal. @@ -7908,6 +8061,11 @@ if [ -n "${LFA_USB_DEVBIND:-}" ]; then for _ub in $LFA_USB_DEVBIND; do [ -n "$_ub" ] && USB_BIND+=(--bind "$_ub"); done IFS="$_ub_ifs"; unset _ub_ifs _ub fi +if [ -n "${LFA_STORAGE_BIND:-}" ]; then + _st_ifs="$IFS"; IFS=';' + for _st in $LFA_STORAGE_BIND; do [ -n "$_st" ] && USB_BIND+=(--bind "$_st"); done + IFS="$_st_ifs"; unset _st_ifs _st +fi USB_WRAP="" if [ -n "${LFA_USB_PRELOAD:-}" ] && [ -n "${LFA_USB_MAP:-}" ]; then USB_WRAP="export LD_PRELOAD=$LFA_USB_PRELOAD; export LFA_USB_MAP=$LFA_USB_MAP; " @@ -7992,6 +8150,17 @@ else echo "2) User terminal ('$TERM_USER' account)" read -p "Select [1-2, default 1]: " TERM_CHOICE fi +if [ -n "${LFA_STORAGE_BIND:-}" ]; then + _st_rfs="$(lfa_rootfs "$DISTRO" 2>/dev/null || true)" + if [ -n "$_st_rfs" ]; then + _st_ifs="$IFS"; IFS=';' + for _st in $LFA_STORAGE_BIND; do + [ -n "$_st" ] && mkdir -p "$_st_rfs${_st##*:}" 2>/dev/null || true + done + IFS="$_st_ifs"; unset _st_ifs _st + fi + unset _st_rfs +fi if [ "$TERM_CHOICE" == "2" ]; then if [ -n "$USB_WRAP" ]; then proot-distro login $NO_SYSVIPC "${USB_BIND[@]}" $DISTRO --user "$TERM_USER" --shared-tmp -- bash -c "${USB_WRAP}exec /bin/bash -l" diff --git a/tests/test-all.sh b/tests/test-all.sh index d2ac41f..e095ec8 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -157,6 +157,9 @@ fresh_env() { # reset HOME/PREFIX, keep stubs export HOME="$T/home" PREFIX="$T/prefix" \ PATH="$T/fakebin${REAL_PREFIX:+:$REAL_PREFIX/bin}:/usr/bin:/bin" TERM="" export LFA_KEEP_SETUP_SCRIPT=1 # inspect the generated guest script + # Never read the *host* /sys/bus/usb/devices: a real device at 001/002 + # would shadow the fake scan cache and make the USB checks host-dependent. + export LFA_USB_SYSFS="$T/usb-sysfs-host" unset GETPROP_SDK FREE_MB PD_V4 } run_script() { # $1=logname, rest of stdin via caller pipe; needs $T/tmpin set @@ -1993,8 +1996,28 @@ check "Y11 auto map" 'map=001/002=9' "$T/y11-auto.log" check "Y11 auto preload" 'preload=/usr/local/lib/lfa-usb-node.so' "$T/y11-auto.log" check "Y11 auto terminal hook" 'lfa-usb-auto' "$T/prefix/bin/terminal-linux" check "Y11 auto terminal binds" 'USB_BIND+=(--bind "$LFA_USB_BIND")' "$T/prefix/bin/terminal-linux" -check "Y11 auto desktop helper" 'pd_login() { proot-distro login "${USB_BIND[@]}" "$@"' "$T/prefix/bin/start-linux" +check "Y11 auto desktop helper" 'pd_login() {' "$T/prefix/bin/start-linux" check "Y11 auto desktop wrap" '${USB_WRAP}mkdir' "$T/prefix/bin/start-linux" +# Storage cards Android exposes to apps: list, probe, bind into sessions. +mkdir -p "$T/storage/CABC-1701/DCIM" "$T/storage/emulated/0/Download" +printf 'x' > "$T/storage/CABC-1701/DCIM/photo.jpg" +LFA_STORAGE_ROOT="$T/storage" "$LFA" usb storage > "$T/y11-storage.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y11 storage exit $rc"; } +check "Y11 storage lists card" 'CABC-1701' "$T/y11-storage.log" +check "Y11 storage path" "$T/storage/CABC-1701" "$T/y11-storage.log" +check "Y11 storage rw probe" 'rw' "$T/y11-storage.log" +LFA_STORAGE_ROOT="$T/storage" "$LFA" usb storage --json > "$T/y11-storage.json" 2>&1 +check "Y11 storage json" '"writable":true' "$T/y11-storage.json" +LFA_STORAGE_ROOT="$T/storage" "$LFA" usb auto -- sh -c 'echo "storage=${LFA_STORAGE_BIND:-}"' \ + > "$T/y11-storage-bind.log" 2>&1 +check "Y11 storage bind card" "$T/storage/CABC-1701:/mnt/sdcard" "$T/y11-storage-bind.log" +check "Y11 storage bind internal" "$T/storage/emulated/0:/sdcard" "$T/y11-storage-bind.log" +check "Y11 storage launcher binds" 'LFA_STORAGE_BIND' "$T/prefix/bin/terminal-linux" +check "Y11 storage desktop binds" 'LFA_STORAGE_BIND' "$T/prefix/bin/start-linux" +[ -d "$UROOT/mnt/sdcard" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /mnt/sdcard"; } +[ -d "$UROOT/sdcard" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /sdcard"; } "$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 check "Y11 auto off" 'USB_AUTO="0"' "$T/home/.config/linux-for-android/usb.conf" [ ! -e "$T/prefix/bin/lfa-usb-auto" ] && pass=$((pass+1)) \ diff --git a/tracker.md b/tracker.md index 9a42a77..15ba177 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=826 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=837 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=826 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=837 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From 1f2e40c8b8c310518cc9e905ca2896a3404f802a Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:14:19 +0530 Subject: [PATCH 03/17] fix: keep storage binds clear of proot-distro's own mounts proot-distro v5 already binds /storage and internal storage at /sdcard and /mnt/sdcard, so our /sdcard bind was a duplicate and /mnt/sdcard collided with its destination - proot printed two overlap warnings per session. Cards now go to /media/, with /mnt/card following the largest volume. That also keeps a Ventoy card's 32 MB VTOYEFI partition out of the alias, so /mnt/card is the exFAT data partition where ISOs are copied. Internal storage is left entirely to proot-distro. --- CHANGELOG.md | 5 +++-- README.md | 4 ++-- docs/TEST-REPORT.md | 4 ++-- docs/USB.md | 15 ++++++++++----- install_linux.sh | 34 ++++++++++++++++++++++++---------- tests/test-all.sh | 16 ++++++++++------ tracker.md | 4 ++-- 7 files changed, 53 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3bd7f77..29506a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,8 +18,9 @@ tag names, define the order. See the table at the bottom. - `lfa usb storage` lists the storage cards Android mounts for apps (`/storage/`), with filesystem, size, free space and a real read/write probe. Sessions started by LFA bind the first card at - `/mnt/sdcard`, further cards at `/mnt/`, and internal storage at - `/sdcard`, so a card reader behaves like a normal directory in the guest. + `/media/` and the largest card at `/mnt/card`, avoiding the + `/sdcard` and `/mnt/sdcard` destinations proot-distro already uses for + internal storage. A card reader then behaves like a normal directory. Mounting the block device itself stays impossible without root: Android's `usb-storage` driver owns the interface and proot has no block layer. - USB automatic mode. `lfa usb enable -i NAME` now makes every later session diff --git a/README.md b/README.md index 7cbecae..b6b05f8 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `837` checks with 0 failures. The same suite runs on the +> The test suite runs `839` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=837 FAIL=0 +./tests/test-all.sh # expect: PASS=839 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index d9fd83e..31bf405 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=837 FAIL=0`. +> Current development suite: `PASS=839 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=837 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=839 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 130dd07..8ed3f99 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -279,17 +279,22 @@ lfa usb storage # CABC-1701 7.4G 7.4G vfat rw /storage/CABC-1701 lfa shell -i ubuntu-5623 -# [*] storage: CABC-1701 -> /mnt/sdcard (rw) -ls /mnt/sdcard +# [*] storage: CABC-1701 -> /mnt/card (rw) +ls /mnt/card ``` Sessions started by LFA bind: | Path | Contents | |---|---| -| `/mnt/sdcard` | first storage card Android exposes | -| `/mnt/` | any further cards | -| `/sdcard` | internal phone storage (`/storage/emulated/0`) | +| `/media/` | every storage card Android exposes | +| `/mnt/card` | the largest card, as a stable alias (Ventoy cards: the data partition) | +| `/sdcard` | internal phone storage (proot-distro binds it itself) | +| `/mnt/sdcard` | also internal storage: proot-distro's own bind | + +The card destinations deliberately avoid `/sdcard` and `/mnt/sdcard`: +proot-distro v5 binds internal storage there already and warns when a +destination is used twice. `lfa usb storage --json` prints the same data for scripts. If `/storage/` is readable but not writable, the mode column says diff --git a/install_linux.sh b/install_linux.sh index e796eb1..d3b9aa9 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2923,7 +2923,7 @@ lfa_usb_status() { echo " automatic mode: $(lfa_usb_conf_get USB_AUTO | grep -qx 1 && echo "on (sessions get the device)" || echo "off")" _vols="$(lfa_usb_storage_rows 2>/dev/null)" if [ -n "$_vols" ]; then - echo " storage cards: $(printf '%s\n' "$_vols" | awk -F '\t' '{ printf "%s%s (%s, %s)", (n++ ? ", " : ""), $1, $3, $6 }') -> /mnt/sdcard" + echo " storage cards: $(printf '%s\n' "$_vols" | awk -F '\t' '{ printf "%s%s (%s, %s)", (n++ ? ", " : ""), $1, $3, $6 }') -> /mnt/card" else echo " storage cards: none mounted for apps" fi @@ -4038,25 +4038,39 @@ lfa_usb_storage() { # [--json] "$_fs" "$_rw" "$_path" done echo "" - echo "Sessions started by lfa bind the first card at /mnt/sdcard," - echo "internal storage at /sdcard." + echo "Sessions started by lfa bind every card at /media/," + echo "plus /mnt/card for the first one. Phone storage is /sdcard." +} + +lfa_usb_storage_alias() { # id of the largest exposed volume + local _root _id _size _best="" _best_k=0 + _root="$(lfa_usb_storage_root)" + for _id in $(lfa_usb_storage_ids); do + _size="$(df -k "$_root/$_id" 2>/dev/null | awk 'NR == 2 { print $2 }')" + case "$_size" in ''|*[!0-9]*) continue ;; esac + if [ "$_size" -gt "$_best_k" ]; then + _best="$_id"; _best_k="$_size" + fi + done + [ -n "$_best" ] && printf '%s\n' "$_best" } lfa_usb_storage_binds() { # host:guest bind specs, ';' separated - local _root _id _guest _n=0 _out="" _ids + local _root _id _out="" _ids _alias _root="$(lfa_usb_storage_root)" _ids="$(lfa_usb_storage_ids)" + _alias="$(lfa_usb_storage_alias)" + # proot-distro already binds /storage and internal storage at /sdcard and + # /mnt/sdcard, and warns when a destination is taken twice. So cards go to + # /media/ (the Linux convention) plus /mnt/card for the largest + # one, which keeps a Ventoy card's 32 MB VTOYEFI volume out of the alias. while IFS= read -r _id; do [ -n "$_id" ] || continue - _n=$((_n + 1)) - if [ "$_n" = "1" ]; then _guest="/mnt/sdcard"; else _guest="/mnt/$_id"; fi - _out="${_out:+$_out;}$_root/$_id:$_guest" + _out="${_out:+$_out;}$_root/$_id:/media/$_id" + [ "$_id" = "$_alias" ] && _out="$_out;$_root/$_id:/mnt/card" done < "$T/y11-storage.json" check "Y11 storage json" '"writable":true' "$T/y11-storage.json" LFA_STORAGE_ROOT="$T/storage" "$LFA" usb auto -- sh -c 'echo "storage=${LFA_STORAGE_BIND:-}"' \ > "$T/y11-storage-bind.log" 2>&1 -check "Y11 storage bind card" "$T/storage/CABC-1701:/mnt/sdcard" "$T/y11-storage-bind.log" -check "Y11 storage bind internal" "$T/storage/emulated/0:/sdcard" "$T/y11-storage-bind.log" +# proot-distro already binds internal storage at /sdcard and /mnt/sdcard, so +# the card must use destinations it does not take. +check "Y11 storage bind media" "$T/storage/CABC-1701:/media/CABC-1701" "$T/y11-storage-bind.log" +check "Y11 storage bind alias" "$T/storage/CABC-1701:/mnt/card" "$T/y11-storage-bind.log" +check_absent "Y11 storage no internal bind" "$T/storage/emulated/0:/sdcard" "$T/y11-storage-bind.log" +check_absent "Y11 storage no sdcard collision" ":/mnt/sdcard" "$T/y11-storage-bind.log" check "Y11 storage launcher binds" 'LFA_STORAGE_BIND' "$T/prefix/bin/terminal-linux" check "Y11 storage desktop binds" 'LFA_STORAGE_BIND' "$T/prefix/bin/start-linux" -[ -d "$UROOT/mnt/sdcard" ] && pass=$((pass+1)) \ - || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /mnt/sdcard"; } -[ -d "$UROOT/sdcard" ] && pass=$((pass+1)) \ - || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /sdcard"; } +[ -d "$UROOT/mnt/card" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /mnt/card"; } +[ -d "$UROOT/media/CABC-1701" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /media/CABC-1701"; } "$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 check "Y11 auto off" 'USB_AUTO="0"' "$T/home/.config/linux-for-android/usb.conf" [ ! -e "$T/prefix/bin/lfa-usb-auto" ] && pass=$((pass+1)) \ diff --git a/tracker.md b/tracker.md index 15ba177..e7257e0 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=837 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=839 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=837 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=839 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From beef91d90faba4ddbfbb9b75b03ed312e76a4377 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:50:20 +0530 Subject: [PATCH 04/17] feat: lfa usb block, and an honest refusal to fake one `lfa usb block` shows the card's real backing device (/dev/block/vold/public:X,Y) and why an app cannot open it: /dev/block is not searchable, the node is 0660 root:media_rw outside the app namespace, and untrusted_app may not open block devices. `lfa usb block write IMAGE` plans a raw write and, with root and --yes, unmounts via sm, dd's the image with conv=fsync, reads the same byte range back and compares SHA-256 before remounting. Without root it exits 3 and explains itself. Deliberately not implemented: a simulated /dev/sdb1. dd and Ventoy would report success while writing to a regular file, leaving the card untouched, which is the worst outcome for a flashing tool. Files stay available through Android's own mount (lfa usb storage). Docs cover the three barriers, the root path (including binding the node into a guest, since proot's /dev is synthetic) and the Ventoy-without-raw- writes workflow. Nine new Y11 checks pin the report, the JSON and the refusal; suite count 848. --- CHANGELOG.md | 7 ++ README.md | 4 +- docs/TEST-REPORT.md | 4 +- docs/USB.md | 64 +++++++++++++++ install_linux.sh | 185 ++++++++++++++++++++++++++++++++++++++++++++ tests/test-all.sh | 24 ++++++ tracker.md | 4 +- 7 files changed, 286 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29506a3..d8c938c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,13 @@ tag names, define the order. See the table at the bottom. internal storage. A card reader then behaves like a normal directory. Mounting the block device itself stays impossible without root: Android's `usb-storage` driver owns the interface and proot has no block layer. +- `lfa usb block` reports the card's real backing device + (`/dev/block/vold/public:X,Y`), whether this app can open it, and whether a + root shell is available. `lfa usb block write IMAGE [-v VOLUME]` plans a + write and, with root and `--yes`, unmounts, `dd`s the image and verifies it + by reading the bytes back. Without root it refuses explicitly instead of + simulating a block device, since a fake `/dev/sdb1` would let `dd` and + Ventoy report success while writing to a file. - USB automatic mode. `lfa usb enable -i NAME` now makes every later session that LFA starts (`lfa shell`, `lfa desktop`, the Terminal shortcut) open with the plugged-in device already available: the launchers call diff --git a/README.md b/README.md index b6b05f8..28d5a4c 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `839` checks with 0 failures. The same suite runs on the +> The test suite runs `848` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=839 FAIL=0 +./tests/test-all.sh # expect: PASS=848 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index 31bf405..c2f59c3 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=839 FAIL=0`. +> Current development suite: `PASS=848 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=839 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=848 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 8ed3f99..4662cb4 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -308,6 +308,70 @@ FILE` (opens Android's picker and copies one file into Termux) or copy with the Files app to internal storage, then bind that. `/mnt/media_rw` is root/media_rw-only and unusable from Termux. +## Raw block devices (`dd`, Ventoy, Etcher) + +The card *is* a block device: Android's `vold` mounts it from +`/dev/block/vold/public:8,65`. That node belongs to `vold` and `init`; an +unprivileged app is refused at three separate doors: + +1. `/dev/block` is not searchable for apps, so the node has no path. +2. Its mode is `0660 root:media_rw`, and even with the group the node is not + in the app's mount namespace. +3. SELinux labels the app domain `untrusted_app`, which cannot open + `block_device`. + +`lfa usb block` shows all of this for the card in front of you: + +```bash +lfa usb block +# VOLUME BACKING DEVICE FS RAW +# CABC-1701 /dev/block/vold/public:8,65 vfat no +# +# CABC-1701: /dev/block/vold/public:8,65 is not in this app's namespace (root needed) +# +# No root: Android keeps block devices for vold/init. Card *files* are +# still fully usable through Android's mount (lfa usb storage). +``` + +Note the last lines: LFA **refuses to fake** the device. A simulated +`/dev/sdb1` would make `dd`, `Ventoy2Disk` and `Etcher` report success while +writing to a plain file, leaving the card untouched — the worst possible +outcome for a flashing tool. Directory access (`lfa usb storage`) is honest; +raw block access is not available here and says so. + +### With root + +If `su` works, the node is reachable and LFA writes and verifies images: + +```bash +lfa usb block write ventoy.img -v CABC-1701 # plan only +lfa usb block write ventoy.img -v CABC-1701 --yes # unmount, dd, read back +``` + +It unmounts the volume with `sm`, writes with `dd conv=fsync`, reads the same +number of bytes back, compares SHA-256, and remounts. On a non-rooted phone +this exits `3` and prints why. + +Even with root the write happens in Termux, not in the guest: proot's `/dev` +is a synthetic tree, so a guest session cannot see `/dev/block`. If you want +the writer inside the guest, bind the node in from Termux as root +(`su -c 'mount --bind /dev/block/vold/public:8,65 ...'`) and start the +session with that bind. + +### Ventoy without raw writes + +Copying ISOs onto an existing Ventoy card works without root, because the +exFAT data partition is the volume Android mounts: + +```bash +cp ubuntu.iso /media/CABC-1701/ # or /mnt/card +sync +``` + +Creating or updating Ventoy itself needs the card's boot sectors, so it is a +PC job (`Ventoy2Disk.sh -i /dev/sdX`) or a rooted-phone job. There is no +userspace trick that avoids this: Ventoy boots from its own MBR/GPT code. + ## Raw descriptor mode: `lfa usb exec` If the preload cannot be built for a guest, or you want the smallest possible diff --git a/install_linux.sh b/install_linux.sh index d3b9aa9..8ed142f 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2751,6 +2751,7 @@ Usage: lfa usb [options] refresh re-read `termux-usb -l` and rebuild the guest view scan [DEV...] request permission and read real descriptors storage [--json] list storage cards Android exposes to apps + block [write IMAGE] show the card's raw block device / write an image watch [--interval N] [--count N] poll for hotplug and print add/remove events enable [-i NAME] install helpers, preload, tty bridge, auto mode @@ -4075,6 +4076,185 @@ EOF return 0 } +lfa_usb_shq() { # single-quote a string for su -c + printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" +} + +lfa_usb_root_ok() { # is a working root shell available on this device? + local _rootcmd="${LFA_ROOT_CMD:-su -c}" + command -v "${_rootcmd%% *}" >/dev/null 2>&1 || return 1 + # shellcheck disable=SC2086 + $_rootcmd true >/dev/null 2>&1 +} + +lfa_usb_block_mounts() { # idnodefs from Android's vold mounts + awk -v OFS='\t' ' + $1 ~ /^\/dev\/block\// && $2 ~ /^\/mnt\/media_rw\// { + id = $2 + sub("^/mnt/media_rw/", "", id) + if (id != "") print id, $1, $3 + }' "${LFA_USB_MOUNTS:-/proc/mounts}" 2>/dev/null | awk '!seen[$1]++' +} + +lfa_usb_block_state() { # $1 = block node -> rw | denied | invisible | notblock + local _node="${LFA_BLOCK_DEV_ROOT:-}$1" + [ -e "$_node" ] || { printf 'invisible\n'; return 0; } + [ -b "$_node" ] || { printf 'notblock\n'; return 0; } + # Opening O_RDWR is the only honest probe: mode bits and SELinux disagree + # often enough that a stat is not an answer. This writes nothing. + if ( exec 3<>"$_node" ) 2>/dev/null; then + exec 3>&- + printf 'rw\n' + else + printf 'denied\n' + fi +} + +lfa_usb_block_reason() { # $1 = state, $2 = node -> one line for humans + case "$1" in + rw) printf '%s is writable by this app\n' "$2" ;; + denied) printf '%s exists but this app may not open it (root needed)\n' "$2" ;; + invisible) printf '%s is not in this app'"'"'s namespace (root needed)\n' "$2" ;; + notblock) printf '%s is not a block device here\n' "$2" ;; + *) printf 'no block device reported by Android\n' ;; + esac +} + +lfa_usb_block() { # [--json] — raw block access for the storage cards + local _json=0 _rows="" _id _node _fs _state _root=no _any=0 + while [ $# -gt 0 ]; do + case "$1" in + --json) _json=1; shift ;; + -h|--help) echo "Usage: lfa usb block [--json]" >&2; return 0 ;; + *) echo "Unknown option: $1" >&2; return 2 ;; + esac + done + lfa_usb_root_ok && _root=yes + _rows="$(lfa_usb_block_mounts)" + if [ "$_json" = "1" ]; then + printf '[' + printf '%s\n' "$_rows" | while IFS="$(printf '\t')" read -r _id _node _fs; do + [ -n "$_id" ] || continue + _state="$(lfa_usb_block_state "$_node")" + printf '%s{"volume":"%s","node":"%s","fs":"%s","state":"%s","root":%s}' \ + "$([ "$_any" = 1 ] && printf ',')" "$_id" "$_node" "$_fs" "$_state" \ + "$([ "$_root" = yes ] && printf true || printf false)" + _any=1 + done + printf ']\n' + return 0 + fi + if [ -z "$_rows" ]; then + echo "No storage card is mounted, so there is no block device to inspect." + echo "Plug a card first; Android mounts it before any app can see it." + return 0 + fi + printf '%-12s %-32s %-6s %s\n' VOLUME "BACKING DEVICE" FS RAW + printf '%s\n' "$_rows" | while IFS="$(printf '\t')" read -r _id _node _fs; do + [ -n "$_id" ] || continue + _state="$(lfa_usb_block_state "$_node")" + printf '%-12s %-32s %-6s %s\n' "$_id" "$_node" "$_fs" \ + "$([ "$_state" = rw ] && printf yes || printf no)" + done + echo "" + printf '%s\n' "$_rows" | while IFS="$(printf '\t')" read -r _id _node _fs; do + [ -n "$_id" ] || continue + _state="$(lfa_usb_block_state "$_node")" + printf ' %s: %s\n' "$_id" "$(lfa_usb_block_reason "$_state" "$_node")" + done + echo "" + if [ "$_root" = yes ]; then + echo "Root shell detected: raw writes are possible." + echo " lfa usb block write IMAGE [-v VOLUME] [--yes]" + else + echo "No root: Android keeps block devices for vold/init. Card *files* are" + echo "still fully usable through Android's mount (lfa usb storage)." + echo "Flashing boot code (Ventoy, Etcher, dd to /dev/...) needs root; LFA" + echo "will not fake a block device, because dd would then write to a file" + echo "and report success while the card stays unchanged." + fi +} + +lfa_usb_block_write() { # IMAGE [-v VOLUME] [--yes] + local _img="" _vol="" _yes=0 _rows _id _node _fs _state _line _size _sha _blocks + while [ $# -gt 0 ]; do + case "$1" in + -v|--volume) _vol="${2:-}"; shift 2 ;; + --yes|-y) _yes=1; shift ;; + -h|--help) + echo "Usage: lfa usb block write IMAGE [-v VOLUME] [--yes]" >&2 + echo "Writes IMAGE to the card's raw block device, then verifies" >&2 + echo "the bytes by reading them back. Without --yes it only plans." >&2 + return 0 ;; + -*) echo "Unknown option: $1" >&2; return 2 ;; + *) _img="$1"; shift ;; + esac + done + [ -n "$_img" ] || { echo "Usage: lfa usb block write IMAGE [-v VOLUME] [--yes]" >&2; return 2; } + [ -f "$_img" ] || { echo "[!] no such image: $_img" >&2; return 2; } + _rows="$(lfa_usb_block_mounts)" + [ -n "$_rows" ] || { echo "[!] no storage card is mounted" >&2; return 3; } + if [ -z "$_vol" ]; then + if [ "$(printf '%s\n' "$_rows" | wc -l)" = "1" ]; then + _vol="$(printf '%s\n' "$_rows" | cut -f1)" + else + echo "[!] more than one card is mounted; pick one with -v:" >&2 + printf '%s\n' "$_rows" | cut -f1 | sed 's/^/ /' >&2 + return 2 + fi + fi + _line="$(printf '%s\n' "$_rows" | awk -F '\t' -v v="$_vol" '$1 == v')" + [ -n "$_line" ] || { echo "[!] volume '$_vol' has no block device" >&2; return 3; } + _node="$(printf '%s\n' "$_line" | cut -f2)" + _fs="$(printf '%s\n' "$_line" | cut -f3)" + _state="$(lfa_usb_block_state "$_node")" + if [ "$_state" != "rw" ]; then + echo "[!] cannot write $_node: $(lfa_usb_block_reason "$_state" "$_node")" >&2 + echo " Run 'lfa usb block' for the full picture." >&2 + return 3 + fi + lfa_usb_root_ok || { + echo "[!] root is required to detach Android's mount and write $_node" >&2 + echo " (= sudo/su on the device; LFA will not simulate a block device)" >&2 + return 3 + } + _size="$(wc -c < "$_img" | tr -d '[:space:]')" + _sha="$(sha256sum "$_img" | awk '{ print $1 }')" + echo "Card: $_vol ($_fs, mounted at /storage/$_vol)" + echo "Device: $_node" + echo "Image: $_img ($(lfa_usb_size_h "$((_size / 1024))"), sha256 $(printf '%s' "$_sha" | cut -c1-8)…)" + echo "" + if [ "$_yes" != "1" ]; then + echo "Dry run. This WOULD erase $_vol. Re-run with --yes to write." + echo "The card's Android mount is unmounted first and remounted after." + return 0 + fi + local _root_cmd="${LFA_ROOT_CMD:-su -c}" + echo "[*] unmounting $_vol" + # shellcheck disable=SC2086 + $_root_cmd "sm unmount $(lfa_usb_shq "$_vol"); sm unmount $(lfa_usb_shq "/storage/$_vol")" \ + >/dev/null 2>&1 || true + sleep 1 + echo "[*] writing $_size bytes" + # shellcheck disable=SC2086 + if ! $_root_cmd "dd if=$(lfa_usb_shq "$_img") of=$(lfa_usb_shq "$_node") bs=1M conv=fsync status=none"; then + echo "[!] dd failed; card is now in an unknown state" >&2 + return 4 + fi + echo "[*] reading the card back to verify" + # shellcheck disable=SC2086 + if ! $_root_cmd "sync; head -c $_size $(lfa_usb_shq "$_node") | sha256sum" \ + | grep -qx "$_sha -"; then + echo "[!] verification failed: the card does not match the image" >&2 + return 4 + fi + echo "[+] verified: $_vol matches $_img" + # shellcheck disable=SC2086 + $_root_cmd "sm mount $(lfa_usb_shq "$_vol")" >/dev/null 2>&1 || true + echo "[*] remount requested; replug the reader if Android does not pick it up" + return 0 +} + lfa_usb_sys_bind() { # print the /sys/bus bind spec when the tree is ready if [ -d "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" ] && \ [ -n "$(ls -A "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" 2>/dev/null)" ]; then @@ -4650,6 +4830,11 @@ lfa_cli_usb() { enable|install) lfa_usb_enable "$@" ;; disable|remove) lfa_usb_disable "$@" ;; storage|sdcard) lfa_usb_storage "$@" ;; + block|bdev) + case "${1:-}" in + write) shift; lfa_usb_block_write "$@" ;; + *) lfa_usb_block "$@" ;; + esac ;; auto) lfa_usb_auto "$@" ;; exec|run) lfa_usb_exec "$@" ;; attach|shell) lfa_usb_attach "$@" ;; diff --git a/tests/test-all.sh b/tests/test-all.sh index 8f7f157..edcafaa 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2022,6 +2022,30 @@ check "Y11 storage desktop binds" 'LFA_STORAGE_BIND' "$T/prefix/bin/start-linux" || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /mnt/card"; } [ -d "$UROOT/media/CABC-1701" ] && pass=$((pass+1)) \ || { fail=$((fail+1)); echo "FAIL: Y11 storage did not create /media/CABC-1701"; } + +# The card is a real block device on Android, but an app cannot open it. +# `lfa usb block` must say exactly that and refuse to write anything. +printf '/dev/block/vold/public:8,65 /mnt/media_rw/CABC-1701 vfat rw,relatime 0 0\n' \ + > "$T/block-mounts" +mkdir -p "$T/blk" +LFA_USB_MOUNTS="$T/block-mounts" LFA_BLOCK_DEV_ROOT="$T/blk" \ + "$LFA" usb block > "$T/y11-block.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) || { fail=$((fail+1)); echo "FAIL: Y11 block exit $rc"; } +check "Y11 block volume" 'CABC-1701' "$T/y11-block.log" +check "Y11 block backing node" '/dev/block/vold/public:8,65' "$T/y11-block.log" +check "Y11 block invisible" 'not in this app' "$T/y11-block.log" +check "Y11 block no fake device" 'will not fake a block device' "$T/y11-block.log" +LFA_USB_MOUNTS="$T/block-mounts" LFA_BLOCK_DEV_ROOT="$T/blk" \ + "$LFA" usb block --json > "$T/y11-block.json" 2>&1 +check "Y11 block json" '"state":"invisible"' "$T/y11-block.json" +printf 'not-an-image' > "$T/fake-image" +LFA_USB_MOUNTS="$T/block-mounts" LFA_BLOCK_DEV_ROOT="$T/blk" \ + "$LFA" usb block write "$T/fake-image" --yes > "$T/y11-block-write.log" 2>&1; rc=$? +[ "$rc" = "3" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 block write should refuse, exit $rc"; } +check "Y11 block write refused" 'cannot write' "$T/y11-block-write.log" +[ -s "$T/fake-image" ] && [ "$(wc -c < "$T/fake-image")" = "12" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 block write touched the image"; } "$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 check "Y11 auto off" 'USB_AUTO="0"' "$T/home/.config/linux-for-android/usb.conf" [ ! -e "$T/prefix/bin/lfa-usb-auto" ] && pass=$((pass+1)) \ diff --git a/tracker.md b/tracker.md index e7257e0..4c9af1b 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=839 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=848 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=839 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=848 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From 38c771dd8b75a994e704e13a2c869848bb2f4b8b Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:07:09 +0530 Subject: [PATCH 05/17] =?UTF-8?q?feat:=20lfa=20usb=20bot=20=E2=80=94=20raw?= =?UTF-8?q?=20card=20access=20without=20root=20or=20a=20block=20node?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The block layer is not the only way to the sectors; it is only the way the kernel offers. Android's USB host API can detach the usb-storage driver from the descriptor termux-usb grants, after which the app can speak USB Mass Storage Bulk-Only Transport itself. That is how EtchDroid flashes drives unrooted, and it is what this command does. `lfa usb bot --probe` is read-only: INQUIRY, READ CAPACITY(10) and sector 0 are decoded into a device line, size, MBR/GPT table and partitions, with --json for scripts. `--write IMAGE --yes` sends WRITE(10) in 1 MiB chunks, SYNCHRONIZE CACHE(10), then reads the same range back and compares it, so a refused or truncated transfer cannot be mistaken for a good flash. The driver detach means the card leaves /storage until the reader is replugged; the command says so before doing anything. A ROM that refuses the detach surfaces the real errno instead of a simulated success. The script has a --selftest covering CBW/CSW layout, descriptor parsing and MBR decoding so CI exercises the protocol without a device. --- CHANGELOG.md | 8 + README.md | 2 +- docs/TEST-REPORT.md | 4 +- docs/USB.md | 48 ++++ install_linux.sh | 74 +++++ lib/lfa-usb-bot.py | 640 ++++++++++++++++++++++++++++++++++++++++++++ tests/test-all.sh | 11 + tracker.md | 4 +- 8 files changed, 786 insertions(+), 5 deletions(-) create mode 100644 lib/lfa-usb-bot.py diff --git a/CHANGELOG.md b/CHANGELOG.md index d8c938c..0370d16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,14 @@ tag names, define the order. See the table at the bottom. by reading the bytes back. Without root it refuses explicitly instead of simulating a block device, since a fake `/dev/sdb1` would let `dd` and Ventoy report success while writing to a file. +- `lfa usb bot` reaches the storage card's sectors with no block device and + no root: it detaches Android's `usb-storage` driver from the + `termux-usb` descriptor and speaks USB Mass Storage Bulk-Only Transport. + `--probe` is read-only (INQUIRY, READ CAPACITY, sector 0 partition table); + `--write IMAGE --yes` writes with `WRITE(10)`, flushes the cache and reads + the range back to verify it. The card leaves `/storage` while the driver is + detached, and a ROM that refuses the detach gets a real errno, not a + simulated success. - USB automatic mode. `lfa usb enable -i NAME` now makes every later session that LFA starts (`lfa shell`, `lfa desktop`, the Terminal shortcut) open with the plugged-in device already available: the launchers call diff --git a/README.md b/README.md index 28d5a4c..d3d15ca 100644 --- a/README.md +++ b/README.md @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=848 FAIL=0 +./tests/test-all.sh # expect: PASS=853 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index c2f59c3..4c73261 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=848 FAIL=0`. +> Current development suite: `PASS=853 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=848 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=853 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 4662cb4..97e4a82 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -358,6 +358,54 @@ the writer inside the guest, bind the node in from Termux as root (`su -c 'mount --bind /dev/block/vold/public:8,65 ...'`) and start the session with that bind. +### Without root: talk to the reader directly + +A block node is not the only way to reach the sectors. It is only the way +the kernel offers. Apps like EtchDroid flash drives on unrooted phones by +asking Android to **detach its `usb-storage` driver** from the reader, then +speaking USB Mass Storage Bulk-Only Transport (BOT) over the descriptor +`termux-usb` handed over. No `/dev` node is involved. + +LFA does the same: + +```bash +lfa usb bot --probe # read-only: INQUIRY, capacity, sector 0 +lfa usb bot --probe --json # same, for scripts +lfa usb bot --write ventoy.img --yes +``` + +`--probe` prints what the card actually is and whether a raw write is +possible on this phone: + +``` +Device: Generic Mass Storage Device (rev ...) +Capacity: 7.4G in 15523840 blocks of 512 bytes +Sector 0: MBR table, signature 0xaa55 + #1 type 0x07 start 2048 (1.0M) size 7.4G +RAW WRITE: possible without root through this transport +``` + +`--write` writes in 1 MiB chunks with `WRITE(10)`, flushes with +`SYNCHRONIZE CACHE(10)`, then reads the same byte range back and compares +it, so a truncated or refused transfer cannot pass as success. + +Things to know: + +- While the command runs, Android's mount of the card is gone: it will + disappear from `/storage` and from `lfa usb storage`. That is unavoidable, + because only one owner can have the device. Replug the reader afterwards + and Android mounts it again. +- The detach is a permission the Android USB host API grants to the app that + owns the descriptor. If a ROM refuses it, the probe fails with the exact + errno (`EBUSY`, `EPERM`) instead of pretending. +- `--write` always needs `--yes`; without it the tool only explains what it + would erase. There is no dry-run that writes part of an image. +- Do not run `--write` while the card is mounted and in use. LFA detaches the + driver, so vold cannot flush anything after that point. + +If the detach is refused, the honest fallbacks remain: `lfa usb block` with +root, or a PC for the one-time Ventoy install. + ### Ventoy without raw writes Copying ISOs onto an existing Ventoy card works without root, because the diff --git a/install_linux.sh b/install_linux.sh index 8ed142f..4df40dd 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2752,6 +2752,8 @@ Usage: lfa usb [options] scan [DEV...] request permission and read real descriptors storage [--json] list storage cards Android exposes to apps block [write IMAGE] show the card's raw block device / write an image + bot [DEV] [--probe|--write IMAGE] [--yes] + talk USB mass storage directly (no block node) watch [--interval N] [--count N] poll for hotplug and print add/remove events enable [-i NAME] install helpers, preload, tty bridge, auto mode @@ -3529,6 +3531,7 @@ lfa_usb_disable() { fi done for _f in "usr/local/libexec/lfa-usb-desc.py" "usr/local/libexec/lfa-usb-tty.py" \ + "usr/local/libexec/lfa-usb-bot.py" \ "usr/local/lib/lfa-usb-node.so"; do [ -e "$_root/$_f" ] && rm -f "$_root/$_f" done @@ -4255,6 +4258,76 @@ lfa_usb_block_write() { # IMAGE [-v VOLUME] [--yes] return 0 } +lfa_usb_stage_bot() { # $1 = guest rootfs + local _src="$LFA_DIR/lib/lfa-usb-bot.py" + local _dst="$1/usr/local/libexec/lfa-usb-bot.py" + if [ ! -f "$_src" ]; then + echo "[!] lib/lfa-usb-bot.py is missing; run menu 12 or reinstall." >&2 + return 1 + fi + if ! mkdir -p "$(dirname "$_dst")" 2>/dev/null; then + echo "[!] Could not create $(dirname "$_dst") in the guest rootfs." >&2 + return 1 + fi + if ! cp -f "$_src" "$_dst" 2>/dev/null; then + echo "[!] Could not copy lib/lfa-usb-bot.py to $_dst." >&2 + return 1 + fi + chmod 755 "$_dst" 2>/dev/null || true +} + +lfa_usb_bot() { # [DEV] [--probe|--write IMAGE] [--yes] [--json] + local _inst="" _dev="" _mode="--probe" _img="" _json="" _no_verify="" _yes="" + local _id _root + local -a _args=() + while [ $# -gt 0 ]; do + case "$1" in + -i|--instance) _inst="${2:-}"; shift 2 ;; + --probe) _mode="--probe"; shift ;; + --write) + _mode="--write"; _img="${2:-}" + if [ $# -ge 2 ]; then shift 2; else shift; fi ;; + --write=*) _mode="--write"; _img="${1#*=}"; shift ;; + --no-verify) _no_verify="--no-verify"; shift ;; + --json) _json="--json"; shift ;; + --yes|-y) _yes="--yes"; shift ;; + --device) + _dev="${2:-}" + if [ $# -ge 2 ]; then shift 2; else shift; fi ;; + -h|--help) lfa_usb_usage; return 0 ;; + --) shift; break ;; + -*) echo "Unknown option: $1" >&2; return 2 ;; + *) _dev="$1"; shift ;; + esac + done + if [ "$_mode" = "--write" ] && [ -z "$_img" ]; then + echo "Usage: lfa usb bot --write IMAGE [--yes]" >&2 + return 2 + fi + if [ -z "$_dev" ]; then + _dev="$(lfa_usb_default_dev)" + [ -n "$_dev" ] || { + echo "[!] No USB device is visible. Connect one and run: lfa usb refresh" >&2 + return 1 + } + echo "[*] Using $_dev (the only visible device)." + fi + lfa_usb_pick_instance "$_inst" || return 1 + _id="$INSTANCE_NAME" + _root="$(pd_rootfs "$_id")" + [ -d "$_root" ] || { echo "[!] Rootfs missing for $_id." >&2; return 1; } + lfa_usb_stage_bot "$_root" || return 1 + echo "[*] Bulk-Only Transport: Android's usb-storage driver is detached for" + echo " this command, so the card leaves /storage until you replug it." + echo " Nothing is written unless --write and --yes are both given." + _args=("$_mode") + [ "$_mode" = "--write" ] && _args+=("$_img") + [ "$_mode" = "--write" ] && [ -n "$_yes" ] && _args+=("$_yes") + [ "$_mode" = "--write" ] && [ -n "$_no_verify" ] && _args+=("$_no_verify") + [ "$_mode" = "--probe" ] && [ -n "$_json" ] && _args+=("$_json") + lfa_usb_exec -i "$_id" "$_dev" -- python3 /usr/local/libexec/lfa-usb-bot.py "${_args[@]}" +} + lfa_usb_sys_bind() { # print the /sys/bus bind spec when the tree is ready if [ -d "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" ] && \ [ -n "$(ls -A "$LFA_USB_BRIDGE/sysroot/bus/usb/devices" 2>/dev/null)" ]; then @@ -4830,6 +4903,7 @@ lfa_cli_usb() { enable|install) lfa_usb_enable "$@" ;; disable|remove) lfa_usb_disable "$@" ;; storage|sdcard) lfa_usb_storage "$@" ;; + bot|bot-probe) lfa_usb_bot "$@" ;; block|bdev) case "${1:-}" in write) shift; lfa_usb_block_write "$@" ;; diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py new file mode 100644 index 0000000..0be6aea --- /dev/null +++ b/lib/lfa-usb-bot.py @@ -0,0 +1,640 @@ +#!/usr/bin/env python3 +"""Talk USB mass storage directly, without a block device node. + +Android's ``usb-storage`` driver owns a card reader's interface and vold +mounts the card, so an app has no path to ``/dev/block/...``. That is the +only reason raw writes look impossible: the block layer is closed, the USB +device is not. + +Termux:API hands over the real usbfs descriptor. On that descriptor this +script detaches the kernel driver, claims the mass-storage interface and +speaks the USB Mass Storage Bulk-Only Transport (BOT) protocol itself: + + lfa-usb-bot.py --probe INQUIRY + READ CAPACITY + sector 0 + lfa-usb-bot.py --write IMAGE SCSI WRITE(10) + read-back verification + lfa-usb-bot.py --selftest protocol bytes, no device + +Read-only by default. ``--write`` needs ``--yes`` and erases the card. + +Usage: + python3 lfa-usb-bot.py [--fd N] --probe [--json] + python3 lfa-usb-bot.py [--fd N] --write IMAGE [--no-verify] [--yes] + python3 lfa-usb-bot.py --selftest + +The descriptor comes from ``$TERMUX_USB_FD`` when ``--fd`` is absent, which +is what ``termux-usb -E -e`` sets up. +""" + +from __future__ import annotations + +import argparse +import ctypes +import errno +import fcntl +import hashlib +import json +import os +import struct +import sys +import time +from typing import Any, Dict, List, Optional, Tuple + + +# -------------------------------------------------------------------------- +# usbfs plumbing +# -------------------------------------------------------------------------- + +def _ioc(direction: int, kind: int, nr: int, size: int) -> int: + return (direction << 30) | (size << 16) | (kind << 8) | nr + + +class CtrlTransfer(ctypes.Structure): + _fields_ = [ + ("bRequestType", ctypes.c_uint8), + ("bRequest", ctypes.c_uint8), + ("wValue", ctypes.c_uint16), + ("wIndex", ctypes.c_uint16), + ("wLength", ctypes.c_uint16), + ("timeout", ctypes.c_uint32), + ("data", ctypes.c_void_p), + ] + + +class BulkTransfer(ctypes.Structure): + _fields_ = [ + ("ep", ctypes.c_uint), + ("len", ctypes.c_uint), + ("timeout", ctypes.c_uint), + ("data", ctypes.c_void_p), + ] + + +class DisconnectClaim(ctypes.Structure): + _fields_ = [ + ("interface", ctypes.c_uint), + ("flags", ctypes.c_uint), + ("driver", ctypes.c_char * 256), + ] + + +USBDEVFS_CONTROL = _ioc(3, ord("U"), 0, ctypes.sizeof(CtrlTransfer)) +USBDEVFS_BULK = _ioc(3, ord("U"), 2, ctypes.sizeof(BulkTransfer)) +USBDEVFS_CLAIMINTERFACE = _ioc(2, ord("U"), 15, 4) +USBDEVFS_RELEASEINTERFACE = _ioc(2, ord("U"), 16, 4) +USBDEVFS_CLEAR_HALT = _ioc(2, ord("U"), 21, 4) +USBDEVFS_DISCONNECT_CLAIM = _ioc(3, ord("U"), 27, ctypes.sizeof(DisconnectClaim)) + +GET_DESCRIPTOR = 0x06 +DT_DEVICE = 1 +DT_CONFIG = 2 +DT_INTERFACE = 4 +DT_ENDPOINT = 5 + +MASS_STORAGE_CLASS = 0x08 +BOT_PROTOCOL = 0x50 + + +class BotError(Exception): + """A transport or SCSI failure.""" + + +def _errno_name(exc: OSError) -> str: + return errno.errorcode.get(exc.errno or 0, "EIO") + + +def _ioctl(fd: int, request: int, arg: Any) -> int: + try: + return int(fcntl.ioctl(fd, request, arg)) + except OSError as exc: + raise BotError("%s (%s)" % (exc.strerror, _errno_name(exc))) from exc + + +def control_transfer(fd: int, request_type: int, request: int, value: int, + index: int, length: int, timeout: int = 3000) -> bytes: + buf = ctypes.create_string_buffer(max(int(length), 1)) + transfer = CtrlTransfer( + request_type & 0xFF, request & 0xFF, value & 0xFFFF, index & 0xFFFF, + length & 0xFFFF, timeout & 0xFFFFFFFF, ctypes.cast(buf, ctypes.c_void_p), + ) + _ioctl(fd, USBDEVFS_CONTROL, transfer) + return bytes(buf.raw)[:length] + + +def get_descriptor(fd: int, dtype: int, index: int = 0, length: int = 255, + langid: int = 0) -> bytes: + return control_transfer(fd, 0x80, GET_DESCRIPTOR, + (dtype << 8) | (index & 0xFF), langid, length) + + +def bulk_transfer(fd: int, ep: int, data: Optional[bytes], length: int, + timeout: int = 15000) -> bytes: + """One USBDEVFS_BULK ioctl. ``data`` None means host->device of ``length``.""" + if data is None: + buf = (ctypes.c_ubyte * max(length, 1))() + else: + buf = (ctypes.c_ubyte * max(len(data), 1)).from_buffer_copy( + data if len(data) else b"\x00") + transfer = BulkTransfer(ep, length, timeout, ctypes.cast(buf, ctypes.c_void_p)) + done = _ioctl(fd, USBDEVFS_BULK, transfer) + return bytes(bytearray(buf))[:done] + + +def clear_halt(fd: int, ep: int) -> None: + try: + fcntl.ioctl(fd, USBDEVFS_CLEAR_HALT, struct.pack("I", ep)) + except OSError: + pass + + +def parse_config(data: bytes) -> Dict[str, Any]: + if len(data) < 9 or data[0] < 9 or data[1] != DT_CONFIG: + raise BotError("invalid configuration descriptor") + total = struct.unpack_from(" end: + break + chunk = data[off:off + length] + if dtype == DT_INTERFACE and len(chunk) >= 9: + current = { + "number": chunk[2], "alternate": chunk[3], + "class": chunk[5], "subclass": chunk[6], "protocol": chunk[7], + "endpoints": [], + } + interfaces.append(current) + elif dtype == DT_ENDPOINT and len(chunk) >= 7 and current is not None: + current["endpoints"].append({ + "address": chunk[2], + "type": chunk[3] & 0x03, + "max_packet": struct.unpack_from(" Tuple[int, int, int, int]: + """Return (interface, alt, ep_in, ep_out) for mass storage bulk-only.""" + fallback = None + for intf in config["interfaces"]: + bulk = [e for e in intf["endpoints"] if e["type"] == 0x02] + ep_in = next((e["address"] for e in bulk if e["address"] & 0x80), None) + ep_out = next((e["address"] for e in bulk if not e["address"] & 0x80), None) + if ep_in is None or ep_out is None: + continue + if intf["class"] == MASS_STORAGE_CLASS and intf["protocol"] == BOT_PROTOCOL: + return intf["number"], intf["alternate"], ep_in, ep_out + if fallback is None: + fallback = (intf["number"], intf["alternate"], ep_in, ep_out) + if fallback is None: + raise BotError("no interface with two bulk endpoints (not mass storage?)") + return fallback + + +def claim_interface(fd: int, interface: int, verbose: bool = True) -> str: + """Claim, detaching Android's kernel driver if it holds the interface.""" + try: + fcntl.ioctl(fd, USBDEVFS_CLAIMINTERFACE, struct.pack("I", interface)) + return "free" + except OSError as exc: + first = _errno_name(exc) + # flags 0 / IF_DRIVER("usb-storage") / EXCEPT_DRIVER(""): + # the kernel's exact semantics vary, so try each and keep the one that works. + attempts = [(0, b""), (1, b"usb-storage"), (2, b"")] + errors = [] + for flags, driver in attempts: + dc = DisconnectClaim(interface, flags, driver) + try: + fcntl.ioctl(fd, USBDEVFS_DISCONNECT_CLAIM, dc) + if verbose: + print("[*] detached the kernel driver and claimed interface %d" + % interface) + return "detached" + except OSError as exc: + errors.append("flags=%d:%s" % (flags, _errno_name(exc))) + raise BotError("cannot claim interface %d (claim: %s; disconnect: %s)" + % (interface, first, ", ".join(errors))) + + +# -------------------------------------------------------------------------- +# Bulk-Only Transport +# -------------------------------------------------------------------------- + +CBW_SIGNATURE = 0x43425355 +CSW_SIGNATURE = 0x53425355 + + +def build_cbw(tag: int, transfer_length: int, direction_in: bool, lun: int, + cdb: bytes) -> bytes: + if len(cdb) > 16: + raise BotError("CDB is longer than 16 bytes") + cb = bytes(cdb) + b"\x00" * (16 - len(cdb)) + return struct.pack(" Tuple[int, int]: + if len(raw) != 13: + raise BotError("short CSW (%d bytes)" % len(raw)) + signature, got_tag, residue, status = struct.unpack(" int: + self.tag = (self.tag + 1) & 0xFFFFFFFF + return self.tag + + def reset_recovery(self) -> None: + try: + control_transfer(self.fd, 0x21, 0xFF, 0, self.interface, 0, timeout=3000) + except BotError: + pass + clear_halt(self.fd, self.ep_in) + clear_halt(self.fd, self.ep_out) + + def command(self, cdb: bytes, length: int = 0, direction_in: bool = False, + data: Optional[bytes] = None, retries: int = 1) -> Tuple[bytes, int]: + """Run one SCSI command; return (payload_in, data_residue).""" + attempt = 0 + while True: + attempt += 1 + tag = self._next_tag() + cbw = build_cbw(tag, length, direction_in, self.lun, cdb) + try: + sent = bulk_transfer(self.fd, self.ep_out, cbw, len(cbw)) + if sent != len(cbw): + raise BotError("short CBW write (%d of %d)" % (sent, len(cbw))) + payload = b"" + if direction_in and length: + payload = bulk_transfer(self.fd, self.ep_in, None, length) + elif (not direction_in) and length and data is not None: + sent = bulk_transfer(self.fd, self.ep_out, data, length) + if sent != length: + raise BotError("short data write (%d of %d)" % (sent, length)) + csw = bulk_transfer(self.fd, self.ep_in, None, 13) + except BotError: + if attempt > retries: + raise + self.reset_recovery() + continue + residue, status = parse_csw(csw, tag) + if status == 0: + return payload, residue + if status == 2: + self.reset_recovery() + if attempt <= retries: + continue + raise BotError("phase error after reset recovery") + # status 1: command failed; caller decides whether to ask for sense + raise BotError("command failed (CSW status 1, residue %d)" % residue) + + # --- SCSI commands --------------------------------------------------- + def inquiry(self, length: int = 36) -> Dict[str, Any]: + payload, _ = self.command(b"\x12\x00\x00\x00" + bytes([length]) + b"\x00", + length, True) + if len(payload) < 36: + raise BotError("short INQUIRY response") + return { + "peripheral": payload[0] & 0x1F, + "vendor": payload[8:16].decode("ascii", "replace").strip(), + "product": payload[16:32].decode("ascii", "replace").strip(), + "revision": payload[32:36].decode("ascii", "replace").strip(), + } + + def test_unit_ready(self) -> None: + self.command(b"\x00" * 6, 0, False) + + def wait_ready(self, tries: int = 8) -> None: + last: Optional[BotError] = None + for _ in range(tries): + try: + self.test_unit_ready() + return + except BotError as exc: + last = exc + time.sleep(0.25) + raise BotError("device never became ready: %s" % last) + + def capacity(self) -> Dict[str, int]: + payload, _ = self.command(b"\x25" + b"\x00" * 9, 8, True) + if len(payload) != 8: + raise BotError("short READ CAPACITY response") + last_lba, block = struct.unpack(">II", payload) + return {"last_lba": last_lba, "blocks": last_lba + 1, "block_size": block} + + def read10(self, lba: int, blocks: int, block_size: int) -> bytes: + cdb = struct.pack(">BBIBHB", 0x28, 0, lba, 0, blocks, 0) + payload, residue = self.command(cdb, blocks * block_size, True) + if len(payload) != blocks * block_size: + raise BotError("short READ(10) payload (%d of %d)" + % (len(payload), blocks * block_size)) + if residue: + raise BotError("READ(10) residue %d" % residue) + return payload + + def write10(self, lba: int, data: bytes, block_size: int) -> None: + blocks = len(data) // block_size + cdb = struct.pack(">BBIBHB", 0x2A, 0, lba, 0, blocks, 0) + _, residue = self.command(cdb, blocks * block_size, False, data) + if residue: + raise BotError("WRITE(10) residue %d" % residue) + + def sync_cache(self) -> None: + self.command(b"\x35" + b"\x00" * 9, 0, False) + + +# -------------------------------------------------------------------------- +# Device open / probe / write +# -------------------------------------------------------------------------- + +def human(n: int) -> str: + value = float(n) + for unit in ("B", "K", "M", "G", "T"): + if value < 1024 or unit == "T": + return "%.1f%s" % (value, unit) if unit != "B" else "%d%s" % (n, unit) + value /= 1024.0 + return "%d" % n + + +def open_bot(fd: int, verbose: bool = True) -> Tuple[Bot, Dict[str, Any]]: + device = get_descriptor(fd, DT_DEVICE, 0, 18) + if len(device) < 18 or device[1] != DT_DEVICE: + raise BotError("cannot read the device descriptor") + vid = struct.unpack_from(" Dict[str, Any]: + if len(sector) < 512: + return {"signature": None, "partitions": []} + result: Dict[str, Any] = { + "signature": "0x%04x" % struct.unpack_from(" int: + bot, info = open_bot(fd) + try: + bot.wait_ready() + inquiry = bot.inquiry() + cap = bot.capacity() + sector = bot.read10(0, 1, cap["block_size"] or 512) + mbr = parse_mbr(sector) + result = dict(info) + result.update({"inquiry": inquiry, "capacity": cap, "mbr": mbr}) + if as_json: + print(json.dumps(result)) + return 0 + print("Device: %s %s (rev %s)" % (inquiry["vendor"], inquiry["product"], + inquiry["revision"])) + print("Capacity: %s in %d blocks of %d bytes" + % (human(cap["blocks"] * cap["block_size"]), cap["blocks"], + cap["block_size"])) + print("Sector 0: %s table, signature %s" + % (mbr["table"].upper(), mbr["signature"])) + if not mbr["partitions"]: + print(" no partitions (blank or not yet flashed)") + for part in mbr["partitions"]: + print(" #%d type %s start %d (%s) size %s%s" + % (part["index"], part["type"], part["start_lba"], + human(part["start_lba"] * 512), human(part["bytes"]), + " bootable" if part["bootable"] else "")) + print("RAW WRITE: possible without root through this transport") + print(" lfa usb bot --write IMAGE --yes") + finally: + try: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + return 0 + + +def write_image(fd: int, path: str, verify: bool) -> int: + size = os.path.getsize(path) + if size == 0: + print("[!] image is empty", file=sys.stderr) + return 2 + bot, info = open_bot(fd) + try: + bot.wait_ready() + inquiry = bot.inquiry() + cap = bot.capacity() + block = cap["block_size"] or 512 + if block not in (512, 1024, 2048, 4096): + print("[!] unsupported logical block size %d" % block, file=sys.stderr) + return 2 + if size > cap["blocks"] * block: + print("[!] image is larger than the card (%s > %s)" + % (human(size), human(cap["blocks"] * block)), file=sys.stderr) + return 2 + print("[*] %s %s: writing %s in %d-byte blocks" + % (inquiry["vendor"], inquiry["product"], human(size), block)) + chunk_blocks = max(1, (1024 * 1024) // block) + written = 0 + with open(path, "rb") as handle: + lba = 0 + while True: + data = handle.read(chunk_blocks * block) + if not data: + break + if len(data) % block: + data += b"\x00" * (block - len(data) % block) + bot.write10(lba, data, block) + written += len(data) + lba += len(data) // block + pct = min(100, int(written * 100 / max(size, 1))) + sys.stderr.write("\r[*] %3d%% %s" % (pct, human(written))) + sys.stderr.flush() + sys.stderr.write("\n") + bot.sync_cache() + print("[+] wrote %s" % human(written)) + if verify: + print("[*] reading the card back") + digest = hashlib.sha256() + remaining = size + with open(path, "rb") as handle: + lba = 0 + while remaining > 0: + want = min(chunk_blocks * block, remaining) + blocks = (want + block - 1) // block + back = bot.read10(lba, blocks, block)[:want] + expect = handle.read(want) + if back != expect: + print("[!] verification failed at byte %d" + % (size - remaining), file=sys.stderr) + return 4 + digest.update(back) + remaining -= want + lba += blocks + with open(path, "rb") as handle: + want = hashlib.sha256(handle.read()).hexdigest() + if digest.hexdigest() != want: + print("[!] verification failed: checksum mismatch", file=sys.stderr) + return 4 + print("[+] verified: card matches the image") + finally: + try: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + print("[*] replug the reader so Android mounts the card again") + return 0 + + +# -------------------------------------------------------------------------- +# Self test (no device, runs in CI) +# -------------------------------------------------------------------------- + +def selftest() -> int: + read10_cdb = b"\x28\x00\x00\x00\x00\x00\x00\x10\x00\x00" + cbw = build_cbw(0x11223344, 512, True, 0, read10_cdb) + assert len(cbw) == 31, len(cbw) + assert struct.unpack_from(" int: + parser = argparse.ArgumentParser( + description="USB mass storage over Bulk-Only Transport, no block node") + parser.add_argument("--fd", default=os.environ.get("TERMUX_USB_FD", ""), + help="usbdevfs descriptor (default: $TERMUX_USB_FD)") + parser.add_argument("--probe", action="store_true", + help="INQUIRY, capacity and sector 0 (read-only)") + parser.add_argument("--write", metavar="IMAGE", + help="write IMAGE to the card (erases it)") + parser.add_argument("--no-verify", action="store_true", + help="skip reading the image back after --write") + parser.add_argument("--yes", action="store_true", + help="confirm that the card will be erased") + parser.add_argument("--json", action="store_true", help="machine output") + parser.add_argument("--selftest", action="store_true") + args = parser.parse_args(argv) + + if args.selftest: + return selftest() + if not args.probe and not args.write: + parser.print_help() + return 2 + if not args.fd: + print("[!] no USB descriptor: TERMUX_USB_FD is empty", file=sys.stderr) + return 2 + try: + fd = int(args.fd) + except ValueError: + print("[!] TERMUX_USB_FD is not a number: %r" % args.fd, file=sys.stderr) + return 2 + try: + if args.write: + if not args.yes: + print("[!] --write erases the card. Add --yes when you mean it.", + file=sys.stderr) + return 2 + return write_image(fd, args.write, not args.no_verify) + return probe(fd, args.json) + except BotError as exc: + print("[!] %s" % exc, file=sys.stderr) + print(" Android may refuse the driver detach on this device.", file=sys.stderr) + print(" If it does, the card's files are still available via" + " 'lfa usb storage'.", file=sys.stderr) + return 5 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test-all.sh b/tests/test-all.sh index edcafaa..fd1625e 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2044,6 +2044,17 @@ LFA_USB_MOUNTS="$T/block-mounts" LFA_BLOCK_DEV_ROOT="$T/blk" \ [ "$rc" = "3" ] && pass=$((pass+1)) \ || { fail=$((fail+1)); echo "FAIL: Y11 block write should refuse, exit $rc"; } check "Y11 block write refused" 'cannot write' "$T/y11-block-write.log" +# Bulk-Only Transport: raw access over USB without a block node. +python3 "$REPO/lib/lfa-usb-bot.py" --selftest > "$T/y11-bot-selftest.log" 2>&1; rc=$? +[ "$rc" = "0" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 bot selftest exit $rc"; } +check "Y11 bot selftest" 'selftest: ok' "$T/y11-bot-selftest.log" +"$LFA" usb bot --write > "$T/y11-bot-noimage.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 bot --write without image exit $rc"; } +check "Y11 bot needs an image" 'Usage: lfa usb bot --write IMAGE' "$T/y11-bot-noimage.log" +"$LFA" usb help > "$T/y11-usage.log" 2>&1 +check "Y11 bot documented" 'talk USB mass storage directly' "$T/y11-usage.log" [ -s "$T/fake-image" ] && [ "$(wc -c < "$T/fake-image")" = "12" ] && pass=$((pass+1)) \ || { fail=$((fail+1)); echo "FAIL: Y11 block write touched the image"; } "$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 diff --git a/tracker.md b/tracker.md index 4c9af1b..ed07f9d 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=848 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=853 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=848 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=853 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From d645124cee56608b9aa58520ac4a00696286a60d Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:12:54 +0530 Subject: [PATCH 06/17] fix: tell the user to replug after a bot probe The driver detach removes the card from /storage, and releasing the interface does not make Android rebind usb-storage; the reader has to be replugged. Say that after the probe too, not only after a write. --- lib/lfa-usb-bot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 0be6aea..8e0a156 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -468,6 +468,7 @@ def probe(fd: int, as_json: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass + print("[*] replug the reader so Android mounts the card again") return 0 From 15f26ef21fa837afa9040293a49a1316b51303ac Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:21:33 +0530 Subject: [PATCH 07/17] docs: state the real suite count in README The README summary line still said 848 while the suite now runs 853 checks, which the Z section reports as a stale count. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d3d15ca..26a624b 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `848` checks with 0 failures. The same suite runs on the +> The test suite runs `853` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is From 6434656065a9eb374d0d534fe6f812c49eb83a25 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:26:26 +0530 Subject: [PATCH 08/17] feat: export the card as a sparse image for guest tools A block device cannot exist inside proot, but a file can, and the real tools accept files. `lfa usb bot --export FILE` streams the card into a sparse image (1 MiB all-zero chunks become holes); `--import FILE --yes` compares each chunk with the card, writes only the differences and reads those back to verify. That makes fdisk, sfdisk, parted, mkfs.*, dd and fsck usable on the card from a desktop session, which is as close to "a real disk in Linux" as the container allows. losetup, mount -o loop and installers that demand S_ISBLK (Ventoy2Disk) remain impossible, and the docs say so. --- CHANGELOG.md | 6 ++ README.md | 4 +- docs/TEST-REPORT.md | 4 +- docs/USB.md | 33 ++++++++++ install_linux.sh | 46 +++++++++++--- lib/lfa-usb-bot.py | 147 +++++++++++++++++++++++++++++++++++++++++++- tests/test-all.sh | 10 +++ tracker.md | 4 +- 8 files changed, 239 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0370d16..8209097 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,12 @@ tag names, define the order. See the table at the bottom. the range back to verify it. The card leaves `/storage` while the driver is detached, and a ROM that refuses the detach gets a real errno, not a simulated success. +- `lfa usb bot --export FILE` reads the card into a sparse image and + `--import FILE --yes` writes it back, rewriting only the 1 MiB chunks that + differ and verifying those. Partitioning, `mkfs`, `dd` and `fsck` then work + on the card from inside a desktop session using the normal tools; a block + device still cannot exist in the guest, so `losetup` and `mount -o loop` + remain impossible. - USB automatic mode. `lfa usb enable -i NAME` now makes every later session that LFA starts (`lfa shell`, `lfa desktop`, the Terminal shortcut) open with the plugged-in device already available: the launchers call diff --git a/README.md b/README.md index 26a624b..9b9a1ca 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ hardware, not simulated. Full details, root causes, and evidence are in | Alpine 3.18 (Android 5) | Yes | Yes | legacy VNC desktop, panel works; X11 and Both hidden | v1.7.1 | | Ubuntu GNOME 46 (experimental) | Yes | Yes | shell and apps run; session services missing | v1.7.0 | -> The test suite runs `853` checks with 0 failures. The same suite runs on the +> The test suite runs `858` checks with 0 failures. The same suite runs on the > devices (`tests/device-matrix.sh`). The table is as of v1.7.1. Ubuntu was > re-verified on v1.7.1, and Alpine 3.18 was re-verified on Android 5 on > 2026-11-04; the other rows were last verified on v1.7.0. A row is @@ -1554,7 +1554,7 @@ plus `script` from util-linux for the pty test, which is skipped if absent: ```bash chmod +x tests/test-all.sh -./tests/test-all.sh # expect: PASS=853 FAIL=0 +./tests/test-all.sh # expect: PASS=858 FAIL=0 ``` The suite is deliberately stubbed. It cannot prove a desktop actually appears. diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md index 4c73261..f0c77c2 100644 --- a/docs/TEST-REPORT.md +++ b/docs/TEST-REPORT.md @@ -1,6 +1,6 @@ # Test report for v1.7.1 -> Current development suite: `PASS=853 FAIL=0`. +> Current development suite: `PASS=858 FAIL=0`. ## USB bridge, 2026-11-18 @@ -11,7 +11,7 @@ phone with an OTG adapter; do not claim them before that run. | Check | Result | |---|---| -| Host suite (`./tests/test-all.sh`) | `PASS=853 FAIL=0` | +| Host suite (`./tests/test-all.sh`) | `PASS=858 FAIL=0` | | Descriptor parser (`python3 lib/usb-desc.py --selftest`) | device and configuration descriptors parsed; sysfs blob built | | Serial bridge (`python3 lib/lfa-usb-tty.py --selftest`) | CH340 divisor encoding, CDC/CP210x detection, endpoint selection | | Preload build | `lib/lfa-usb-node.c` built for the guest architecture, no `DT_NEEDED`; aarch64 prebuilt bundled | diff --git a/docs/USB.md b/docs/USB.md index 97e4a82..eddb6f6 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -406,6 +406,39 @@ Things to know: If the detach is refused, the honest fallbacks remain: `lfa usb block` with root, or a PC for the one-time Ventoy install. +### From a desktop session: the card as an image file + +The guest still cannot have `/dev/sdb`: proot has no block layer, no +`mknod`, no `/dev/loop*` and no `mount(2)`. What it *can* have is the card's +bytes as a file, and the real tools accept files: + +```bash +lfa usb bot --export ~/card.img # read-only, sparse +lfa shell -i ubuntu-5623 + +fdisk -l ~/card.img # real fdisk, real partition table +sfdisk ~/card.img < layout # repartition +mkfs.vfat -F32 ~/card.img # format the image, not the card +dd if=file.bin of=~/card.img bs=1M conv=notrunc seek=2048 +fsck.vfat ~/card.img + +exit +lfa usb bot --import ~/card.img --yes # write back only changed chunks +``` + +`--export` writes a **sparse** file: 1 MiB chunks that are entirely zero +become holes, so a mostly empty 8 GB card costs only a few MB on disk. The +read is still the whole card over USB, so expect minutes, not seconds. + +`--import` compares each 1 MiB chunk with the card and writes only the ones +that differ, then reads those back to confirm. A small edit writes a small +amount; a brand-new image writes everything. + +What works this way: `fdisk`, `sfdisk`, `parted`, `mkfs.*` (files are valid +targets), `dd`, `fsck`, `debugfs`, byte patching. What does not: +`losetup`, `mount -o loop`, and installers that insist on `S_ISBLK` +(Ventoy2Disk). The kernel is still missing; only the storage moved. + ### Ventoy without raw writes Copying ISOs onto an existing Ventoy card works without root, because the diff --git a/install_linux.sh b/install_linux.sh index 4df40dd..406a549 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2752,7 +2752,7 @@ Usage: lfa usb [options] scan [DEV...] request permission and read real descriptors storage [--json] list storage cards Android exposes to apps block [write IMAGE] show the card's raw block device / write an image - bot [DEV] [--probe|--write IMAGE] [--yes] + bot [DEV] [--probe|--write IMAGE|--export FILE|--import FILE] talk USB mass storage directly (no block node) watch [--interval N] [--count N] poll for hotplug and print add/remove events @@ -4276,8 +4276,9 @@ lfa_usb_stage_bot() { # $1 = guest rootfs chmod 755 "$_dst" 2>/dev/null || true } -lfa_usb_bot() { # [DEV] [--probe|--write IMAGE] [--yes] [--json] - local _inst="" _dev="" _mode="--probe" _img="" _json="" _no_verify="" _yes="" +lfa_usb_bot() { # [DEV] [--probe|--write IMAGE|--export FILE|--import FILE] + local _inst="" _dev="" _mode="--probe" _img="" _file="" _json="" _no_verify="" + local _full="" _yes="" local _id _root local -a _args=() while [ $# -gt 0 ]; do @@ -4288,6 +4289,15 @@ lfa_usb_bot() { # [DEV] [--probe|--write IMAGE] [--yes] [--json] _mode="--write"; _img="${2:-}" if [ $# -ge 2 ]; then shift 2; else shift; fi ;; --write=*) _mode="--write"; _img="${1#*=}"; shift ;; + --export) + _mode="--export"; _file="${2:-}" + if [ $# -ge 2 ]; then shift 2; else shift; fi ;; + --export=*) _mode="--export"; _file="${1#*=}"; shift ;; + --import) + _mode="--import"; _file="${2:-}" + if [ $# -ge 2 ]; then shift 2; else shift; fi ;; + --import=*) _mode="--import"; _file="${1#*=}"; shift ;; + --full) _full="--full"; shift ;; --no-verify) _no_verify="--no-verify"; shift ;; --json) _json="--json"; shift ;; --yes|-y) _yes="--yes"; shift ;; @@ -4304,6 +4314,14 @@ lfa_usb_bot() { # [DEV] [--probe|--write IMAGE] [--yes] [--json] echo "Usage: lfa usb bot --write IMAGE [--yes]" >&2 return 2 fi + if [ "$_mode" = "--export" ] && [ -z "$_file" ]; then + echo "Usage: lfa usb bot --export FILE" >&2 + return 2 + fi + if [ "$_mode" = "--import" ] && [ -z "$_file" ]; then + echo "Usage: lfa usb bot --import FILE [--yes]" >&2 + return 2 + fi if [ -z "$_dev" ]; then _dev="$(lfa_usb_default_dev)" [ -n "$_dev" ] || { @@ -4320,11 +4338,23 @@ lfa_usb_bot() { # [DEV] [--probe|--write IMAGE] [--yes] [--json] echo "[*] Bulk-Only Transport: Android's usb-storage driver is detached for" echo " this command, so the card leaves /storage until you replug it." echo " Nothing is written unless --write and --yes are both given." - _args=("$_mode") - [ "$_mode" = "--write" ] && _args+=("$_img") - [ "$_mode" = "--write" ] && [ -n "$_yes" ] && _args+=("$_yes") - [ "$_mode" = "--write" ] && [ -n "$_no_verify" ] && _args+=("$_no_verify") - [ "$_mode" = "--probe" ] && [ -n "$_json" ] && _args+=("$_json") + case "$_mode" in + --probe) + _args=("--probe") + [ -n "$_json" ] && _args+=("$_json") + ;; + --write) + _args=("--write" "$_img") + [ -n "$_yes" ] && _args+=("$_yes") + [ -n "$_no_verify" ] && _args+=("$_no_verify") + ;; + --export) _args=("--export" "$_file") ;; + --import) + _args=("--import" "$_file") + [ -n "$_full" ] && _args+=("$_full") + [ -n "$_yes" ] && _args+=("$_yes") + ;; + esac lfa_usb_exec -i "$_id" "$_dev" -- python3 /usr/local/libexec/lfa-usb-bot.py "${_args[@]}" } diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 8e0a156..60aa590 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -19,8 +19,14 @@ Usage: python3 lfa-usb-bot.py [--fd N] --probe [--json] python3 lfa-usb-bot.py [--fd N] --write IMAGE [--no-verify] [--yes] + python3 lfa-usb-bot.py [--fd N] --export FILE + python3 lfa-usb-bot.py [--fd N] --import FILE [--full] [--yes] python3 lfa-usb-bot.py --selftest +--export writes the whole card to a sparse file so ordinary tools (fdisk, +sfdisk, mkfs, dd, fsck) can work on it inside the guest; --import writes the +file back, touching only the 1 MiB chunks that differ. + The descriptor comes from ``$TERMUX_USB_FD`` when ``--fd`` is absent, which is what ``termux-usb -E -e`` sets up. """ @@ -544,6 +550,125 @@ def write_image(fd: int, path: str, verify: bool) -> int: return 0 +# -------------------------------------------------------------------------- +# Card <-> image file, for tools that only accept files +# -------------------------------------------------------------------------- + +CHUNK = 1024 * 1024 + + +def _chunk_geometry(block: int) -> Tuple[int, int]: + blocks = max(1, CHUNK // block) + return blocks, blocks * block + + +def _progress(done: int, total: int, label: str) -> None: + pct = min(100, int(done * 100 / max(total, 1))) + sys.stderr.write("\r[%s] %3d%% %s of %s" % (label, pct, human(done), human(total))) + sys.stderr.flush() + + +def export_image(fd: int, path: str) -> int: + """Read the card into a sparse file: holes for all-zero chunks.""" + bot, info = open_bot(fd) + try: + bot.wait_ready() + cap = bot.capacity() + block = cap["block_size"] or 512 + blocks_per_chunk, chunk_size = _chunk_geometry(block) + total = cap["blocks"] * block + holes = 0 + written = 0 + lba = 0 + with open(path, "wb") as out: + out.truncate(total) + while lba < cap["blocks"]: + blocks = min(blocks_per_chunk, cap["blocks"] - lba) + data = bot.read10(lba, blocks, block) + if data.count(0) == len(data): + holes += len(data) # leave a hole in the file + else: + out.seek(lba * block) + out.write(data) + written += len(data) + lba += blocks + _progress(lba * block, total, "export") + out.flush() + os.fsync(out.fileno()) + sys.stderr.write("\n") + print("[+] %s: %s (%s data, %s holes)" + % (path, human(total), human(written), human(holes))) + print("[*] work on it with fdisk/sfdisk/mkfs/dd, then: lfa usb bot" + " --import %s" % os.path.basename(path)) + finally: + try: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + print("[*] replug the reader so Android mounts the card again") + return 0 + + +def import_image(fd: int, path: str, full: bool) -> int: + """Write a card image back, rewriting only the chunks that differ.""" + size = os.path.getsize(path) + bot, info = open_bot(fd) + try: + bot.wait_ready() + cap = bot.capacity() + block = cap["block_size"] or 512 + blocks_per_chunk, chunk_size = _chunk_geometry(block) + total = cap["blocks"] * block + if size > total: + print("[!] image is larger than the card (%s > %s)" + % (human(size), human(total)), file=sys.stderr) + return 2 + changed: List[Tuple[int, int]] = [] + changed_bytes = 0 + offset = 0 + with open(path, "rb") as src: + while offset < size: + want = min(chunk_size, size - offset) + blocks = (want + block - 1) // block + expect = src.read(want) + if len(expect) < blocks * block: + expect += b"\x00" * (blocks * block - len(expect)) + current = bot.read10(offset // block, blocks, block) + if full or current != expect: + bot.write10(offset // block, expect, block) + changed.append((offset, len(expect))) + changed_bytes += len(expect) + offset += want + _progress(offset, size, "import") + sys.stderr.write("\n") + bot.sync_cache() + print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) + if not changed: + print("[*] card already matched the image; nothing to verify") + print("[*] replug the reader so Android mounts the card again") + return 0 + print("[*] verifying the chunks that changed") + with open(path, "rb") as src: + for offset, length in changed: + src.seek(offset) + expect = src.read(length) + if len(expect) < length: + expect += b"\x00" * (length - len(expect)) + back = bot.read10(offset // block, length // block, block) + if back != expect: + print("[!] verification failed at byte %d" % offset, + file=sys.stderr) + return 4 + print("[+] verified %d chunk(s)" % len(changed)) + finally: + try: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + print("[*] replug the reader so Android mounts the card again") + return 0 + + # -------------------------------------------------------------------------- # Self test (no device, runs in CI) # -------------------------------------------------------------------------- @@ -602,6 +727,13 @@ def main(argv: Optional[List[str]] = None) -> int: help="write IMAGE to the card (erases it)") parser.add_argument("--no-verify", action="store_true", help="skip reading the image back after --write") + parser.add_argument("--export", metavar="FILE", + help="write the whole card to a sparse file (read-only)") + parser.add_argument("--import", dest="import_file", metavar="FILE", + help="write FILE back, touching only changed chunks") + parser.add_argument("--full", action="store_true", + help="with --import: write every chunk, not only the" + " ones that differ") parser.add_argument("--yes", action="store_true", help="confirm that the card will be erased") parser.add_argument("--json", action="store_true", help="machine output") @@ -610,9 +742,14 @@ def main(argv: Optional[List[str]] = None) -> int: if args.selftest: return selftest() - if not args.probe and not args.write: + actions = [bool(args.probe), bool(args.write), bool(args.export), + bool(args.import_file)] + if sum(actions) != 1: parser.print_help() return 2 + if args.full and not args.import_file: + print("[!] --full only applies to --import", file=sys.stderr) + return 2 if not args.fd: print("[!] no USB descriptor: TERMUX_USB_FD is empty", file=sys.stderr) return 2 @@ -628,6 +765,14 @@ def main(argv: Optional[List[str]] = None) -> int: file=sys.stderr) return 2 return write_image(fd, args.write, not args.no_verify) + if args.export: + return export_image(fd, args.export) + if args.import_file: + if not args.yes: + print("[!] --import overwrites the card. Add --yes when you mean it.", + file=sys.stderr) + return 2 + return import_image(fd, args.import_file, args.full) return probe(fd, args.json) except BotError as exc: print("[!] %s" % exc, file=sys.stderr) diff --git a/tests/test-all.sh b/tests/test-all.sh index fd1625e..a637841 100755 --- a/tests/test-all.sh +++ b/tests/test-all.sh @@ -2055,6 +2055,16 @@ check "Y11 bot selftest" 'selftest: ok' "$T/y11-bot-selftest.log" check "Y11 bot needs an image" 'Usage: lfa usb bot --write IMAGE' "$T/y11-bot-noimage.log" "$LFA" usb help > "$T/y11-usage.log" 2>&1 check "Y11 bot documented" 'talk USB mass storage directly' "$T/y11-usage.log" +# Card as an image file, for fdisk/mkfs/dd inside the guest. +"$LFA" usb bot --export > "$T/y11-bot-noexport.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 bot --export without file exit $rc"; } +check "Y11 bot export usage" 'Usage: lfa usb bot --export FILE' "$T/y11-bot-noexport.log" +"$LFA" usb bot --import > "$T/y11-bot-noimport.log" 2>&1; rc=$? +[ "$rc" = "2" ] && pass=$((pass+1)) \ + || { fail=$((fail+1)); echo "FAIL: Y11 bot --import without file exit $rc"; } +check "Y11 bot import usage" 'Usage: lfa usb bot --import FILE' "$T/y11-bot-noimport.log" +check "Y11 bot export documented" '--export FILE' "$T/y11-usage.log" [ -s "$T/fake-image" ] && [ "$(wc -c < "$T/fake-image")" = "12" ] && pass=$((pass+1)) \ || { fail=$((fail+1)); echo "FAIL: Y11 block write touched the image"; } "$LFA" usb disable -i debian > "$T/y11-auto-disable.log" 2>&1 diff --git a/tracker.md b/tracker.md index ed07f9d..8b1f7f6 100644 --- a/tracker.md +++ b/tracker.md @@ -7,7 +7,7 @@ Status values: | Status | Meaning | |---|---| -| `done` | code changed, suite green (`PASS=853 FAIL=0`), lint clean | +| `done` | code changed, suite green (`PASS=858 FAIL=0`), lint clean | | `partial` | the main risk is addressed; a documented remainder is listed | | `deferred` | deliberately not fixed in this pass, with the reason recorded | | `device` | also exercised on the Vivo V2437 | @@ -53,7 +53,7 @@ Lint: `shellcheck -S warning` clean, `bash -n` clean, CI workflow added. | Android 5/6 refusal | `done` | explicit explanation, `--remove-old` warning, VNC restore command | | `start-linux` notice | `done` | stderr, interactive classic runs only; `lfa notice`, `--no-notice`, `LFA_NO_NOTICE` | | Boot script ownership | `done` | switching a non-autostart instance no longer hijacks another instance's boot script | -| Host suite | `done` | `PASS=853 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | +| Host suite | `done` | `PASS=858 FAIL=0`; Y1-Y11 cover CLI, switch, removal, guard, `-i`, legacy, SDK 24/25, compat/android, matrix, AppImage, USB bridge (attach/tty/flash) | | Device verification | `done` | Vivo V2437 (SDK 36): VNC `PASS=14`, Both switch `PASS=22`, X11 `PASS=14`, VirGL fallback, shims, bridge, `--software`; Oppo SDK 22 pending (off network) | ## Android CI and compatibility layers (2026-11-05) From b5c92438661c92bb14010b261ac0c13e4bb88a05 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:48:32 +0530 Subject: [PATCH 09/17] fix: encode USBDEVFS_DISCONNECT_CLAIM as _IOR, not _IOWR The kernel header defines it with _IOC_READ, and usbfs compares the whole 32-bit command, so the wrong direction bit never reaches the permission or driver checks: every attempt came back ENOTTY ("inappropriate ioctl"), which reads like a ROM restriction but is not. The --selftest now pins every ioctl encoding this script uses against the numbers from , so a mismatch fails in CI instead of on a phone, and an ENOTTY at runtime says plainly that it is an LFA bug. --- lib/lfa-usb-bot.py | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 60aa590..1d2c4fd 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -88,7 +88,10 @@ class DisconnectClaim(ctypes.Structure): USBDEVFS_CLAIMINTERFACE = _ioc(2, ord("U"), 15, 4) USBDEVFS_RELEASEINTERFACE = _ioc(2, ord("U"), 16, 4) USBDEVFS_CLEAR_HALT = _ioc(2, ord("U"), 21, 4) -USBDEVFS_DISCONNECT_CLAIM = _ioc(3, ord("U"), 27, ctypes.sizeof(DisconnectClaim)) +# _IOR, not _IOWR: the kernel header defines it with _IOC_READ, and a +# direction mismatch makes usbfs reject the request with ENOTTY before it +# ever looks at the permission or the driver name. +USBDEVFS_DISCONNECT_CLAIM = _ioc(2, ord("U"), 27, ctypes.sizeof(DisconnectClaim)) GET_DESCRIPTOR = 0x06 DT_DEVICE = 1 @@ -712,6 +715,15 @@ def selftest() -> int: assert mbr["partitions"][0]["start_lba"] == 2048 assert human(1024) == "1.0K" and human(1536) == "1.5K" + + # The ioctl encodings must match ; a wrong + # direction bit is indistinguishable from "unsupported" at runtime. + assert USBDEVFS_CONTROL == 0xC0185500 + assert USBDEVFS_BULK == 0xC0185502 + assert USBDEVFS_CLAIMINTERFACE == 0x8004550F + assert USBDEVFS_RELEASEINTERFACE == 0x80045510 + assert USBDEVFS_CLEAR_HALT == 0x80045515 + assert USBDEVFS_DISCONNECT_CLAIM == 0x8108551B print("selftest: ok") return 0 @@ -776,6 +788,9 @@ def main(argv: Optional[List[str]] = None) -> int: return probe(fd, args.json) except BotError as exc: print("[!] %s" % exc, file=sys.stderr) + if "ENOTTY" in str(exc): + print(" ENOTTY means the kernel does not know that ioctl at all;" + " this is an LFA bug, not a permission problem.", file=sys.stderr) print(" Android may refuse the driver detach on this device.", file=sys.stderr) print(" If it does, the card's files are still available via" " 'lfa usb storage'.", file=sys.stderr) From 921376b4cd69ef52a2dc3703a18e63a7a1ab0b40 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 14:55:51 +0530 Subject: [PATCH 10/17] fix: return byte counts for bulk OUT, and split BOT data phases bulk_transfer() returned the transfer buffer for both directions, so the first CBW comparison did `bytes != int` and raised TypeError before any SCSI command ran. Split transfers into MAX_BULK slices: usbfs refuses a single BULK request larger than 16 KiB, which would have broken every 1 MiB read and write as soon as the probe got past TEST UNIT READY. A bulk pipe is a stream, so the device sees the same bytes. Also issue the Bulk-Only reset right after claiming: usb-storage may have been interrupted mid-command when the driver was detached. Unexpected exceptions at the CLI boundary now print one line instead of a traceback. --- lib/lfa-usb-bot.py | 77 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 57 insertions(+), 20 deletions(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 1d2c4fd..d455227 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -135,17 +135,41 @@ def get_descriptor(fd: int, dtype: int, index: int = 0, length: int = 255, (dtype << 8) | (index & 0xFF), langid, length) -def bulk_transfer(fd: int, ep: int, data: Optional[bytes], length: int, - timeout: int = 15000) -> bytes: - """One USBDEVFS_BULK ioctl. ``data`` None means host->device of ``length``.""" - if data is None: - buf = (ctypes.c_ubyte * max(length, 1))() - else: - buf = (ctypes.c_ubyte * max(len(data), 1)).from_buffer_copy( - data if len(data) else b"\x00") - transfer = BulkTransfer(ep, length, timeout, ctypes.cast(buf, ctypes.c_void_p)) - done = _ioctl(fd, USBDEVFS_BULK, transfer) - return bytes(bytearray(buf))[:done] +# usbfs refuses a single USBDEVFS_BULK request larger than this, so a data +# phase is split into slices; USB bulk is a stream, the device cannot tell. +MAX_BULK = 16384 + + +def bulk_out(fd: int, ep: int, data: bytes, timeout: int = 15000) -> int: + """Host -> device; returns the number of bytes the device accepted.""" + total = 0 + for offset in range(0, len(data), MAX_BULK): + piece = data[offset:offset + MAX_BULK] + buf = (ctypes.c_ubyte * len(piece)).from_buffer_copy(piece) + transfer = BulkTransfer(ep, len(piece), timeout, + ctypes.cast(buf, ctypes.c_void_p)) + done = _ioctl(fd, USBDEVFS_BULK, transfer) + total += done + if done != len(piece): + break + return total + + +def bulk_in(fd: int, ep: int, length: int, timeout: int = 15000) -> bytes: + """Device -> host; returns at most ``length`` bytes (short is legal).""" + out = bytearray() + while len(out) < length: + want = min(MAX_BULK, length - len(out)) + buf = (ctypes.c_ubyte * max(want, 1))() + transfer = BulkTransfer(ep, want, timeout, + ctypes.cast(buf, ctypes.c_void_p)) + done = _ioctl(fd, USBDEVFS_BULK, transfer) + if done <= 0: + break + out += bytes(bytearray(buf))[:done] + if done < want: + break + return bytes(out) def clear_halt(fd: int, ep: int) -> None: @@ -289,17 +313,17 @@ def command(self, cdb: bytes, length: int = 0, direction_in: bool = False, tag = self._next_tag() cbw = build_cbw(tag, length, direction_in, self.lun, cdb) try: - sent = bulk_transfer(self.fd, self.ep_out, cbw, len(cbw)) + sent = bulk_out(self.fd, self.ep_out, cbw) if sent != len(cbw): raise BotError("short CBW write (%d of %d)" % (sent, len(cbw))) payload = b"" if direction_in and length: - payload = bulk_transfer(self.fd, self.ep_in, None, length) + payload = bulk_in(self.fd, self.ep_in, length) elif (not direction_in) and length and data is not None: - sent = bulk_transfer(self.fd, self.ep_out, data, length) + sent = bulk_out(self.fd, self.ep_out, data) if sent != length: raise BotError("short data write (%d of %d)" % (sent, length)) - csw = bulk_transfer(self.fd, self.ep_in, None, 13) + csw = bulk_in(self.fd, self.ep_in, 13) except BotError: if attempt > retries: raise @@ -405,6 +429,8 @@ def open_bot(fd: int, verbose: bool = True) -> Tuple[Bot, Dict[str, Any]]: except BotError: pass bot = Bot(fd, interface, ep_in, ep_out) + # usb-storage may have been interrupted mid-command while we detached it. + bot.reset_recovery() try: luns = control_transfer(fd, 0xA1, 0xFE, 0, interface, 1) if luns: @@ -477,7 +503,8 @@ def probe(fd: int, as_json: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] replug the reader so Android mounts the card again") + print("[*] Android usually remounts the card on its own; replug the" + " reader if it does not") return 0 @@ -549,7 +576,8 @@ def write_image(fd: int, path: str, verify: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] replug the reader so Android mounts the card again") + print("[*] Android usually remounts the card on its own; replug the" + " reader if it does not") return 0 @@ -608,7 +636,8 @@ def export_image(fd: int, path: str) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] replug the reader so Android mounts the card again") + print("[*] Android usually remounts the card on its own; replug the" + " reader if it does not") return 0 @@ -648,7 +677,8 @@ def import_image(fd: int, path: str, full: bool) -> int: print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) if not changed: print("[*] card already matched the image; nothing to verify") - print("[*] replug the reader so Android mounts the card again") + print("[*] Android usually remounts the card on its own; replug the" + " reader if it does not") return 0 print("[*] verifying the chunks that changed") with open(path, "rb") as src: @@ -668,7 +698,8 @@ def import_image(fd: int, path: str, full: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] replug the reader so Android mounts the card again") + print("[*] Android usually remounts the card on its own; replug the" + " reader if it does not") return 0 @@ -795,6 +826,12 @@ def main(argv: Optional[List[str]] = None) -> int: print(" If it does, the card's files are still available via" " 'lfa usb storage'.", file=sys.stderr) return 5 + except Exception as exc: # noqa: BLE001 - CLI boundary + print("[!] unexpected failure: %s: %s" % (type(exc).__name__, exc), + file=sys.stderr) + print(" Run with --probe again; if it repeats, please report it.", + file=sys.stderr) + return 5 if __name__ == "__main__": From 50275e21a73f352f10718a50925c7eb6c70410a6 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:04:45 +0530 Subject: [PATCH 11/17] feat: name partitions in the probe, and refresh before picking the device The probe now reads each partition's boot sector and prints its filesystem and volume label, so an existing Ventoy card is obvious: the 32 MB type-0xef partition carries the VTOYEFI label, and the report says to put ISOs on the data partition instead of flashing. The labels are in --json too. A detach makes Android re-enumerate the reader (001/002 became 001/003 for the next command), so `lfa usb bot` refreshes the cached device list before choosing the only visible device. --- install_linux.sh | 3 +++ lib/lfa-usb-bot.py | 50 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/install_linux.sh b/install_linux.sh index 406a549..dbeef8f 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -4323,6 +4323,9 @@ lfa_usb_bot() { # [DEV] [--probe|--write IMAGE|--export FILE|--import FILE] return 2 fi if [ -z "$_dev" ]; then + # A detach makes Android re-enumerate the reader, so the cached + # bus/dev number is stale by the next command. Refresh first. + lfa_usb_refresh >/dev/null 2>&1 || true _dev="$(lfa_usb_default_dev)" [ -n "$_dev" ] || { echo "[!] No USB device is visible. Connect one and run: lfa usb refresh" >&2 diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index d455227..912fe0f 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -441,6 +441,26 @@ def open_bot(fd: int, verbose: bool = True) -> Tuple[Bot, Dict[str, Any]]: "interface": interface, "ep_in": ep_in, "ep_out": ep_out} +def describe_volume(sector: bytes) -> Tuple[str, str]: + """Filesystem name and volume label from a partition's boot sector.""" + if len(sector) < 512: + return "?", "" + if sector[3:11] == b"EXFAT ": + return "exFAT", "" + if sector[3:11] == b"NTFS ": + return "NTFS", "" + if sector[0x52:0x5A] == b"FAT32 ": + label = sector[0x47:0x52] + return "FAT32", label.decode("ascii", "replace").strip() + for name in ("FAT16", "FAT12"): + if sector[0x36:0x3E] == name.ljust(8).encode(): + label = sector[0x2B:0x36] + return name, label.decode("ascii", "replace").strip() + if struct.unpack_from(" Dict[str, Any]: if len(sector) < 512: return {"signature": None, "partitions": []} @@ -477,6 +497,14 @@ def probe(fd: int, as_json: bool) -> int: cap = bot.capacity() sector = bot.read10(0, 1, cap["block_size"] or 512) mbr = parse_mbr(sector) + # Read each partition's boot sector so the report can name the + # filesystem and label (VTOYEFI is how an existing Ventoy card shows). + for part in mbr["partitions"]: + try: + boot = bot.read10(part["start_lba"], 1, cap["block_size"] or 512) + part["fs"], part["label"] = describe_volume(boot) + except BotError: + part["fs"], part["label"] = "?", "" result = dict(info) result.update({"inquiry": inquiry, "capacity": cap, "mbr": mbr}) if as_json: @@ -492,10 +520,19 @@ def probe(fd: int, as_json: bool) -> int: if not mbr["partitions"]: print(" no partitions (blank or not yet flashed)") for part in mbr["partitions"]: - print(" #%d type %s start %d (%s) size %s%s" + extra = "" + if part["fs"] != "?": + extra += " " + part["fs"] + if part["label"]: + extra += ' "%s"' % part["label"] + print(" #%d type %s start %d (%s) size %s%s%s" % (part["index"], part["type"], part["start_lba"], human(part["start_lba"] * 512), human(part["bytes"]), - " bootable" if part["bootable"] else "")) + " bootable" if part["bootable"] else "", extra)) + labels = [p.get("label", "").upper() for p in mbr["partitions"]] + if any(label.startswith("VTOY") for label in labels): + print(" This card already has Ventoy: put ISOs on the data") + print(" partition (/mnt/card). Flashing is not needed.") print("RAW WRITE: possible without root through this transport") print(" lfa usb bot --write IMAGE --yes") finally: @@ -747,6 +784,15 @@ def selftest() -> int: assert human(1024) == "1.0K" and human(1536) == "1.5K" + fat32 = bytearray(512) + fat32[0x52:0x5A] = b"FAT32 " + fat32[0x47:0x52] = b"VTOYEFI " + struct.pack_into("; a wrong # direction bit is indistinguishable from "unsupported" at runtime. assert USBDEVFS_CONTROL == 0xC0185500 From 0cc764635e055c351b046e86566d6f5765901979 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:27:03 +0530 Subject: [PATCH 12/17] feat: ask Android to remount the card after a Bulk-Only session Unbinding usb-storage is one-way from userspace: releasing the interface does not make the driver core probe again, so after a probe the card stayed gone from /storage until the reader was physically replugged. After a command, check /proc/mounts for a removable volume; if there is none, issue USBDEVFS_RESET and look again, reporting which of the two happened. A refused reset falls back to telling the user to replug, instead of claiming the card is back. The probe also prints the filesystem and label of each partition now, which is how an existing Ventoy card is recognised (FAT16 "VTOYEFI"), and the docs warn that a FAT32 data partition cannot hold an ISO over 4 GiB. --- docs/USB.md | 21 +++++++++++++++++ lib/lfa-usb-bot.py | 59 ++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 70 insertions(+), 10 deletions(-) diff --git a/docs/USB.md b/docs/USB.md index eddb6f6..aeb39ab 100644 --- a/docs/USB.md +++ b/docs/USB.md @@ -439,6 +439,27 @@ targets), `dd`, `fsck`, `debugfs`, byte patching. What does not: `losetup`, `mount -o loop`, and installers that insist on `S_ISBLK` (Ventoy2Disk). The kernel is still missing; only the storage moved. +### Checking an existing Ventoy card + +`lfa usb bot --probe` reads each partition's boot sector, so the report +names the filesystem and the volume label: + +``` +#1 type 0x07 start 2048 size 7.4G bootable FAT32 "NO NAME" +#2 type 0xef start 15540224 size 32.0M FAT16 "VTOYEFI" +This card already has Ventoy: put ISOs on the data partition (/mnt/card). +``` + +`VTOYEFI` is the 32 MB partition Ventoy creates; when it is present the card +is already bootable and nothing needs flashing. Watch the data partition's +filesystem: **FAT32 cannot hold an ISO larger than 4 GiB**, so a card with a +FAT32 data partition needs small ISOs, or a reinstall with Ventoy's default +exFAT (a PC job, since the installer wants a block device). + +A Bulk-Only session unbinds `usb-storage`, and the driver core only looks +again when the device re-enumerates. LFA asks for a USB reset afterwards and +reports whether Android remounted the card; if it did not, replug the reader. + ### Ventoy without raw writes Copying ISOs onto an existing Ventoy card works without root, because the diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 912fe0f..1000831 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -88,6 +88,7 @@ class DisconnectClaim(ctypes.Structure): USBDEVFS_CLAIMINTERFACE = _ioc(2, ord("U"), 15, 4) USBDEVFS_RELEASEINTERFACE = _ioc(2, ord("U"), 16, 4) USBDEVFS_CLEAR_HALT = _ioc(2, ord("U"), 21, 4) +USBDEVFS_RESET = _ioc(0, ord("U"), 20, 0) # _IOR, not _IOWR: the kernel header defines it with _IOC_READ, and a # direction mismatch makes usbfs reject the request with ENOTTY before it # ever looks at the permission or the driver name. @@ -232,6 +233,9 @@ def claim_interface(fd: int, interface: int, verbose: bool = True) -> str: """Claim, detaching Android's kernel driver if it holds the interface.""" try: fcntl.ioctl(fd, USBDEVFS_CLAIMINTERFACE, struct.pack("I", interface)) + if verbose: + print("[*] interface %d was already free (Android had released it)" + % interface) return "free" except OSError as exc: first = _errno_name(exc) @@ -540,8 +544,7 @@ def probe(fd: int, as_json: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] Android usually remounts the card on its own; replug the" - " reader if it does not") + restore_android(fd) return 0 @@ -613,11 +616,50 @@ def write_image(fd: int, path: str, verify: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] Android usually remounts the card on its own; replug the" - " reader if it does not") + restore_android(fd) return 0 +def android_has_card() -> bool: + """Is a removable volume mounted under /storage right now?""" + try: + with open("/proc/mounts", "r") as handle: + for line in handle: + fields = line.split() + if len(fields) < 2: + continue + target = fields[1] + if target.startswith("/storage/") and not target.startswith( + "/storage/emulated"): + return True + except OSError: + return False + return False + + +def restore_android(fd: int) -> None: + """Nudge the kernel to re-probe usb-storage so Android remounts the card. + + Releasing the interface is not enough: the driver was unbound, and the + driver core only looks again when the device re-enumerates. A USB reset + is the closest thing to a replug an app can ask for. If it is refused, + say so instead of pretending the card is back. + """ + if android_has_card(): + print("[*] Android has the card mounted again") + return + try: + fcntl.ioctl(fd, USBDEVFS_RESET) + except OSError: + pass + time.sleep(1.0) + if android_has_card(): + print("[+] card is mounted again; /mnt/card works") + else: + print("[*] Android has not remounted the card; replug the reader to" + " use /mnt/card again") + + # -------------------------------------------------------------------------- # Card <-> image file, for tools that only accept files # -------------------------------------------------------------------------- @@ -673,8 +715,7 @@ def export_image(fd: int, path: str) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] Android usually remounts the card on its own; replug the" - " reader if it does not") + restore_android(fd) return 0 @@ -714,8 +755,7 @@ def import_image(fd: int, path: str, full: bool) -> int: print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) if not changed: print("[*] card already matched the image; nothing to verify") - print("[*] Android usually remounts the card on its own; replug the" - " reader if it does not") + restore_android(fd) return 0 print("[*] verifying the chunks that changed") with open(path, "rb") as src: @@ -735,8 +775,7 @@ def import_image(fd: int, path: str, full: bool) -> int: fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) except OSError: pass - print("[*] Android usually remounts the card on its own; replug the" - " reader if it does not") + restore_android(fd) return 0 From 8466deb6e6e9c2021b27c42caf44d3b949bc59cc Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:04:58 +0530 Subject: [PATCH 13/17] feat: rebind usb-storage with USBDEVFS_CONNECT before resetting USBDEVFS_CONNECT makes the driver core attach an unclaimed interface again, which is what Android's vold needs to see the card and mount it. It is the first thing tried after a session now; USBDEVFS_RESET (re-enumeration) is the fallback, and the mount table is polled for a few seconds between them. If neither brings the volume back, the message says to replug instead of assuming it worked. Progress lines no longer use carriage returns when stderr is a pipe: a redirected run prints one line per 10% instead of a single mangled line. --- lib/lfa-usb-bot.py | 55 ++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 46 insertions(+), 9 deletions(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 1000831..c7342c4 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -89,6 +89,7 @@ class DisconnectClaim(ctypes.Structure): USBDEVFS_RELEASEINTERFACE = _ioc(2, ord("U"), 16, 4) USBDEVFS_CLEAR_HALT = _ioc(2, ord("U"), 21, 4) USBDEVFS_RESET = _ioc(0, ord("U"), 20, 0) +USBDEVFS_CONNECT = _ioc(0, ord("U"), 23, 0) # _IOR, not _IOWR: the kernel header defines it with _IOC_READ, and a # direction mismatch makes usbfs reject the request with ENOTTY before it # ever looks at the permission or the driver name. @@ -648,16 +649,33 @@ def restore_android(fd: int) -> None: if android_has_card(): print("[*] Android has the card mounted again") return + + def wait(seconds: float) -> bool: + deadline = time.time() + seconds + while time.time() < deadline: + if android_has_card(): + return True + time.sleep(0.25) + return android_has_card() + + # 1. Ask the driver core to bind the now-unclaimed interface again. + try: + fcntl.ioctl(fd, USBDEVFS_CONNECT) + except OSError: + pass + if wait(5.0): + print("[+] usb-storage rebound; /mnt/card works again") + return + # 2. Re-enumerate the device, which makes the kernel probe its drivers. try: fcntl.ioctl(fd, USBDEVFS_RESET) except OSError: pass - time.sleep(1.0) - if android_has_card(): + if wait(5.0): print("[+] card is mounted again; /mnt/card works") - else: - print("[*] Android has not remounted the card; replug the reader to" - " use /mnt/card again") + return + print("[*] Android has not remounted the card; replug the reader to" + " use /mnt/card again") # -------------------------------------------------------------------------- @@ -672,10 +690,25 @@ def _chunk_geometry(block: int) -> Tuple[int, int]: return blocks, blocks * block +_progress_last = {"pct": -1} + + def _progress(done: int, total: int, label: str) -> None: pct = min(100, int(done * 100 / max(total, 1))) - sys.stderr.write("\r[%s] %3d%% %s of %s" % (label, pct, human(done), human(total))) - sys.stderr.flush() + line = "[%s] %3d%% %s of %s" % (label, pct, human(done), human(total)) + if sys.stderr.isatty(): + sys.stderr.write("\r" + line) + sys.stderr.flush() + return + # Piped output: one line per 10%, so logs and CI stay readable. + if pct >= _progress_last["pct"] + 10 or pct == 100: + _progress_last["pct"] = pct + sys.stderr.write(line + "\n") + sys.stderr.flush() + + +def _progress_reset() -> None: + _progress_last["pct"] = -1 def export_image(fd: int, path: str) -> int: @@ -687,6 +720,7 @@ def export_image(fd: int, path: str) -> int: block = cap["block_size"] or 512 blocks_per_chunk, chunk_size = _chunk_geometry(block) total = cap["blocks"] * block + _progress_reset() holes = 0 written = 0 lba = 0 @@ -705,7 +739,8 @@ def export_image(fd: int, path: str) -> int: _progress(lba * block, total, "export") out.flush() os.fsync(out.fileno()) - sys.stderr.write("\n") + if sys.stderr.isatty(): + sys.stderr.write("\n") print("[+] %s: %s (%s data, %s holes)" % (path, human(total), human(written), human(holes))) print("[*] work on it with fdisk/sfdisk/mkfs/dd, then: lfa usb bot" @@ -733,6 +768,7 @@ def import_image(fd: int, path: str, full: bool) -> int: print("[!] image is larger than the card (%s > %s)" % (human(size), human(total)), file=sys.stderr) return 2 + _progress_reset() changed: List[Tuple[int, int]] = [] changed_bytes = 0 offset = 0 @@ -750,7 +786,8 @@ def import_image(fd: int, path: str, full: bool) -> int: changed_bytes += len(expect) offset += want _progress(offset, size, "import") - sys.stderr.write("\n") + if sys.stderr.isatty(): + sys.stderr.write("\n") bot.sync_cache() print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) if not changed: From cd3d9c5869d5c259fbaa71413288bafb68064561 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:37:20 +0530 Subject: [PATCH 14/17] fix: do not flush a read-only session, and say where a transfer died `--import` sent SYNCHRONIZE CACHE(10) even when every chunk matched and nothing had been written. This 14cd:1212 bridge answers that command with a 15 s stall, so a successful comparison ended in ETIMEDOUT right after 100%. The flush now runs only when something was actually written, a refused flush is a warning (the read-back is the real check), and read/write failures carry the byte offset they stopped at. The "Android refused the detach" hint is only printed for claim errors; mid-transfer failures suggest a replug. --- lib/lfa-usb-bot.py | 52 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index c7342c4..d97c3df 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -579,14 +579,22 @@ def write_image(fd: int, path: str, verify: bool) -> int: break if len(data) % block: data += b"\x00" * (block - len(data) % block) - bot.write10(lba, data, block) + try: + bot.write10(lba, data, block) + except BotError as exc: + raise BotError("write failed at byte %d of %d: %s" + % (lba * block, size, exc)) from exc written += len(data) lba += len(data) // block pct = min(100, int(written * 100 / max(size, 1))) sys.stderr.write("\r[*] %3d%% %s" % (pct, human(written))) sys.stderr.flush() sys.stderr.write("\n") - bot.sync_cache() + try: + bot.sync_cache() + except BotError as exc: + print("[!] SYNCHRONIZE CACHE failed (%s); verifying anyway" % exc, + file=sys.stderr) print("[+] wrote %s" % human(written)) if verify: print("[*] reading the card back") @@ -728,7 +736,11 @@ def export_image(fd: int, path: str) -> int: out.truncate(total) while lba < cap["blocks"]: blocks = min(blocks_per_chunk, cap["blocks"] - lba) - data = bot.read10(lba, blocks, block) + try: + data = bot.read10(lba, blocks, block) + except BotError as exc: + raise BotError("read failed at byte %d of %d: %s" + % (lba * block, total, exc)) from exc if data.count(0) == len(data): holes += len(data) # leave a hole in the file else: @@ -779,16 +791,29 @@ def import_image(fd: int, path: str, full: bool) -> int: expect = src.read(want) if len(expect) < blocks * block: expect += b"\x00" * (blocks * block - len(expect)) - current = bot.read10(offset // block, blocks, block) + try: + current = bot.read10(offset // block, blocks, block) + except BotError as exc: + raise BotError("read failed at byte %d of %d: %s" + % (offset, size, exc)) from exc if full or current != expect: - bot.write10(offset // block, expect, block) + try: + bot.write10(offset // block, expect, block) + except BotError as exc: + raise BotError("write failed at byte %d of %d: %s" + % (offset, size, exc)) from exc changed.append((offset, len(expect))) changed_bytes += len(expect) offset += want _progress(offset, size, "import") if sys.stderr.isatty(): sys.stderr.write("\n") - bot.sync_cache() + if changed: + try: + bot.sync_cache() + except BotError as exc: + print("[!] the card refused SYNCHRONIZE CACHE (%s); the read-back" + " below is the real check" % exc, file=sys.stderr) print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) if not changed: print("[*] card already matched the image; nothing to verify") @@ -940,13 +965,20 @@ def main(argv: Optional[List[str]] = None) -> int: return import_image(fd, args.import_file, args.full) return probe(fd, args.json) except BotError as exc: + text = str(exc) print("[!] %s" % exc, file=sys.stderr) - if "ENOTTY" in str(exc): + if "ENOTTY" in text: print(" ENOTTY means the kernel does not know that ioctl at all;" " this is an LFA bug, not a permission problem.", file=sys.stderr) - print(" Android may refuse the driver detach on this device.", file=sys.stderr) - print(" If it does, the card's files are still available via" - " 'lfa usb storage'.", file=sys.stderr) + elif "claim" in text or "detach" in text: + print(" Android refused to release the reader's interface.", + file=sys.stderr) + print(" The card's files are still available via" + " 'lfa usb storage'.", file=sys.stderr) + else: + print(" The reader stopped answering mid-transfer. Unplug and" + " replug it, then retry; the offset above says how far it" + " got.", file=sys.stderr) return 5 except Exception as exc: # noqa: BLE001 - CLI boundary print("[!] unexpected failure: %s: %s" % (type(exc).__name__, exc), From fd86e849993e9b7b3939bdeff594db6fbd0c03ab Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:22:56 +0530 Subject: [PATCH 15/17] fix: survive a refused flush and report where chunks changed A 15 s timeout per attempt is far too long for a command this bridge simply does not implement; the flush now fails after 4 s with no retry, and the transport is reset before verification so a wedged bridge does not make the read-back look like a bad write. Verification reads retry once after a reset, changed chunk offsets are printed (the FAT32 boot sector of partition 1 is byte 1048576, so a diff there is Android's own mount metadata, not corruption), and a mismatch now distinguishes "could not read" from "read different bytes". --- lib/lfa-usb-bot.py | 50 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index d97c3df..fc0b177 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -310,7 +310,8 @@ def reset_recovery(self) -> None: clear_halt(self.fd, self.ep_out) def command(self, cdb: bytes, length: int = 0, direction_in: bool = False, - data: Optional[bytes] = None, retries: int = 1) -> Tuple[bytes, int]: + data: Optional[bytes] = None, retries: int = 1, + timeout: int = 15000) -> Tuple[bytes, int]: """Run one SCSI command; return (payload_in, data_residue).""" attempt = 0 while True: @@ -318,17 +319,17 @@ def command(self, cdb: bytes, length: int = 0, direction_in: bool = False, tag = self._next_tag() cbw = build_cbw(tag, length, direction_in, self.lun, cdb) try: - sent = bulk_out(self.fd, self.ep_out, cbw) + sent = bulk_out(self.fd, self.ep_out, cbw, timeout) if sent != len(cbw): raise BotError("short CBW write (%d of %d)" % (sent, len(cbw))) payload = b"" if direction_in and length: - payload = bulk_in(self.fd, self.ep_in, length) + payload = bulk_in(self.fd, self.ep_in, length, timeout) elif (not direction_in) and length and data is not None: - sent = bulk_out(self.fd, self.ep_out, data) + sent = bulk_out(self.fd, self.ep_out, data, timeout) if sent != length: raise BotError("short data write (%d of %d)" % (sent, length)) - csw = bulk_in(self.fd, self.ep_in, 13) + csw = bulk_in(self.fd, self.ep_in, 13, timeout) except BotError: if attempt > retries: raise @@ -396,8 +397,11 @@ def write10(self, lba: int, data: bytes, block_size: int) -> None: if residue: raise BotError("WRITE(10) residue %d" % residue) - def sync_cache(self) -> None: - self.command(b"\x35" + b"\x00" * 9, 0, False) + def sync_cache(self, timeout: int = 4000) -> None: + # Many cheap bridges stall on this command instead of rejecting it. + # Fail fast and let the caller recover rather than burning 15 s twice. + self.command(b"\x35" + b"\x00" * 9, 0, False, retries=0, + timeout=timeout) # -------------------------------------------------------------------------- @@ -812,9 +816,17 @@ def import_image(fd: int, path: str, full: bool) -> int: try: bot.sync_cache() except BotError as exc: - print("[!] the card refused SYNCHRONIZE CACHE (%s); the read-back" - " below is the real check" % exc, file=sys.stderr) - print("[+] wrote %s in %d chunk(s)" % (human(changed_bytes), len(changed))) + print("[!] the card refused SYNCHRONIZE CACHE (%s); resetting the" + " transport and verifying by read-back" % exc, file=sys.stderr) + try: + bot.reset_recovery() + bot.wait_ready() + except BotError: + pass + where = ", ".join(str(off) for off, _ in changed[:4]) + print("[+] wrote %s in %d chunk(s)%s" + % (human(changed_bytes), len(changed), + (" at byte " + where) if where else "")) if not changed: print("[*] card already matched the image; nothing to verify") restore_android(fd) @@ -826,9 +838,23 @@ def import_image(fd: int, path: str, full: bool) -> int: expect = src.read(length) if len(expect) < length: expect += b"\x00" * (length - len(expect)) - back = bot.read10(offset // block, length // block, block) + back = b"" + for attempt in (1, 2): + try: + back = bot.read10(offset // block, length // block, block) + break + except BotError as exc: + if attempt == 2: + raise BotError("verification read failed at byte %d: %s" + % (offset, exc)) from exc + try: + bot.reset_recovery() + bot.wait_ready() + except BotError: + pass if back != expect: - print("[!] verification failed at byte %d" % offset, + print("[!] verification failed at byte %d: the card returned" + " different bytes than the image" % offset, file=sys.stderr) return 4 print("[+] verified %d chunk(s)" % len(changed)) From 479aafee959f18ffd78933d74ce4835acd76c895 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:11:13 +0530 Subject: [PATCH 16/17] feat: retry a dropped link, and make --export resumable This 14cd:1212 bridge occasionally drops the USB link under sustained load (EPROTO partway through a 7.4 GB read), so every chunk read now gets up to three attempts with a Bulk-Only reset and CLEAR_HALT between them, and ENODEV/ESHUTDOWN stop immediately instead of retrying a dead descriptor. --export writes its offset to FILE.lfa-progress every 32 MiB and removes it on success, so a dropped link costs a re-run rather than the whole read. --import is already restartable by nature: chunks that reached the card match the image next time and are skipped. --- lib/lfa-usb-bot.py | 93 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 71 insertions(+), 22 deletions(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index fc0b177..598c25c 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -380,6 +380,32 @@ def capacity(self) -> Dict[str, int]: last_lba, block = struct.unpack(">II", payload) return {"last_lba": last_lba, "blocks": last_lba + 1, "block_size": block} + def read10_retry(self, lba: int, blocks: int, block_size: int, + tries: int = 3) -> bytes: + """read10, resetting the transport between attempts. + + Cheap bridges drop the link under sustained load (EPROTO/ETIMEDOUT); + the read is idempotent, so it is worth asking again before failing. + """ + last: Optional[BotError] = None + for attempt in range(tries): + try: + return self.read10(lba, blocks, block_size) + except BotError as exc: + last = exc + text = str(exc) + if "ENODEV" in text or "ESHUTDOWN" in text: + break # the reader re-enumerated; stop + if attempt + 1 == tries: + break + try: + self.reset_recovery() + self.wait_ready(tries=4) + except BotError: + pass + time.sleep(0.5) + raise last if last else BotError("read failed") + def read10(self, lba: int, blocks: int, block_size: int) -> bytes: cdb = struct.pack(">BBIBHB", 0x28, 0, lba, 0, blocks, 0) payload, residue = self.command(cdb, blocks * block_size, True) @@ -726,6 +752,7 @@ def _progress_reset() -> None: def export_image(fd: int, path: str) -> int: """Read the card into a sparse file: holes for all-zero chunks.""" bot, info = open_bot(fd) + state = path + ".lfa-progress" try: bot.wait_ready() cap = bot.capacity() @@ -735,26 +762,48 @@ def export_image(fd: int, path: str) -> int: _progress_reset() holes = 0 written = 0 - lba = 0 - with open(path, "wb") as out: - out.truncate(total) - while lba < cap["blocks"]: - blocks = min(blocks_per_chunk, cap["blocks"] - lba) - try: - data = bot.read10(lba, blocks, block) - except BotError as exc: - raise BotError("read failed at byte %d of %d: %s" - % (lba * block, total, exc)) from exc - if data.count(0) == len(data): - holes += len(data) # leave a hole in the file - else: - out.seek(lba * block) - out.write(data) - written += len(data) - lba += blocks - _progress(lba * block, total, "export") - out.flush() - os.fsync(out.fileno()) + start = 0 + if os.path.exists(state): + try: + with open(state, "r") as handle: + start = int(handle.read().strip() or "0") + except (OSError, ValueError): + start = 0 + start = max(0, min(start, total)) + start -= start % chunk_size + lba = start // block + if start: + print("[*] resuming at %s of %s" % (human(start), human(total))) + mode = "r+b" if start and os.path.exists(path) else "wb" + persisted = lba + try: + with open(path, mode) as out: + if not start: + out.truncate(total) + while lba < cap["blocks"]: + blocks = min(blocks_per_chunk, cap["blocks"] - lba) + data = bot.read10_retry(lba, blocks, block) + if data.count(0) == len(data): + holes += len(data) # leave a hole in the file + else: + out.seek(lba * block) + out.write(data) + written += len(data) + lba += blocks + _progress(lba * block, total, "export") + # A crash costs at most 32 MiB of re-reading. + if lba - persisted >= blocks_per_chunk * 32: + with open(state, "w") as handle: + handle.write(str(lba * block)) + persisted = lba + out.flush() + os.fsync(out.fileno()) + except BotError as exc: + with open(state, "w") as handle: + handle.write(str(lba * block)) + raise BotError("%s (saved progress at %s; re-run the same command" + " to resume)" % (exc, human(lba * block))) from exc + os.unlink(state) if sys.stderr.isatty(): sys.stderr.write("\n") print("[+] %s: %s (%s data, %s holes)" @@ -796,7 +845,7 @@ def import_image(fd: int, path: str, full: bool) -> int: if len(expect) < blocks * block: expect += b"\x00" * (blocks * block - len(expect)) try: - current = bot.read10(offset // block, blocks, block) + current = bot.read10_retry(offset // block, blocks, block) except BotError as exc: raise BotError("read failed at byte %d of %d: %s" % (offset, size, exc)) from exc @@ -841,7 +890,7 @@ def import_image(fd: int, path: str, full: bool) -> int: back = b"" for attempt in (1, 2): try: - back = bot.read10(offset // block, length // block, block) + back = bot.read10_retry(offset // block, length // block, block) break except BotError as exc: if attempt == 2: From b873e34a095ce208c6b073e2f4fd13064c9a2644 Mon Sep 17 00:00:00 2001 From: pdev <300827144+pdev-labs@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:34:21 +0530 Subject: [PATCH 17/17] feat: narrate verification so a transport reset does not look like a hang After a refused flush the tool resets the link and retries the read-back, which can take up to ~30s with no output. Print the chunk offsets being verified, a line per chunk when there are few, and the retry itself. --- lib/lfa-usb-bot.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py index 598c25c..3e40ba0 100644 --- a/lib/lfa-usb-bot.py +++ b/lib/lfa-usb-bot.py @@ -880,9 +880,14 @@ def import_image(fd: int, path: str, full: bool) -> int: print("[*] card already matched the image; nothing to verify") restore_android(fd) return 0 - print("[*] verifying the chunks that changed") + print("[*] verifying %d chunk(s): %s" + % (len(changed), ", ".join(str(off) for off, _ in changed[:8]) + + (" ..." if len(changed) > 8 else ""))) with open(path, "rb") as src: for offset, length in changed: + if len(changed) <= 8: + print("[*] reading back byte %d (%s)" + % (offset, human(length))) src.seek(offset) expect = src.read(length) if len(expect) < length: @@ -896,6 +901,8 @@ def import_image(fd: int, path: str, full: bool) -> int: if attempt == 2: raise BotError("verification read failed at byte %d: %s" % (offset, exc)) from exc + print("[*] transport stalled; resetting and retrying" + " (attempt %d of 2)" % (attempt + 1)) try: bot.reset_recovery() bot.wait_ready() @@ -906,6 +913,8 @@ def import_image(fd: int, path: str, full: bool) -> int: " different bytes than the image" % offset, file=sys.stderr) return 4 + if len(changed) <= 8: + print("[+] byte %d matches" % offset) print("[+] verified %d chunk(s)" % len(changed)) finally: try: