Skip to content

feat: a real USB port in the guest through Termux:API - #2

Merged
pdev-labs merged 16 commits into
mainfrom
feat/usb-real-port
Nov 22, 2026
Merged

pdev-labs merged 16 commits into
mainfrom
feat/usb-real-port

Conversation

@pdev-labs

Copy link
Copy Markdown
Owner

What this does

Gives the Linux guest a real userspace USB port instead of the old
descriptor-only lfa usb exec:

  • lfa usb attach → /dev/bus/usb/BBB/DDD + a /sys/bus/usb/devices tree,
    so unmodified lsusb, PyUSB, dfu-util and friends work.
  • lfa usb tty → /dev/ttyUSB0 for serial tools.
  • lfa usb flash → esptool installed and run inside the distribution,
    no more nrflash delegation.

Nothing is faked at the transfer level. Termux:API opens the real usbfs
descriptor; every ioctl/read/write afterwards goes to the kernel.
Only the node name is virtual, because proot cannot call mknod.

How it works

  1. termux-usb -E -e puts the real fd in TERMUX_USB_FD; fds survive
    fork/exec, so proot's guest sees the same descriptor.
  2. lib/usb-desc.py --sysfs writes device/configuration/interface/endpoint
    files from the real descriptors; the session binds that tree over
    /sys/bus/usb/devices.
  3. lib/lfa-usb-node.c (preload) duplicates the inherited fd on open() of
    the node path, reports SYSFS_MAGIC for /sys (libudev rejects syspaths
    elsewhere), and replaces the udev hotplug monitor with an idle pipe.
    It is -nostdlib (no DT_NEEDED) so one build per architecture works on
    glibc, musl and bionic; aarch64 is bundled.
  4. lib/lfa-usb-tty.py claims the bulk endpoints and exposes a pty as
    /dev/ttyUSB0 for CDC-ACM, CP210x and CH340, forwarding baud changes and
    DTR/RTS so esptool's auto-reset sequence reaches the board.

Verification

  • Host suite: PASS=784 FAIL=0 (./tests/test-all.sh), including new
    checks for the preload map (open/read/write, unmapped path, DTR/RTS
    forwarding), the sysfs tree, the tty session and the esptool wrapper.
  • Outside the fake harness, the extracted Ubuntu arm64 libusb/lsusb
    enumerated the synthetic tree bound over /sys through the preload:
    strings, interface class, endpoint address and packet size all came from
    the real descriptors.
  • A fake-device harness (tests/usb-tty-plumbing.py) runs the real serial
    bridge against a socketpair and relays bytes through the pty both ways.

Not verified yet

Real hardware. Needs a phone with an OTG adapter: lfa usb attach +
lsusb -v, lfa usb tty, then a board flash. docs/USB.md and
docs/TEST-REPORT.md say so rather than claiming it.

Limits

  • Kernel drivers (usbhid, usb-storage, USB audio) still do not attach;
    this is a userspace port.
  • One device per session (Termux:API grants one fd per invocation).
  • No hotplug events inside the guest; lfa usb watch polls.
  • lsusb -t is empty because the tree has no host-controller root hub.

Also fixed

A failing advisory update check (e.g. curl exit 28 on a timeout) aborted
the interactive installer through set -e before the menu. It is now
guarded, with a stub-curl regression test (this was the intermittent L2
pty-test failure).

The guest now gets /dev/bus/usb/BBB/DDD for libusb programs and
/dev/ttyUSB0 for serial programs, backed by the real descriptor that
Termux:API opened. Nothing is simulated at the transfer level; only the
node name is virtual, because proot cannot call mknod.

- lib/lfa-usb-node.c: freestanding preload that duplicates the inherited
  usbfs fd on open(), reports SYSFS_MAGIC for /sys so libudev accepts the
  syspath, stubs the udev hotplug monitor, and forwards DTR/RTS ioctls.
  Built with -nostdlib (no DT_NEEDED) for glibc, musl and bionic; an
  aarch64 object is bundled and lib/build-usb-shim.sh rebuilds it.
