GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - lianwei/rustbox: Rustbox tools

BranchesTags
Open more actions menu

Latest commit

 

History

1 Commit
1 Commit

Folders and files

NameName
Last commit message
Last commit date
.cargo
.cargo
 
 
script_test
script_test
 
 
src
src
 
 
tests
tests
 
 
.gitignore
.gitignore
 
 
Android.bp
Android.bp
 
 
Cargo.lock
Cargo.lock
 
 
Cargo.toml
Cargo.toml
 
 
LICENSE
LICENSE
 
 
README.android.md
README.android.md
 
 
README.md
README.md
 
 

Repository files navigation

Rustbox

A comprehensive, single-binary implementation of standard Unix/Linux command-line utilities written in Rust. Rustbox bundles 285 applets into one statically- linkable executable, targeting both desktop Linux and Android devices.

Features

  • 285 commands covering core utilities, networking, filesystem, process management, compression, hardware access, and more
  • Single binary — all applets compile into one rustbox executable (~4.3 MB release build with all features)
  • Feature-gated compilation — build only the applets you need via Cargo features
  • Android cross-compilation — first-class support for 4 Android ABIs via NDK (see README.android.md)
  • Pure Rust cryptography — SHA-1, SHA-256, SHA-512, and SHA-3 implemented without external C libraries
  • Comprehensive test suite — 1,894 unit tests, 2,068+ integration tests, and 253 shell test scripts

Quick Start

# Build with all default applets
cargo build

# Build release (optimized for size)
cargo build --release

# Run an applet
cargo run -- ls -la
cargo run -- cat /etc/hostname
cargo run -- ping -c 3 localhost

# Build only specific applets
cargo build --no-default-features --features "ls,cat,grep"

# List all compiled applets
cargo run -- --list

Project Structure

rustbox/
├── src/
│   ├── main.rs              # Entry point and applet dispatcher
│   ├── applets.rs           # Applet registry (name → function mapping)
│   ├── applets/             # 267 applet implementation files
│   │   ├── basename.rs
│   │   ├── cat.rs
│   │   ├── cp.rs
│   │   ├── grep.rs
│   │   ├── ls.rs
│   │   ├── ping.rs
│   │   ├── ps.rs
│   │   ├── sh.rs
│   │   └── ...
│   ├── types.rs             # Cross-platform ioctl type portability
│   ├── term.rs              # Terminal size detection
│   ├── timeutil.rs          # Time formatting (ls, ps, dmesg, cal)
│   ├── helper/              # Shared helpers (ownership/permissions)
│   ├── sha.rs               # SHA-1/256/512 implementations
│   ├── sha3.rs              # SHA-3 (Keccak) implementation
│   ├── i2c_common.rs        # Shared I2C bus helpers
│   └── blkid_helper.rs      # Block device ID resolution
├── tests/                   # 216 integration test files
├── script_test/             # 253 shell test scripts
├── .cargo/config.toml       # Android NDK linker configuration
├── Cargo.toml               # Features, dependencies, profiles
├── LICENSE                   # BSD-2-Clause
└── README.android.md        # Android cross-compilation guide

Architecture

Multi-Applet Launcher

Rustbox follows the BusyBox multi-call binary pattern. A single main() dispatches to the appropriate applet based on the first argument:

rustbox <applet> [args...]
         │
         ▼
    ┌──────────┐     ┌──────────────────────────┐
    │ main.rs  │────▶│ applets::applets()        │
    │          │     │ Vec<Applet { name, run }> │
    └──────────┘     └──────────────────────────┘
                              │
              match name ─────┼─────────────────┐
                    │         │                  │
                    ▼         ▼                  ▼
               basename::run  ls::run       grep::run
               → i32          → i32         → i32

Each applet is a Rust module with a public run(args: &[String]) -> i32 function that returns a Unix exit code. Applets are registered in src/applets.rs via a Vec<Applet> built with feature-gated #[cfg] attributes:

pub struct Applet {
    pub name: &'static str,
    pub run: fn(&[String]) -> i32,
}

pub fn applets() -> Vec<Applet> {
    vec![
        #[cfg(feature = "ls")]
        Applet { name: "ls", run: |args| ls::run(args) },
        // ... 285 entries
    ]
}

Feature-Gated Compilation

Every applet is behind a Cargo feature flag, enabling minimal builds:

# Full build (~285 applets)
cargo build

# Minimal build (only cat and echo)
cargo build --no-default-features --features "cat,echo"

Features that require external crates declare optional dependencies:

Feature Dependency
grep, egrep, fgrep, cut, expr, pgrep, pkill, ping regex
gzip, gunzip, zcat, unzip flate2
bzip2, bunzip2, bzcat, tar bzip2
uuidgen getrandom, md5, sha1_smol

Shared Modules

