diff --git a/CHANGELOG.md b/CHANGELOG.md index bb9e898..8209097 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,44 @@ 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 + `/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. +- `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. +- `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. +- `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 + `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..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 `811` 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=811 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 662877c..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=811 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=811 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 32c534d..aeb39ab 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 ``` @@ -100,8 +133,9 @@ 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, 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 @@ -226,6 +260,220 @@ 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/card (rw) +ls /mnt/card +``` + +Sessions started by LFA bind: + +| Path | Contents | +|---|---| +| `/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 +`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 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. + +### 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. + +### 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. + +### 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 +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 4709bb0..dbeef8f 100755 --- a/install_linux.sh +++ b/install_linux.sh @@ -2750,9 +2750,13 @@ 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 + block [write IMAGE] show the card's raw block device / write an image + 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 - 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 +2771,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 +2923,13 @@ 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")" + _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/card" + 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" @@ -3139,6 +3151,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 +3502,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 +3522,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 @@ -3511,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 @@ -3932,6 +3953,567 @@ 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 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 _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 + _out="${_out:+$_out;}$_root/$_id:/media/$_id" + [ "$_id" = "$_alias" ] && _out="$_out;$_root/$_id:/mnt/card" + done </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_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|--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 + 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 ;; + --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 ;; + --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 [ "$_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 + # 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 + 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." + 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[@]}" +} + +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 + # 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" ] || \ + [ "$(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 +4615,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 +4935,14 @@ lfa_cli_usb() { watch|monitor) lfa_usb_watch "$@" ;; 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 "$@" ;; + *) lfa_usb_block "$@" ;; + esac ;; + auto) lfa_usb_auto "$@" ;; exec|run) lfa_usb_exec "$@" ;; attach|shell) lfa_usb_attach "$@" ;; tty|serial) lfa_usb_tty "$@" ;; @@ -7291,6 +7848,44 @@ 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 +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() { + 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. LAST_SERVER_FILE="$HOME/.config/linux-for-android/last-server-$INSTANCE_NAME" @@ -7401,10 +7996,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 +8093,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 +8134,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 +8354,29 @@ 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 +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 + TERM_MODE="" EXPLICIT_INSTANCE=0 PRESELECT_INSTANCE="" @@ -7838,10 +8456,29 @@ 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 - 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/lib/lfa-usb-bot.py b/lib/lfa-usb-bot.py new file mode 100644 index 0000000..3e40ba0 --- /dev/null +++ b/lib/lfa-usb-bot.py @@ -0,0 +1,1076 @@ +#!/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 [--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. +""" + +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_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. +USBDEVFS_DISCONNECT_CLAIM = _ioc(2, 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) + + +# 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: + 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)) + if verbose: + print("[*] interface %d was already free (Android had released it)" + % 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, + timeout: int = 15000) -> 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_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, timeout) + elif (not direction_in) and length and data is not None: + 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, timeout) + 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_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) + 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, 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) + + +# -------------------------------------------------------------------------- +# 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(" 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": []} + 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) + # 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: + 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"]: + 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 "", 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: + try: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + restore_android(fd) + 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) + 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") + 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") + 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 + 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 + + 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 + if wait(5.0): + print("[+] card is mounted again; /mnt/card works") + return + print("[*] Android has not remounted the card; replug the reader to" + " use /mnt/card again") + + +# -------------------------------------------------------------------------- +# 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 + + +_progress_last = {"pct": -1} + + +def _progress(done: int, total: int, label: str) -> None: + pct = min(100, int(done * 100 / max(total, 1))) + 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: + """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() + block = cap["block_size"] or 512 + blocks_per_chunk, chunk_size = _chunk_geometry(block) + total = cap["blocks"] * block + _progress_reset() + holes = 0 + written = 0 + 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)" + % (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 + restore_android(fd) + 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 + _progress_reset() + 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)) + try: + 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 + if full or current != expect: + 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") + if changed: + try: + bot.sync_cache() + except BotError as exc: + 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) + return 0 + 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: + expect += b"\x00" * (length - len(expect)) + back = b"" + for attempt in (1, 2): + try: + back = bot.read10_retry(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 + print("[*] transport stalled; resetting and retrying" + " (attempt %d of 2)" % (attempt + 1)) + try: + bot.reset_recovery() + bot.wait_ready() + except BotError: + pass + if back != expect: + print("[!] verification failed at byte %d: the card returned" + " 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: + fcntl.ioctl(fd, USBDEVFS_RELEASEINTERFACE, struct.pack("I", bot.interface)) + except OSError: + pass + restore_android(fd) + 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("; 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 + + +def main(argv: Optional[List[str]] = None) -> 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("--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") + parser.add_argument("--selftest", action="store_true") + args = parser.parse_args(argv) + + if args.selftest: + return selftest() + 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 + 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) + 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: + text = str(exc) + print("[!] %s" % exc, file=sys.stderr) + 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) + 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), + file=sys.stderr) + print(" Run with --probe again; if it repeats, please report it.", + file=sys.stderr) + return 5 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test-all.sh b/tests/test-all.sh index 42f232f..a637841 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 @@ -1974,6 +1977,101 @@ 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() {' "$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 +# 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/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"; } + +# 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" +# 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" +# 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 +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..8b1f7f6 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=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=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=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)