- lib/usb-desc.py: raw descriptor reader plus a sysfs writer that fills
  the device, configuration, interface and endpoint files usbutils and
  libusb walk, from the real descriptors.
- lib/lfa-usb-tty.py: bulk-endpoint-to-pty bridge for CDC-ACM, CP210x and
  CH340, with baud polling and line-state merging so esptool auto-reset
  reaches the board.
- lfa usb attach/tty: descriptor pass, sysfs bind, LFA_USB_MAP, preload,
  placeholder nodes with a manifest so disable removes them again.
- lfa usb flash now installs and runs esptool inside the guest and maps
  probe/write/verify/erase/read to the v4 or v5 spelling.
- lsusb helper hands over to the distribution's usbutils when a mapped
  session is active.
- fix: a failing advisory update check (curl timeout 28) aborted the
  interactive installer through set -e before the menu.
- docs/USB.md rewritten; README, architecture, incompatibilities,
  changelog, test report and tracker updated.

Host suite: PASS=784 FAIL=0.
- rename the multi-select scratch array so it cannot collide with the
  string variable of the same name in lfa_usb_print_changes
- disable SC2046 as well as SC2086 for the pd_login_flags word list
- assign and export LFA_USB_PD_FLAGS separately in the three sessions
- use CDPATH='' in lib/build-usb-shim.sh
- a working `termux-usb -l` now counts as proof that Termux:API is
  installed: `pm list packages` cannot see other apps on Android 11+,
  so the old text told the user to install an app they already had
- report host mode as "not advertised" instead of "no" when the
  feature list has no android.hardware.usb.host entry (common on
  Vivo/Oppo builds that still support OTG)
- the lsusb/lfa-usb helpers honor an explicit LFA_USB_BRIDGE instead of
  falling back to /tmp/lfa-usb, which could read a stale directory
- tests: hidden-pm status checks, docs and counts (787)
`lfa usb scan` returned to the prompt without a word when it could not
decide which distribution to use (more than one installed and no instance
remembered). It now:

- reuses the instance saved by `lfa usb enable`, so plain `lfa usb scan`
  works with several distros installed
- prints "Choose a distribution: lfa usb <command> -i NAME" with the
  installed list, or names the saved instance that disappeared
- reports a failed helper copy (usb-desc.py / the callback) instead of
  returning 1 silently

Tests cover the saved-but-missing instance path. Suite: 790 checks.
`lfa usb attach` wrapped the session in `lfa_android_timeout 0`, which
ran `timeout 0 termux-usb ...`. GNU timeout puts the command in its own
process group, so the guest shell became a background job: interactive
reads either stopped (SIGTTIN) or failed with EIO, and `lfa usb attach`
looked wedged even though `-- true` worked.

Zero already means "no limit", so run the command directly. Adds a
regression test that a zero timeout never invokes timeout while real
timeouts still do.
`termux-usb` runs the -e callback inside `OUTPUT="$(...)"`, so the
guest's stdout was captured by the Termux script and only printed when
the session exited. A shell still got its prompt (stderr) and echoed
typing, but every command looked silent; the earlier trace only appeared
at the end.

In the callback, when stdout is not a tty but stderr still is, point
stdout at the terminal. Interactive sessions now behave normally and the
guest sees a tty on stdout. Redirecting both streams
(`lfa usb attach -- cmd > log 2>&1`) still captures everything.

Adds a pty regression test for both branches.
proot-distro v5+ binds the host /dev over the rootfs /dev, so the
placeholder created at <rootfs>/dev/bus/usb/BBB/DDD was never visible:
`ls -l /dev/bus/usb/001/002` said No such file or directory, and a
program that stats the path before opening it gave up early.

perpare_nodes now also writes the node into a Termux-side shadow tree,
and attach/tty pass it to the guest as
`--bind=<shadow>/dev/bus/usb:/dev/bus/usb`. Custom binds are appended
after proot-distro's default binds, so this one wins. The rootfs
placeholder stays for proot-distro versions that do not bind /dev.