Module Purpose Used by
types.rs Ioctl request type portability (c_int on Android, c_ulong on glibc) chattr, fstrim, ifconfig, setkeycodes, ...
term.rs Terminal size via TIOCGWINSZ / $LINES×$COLUMNS ls, top, more, ...
timeutil.rs SystemTime ↔ libc::tm conversion, ls-style date formatting ls, ps, dmesg, cal
helper/ownership.rs User/group resolution (getpwnam/getgrnam), recursive chown chown, chgrp, cp, install, ...
sha.rs Pure-Rust SHA-1, SHA-256, SHA-512 sha1sum, sha256sum, sha512sum
sha3.rs Pure-Rust SHA-3 (Keccak-f[1600]) sha3sum
i2c_common.rs I2C bus device helpers i2cdetect, i2cdump, i2cget, i2cset, i2ctransfer
blkid_helper.rs Resolves LABEL=, UUID=, PARTUUID= via /dev/disk/by-* blkid, swapon, swapoff

Applet Implementation Pattern

Each applet follows a consistent structure with inline while/match argument parsing:

// src/applets/example.rs

pub fn run(args: &[String]) -> i32 {
    let mut flag = false;
    let mut opt: Option<String> = None;
    let mut operands = Vec::new();

    let mut i = 0;
    while i < args.len() {
        match args[i].as_str() {
            "--help" | "-h" => {
                print_help();
                return 0;
            }
            "--version" => {
                println!("example (rustbox) {}", env!("CARGO_PKG_VERSION"));
                return 0;
            }
            "-f" | "--flag" => flag = true,
            "-o" | "--option" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("example: option '-o' requires an argument");
                    eprintln!("Try 'example --help' for more information.");
                    return 1;
                }
                opt = Some(args[i].clone());
            }
            "--" => {
                operands.extend_from_slice(&args[i + 1..]);
                break;
            }
            s if s.starts_with("--") => {
                eprintln!("example: unrecognized option '{}'", s);
                eprintln!("Try 'example --help' for more information.");
                return 1;
            }
            s if s.starts_with('-') && s != "-" => {
                for ch in s[1..].chars() {
                    match ch {
                        'f' => flag = true,
                        _ => {
                            eprintln!("example: invalid option -- '{}'", ch);
                            eprintln!("Try 'example --help' for more information.");
                            return 1;
                        }
                    }
                }
            }
            _ => operands.push(args[i].clone()),
        }
        i += 1;
    }

    // Execute core logic
    if let Err(e) = do_work(flag, opt.as_deref(), &operands) {
        eprintln!("example: {}", e);
        return 1;
    }

    0 // success exit code
}

Conventions:

  • Return i32 exit codes (0 = success, 1 = error, 2 = usage error)
  • Print errors to stderr with eprintln!("{applet_name}: {error}")
  • GNU-style error messages: "invalid option -- 'x'", "unrecognized option '--foo'", "option '-x' requires an argument"
  • Follow error messages with "Try '{applet_name} --help' for more information."
  • Support --help and --version (long-only or with -h/-V short forms)
  • Use -- to separate options from operands
  • Combined short flags (e.g., -abc) handled in the starts_with('-') arm, but only for boolean flags — not -h/-V or argument-taking options

Applet Categories

Core Utilities

[, [[, basename, cat, chmod, chown, chgrp, cksum, cmp, cp, cut, date, dd, df, diff, dirname, du, echo, env, expand, expr, factor, false, file, find, head, id, install, ln, ls, mkdir, mkfifo, mknod, mktemp, more, mv, nl, od, paste, patch, printenv, printf, pwd, readlink, realpath, rm, rmdir, sed, seq, shred, shuf, sleep, sort, split, stat, strings, sync, tac, tail, tee, test, time, timeout, touch, tr, true, truncate, tty, uname, unexpand, uniq, unlink, uptime, usleep, wc, which, who, whoami, xargs, xxd, yes

Text Processing

awk, grep, egrep, fgrep, sed, cut, diff, cmp, sort, uniq, tr, expand, unexpand, paste, wc, nl, rev, fold

Compression & Archiving

ar, bzip2, bunzip2, bzcat, cpio, gzip, gunzip, lzcat, lzma, lzop, tar, uncompress, unlzma, unxz, unzip, xz, xzcat, zcat

Process Management

kill, killall, nice, nohup, pgrep, pidof, pkill, ps, renice, setsid, time, timeout, top, w, watch, ionice, iorenice, iotop, chrt, taskset, uclampset, nproc, pmap

Networking

arp, arping, brctl, hostname, ifconfig, ifdown, ifup, ip, nameif, nbd-client, nc, netstat, nslookup, ping, ping6, route, ssl_client, tc, telnet, telnetd, tftp, traceroute, traceroute6, vconfig, wget

Filesystem & Disk

blkdiscard, blkid, blockdev, chattr, crc32, df, fallocate, freeramdisk, fsfreeze, fstrim, fsync, losetup, lsattr, md5sum, mkdosfs, mke2fs, mkswap, mount, partprobe, sha1sum, sha256sum, sha3sum, sha512sum, swapoff, swapon, umount

System Administration

chpasswd, chroot, crond, crontab, dmesg, free, getty, groups, halt, hwclock, insmod, lsmod, logname, modinfo, modprobe, nsenter, pivot_root, poweroff, reboot, resume, rfkill, rmmod, rtcwake, run-init, run-parts, start-stop-daemon, su, svc, svok, switch_root, sysctl, syslogd, ulimit, unshare, vmstat, watchdog

Console & Terminal

cal, chvt, clear, deallocvt, less, openvt, reset, setkeycodes, stty, vi

Hardware & Device

devmem, getevent, gpiodetect, gpiofind, gpioget, gpioinfo, gpioset, i2cdetect, i2cdump, i2cget, i2cset, i2ctransfer, lspci, lsscsi, lsusb, sendevent, ubirename, uevent

Encoding & Conversion

ascii, base64, dos2unix, hexdump, iconv, unix2dos, uudecode, uuencode

SELinux

chcon, getenforce, load_policy, restorecon, runcon, setenforce, setfattr, getfattr

Shell

sh, ash, cttyhack

Miscellaneous

arch, bc, dc, hostid, logger, log, lsof, mdev, microcom, nologin, rdate, readelf, setpriv, ts, tunctl, uuidgen

Testing

Rustbox has three layers of testing:

# Unit tests (1,894 tests embedded in source files)
cargo test

# Integration tests (2,068+ tests in tests/*.rs)
cargo test --test basename
cargo test --test ls

# Shell tests (253 scripts in script_test/)
sh script_test/test_ls.sh
sh script_test/test_grep.sh

# Test a specific feature in isolation
cargo test --no-default-features --features cp

Test Coverage

Layer Count Location Description
Unit tests 1,894 src/applets/*.rs (#[cfg(test)]) Argument parsing, internal logic, edge cases
Integration tests 2,068+ tests/*.rs End-to-end CLI behavior via Command
Shell tests 253 scripts script_test/test_*.sh Real-world scenarios, signal handling, permissions

Building

Requirements

  • Rust (nightly recommended — uses is_multiple_of and other nightly features)
  • Linux host (or cross-compilation target)

Build Commands

# Debug build (all default applets)
cargo build

# Release build (optimized for size: LTO, strip, panic=abort)
cargo build --release

# Selective build
cargo build --no-default-features --features "cat,ls,grep,find"

# Check code quality
cargo fmt              # Format code
cargo clippy --all-targets --all-features   # Lint (must be warning-free)

Release Profile

The release profile is tuned for minimal binary size:

[profile.release]
opt-level = "z"        # Optimize for size
lto = true             # Link-time optimization
codegen-units = 1      # Single codegen unit for better optimization
panic = "abort"        # No unwinding overhead
strip = "symbols"      # Strip debug symbols

Android Cross-Compilation

Rustbox supports cross-compiling for Android via the NDK. Four ABIs are configured in .cargo/config.toml:

Target Linker
x86_64-linux-android x86_64-linux-android32-clang
aarch64-linux-android aarch64-linux-android32-clang
armv7-linux-androideabi armv7a-linux-androideabi32-clang
i686-linux-android i686-linux-android32-clang
# Add NDK to PATH
export PATH="$HOME/Android/Sdk/ndk/29.0.14033849/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH"

# Build for arm64
rustup target add aarch64-linux-android
cargo build --target aarch64-linux-android --release

# Deploy to device
adb push target/aarch64-linux-android/release/rustbox /data/local/tmp/
adb shell chmod +x /data/local/tmp/rustbox
adb shell /data/local/tmp/rustbox ls /sdcard

See README.android.md for the full guide.

Note: Some applets are excluded from Android builds due to NDK limitations: iconv (no libc exposure), mkpasswd/passwd/su (no crypt), lzcat/lzma/tar (no liblzma), poweroff/reboot (no reboot syscall wrapper).

Dependencies

Rustbox minimizes external dependencies. Most applets use only the standard library and libc:

Crate Version Purpose Optional
libc 0.2 POSIX syscalls, ioctl, signal handling No
regex 1 Pattern matching (grep, awk, sed, pgrep/pkill) Yes
flate2 1 gzip/deflate compression Yes
bzip2 0.4 bzip2 compression Yes
getrandom 0.2 OS random bytes (uuidgen) Yes
md5 0.7 MD5 hashing (uuidgen v3) Yes
sha1_smol 1.0 SHA-1 hashing (uuidgen v5) Yes

Contributing

  • Format with cargo fmt before committing
  • Ensure cargo clippy --all-targets --all-features is warning-free
  • Write commits in present tense: ls: add --color=always support
  • Include unit tests for argument parsing and edge cases
  • Include integration tests for CLI behavior
  • Test with cargo test --no-default-features --features <applet> to verify isolated builds

License

BSD-2-Clause — Copyright (c) 2025 by Lianwei Wang

About

Rustbox tools

Resources

Readme
BSD-2-Clause license
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.