Adds checks for the shadow node and the bind argument.
proot-distro v5 removes LD_PRELOAD from the environment it passes to
proot (`child_env.pop("LD_PRELOAD", None)`), so the session ran without
the udev stubs. libusb then failed at init with

    libusb: error [linux_udev_start_event_monitor] could not initialize udev monitor
    unable to initialize libusb: -99

and the real usbutils lsusb never touched the synthetic sysfs.

The generated attach/tty guest scripts now export LD_PRELOAD themselves,
after proot has started, where that filter cannot reach. The session
shell, lsusb, libusb programs and the tty bridge all inherit it.

Adds checks that both generated scripts carry the export.
The guest profile written by real-feel.sh unsets every LD_PRELOAD to
hide Termux variables, so an interactive session (`bash -l`) lost the
usbfs shim right after starting. libusb then failed with -99 again, even
though the session script exported the preload.

The profile now keeps LD_PRELOAD when LFA_USB_MAP is set (a live USB
session) and still drops any other one, which would be a Termux/bionic
object the guest cannot load.

Adds checks for both branches.
libudev scans /sys/bus and /sys/class before it looks at
/sys/bus/usb/devices. On Android /sys is not readable for an app, so
udev_enumerate_scan_devices() returned EACCES and libusb reported an
empty device list; lsusb exited silently even though the descriptors
and the node were present.

Bind a small readable /sys/bus (with just our usb/devices tree) and an
empty /sys/class for the session. The synthetic subsystem links are now
absolute: proot resolves a relative "../../../../bus/usb" against the
host path of the bind source, where it dangles.

Verified with libusb 1.0.27 against the real descriptors: one device,
descriptor rc 0.
The fake proot-distro logs to $HOME/pd-calls.log, but the attach session
runs with the guest user's HOME, so those lines land elsewhere. The
session's own log carries the fake's argv echo; assert against it.
Termux:API can hand the device over with FD_CLOEXEC, so the descriptor was
open in the session shell but closed in every child. `os.dup(7)` returned
EBADF, the node open fell through to the placeholder file, and control
transfers failed with ENOTTY (device qualifier, status) even though
descriptors still came from sysfs.

The generated attach/tty scripts now duplicate the descriptor without the
flag and rewrite LFA_USB_MAP to the new number; the login profile keeps
TERMUX_USB_FD in a USB session instead of stripping it with the other
Termux variables. The preload also stops masking dup() failures as EBADF.

Rebuilt the bundled aarch64 shim.
printf turns %% into a literal %, so the script gets ${VAR%=*}, which
strips the fd suffix exactly the same way.
bash's "{var}<&N" redirection allocates the target with F_DUPFD_CLOEXEC on
some builds, so the duplicate looked fine in the session shell (FD=10) and
was still closed in every child: lfa-usb desc got EBADF and libusb could
not open the node, while descriptors kept coming from sysfs.

Use a plain redirection onto a free high fd instead (dup2() always clears
close-on-exec), rewrite LFA_USB_MAP to the new number, and print whether a
child really inherited it so a silent EBADF cannot hide again.
The previous round added three checks but bumped 806 to 808; the real total
was 809 (808 passed, 1 failed). This commit's extra check makes it 810.
The session's login shell marks inherited descriptors close-on-exec, so the
device fd stayed in bash and disappeared in every child. lsusb then opened
the placeholder file (`Couldn't open device`, control transfers ENOTTY) and
lfa-usb desc got EBADF, while descriptors still came from sysfs - which is
why the dump looked almost right.

Reproduced outside the guest: `bash -l -i` keeps fd 10 and its children do
not, while `bash -i` and `bash -l -c` keep it. The preload now clears
FD_CLOEXEC on the mapped fds (and the tty fd) inside execve, so the first
child inherits a plain descriptor and nothing re-sets the flag.

Rebuilt the bundled aarch64 shim; added a regression check that sets
FD_CLOEXEC and then execs /bin/sh.
@pdev-labs
pdev-labs merged commit bf5c268 into main Nov 22, 2026
4 of 10 checks passed
@pdev-labs
pdev-labs deleted the feat/usb-real-port branch November 22, 2026 13:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant