22 Commits

Author SHA1 Message Date
Siavash Sameni
89391e1781 Add OpenWrt ipk packaging + split client/server binaries
Some checks failed
CI / test (push) Failing after 1m27s
OpenWrt package (deploy/openwrt/):
- build-ipk.sh: creates .ipk from pre-built binary (no SDK needed)
- Makefile: for OpenWrt SDK integration
- ProCD init script with UCI config
- Supports all architectures (x86_64, aarch64, mipsel, mips)

Split binaries for embedded (src/bin/):
- btest-client: client-only, no server/syslog/csv
- btest-server: server-only, no client
- release-small profile: opt-level=z + panic=abort

Sizes (compressed .tar.gz):
  Full btest:    ~1 MB
  btest-client:  ~500 KB (release-small)
  btest-server:  ~550 KB (release-small)

Install on OpenWrt:
  opkg install btest-rs_0.6.0-1_x86_64.ipk

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:44:57 +04:00
Siavash Sameni
8c853c3605 Parallel agent work: bandwidth fix, CPU platforms, packaging
All checks were successful
CI / test (push) Successful in 2m8s
5 agents ran in parallel:

1. Fix bandwidth limit (-b): new advance_next_send() prevents drift
   bursts by resetting when >2x interval behind (bandwidth.rs, client.rs, server.rs)

2. Windows + FreeBSD CPU support (cpu.rs):
   - Windows: GetSystemTimes via raw FFI
   - FreeBSD: sysctl kern.cp_time parsing

3. Ubuntu .deb packaging (deploy/deb/):
   - build-deb.sh: creates .deb from pre-built binary
   - test-deb.sh: tests in Ubuntu Docker container

4. Fedora/RHEL RPM packaging (deploy/rpm/):
   - btest-rs.spec: full RPM spec with systemd unit
   - build-rpm.sh + test-rpm.sh

5. Alpine Linux apk packaging (deploy/alpine/):
   - APKBUILD with OpenRC init script
   - test-alpine.sh

58 tests pass, zero warnings.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:04:00 +04:00
Siavash Sameni
fe28c04c19 Simplify AUR test: use yay like a real user
All checks were successful
CI / test (push) Successful in 2m7s
Instead of manually setting up rust + makepkg, install yay first
then `yay -S btest-rs --noconfirm` — exactly how a user would.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:51:02 +04:00
Siavash Sameni
66be99bef0 Add remote AUR test script
All checks were successful
CI / test (push) Successful in 2m9s
scripts/test-aur-remote.sh: SSHes to a remote x86_64 server, spins up
an Arch Docker container, installs btest-rs from AUR, runs TCP + UDP
loopback tests, and cleans up.

Usage: ./scripts/test-aur-remote.sh root@myserver

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:48:16 +04:00
Siavash Sameni
94b122ac25 Add AUR package (PKGBUILD) with systemd service and test script
All checks were successful
CI / test (push) Successful in 2m11s
- deploy/aur/PKGBUILD: builds from source, installs binary + man page + systemd unit
- deploy/aur/.SRCINFO: AUR metadata
- deploy/aur/test-aur.sh: tests PKGBUILD in Docker Arch container
- Supports x86_64, aarch64, armv7h architectures

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:33:55 +04:00
Siavash Sameni
a07158ed22 Fix sync-github-release: merge all checksums into one file
All checks were successful
CI / test (push) Successful in 2m9s
Merges separate .sha256 files (from macOS build) into the main
checksums-sha256.txt, adds missing checksums, deduplicates.
Added macOS to release notes table.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:44:18 +04:00
Siavash Sameni
1cd552d2dc Update Docker references to GHCR as primary registry
All checks were successful
CI / test (push) Successful in 2m9s
- docker-compose.yml: ghcr.io/manawenuz/btest-rs
- docs/docker.md: GHCR for pull/run examples, both registries documented
- README: GitHub + Gitea issue tracker links
- Version refs updated to 0.6.0

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:40:28 +04:00
Siavash Sameni
3af40cb275 Add RPi install docs, GHCR support, push-docker-all script
All checks were successful
CI / test (push) Successful in 2m10s
- README: Raspberry Pi install section with auto-detect architecture
- README: pre-built binary download section for all platforms
- Docker docs: dual registry (Gitea + GHCR)
- scripts/push-docker-all.sh: push to both registries in one command

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:29:48 +04:00
Siavash Sameni
f0a48092ed v0.6.0: CPU monitoring, CSV with CPU, docs update, cleanup
Some checks failed
CI / test (push) Failing after 1m27s
Build & Release / release (push) Successful in 3m17s
New in v0.6.0:
- CPU usage: local/remote shown per interval (cpu: 12%/33%)
- Warning indicator (!) when CPU > 70% on either side
- MikroTik CPU encoding: 0x80 | percentage in status byte 1
- CSV includes local_cpu_pct and remote_cpu_pct columns
- Status message format corrected to match MikroTik wire format:
  [type:1][cpu:1][00:2][seq:4 LE][bytes:4 LE]
- Removed btest-opensource submodule (fully reimplemented)
- Deleted research/ecsrp5 branch
- Updated all docs: architecture, user-guide, man page, protocol
- Version bumped to 0.6.0

58 tests, all passing. Zero warnings.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:16:25 +04:00
Siavash Sameni
27354108fc Fix CPU reporting: MikroTik uses 0x80|pct encoding, add CPU to CSV
All checks were successful
CI / test (push) Successful in 2m9s
- MikroTik encodes CPU as 0x80 | percentage (high bit flag)
- Deserialize: mask with 0x7F and cap at 100
- Serialize: set high bit (0x80 | cpu) to match MikroTik format
- CSV now includes local_cpu_pct and remote_cpu_pct columns
- Both client and server write CPU to CSV

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 11:08:11 +04:00
Siavash Sameni
24f634170d Add CPU usage monitoring, remove btest-opensource submodule
All checks were successful
CI / test (push) Successful in 2m16s
CPU usage feature:
- New cpu.rs module: background sampler thread, cross-platform (macOS + Linux)
- Status message byte 1 now carries CPU load (0-100%), matching MikroTik format
- Status format corrected: [type][cpu][00][00][seq:4 LE][bytes:4 LE]
- Client and server exchange CPU in every status message
- Display format: "cpu: 40%/12%" (local/remote), "!" warning if > 70%
- Both client and server show local + remote CPU per interval
- Syslog TEST_END could include CPU averages (future enhancement)

Removed btest-opensource submodule — we've fully reimplemented the protocol
with EC-SRP5 auth, multi-connection, IPv6, syslog, CSV, and CPU monitoring.
The original project is still credited in LICENSE and README.

58 tests, all passing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:53:00 +04:00
Siavash Sameni
10dd0c3835 Add KNOWN_ISSUES.md, update architecture docs
Some checks failed
CI / test (push) Failing after 1m32s
KNOWN_ISSUES.md documents:
- IPv6 UDP on macOS (ENOBUFS, server mode)
- macOS UDP send buffer saturation (first 2-3 seconds)
- Windows binaries untested
- IPv6 UDP on Linux untested
- EC-SRP5 occasional auth failure
- MikroTik speed adaptation staircase
- TCP multi-connection bandwidth reporting
- Bandwidth limit (-b) not fully effective
- Platform test matrix

Architecture docs updated with:
- Shared BandwidthState for timeout survival
- IPv6 socket handling details
- Complete file layout including tests, deploy, proto-test

54 tests, all passing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:39:18 +04:00
Siavash Sameni
5bb224cb3b Remove test CSV from repo, add to gitignore
Some checks failed
CI / test (push) Failing after 1m31s
2026-04-01 10:30:56 +04:00
Siavash Sameni
68eb0c7f96 Add comprehensive integration tests (20 new tests, 54 total)
Some checks failed
CI / test (push) Has been cancelled
New test suite covers:
- TCP IPv4: send, receive, both
- UDP IPv4: send, receive, both
- TCP IPv6: send, receive, both
- UDP IPv6: send, receive, both
- MD5 authentication flow
- EC-SRP5 authentication flow
- EC-SRP5 wrong password rejection
- CSV file creation (client + server)
- Syslog event emission (AUTH_SUCCESS, TEST_START, TEST_END)
- BandwidthState record_interval and running flag

Each test starts a server, runs a client for 2 seconds, verifies
bytes transferred > 0, then cleans up.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:30:37 +04:00
Siavash Sameni
23db39a84e Add CSV output to server mode
All checks were successful
CI / test (push) Successful in 1m26s
Server now writes a CSV row for each completed test with peer IP,
protocol, direction, duration, avg speeds, bytes, and lost packets.

Verified on loopback: TX 35 Gbps, RX 51 Gbps captured in CSV.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:19:15 +04:00
Siavash Sameni
d19ad25a3c Fix client stats: shared BandwidthState survives timeout cancellation
All checks were successful
CI / test (push) Successful in 1m24s
The state is now created in main.rs and passed into run_client, so
when --duration timeout cancels the future, the stats are still
accessible via shared_state.summary(). CSV and syslog now show
real speeds and byte counts.

Verified: TCP loopback shows 32 Gbps in CSV output.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 10:05:50 +04:00
Siavash Sameni
5b07a079fe Fix client CSV/syslog: return actual stats from run_client
All checks were successful
CI / test (push) Successful in 1m23s
run_client and sub-functions now return (tx_bytes, rx_bytes, lost, intervals).
BandwidthState::record_interval() called in both TCP and UDP client status
loops. CSV and syslog TEST_END now show real speeds and byte counts.

Also raised client UDP TX error threshold from 1000 to 50000 with
adaptive backoff matching the server.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:52:46 +04:00
Siavash Sameni
949c4908ad Add client syslog events, fix client UDP TX error threshold
All checks were successful
CI / test (push) Successful in 1m26s
- Client mode now emits TEST_START and TEST_END syslog events
- Client UDP TX threshold raised from 1000 to 50000 with adaptive backoff
  (matching server behavior) — prevents premature TX death on macOS
- Updated all docs (README, user-guide, architecture, protocol, docker)
- Added results.csv to gitignore

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:40:52 +04:00
Siavash Sameni
751a9d5f13 Add --duration, --csv, --quiet flags for automated testing
All checks were successful
CI / test (push) Successful in 1m27s
- --duration N: run client test for N seconds then exit
- --csv <file>: append results to CSV (creates with headers if new)
- --quiet/-q: suppress terminal output (for scripted/machine use)

CSV columns: timestamp, host, port, protocol, direction, duration_s,
  tx_avg_mbps, rx_avg_mbps, tx_bytes, rx_bytes, lost_packets, auth_type

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:30:58 +04:00
Siavash Sameni
ce01d514b2 Add speed/bytes/duration to syslog TEST_END events
All checks were successful
CI / test (push) Successful in 1m24s
TEST_END now includes: duration, avg TX/RX Mbps, total bytes, lost packets.
All test functions track cumulative totals via BandwidthState::record_interval()
and return summary stats.

Example:
  TEST_END peer=172.16.81.1:59070 proto=UDP dir=TX duration=6s
    tx_avg=275.00Mbps rx_avg=0.00Mbps tx_bytes=206250000 rx_bytes=0 lost=0

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 09:23:11 +04:00
Siavash Sameni
7bc54a977c Fix syslog-ng filter: match on MESSAGE not program()
All checks were successful
CI / test (push) Successful in 1m29s
With flags(no-parse) on the source, syslog-ng doesn't extract
the program name. Use match("btest-rs:" value("MESSAGE")) instead.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 08:56:48 +04:00
Siavash Sameni
a925a7778d Fix syslog format + add syslog-ng config
All checks were successful
CI / test (push) Successful in 1m30s
- Syslog now uses RFC 3164 (BSD) format with proper timestamps
  and facility=local0 for easy filtering
- Added deploy/syslog-ng-btest.conf with filters for:
  - All btest events (all.log + daily rotation)
  - Auth events only (auth.log)
  - Test events only (tests.log)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 08:48:35 +04:00
46 changed files with 3885 additions and 297 deletions

2
.gitignore vendored
View File

@@ -5,3 +5,5 @@ btest_original
.env .env
proto-test/venv/ proto-test/venv/
**/__pycache__/ **/__pycache__/
results.csv
server_results.csv

3
.gitmodules vendored
View File

@@ -1,3 +0,0 @@
[submodule "btest-opensource"]
path = btest-opensource
url = https://github.com/samm-git/btest-opensource

2
Cargo.lock generated
View File

@@ -99,7 +99,7 @@ dependencies = [
[[package]] [[package]]
name = "btest-rs" name = "btest-rs"
version = "0.5.0" version = "0.6.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"bytes", "bytes",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "btest-rs" name = "btest-rs"
version = "0.5.0" version = "0.6.0"
edition = "2021" edition = "2021"
description = "MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth — a Rust reimplementation" description = "MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth — a Rust reimplementation"
license = "MIT AND Apache-2.0" license = "MIT AND Apache-2.0"
@@ -16,6 +16,14 @@ path = "src/lib.rs"
name = "btest" name = "btest"
path = "src/main.rs" path = "src/main.rs"
[[bin]]
name = "btest-client"
path = "src/bin/client_only.rs"
[[bin]]
name = "btest-server"
path = "src/bin/server_only.rs"
[dependencies] [dependencies]
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
clap = { version = "4", features = ["derive"] } clap = { version = "4", features = ["derive"] }
@@ -38,3 +46,9 @@ opt-level = 3
lto = true lto = true
strip = true strip = true
codegen-units = 1 codegen-units = 1
# Minimal size profile for embedded/OpenWrt targets
[profile.release-small]
inherits = "release"
opt-level = "z"
panic = "abort"

125
KNOWN_ISSUES.md Normal file
View File

@@ -0,0 +1,125 @@
# Known Issues
This document tracks known limitations, bugs, and platform-specific issues in btest-rs. If you encounter an issue not listed here, please report it at: **https://git.manko.yoga/manawenuz/btest-rs/issues**
## IPv6 UDP on macOS (Server Mode)
**Severity:** High
**Affects:** macOS only (server mode, UDP, IPv6)
**Status:** Open
When running as a server on macOS and a MikroTik client connects over IPv6 UDP, the server's UDP transmit hits `ENOBUFS` (error 55 — "No buffer space available") repeatedly. This causes:
- Direction "receive" (server TX): intermittent packet bursts with gaps, MikroTik shows unstable or low speed
- Direction "send" (server RX): works, but speed drops over time due to MikroTik's speed adaptation receiving irregular status feedback
- Direction "both": TX side severely degraded
**Root cause:** macOS kernel returns `ENOBUFS` on IPv6 `send_to()` much more aggressively than IPv4 due to smaller interface output queues and per-packet NDP overhead. Connected sockets (`send()`) perform better than unconnected (`send_to()`), but still hit limits under high throughput.
**Workaround:** Use IPv4 for UDP tests on macOS, or deploy the server on Linux where IPv6 UDP works correctly.
**Not affected:**
- IPv4 UDP (all directions, all platforms)
- IPv6 TCP (all directions, all platforms)
- Client mode over IPv6 (connecting TO a MikroTik server works fine at 600+ Mbps)
## IPv6 UDP — Not Tested on Linux
**Severity:** Unknown
**Affects:** Linux server, IPv6, UDP
**Status:** Untested
IPv6 UDP in server mode has not been thoroughly tested on Linux. The macOS ENOBUFS issue is kernel-specific and likely does not exist on Linux (which has much better IPv6 UDP buffer management). Testing and reports welcome.
## macOS UDP Send Buffer Saturation
**Severity:** Medium
**Affects:** macOS (client and server, IPv4 and IPv6, UDP)
**Status:** Mitigated
On macOS, when sending UDP at unlimited speed, the kernel buffer fills quickly and returns `ENOBUFS`. The adaptive backoff mechanism (200μs → 10ms) mitigates this, but the first few seconds of a test may show:
- Interval 1: high burst (40-300 Mbps depending on conditions)
- Interval 2: 0 bps (buffer full, backoff in effect)
- Interval 3+: gradually recovers to steady state
This causes the first 2-3 seconds of UDP tests to be unreliable on macOS. On Linux, this issue does not occur.
**Workaround:** Ignore the first few seconds of results, or use TCP mode which does not have this issue.
## Windows Binaries Not Tested
**Severity:** Unknown
**Affects:** Windows x86_64
**Status:** Untested
Windows binaries are cross-compiled from Linux using `gcc-mingw-w64` in CI. They have never been tested on actual Windows systems. Issues may include:
- Socket behavior differences (Winsock vs BSD sockets)
- IPv6 dual-stack handling
- Path separator issues in CSV output
- Console output encoding
**Help wanted:** If you test on Windows, please report your findings.
## EC-SRP5 Server Authentication — Occasional Failure
**Severity:** Low
**Affects:** Server mode with `--ecsrp5`
**Status:** Mostly fixed
EC-SRP5 server authentication occasionally fails with "client proof mismatch". This was largely fixed by storing the correct gamma parity from key derivation, but edge cases may still exist with certain salt/password combinations due to the Curve25519 Weierstrass arithmetic.
**Workaround:** Retry the connection. If it fails consistently, restart the server (which regenerates the salt).
## MikroTik Speed Adaptation Staircase (Server RX, UDP)
**Severity:** Low
**Affects:** Server mode, UDP, direction "send" (MikroTik sends to us)
**Status:** MikroTik client behavior
When MikroTik connects as a client and sends data (direction "send"), the speed may gradually decrease in a staircase pattern over 30-60 seconds. This is caused by MikroTik's client-side speed adaptation algorithm, not by our server.
The original C btest-opensource server exhibits the same behavior. Single-connection mode (`connection-count=1`) provides the best results.
## TCP Multi-Connection Bandwidth Reporting
**Severity:** Low
**Affects:** Server mode, TCP, `connection-count > 1`
**Status:** Open
With TCP multi-connection, the server correctly handles all connections and data flows, but bandwidth is only measured on the primary connection's status loop. MikroTik may show lower-than-actual speeds because status messages are not distributed across all connections.
## Bandwidth Limit (`-b`) Not Fully Effective
**Severity:** Low
**Affects:** Client mode, `-b` flag
**Status:** Open
The `-b` bandwidth limit flag does not reliably cap speed. The `calc_send_interval` function computes the inter-packet delay correctly, but tokio's timer resolution and task scheduling can cause actual throughput to exceed the specified limit, especially for high bandwidth values.
---
## Reporting Issues
Found a bug or unexpected behavior? Please report it:
- **Issue tracker:** https://git.manko.yoga/manawenuz/btest-rs/issues
- **Include:** OS/platform, btest-rs version (`btest --version`), MikroTik RouterOS version, protocol (TCP/UDP), direction, connection count, and the full command line used.
- **Packet captures:** If possible, attach a tcpdump/pcap capture. Use: `sudo tcpdump -i <interface> -w capture.pcap -s 200 'host <mikrotik_ip> and (port 2000 or portrange 2001-2356)'`
- **Debug logs:** Run with `-vv` to get hex-level status exchange dumps.
## Platform Test Matrix
| Platform | TCP4 | UDP4 | TCP6 | UDP6 | Notes |
|----------|------|------|------|------|-------|
| macOS (ARM64) | Pass | Pass* | Pass | Fail** | *UDP send buffer saturation on first seconds |
| macOS (x86_64) | Untested | Untested | Untested | Untested | |
| Linux (x86_64) | Pass | Pass | Pass | Untested | Deployed on Ubuntu 24.04 |
| Linux (aarch64) | Untested | Untested | Untested | Untested | RPi builds available |
| Linux (armv7) | Untested | Untested | Untested | Untested | RPi builds available |
| Windows (x86_64) | Untested | Untested | Untested | Untested | Cross-compiled, never tested |
**Pass** = verified against MikroTik RouterOS 7.x
**Fail** = known issue documented above
**Untested** = builds available but not verified

224
README.md
View File

@@ -1,20 +1,23 @@
# btest-rs # btest-rs
A Rust reimplementation of the [MikroTik Bandwidth Test (btest)](https://wiki.mikrotik.com/wiki/Manual:Tools/Bandwidth_Test) protocol. Both server and client modes, compatible with MikroTik RouterOS devices. A Rust reimplementation of the [MikroTik Bandwidth Test (btest)](https://wiki.mikrotik.com/wiki/Manual:Tools/Bandwidth_Test) protocol. Both server and client modes, fully compatible with MikroTik RouterOS devices.
## Based on ## Features
This project is a clean-room Rust reimplementation based on the protocol reverse-engineering work done by **Alex Samorukov** in [btest-opensource](https://github.com/samm-git/btest-opensource). The original C implementation and protocol documentation were invaluable in making this project possible. Full credit to Alex and all contributors to that project. - **Full protocol support** -- TCP and UDP data transfer, IPv4 and IPv6
- **EC-SRP5 authentication** -- modern RouterOS >= 6.43 Curve25519-based auth (server and client)
The original `btest-opensource` project is included as a git submodule for reference and protocol documentation. - **MD5 authentication** -- legacy RouterOS < 6.43 challenge-response auth
- **Multi-connection support** -- handles MikroTik's multi-connection UDP mode
## Why Rust? - **Bidirectional testing** -- simultaneous upload and download
- **Syslog logging** -- send structured events (auth, test start/end) to a remote syslog server
- **Single static binary** - 2 MB, zero dependencies, runs anywhere - **CSV output** -- append machine-readable test results to a CSV file
- **Cross-platform** - macOS, Linux (x86_64, ARM64), Docker - **CPU usage monitoring** -- local and remote CPU shown per interval, warning at >70%
- **Async I/O** - tokio-based, handles many concurrent connections efficiently - **Timed tests** -- `--duration` flag to automatically stop after N seconds
- **Memory safe** - no buffer overflows, no use-after-free, no data races - **Quiet mode** -- suppress terminal output for scripted/automated use
- **Easy deployment** - `scp` one file, done. Or use the systemd installer. - **NAT traversal** -- probe packet to open firewall holes for UDP receive
- **Single static binary** -- ~2 MB, zero runtime dependencies (musl build)
- **Cross-platform** -- macOS, Linux (x86_64, ARM64), Docker
- **Async I/O** -- tokio-based, handles many concurrent connections efficiently
## Performance ## Performance
@@ -29,53 +32,102 @@ Tested over WiFi 6E (MikroTik RouterOS <-> macOS):
| Client TCP bidirectional | TCP | **264/264 Mbps** | | Client TCP bidirectional | TCP | **264/264 Mbps** |
| Server bidirectional | UDP | **280/393 Mbps** | | Server bidirectional | UDP | **280/393 Mbps** |
On wired gigabit links, expect line-rate performance in both TCP and UDP modes.
## Installation ## Installation
### Pre-built binary
```bash
# Build for Linux x86_64 from macOS (requires Docker)
scripts/build-linux.sh
# Copy to server
scp dist/btest root@yourserver:/usr/local/bin/btest
```
### From source ### From source
```bash ```bash
cargo install --path . cargo install --path .
``` ```
### Pre-built binaries
Download from [releases](https://git.manko.yoga/manawenuz/btest-rs/releases) or [GitHub releases](https://github.com/manawenuz/btest-rs/releases):
```bash
# Linux x86_64
curl -L <release-url>/btest-linux-x86_64.tar.gz | tar xz
sudo mv btest /usr/local/bin/
# Raspberry Pi 4/5 (64-bit OS)
curl -L <release-url>/btest-linux-aarch64.tar.gz | tar xz
sudo mv btest /usr/local/bin/
# Raspberry Pi 3/Zero 2 (32-bit OS)
curl -L <release-url>/btest-linux-armv7.tar.gz | tar xz
sudo mv btest /usr/local/bin/
# Windows
# Download btest-windows-x86_64.zip from releases
```
### Raspberry Pi
The static musl binaries run on any Raspberry Pi without dependencies:
```bash
# On the Pi — detect architecture and install
ARCH=$(uname -m)
case $ARCH in
aarch64) FILE=btest-linux-aarch64.tar.gz ;;
armv7l) FILE=btest-linux-armv7.tar.gz ;;
*) echo "Unsupported: $ARCH"; exit 1 ;;
esac
curl -LO "https://github.com/manawenuz/btest-rs/releases/latest/download/$FILE"
tar xzf "$FILE"
sudo mv btest /usr/local/bin/
rm "$FILE"
# Run as server
btest -s -a admin -p password --ecsrp5
# Or install as systemd service
curl -LO https://raw.githubusercontent.com/manawenuz/btest-rs/main/scripts/install-service.sh
sudo bash install-service.sh --auth-user admin --auth-pass password
```
### Docker ### Docker
```bash ```bash
docker compose up -d # Server on port 2000 docker compose up -d
``` ```
See [docs/docker.md](docs/docker.md) for full Docker and deployment options.
### systemd service ### systemd service
```bash ```bash
# On the target Linux server:
sudo ./scripts/install-service.sh sudo ./scripts/install-service.sh
sudo ./scripts/install-service.sh --auth-user admin --auth-pass secret sudo ./scripts/install-service.sh --auth-user admin --auth-pass secret
sudo ./scripts/install-service.sh --auth-user admin --auth-pass secret --port 2000
``` ```
## Usage The installer creates a dedicated `btest` system user, installs a hardened systemd unit, and enables the service.
## Quick Start
### Server mode ### Server mode
MikroTik devices connect to this server to run bandwidth tests. MikroTik devices connect to this server to run bandwidth tests.
```bash ```bash
# Basic server (no auth) # No authentication
btest -s btest -s
# With authentication # MD5 authentication (legacy RouterOS)
btest -s -a admin -p password btest -s -a admin -p password
# Custom port with verbose logging # EC-SRP5 authentication (RouterOS >= 6.43)
btest -s -P 2000 -v btest -s -a admin -p password --ecsrp5
# Custom port, verbose logging
btest -s -P 3000 -v
# With syslog and CSV logging
btest -s -a admin -p password --syslog 192.168.1.1:514 --csv /var/log/btest.csv
``` ```
### Client mode ### Client mode
@@ -89,24 +141,62 @@ btest -c 192.168.88.1 -r
# TCP upload test # TCP upload test
btest -c 192.168.88.1 -t btest -c 192.168.88.1 -t
# Bidirectional # Bidirectional TCP
btest -c 192.168.88.1 -t -r btest -c 192.168.88.1 -t -r
# UDP with bandwidth limit # UDP download with bandwidth limit
btest -c 192.168.88.1 -r -u -b 100M btest -c 192.168.88.1 -r -u -b 100M
# With authentication # With authentication
btest -c 192.168.88.1 -r -a admin -p password btest -c 192.168.88.1 -r -a admin -p password
# Timed test (30 seconds), results to CSV
btest -c 192.168.88.1 -r -d 30 --csv results.csv
# Quiet mode (no terminal output)
btest -c 192.168.88.1 -r -d 10 --csv results.csv -q
# UDP through NAT
btest -c 192.168.88.1 -r -u -n
``` ```
### Debug logging ### Debug logging
```bash ```bash
btest -s -v # info + debug btest -s -v # debug messages
btest -s -vv # info + debug + trace (hex dumps of status exchange) btest -s -vv # trace messages (hex dumps of status exchange)
btest -s -vvv # maximum verbosity
``` ```
## MikroTik Setup ## CLI Reference
```
Usage: btest [OPTIONS]
Options:
-s, --server Run in server mode
-c, --client <HOST> Run in client mode, connect to HOST
-t, --transmit Client transmits data (upload test)
-r, --receive Client receives data (download test)
-u, --udp Use UDP instead of TCP
-b, --bandwidth <BW> Target bandwidth limit (e.g., 100M, 1G, 500K)
-P, --port <PORT> Listen/connect port [default: 2000]
--listen <ADDR> IPv4 listen address [default: 0.0.0.0] (use "none" to disable)
--listen6 [<ADDR>] Enable IPv6 listener [default: ::] (experimental)
-a, --authuser <USER> Authentication username
-p, --authpass <PASS> Authentication password
--ecsrp5 Use EC-SRP5 authentication (RouterOS >= 6.43)
-n, --nat NAT traversal mode (send UDP probe packet)
-d, --duration <SECS> Test duration in seconds (client mode, 0=unlimited) [default: 0]
--csv <FILE> Output results to CSV file (appends if file exists)
-q, --quiet Suppress terminal output (use with --csv)
--syslog <HOST:PORT> Send logs to remote syslog server (UDP, RFC 3164)
-v, --verbose Increase log verbosity (-v, -vv, -vvv)
-h, --help Show help
-V, --version Show version
```
## MikroTik Configuration
### Enable btest server on MikroTik (for client mode) ### Enable btest server on MikroTik (for client mode)
@@ -116,41 +206,57 @@ btest -s -vv # info + debug + trace (hex dumps of status exchange)
### Run btest from MikroTik (connecting to our server) ### Run btest from MikroTik (connecting to our server)
**Important: Set Connection Count to 1** — multi-connection mode is not supported.
``` ```
/tool/bandwidth-test address=<server-ip> direction=both protocol=udp user=admin password=password connection-count=1 /tool/bandwidth-test address=<server-ip> direction=both protocol=udp \
user=admin password=password
``` ```
## Protocol ## Protocol
The MikroTik btest protocol uses: The MikroTik btest protocol uses:
- **TCP port 2000** for control (handshake, auth, status exchange)
- **UDP ports 2001+** for data transfer - **TCP port 2000** for control (handshake, authentication, status exchange)
- **MD5 challenge-response** authentication (RouterOS < 6.43) - **UDP ports 2001+** for data transfer (server side)
- **UDP ports 2257+** for data transfer (client side, offset +256)
- **MD5 double-hash challenge-response** authentication (RouterOS < 6.43)
- **EC-SRP5 Curve25519 Weierstrass** authentication (RouterOS >= 6.43)
- **1-second status interval** with dynamic speed adjustment - **1-second status interval** with dynamic speed adjustment
See the [original protocol documentation](btest-opensource/README.md) for wire-format details. See [docs/protocol.md](docs/protocol.md) for the full wire-format specification.
## Authentication ## Authentication
Both MD5 (legacy) and EC-SRP5 (RouterOS >= 6.43) authentication are supported: Both legacy and modern MikroTik authentication schemes are supported:
```bash | Scheme | RouterOS Version | Flag |
# Server with MD5 auth (legacy clients) |--------|-----------------|------|
btest -s -a admin -p password | None | Any | (no flags) |
| MD5 challenge-response | < 6.43 | `-a USER -p PASS` |
| EC-SRP5 (Curve25519) | >= 6.43 | `-a USER -p PASS --ecsrp5` |
# Server with EC-SRP5 auth (modern RouterOS clients) In server mode, `--ecsrp5` advertises EC-SRP5 to connecting clients. Without it, MD5 is advertised. In client mode, the authentication type is auto-detected from the server's response.
btest -s -a admin -p password --ecsrp5
# Client auto-detects auth type ## Known Issues
btest -c 192.168.88.1 -r -a admin -p password
```
## Known Limitations See [KNOWN_ISSUES.md](KNOWN_ISSUES.md) for the full list including:
- **IPv6 support is experimental** (`--listen6`). TCP over IPv6 works fully. UDP over IPv6 has issues on macOS due to kernel ENOBUFS limitations with `send_to()`. On Linux, IPv6 UDP works fine. IPv6 is disabled by default. - **IPv6 UDP on macOS** — server TX hits ENOBUFS, use IPv4 or deploy on Linux
- **Multi-connection UDP** is supported. MikroTik's multi-connection mode sends from multiple source ports which are all accepted by the server. - **macOS UDP send buffer** — first 2-3 seconds unreliable on unlimited speed tests
- **Windows binaries** — cross-compiled but untested
- **IPv6 UDP on Linux** — untested, likely works fine
Contributions and bug reports welcome:
- https://github.com/manawenuz/btest-rs/issues
- https://git.manko.yoga/manawenuz/btest-rs/issues
## Documentation
- [User Guide](docs/user-guide.md) -- complete CLI reference with examples for every mode
- [Architecture](docs/architecture.md) -- module structure, threading model, design decisions
- [Protocol Specification](docs/protocol.md) -- wire format, authentication, status exchange
- [Docker & Deployment](docs/docker.md) -- Docker, Docker Compose, systemd, firewall rules
- [EC-SRP5 Research](docs/ecsrp5-research.md) -- reverse-engineering notes and cryptographic details
- [Man Page](docs/man/btest.1) -- Unix manual page (install to `/usr/share/man/man1/`)
## Testing ## Testing
@@ -163,12 +269,12 @@ scripts/test-docker.sh # Docker container test
## Credits ## Credits
- **[btest-opensource](https://github.com/samm-git/btest-opensource)** by [Alex Samorukov](https://github.com/samm-git) — Original C implementation and protocol reverse-engineering. Licensed under MIT. - **[btest-opensource](https://github.com/samm-git/btest-opensource)** by [Alex Samorukov](https://github.com/samm-git) -- original C implementation and protocol reverse-engineering. Licensed under **MIT**.
- **[Margin Research](https://github.com/MarginResearch/mikrotik_authentication)** EC-SRP5 authentication reverse-engineering (Curve25519 Weierstrass, SRP key exchange). Licensed under Apache 2.0. - **[Margin Research](https://github.com/MarginResearch/mikrotik_authentication)** -- EC-SRP5 authentication reverse-engineering (Curve25519 Weierstrass, SRP key exchange). Licensed under **Apache 2.0**.
- **MikroTik** — Creator of the bandwidth test protocol and RouterOS. - **MikroTik** -- creator of the bandwidth test protocol and RouterOS.
## License ## License
MIT License - see [LICENSE](LICENSE). MIT License -- see [LICENSE](LICENSE).
This project is derived from [btest-opensource](https://github.com/samm-git/btest-opensource) (MIT License, Copyright 2016 Alex Samorukov). The original license and copyright notice are preserved as required. This project is derived from [btest-opensource](https://github.com/samm-git/btest-opensource) (MIT License, Copyright 2016 Alex Samorukov). The EC-SRP5 implementation is based on research by [Margin Research](https://github.com/MarginResearch/mikrotik_authentication) (Apache License 2.0). Original license and copyright notices are preserved as required.

Submodule btest-opensource deleted from 5040a01267

52
deploy/alpine/APKBUILD Normal file
View File

@@ -0,0 +1,52 @@
# Maintainer: Siavash Sameni <manwe at manko dot yoga>
pkgname=btest-rs
pkgver=0.6.0
pkgrel=0
pkgdesc="MikroTik Bandwidth Test server and client with EC-SRP5 auth"
url="https://github.com/manawenuz/btest-rs"
license="MIT AND Apache-2.0"
arch="x86_64 aarch64 armv7"
makedepends="cargo rust"
install="$pkgname.pre-install"
source="$pkgname-$pkgver.tar.gz::https://github.com/manawenuz/btest-rs/archive/refs/tags/v$pkgver.tar.gz
btest.initd
"
sha256sums="SKIP
SKIP
"
prepare() {
default_prepare
cd "$builddir"
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}
build() {
cd "$builddir"
export CARGO_TARGET_DIR=target
cargo build --frozen --release
}
check() {
cd "$builddir"
cargo test --frozen --release
}
package() {
cd "$builddir"
# binary
install -Dm755 "target/release/btest" "$pkgdir/usr/bin/btest"
# man page
install -Dm644 "docs/man/btest.1" "$pkgdir/usr/share/man/man1/btest.1"
# license
install -Dm644 "LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
# documentation
install -Dm644 "README.md" "$pkgdir/usr/share/doc/$pkgname/README.md"
# OpenRC init script
install -Dm755 "$srcdir/btest.initd" "$pkgdir/etc/init.d/btest"
}

37
deploy/alpine/btest.initd Executable file
View File

@@ -0,0 +1,37 @@
#!/sbin/openrc-run
# OpenRC init script for btest-rs
# MikroTik Bandwidth Test server
name="btest"
description="MikroTik Bandwidth Test Server (btest-rs)"
command="/usr/bin/btest"
command_args="-s"
command_background=true
pidfile="/run/$name.pid"
# Run as dedicated user if it exists, otherwise root
command_user="btest:btest"
# Logging
output_log="/var/log/$name/$name.log"
error_log="/var/log/$name/$name.err"
depend() {
need net
after firewall
use dns logger
}
start_pre() {
# Create log directory
checkpath -d -m 0755 -o "$command_user" /var/log/$name
# Create runtime directory
checkpath -d -m 0755 -o "$command_user" /run
}
stop() {
ebegin "Stopping $name"
start-stop-daemon --stop --pidfile "$pidfile" --retry TERM/5/KILL/3
eend $?
}

118
deploy/alpine/test-alpine.sh Executable file
View File

@@ -0,0 +1,118 @@
#!/bin/sh
# Test Alpine Linux packaging for btest-rs
# Runs inside an Alpine Docker container to build and verify the APK.
#
# Usage (from repository root):
# docker run --rm -v "$PWD":/src alpine:latest /src/deploy/alpine/test-alpine.sh
#
set -eu
ALPINE_DIR="/src/deploy/alpine"
echo "=== Alpine APK packaging test ==="
echo "Alpine version: $(cat /etc/alpine-release)"
# ── Install build dependencies ──────────────────────────────────────
echo "--- Installing build dependencies ---"
apk update
apk add --no-cache \
alpine-sdk \
rust \
cargo \
sudo
# ── Create a non-root build user (abuild refuses to run as root) ──
echo "--- Setting up build user ---"
adduser -D builder
addgroup builder abuild
echo "builder ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
# ── Prepare build tree ──────────────────────────────────────────────
echo "--- Preparing build tree ---"
BUILD_DIR="/home/builder/btest-rs"
mkdir -p "$BUILD_DIR"
cp "$ALPINE_DIR/APKBUILD" "$BUILD_DIR/"
cp "$ALPINE_DIR/btest.initd" "$BUILD_DIR/"
# Generate signing key (required by abuild)
su builder -c "abuild-keygen -a -n -q"
sudo cp /home/builder/.abuild/*.rsa.pub /etc/apk/keys/
# ── Build the package ──────────────────────────────────────────────
echo "--- Building APK ---"
cd "$BUILD_DIR"
chown -R builder:builder "$BUILD_DIR"
su builder -c "abuild -r"
echo "--- Build succeeded ---"
# ── Locate and install the package ──────────────────────────────────
echo "--- Installing built APK ---"
APK_FILE=$(find /home/builder/packages -name "btest-rs-*.apk" -not -name "*doc*" | head -1)
if [ -z "$APK_FILE" ]; then
echo "FAIL: APK file not found"
exit 1
fi
echo "Found APK: $APK_FILE"
apk add --allow-untrusted "$APK_FILE"
# ── Verify installation ────────────────────────────────────────────
echo "--- Verifying installation ---"
FAIL=0
# Binary exists and is executable
if command -v btest >/dev/null 2>&1; then
echo "PASS: btest binary installed"
else
echo "FAIL: btest binary not found in PATH"
FAIL=1
fi
# Binary runs (show version / help)
if btest --help >/dev/null 2>&1; then
echo "PASS: btest --help exits successfully"
else
echo "FAIL: btest --help failed"
FAIL=1
fi
# Man page installed
if [ -f /usr/share/man/man1/btest.1 ]; then
echo "PASS: man page installed"
else
echo "FAIL: man page not found"
FAIL=1
fi
# License installed
if [ -f /usr/share/licenses/btest-rs/LICENSE ]; then
echo "PASS: LICENSE installed"
else
echo "FAIL: LICENSE not found"
FAIL=1
fi
# OpenRC init script installed
if [ -f /etc/init.d/btest ]; then
echo "PASS: OpenRC init script installed"
else
echo "FAIL: OpenRC init script not found"
FAIL=1
fi
# Init script is executable
if [ -x /etc/init.d/btest ]; then
echo "PASS: init script is executable"
else
echo "FAIL: init script is not executable"
FAIL=1
fi
# ── Summary ─────────────────────────────────────────────────────────
echo ""
if [ "$FAIL" -eq 0 ]; then
echo "=== All Alpine packaging tests PASSED ==="
else
echo "=== Some Alpine packaging tests FAILED ==="
exit 1
fi

15
deploy/aur/.SRCINFO Normal file
View File

@@ -0,0 +1,15 @@
pkgbase = btest-rs
pkgdesc = MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth
pkgver = 0.6.0
pkgrel = 1
url = https://github.com/manawenuz/btest-rs
arch = x86_64
arch = aarch64
arch = armv7h
license = MIT
license = Apache-2.0
makedepends = cargo
source = btest-rs-0.6.0.tar.gz::https://github.com/manawenuz/btest-rs/archive/refs/tags/v0.6.0.tar.gz
sha256sums = SKIP
pkgname = btest-rs

58
deploy/aur/PKGBUILD Normal file
View File

@@ -0,0 +1,58 @@
# Maintainer: Siavash Sameni <manwe at manko dot yoga>
pkgname=btest-rs
pkgver=0.6.0
pkgrel=1
pkgdesc="MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth"
arch=('x86_64' 'aarch64' 'armv7h')
url="https://github.com/manawenuz/btest-rs"
license=('MIT' 'Apache-2.0')
depends=()
makedepends=('cargo')
source=("$pkgname-$pkgver.tar.gz::https://github.com/manawenuz/btest-rs/archive/refs/tags/v$pkgver.tar.gz")
sha256sums=('SKIP')
prepare() {
cd "$pkgname-$pkgver"
export RUSTUP_TOOLCHAIN=stable
cargo fetch --locked --target "$(rustc -vV | sed -n 's/host: //p')"
}
build() {
cd "$pkgname-$pkgver"
export RUSTUP_TOOLCHAIN=stable
export CARGO_TARGET_DIR=target
cargo build --frozen --release
}
package() {
cd "$pkgname-$pkgver"
install -Dm755 "target/release/btest" "$pkgdir/usr/bin/btest"
install -Dm644 "LICENSE" "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
install -Dm644 "docs/man/btest.1" "$pkgdir/usr/share/man/man1/btest.1"
install -Dm644 "README.md" "$pkgdir/usr/share/doc/$pkgname/README.md"
# systemd service
install -Dm644 /dev/stdin "$pkgdir/usr/lib/systemd/system/btest.service" <<EOF
[Unit]
Description=MikroTik Bandwidth Test Server (btest-rs)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/btest -s
Restart=always
RestartSec=5
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
}

40
deploy/aur/test-aur.sh Executable file
View File

@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Test the PKGBUILD in a Docker Arch Linux container.
# Usage: ./deploy/aur/test-aur.sh
set -euo pipefail
cd "$(dirname "$0")/../.."
echo "=== Testing AUR PKGBUILD in Arch Linux container ==="
docker run --rm -v "$(pwd):/src:ro" archlinux:latest bash -c '
set -euo pipefail
# Install base-devel and rust
pacman -Syu --noconfirm base-devel rustup git
rustup default stable
# Create build user (makepkg refuses to run as root)
useradd -m builder
echo "builder ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
# Copy source and PKGBUILD
su builder -c "
mkdir -p /tmp/build && cd /tmp/build
cp /src/deploy/aur/PKGBUILD .
# Build the package
makepkg -si --noconfirm
# Verify
echo ''
echo '=== Installed ==='
btest --version
btest --help | head -5
echo ''
echo '=== Files ==='
pacman -Ql btest-rs
echo ''
echo '=== SUCCESS ==='
"
'

208
deploy/deb/build-deb.sh Executable file
View File

@@ -0,0 +1,208 @@
#!/usr/bin/env bash
# build-deb.sh -- Build a Debian/Ubuntu .deb package for btest-rs
#
# Usage:
# ./deploy/deb/build-deb.sh # uses dist/btest or target/release/btest
# BTEST_BIN=path/to/btest ./deploy/deb/build-deb.sh
#
# Requirements: dpkg-deb, gzip (standard on Debian/Ubuntu build hosts)
set -euo pipefail
###############################################################################
# Package metadata
###############################################################################
PKG_NAME="btest-rs"
PKG_VERSION="0.6.0"
PKG_ARCH="amd64"
PKG_MAINTAINER="Siavash Sameni <manwe@manko.yoga>"
PKG_DESCRIPTION="MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth"
PKG_HOMEPAGE="https://github.com/manawenuz/btest-rs"
PKG_LICENSE="MIT AND Apache-2.0"
PKG_SECTION="net"
PKG_PRIORITY="optional"
###############################################################################
# Paths
###############################################################################
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Locate the pre-built binary
if [[ -n "${BTEST_BIN:-}" ]]; then
: # caller provided an explicit path
elif [[ -f "$REPO_ROOT/dist/btest" ]]; then
BTEST_BIN="$REPO_ROOT/dist/btest"
elif [[ -f "$REPO_ROOT/target/release/btest" ]]; then
BTEST_BIN="$REPO_ROOT/target/release/btest"
else
echo "Error: cannot find btest binary."
echo " Build first (cargo build --release) or set BTEST_BIN=path/to/btest"
exit 1
fi
# Verify the binary exists and is executable
if [[ ! -f "$BTEST_BIN" ]]; then
echo "Error: $BTEST_BIN does not exist."
exit 1
fi
echo "==> Using binary: $BTEST_BIN"
###############################################################################
# Prepare staging tree
###############################################################################
DEB_FILE="${PKG_NAME}_${PKG_VERSION}_${PKG_ARCH}.deb"
STAGE="$(mktemp -d)"
trap 'rm -rf "$STAGE"' EXIT
echo "==> Staging in $STAGE"
# Binary
install -Dm755 "$BTEST_BIN" "$STAGE/usr/bin/btest"
# Man page
if [[ -f "$REPO_ROOT/docs/man/btest.1" ]]; then
install -Dm644 "$REPO_ROOT/docs/man/btest.1" "$STAGE/usr/share/man/man1/btest.1"
gzip -9n "$STAGE/usr/share/man/man1/btest.1"
else
echo "Warning: docs/man/btest.1 not found -- skipping man page"
fi
# systemd service unit
install -d "$STAGE/usr/lib/systemd/system"
cat > "$STAGE/usr/lib/systemd/system/btest.service" <<'UNIT'
[Unit]
Description=MikroTik Bandwidth Test Server (btest-rs)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/btest -s
Restart=always
RestartSec=5
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
ProtectKernelTunables=yes
ProtectControlGroups=yes
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
UNIT
# Documentation
install -Dm644 "$REPO_ROOT/README.md" "$STAGE/usr/share/doc/$PKG_NAME/README.md"
# License
install -Dm644 "$REPO_ROOT/LICENSE" "$STAGE/usr/share/licenses/$PKG_NAME/LICENSE"
# Debian copyright file (policy-compliant copy in /usr/share/doc)
install -d "$STAGE/usr/share/doc/$PKG_NAME"
cat > "$STAGE/usr/share/doc/$PKG_NAME/copyright" <<COPY
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: $PKG_NAME
Upstream-Contact: $PKG_MAINTAINER
Source: $PKG_HOMEPAGE
Files: *
Copyright: 2024-2026 Siavash Sameni
License: MIT AND Apache-2.0
COPY
###############################################################################
# Calculate installed size (in KiB, as Debian policy requires)
###############################################################################
INSTALLED_SIZE=$(du -sk "$STAGE" | cut -f1)
###############################################################################
# DEBIAN/control
###############################################################################
install -d "$STAGE/DEBIAN"
cat > "$STAGE/DEBIAN/control" <<CTRL
Package: $PKG_NAME
Version: $PKG_VERSION
Architecture: $PKG_ARCH
Maintainer: $PKG_MAINTAINER
Installed-Size: $INSTALLED_SIZE
Section: $PKG_SECTION
Priority: $PKG_PRIORITY
Homepage: $PKG_HOMEPAGE
Description: $PKG_DESCRIPTION
A high-performance Rust implementation of the MikroTik Bandwidth Test
protocol, supporting both server and client modes with EC-SRP5
authentication. Supports TCP/UDP throughput testing and is fully
compatible with RouterOS btest clients.
CTRL
###############################################################################
# DEBIAN/conffiles (mark the systemd unit as a conffile)
###############################################################################
cat > "$STAGE/DEBIAN/conffiles" <<'CF'
/usr/lib/systemd/system/btest.service
CF
###############################################################################
# Maintainer scripts
###############################################################################
# postinst -- reload systemd after install
cat > "$STAGE/DEBIAN/postinst" <<'POST'
#!/bin/sh
set -e
if [ "$1" = "configure" ]; then
if command -v systemctl >/dev/null 2>&1; then
systemctl daemon-reload || true
echo ""
echo "btest-rs installed. To start the server:"
echo " sudo systemctl enable --now btest.service"
echo ""
fi
fi
POST
chmod 755 "$STAGE/DEBIAN/postinst"
# prerm -- stop service before removal
cat > "$STAGE/DEBIAN/prerm" <<'PRERM'
#!/bin/sh
set -e
if [ "$1" = "remove" ] || [ "$1" = "deconfigure" ]; then
if command -v systemctl >/dev/null 2>&1; then
systemctl stop btest.service 2>/dev/null || true
systemctl disable btest.service 2>/dev/null || true
fi
fi
PRERM
chmod 755 "$STAGE/DEBIAN/prerm"
# postrm -- clean up after removal
cat > "$STAGE/DEBIAN/postrm" <<'POSTRM'
#!/bin/sh
set -e
if [ "$1" = "purge" ] || [ "$1" = "remove" ]; then
if command -v systemctl >/dev/null 2>&1; then
systemctl daemon-reload || true
fi
fi
POSTRM
chmod 755 "$STAGE/DEBIAN/postrm"
###############################################################################
# Build .deb
###############################################################################
OUTPUT_DIR="${OUTPUT_DIR:-$REPO_ROOT/dist}"
mkdir -p "$OUTPUT_DIR"
echo "==> Building $DEB_FILE ..."
dpkg-deb --root-owner-group --build "$STAGE" "$OUTPUT_DIR/$DEB_FILE"
echo "==> Package ready: $OUTPUT_DIR/$DEB_FILE"
echo ""
dpkg-deb --info "$OUTPUT_DIR/$DEB_FILE"
echo ""
dpkg-deb --contents "$OUTPUT_DIR/$DEB_FILE"

104
deploy/deb/test-deb.sh Executable file
View File

@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# test-deb.sh -- Smoke-test a btest-rs .deb inside an Ubuntu Docker container
#
# Usage:
# ./deploy/deb/test-deb.sh # auto-finds dist/*.deb
# ./deploy/deb/test-deb.sh path/to/btest-rs_*.deb
#
# Requirements: docker
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
IMAGE="${TEST_IMAGE:-ubuntu:24.04}"
###############################################################################
# Locate the .deb
###############################################################################
if [[ -n "${1:-}" ]]; then
DEB_PATH="$1"
else
DEB_PATH="$(ls -1t "$REPO_ROOT"/dist/btest-rs_*.deb 2>/dev/null | head -1 || true)"
fi
if [[ -z "$DEB_PATH" || ! -f "$DEB_PATH" ]]; then
echo "Error: no .deb file found."
echo " Build first: ./deploy/deb/build-deb.sh"
echo " Or pass path: $0 path/to/btest-rs_*.deb"
exit 1
fi
DEB_FILE="$(basename "$DEB_PATH")"
DEB_DIR="$(cd "$(dirname "$DEB_PATH")" && pwd)"
echo "==> Testing $DEB_FILE in $IMAGE"
echo ""
###############################################################################
# Run tests inside a disposable container
###############################################################################
docker run --rm \
-v "$DEB_DIR/$DEB_FILE:/tmp/$DEB_FILE:ro" \
"$IMAGE" \
bash -euxc "
###################################################################
# 1. Install the .deb
###################################################################
apt-get update -qq
dpkg -i /tmp/$DEB_FILE || apt-get install -f -y # resolve deps if any
###################################################################
# 2. Verify files are in place
###################################################################
echo '--- Checking installed files ---'
test -x /usr/bin/btest
test -f /usr/lib/systemd/system/btest.service
test -f /usr/share/doc/btest-rs/README.md
test -f /usr/share/licenses/btest-rs/LICENSE
# Man page (may be gzipped)
test -f /usr/share/man/man1/btest.1.gz || test -f /usr/share/man/man1/btest.1
echo 'All expected files present.'
###################################################################
# 3. btest --version
###################################################################
echo ''
echo '--- btest --version ---'
btest --version
###################################################################
# 4. Quick loopback server+client test
###################################################################
echo ''
echo '--- Loopback smoke test ---'
# Start server in background
btest -s &
SERVER_PID=\$!
sleep 1
# Run a short TCP test against localhost
if btest -c 127.0.0.1 -d 2 2>&1; then
echo 'Loopback TCP test passed.'
else
echo 'Warning: loopback test returned non-zero (may be expected in container).'
fi
# Tear down
kill \$SERVER_PID 2>/dev/null || true
wait \$SERVER_PID 2>/dev/null || true
###################################################################
# 5. Package metadata sanity
###################################################################
echo ''
echo '--- dpkg metadata ---'
dpkg -s btest-rs | head -20
echo ''
echo '=== All tests passed ==='
"
echo ""
echo "==> .deb smoke test completed successfully."

57
deploy/openwrt/Makefile Normal file
View File

@@ -0,0 +1,57 @@
# OpenWrt package Makefile for btest-rs
#
# To build:
# 1. Clone the OpenWrt SDK for your target
# 2. Copy this directory to package/btest-rs/ in the SDK
# 3. Run: make package/btest-rs/compile V=s
#
# Or use the pre-built binary approach (see build-ipk.sh)
include $(TOPDIR)/rules.mk
PKG_NAME:=btest-rs
PKG_VERSION:=0.6.0
PKG_RELEASE:=1
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
PKG_SOURCE_URL:=https://github.com/manawenuz/btest-rs/archive/refs/tags/v$(PKG_VERSION).tar.gz
PKG_HASH:=skip
PKG_BUILD_DEPENDS:=rust/host
PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
include $(INCLUDE_DIR)/package.mk
define Package/btest-rs
SECTION:=net
CATEGORY:=Network
TITLE:=MikroTik Bandwidth Test server and client
URL:=https://github.com/manawenuz/btest-rs
DEPENDS:=
PKGARCH:=$(ARCH)
endef
define Package/btest-rs/description
A Rust reimplementation of the MikroTik Bandwidth Test (btest) protocol.
Supports TCP/UDP, IPv4/IPv6, EC-SRP5 and MD5 authentication,
multi-connection, syslog, CSV output, and CPU monitoring.
endef
define Build/Compile
cd $(PKG_BUILD_DIR) && \
CARGO_TARGET_DIR=$(PKG_BUILD_DIR)/target \
cargo build --release --target $(RUSTC_TARGET)
endef
define Package/btest-rs/install
$(INSTALL_DIR) $(1)/usr/bin
$(INSTALL_BIN) $(PKG_BUILD_DIR)/target/$(RUSTC_TARGET)/release/btest $(1)/usr/bin/btest
$(INSTALL_DIR) $(1)/etc/init.d
$(INSTALL_BIN) ./files/btest.init $(1)/etc/init.d/btest
$(INSTALL_DIR) $(1)/etc/config
$(INSTALL_CONF) ./files/btest.config $(1)/etc/config/btest
endef
$(eval $(call BuildPackage,btest-rs))

117
deploy/openwrt/build-ipk.sh Executable file
View File

@@ -0,0 +1,117 @@
#!/usr/bin/env bash
# Build an OpenWrt .ipk package from a pre-built static binary.
# No OpenWrt SDK needed — just packages the binary with metadata.
#
# Usage:
# ./deploy/openwrt/build-ipk.sh <arch> [binary-path]
#
# Examples:
# ./deploy/openwrt/build-ipk.sh x86_64 dist/btest # from cross-compiled binary
# ./deploy/openwrt/build-ipk.sh aarch64 dist/btest # for RPi/ARM64 routers
# ./deploy/openwrt/build-ipk.sh mipsel target/release/btest # for MIPS little-endian
#
# Supported architectures: x86_64, aarch64, arm_cortex-a7, mipsel_24kc, mips_24kc
set -euo pipefail
cd "$(dirname "$0")/../.."
ARCH="${1:?Usage: $0 <arch> [binary-path]}"
BINARY="${2:-dist/btest}"
VERSION="0.6.0"
PKG_NAME="btest-rs"
OUTPUT_DIR="dist"
if [ ! -f "$BINARY" ]; then
echo "Error: binary not found at $BINARY"
echo "Build it first: cargo build --release --target <target>"
exit 1
fi
mkdir -p "$OUTPUT_DIR"
WORKDIR=$(mktemp -d)
trap "rm -rf $WORKDIR" EXIT
echo "=== Building ${PKG_NAME}_${VERSION}_${ARCH}.ipk ==="
# Create package structure
mkdir -p "$WORKDIR/data/usr/bin"
mkdir -p "$WORKDIR/data/etc/init.d"
mkdir -p "$WORKDIR/data/etc/config"
mkdir -p "$WORKDIR/control"
# Install files
cp "$BINARY" "$WORKDIR/data/usr/bin/btest"
chmod 755 "$WORKDIR/data/usr/bin/btest"
cp deploy/openwrt/files/btest.init "$WORKDIR/data/etc/init.d/btest"
chmod 755 "$WORKDIR/data/etc/init.d/btest"
cp deploy/openwrt/files/btest.config "$WORKDIR/data/etc/config/btest"
# Calculate installed size
INSTALLED_SIZE=$(du -sk "$WORKDIR/data" | awk '{print $1}')
# Control file
cat > "$WORKDIR/control/control" << EOF
Package: ${PKG_NAME}
Version: ${VERSION}-1
Depends: libc
Source: https://github.com/manawenuz/btest-rs
License: MIT AND Apache-2.0
Section: net
SourceName: ${PKG_NAME}
Maintainer: Siavash Sameni <manwe@manko.yoga>
Architecture: ${ARCH}
Installed-Size: ${INSTALLED_SIZE}
Description: MikroTik Bandwidth Test server and client
A Rust reimplementation of the MikroTik btest protocol.
Supports TCP/UDP, EC-SRP5 and MD5 auth, IPv4/IPv6.
EOF
# Post-install script
cat > "$WORKDIR/control/postinst" << 'EOF'
#!/bin/sh
[ "${IPKG_NO_SCRIPT}" = "1" ] && exit 0
/etc/init.d/btest enable 2>/dev/null || true
exit 0
EOF
chmod 755 "$WORKDIR/control/postinst"
# Pre-remove script
cat > "$WORKDIR/control/prerm" << 'EOF'
#!/bin/sh
/etc/init.d/btest stop 2>/dev/null || true
/etc/init.d/btest disable 2>/dev/null || true
exit 0
EOF
chmod 755 "$WORKDIR/control/prerm"
# Conffiles
cat > "$WORKDIR/control/conffiles" << EOF
/etc/config/btest
EOF
# Build the .ipk (it's just a tar.gz of tar.gz's)
cd "$WORKDIR"
# Create data.tar.gz
(cd data && tar czf ../data.tar.gz .)
# Create control.tar.gz
(cd control && tar czf ../control.tar.gz .)
# Create debian-binary
echo "2.0" > debian-binary
# Package it all
tar czf "${PKG_NAME}_${VERSION}-1_${ARCH}.ipk" debian-binary control.tar.gz data.tar.gz
cd -
cp "$WORKDIR/${PKG_NAME}_${VERSION}-1_${ARCH}.ipk" "$OUTPUT_DIR/"
echo ""
echo "Package: $OUTPUT_DIR/${PKG_NAME}_${VERSION}-1_${ARCH}.ipk"
ls -lh "$OUTPUT_DIR/${PKG_NAME}_${VERSION}-1_${ARCH}.ipk"
echo ""
echo "Install on OpenWrt:"
echo " scp $OUTPUT_DIR/${PKG_NAME}_${VERSION}-1_${ARCH}.ipk root@router:/tmp/"
echo " ssh root@router 'opkg install /tmp/${PKG_NAME}_${VERSION}-1_${ARCH}.ipk'"
echo " ssh root@router '/etc/init.d/btest enable && /etc/init.d/btest start'"

View File

@@ -0,0 +1,7 @@
config server
option enabled '0'
option port '2000'
option auth_user ''
option auth_pass ''
option ecsrp5 '0'
option syslog ''

34
deploy/openwrt/files/btest.init Executable file
View File

@@ -0,0 +1,34 @@
#!/bin/sh /etc/rc.common
# btest-rs OpenWrt init script
START=90
STOP=10
USE_PROCD=1
start_service() {
local enabled port auth_user auth_pass ecsrp5 syslog
config_load btest
config_get_bool enabled server enabled 0
[ "$enabled" -eq 0 ] && return
config_get port server port 2000
config_get auth_user server auth_user ''
config_get auth_pass server auth_pass ''
config_get_bool ecsrp5 server ecsrp5 0
config_get syslog server syslog ''
procd_open_instance
procd_set_param command /usr/bin/btest -s -P "$port"
[ -n "$auth_user" ] && procd_append_param command -a "$auth_user"
[ -n "$auth_pass" ] && procd_append_param command -p "$auth_pass"
[ "$ecsrp5" -eq 1 ] && procd_append_param command --ecsrp5
[ -n "$syslog" ] && procd_append_param command --syslog "$syslog"
procd_set_param respawn
procd_set_param stdout 1
procd_set_param stderr 1
procd_close_instance
}

73
deploy/rpm/btest-rs.spec Normal file
View File

@@ -0,0 +1,73 @@
Name: btest-rs
Version: 0.6.0
Release: 1%{?dist}
Summary: MikroTik Bandwidth Test (btest) server and client with EC-SRP5 auth
License: MIT AND Apache-2.0
URL: https://github.com/manawenuz/btest-rs
Source0: https://github.com/manawenuz/btest-rs/archive/refs/tags/v%{version}.tar.gz
BuildRequires: cargo
BuildRequires: rust
ExclusiveArch: x86_64 aarch64
%description
A Rust reimplementation of the MikroTik Bandwidth Test (btest) protocol,
providing both server and client functionality with EC-SRP5 authentication.
%prep
%autosetup -n %{name}-%{version}
%build
export CARGO_TARGET_DIR=target
cargo build --release
%install
install -Dm755 target/release/btest %{buildroot}%{_bindir}/btest
install -Dm644 docs/man/btest.1 %{buildroot}%{_mandir}/man1/btest.1
install -Dm644 LICENSE %{buildroot}%{_datadir}/licenses/%{name}/LICENSE
# systemd service unit
install -d %{buildroot}%{_unitdir}
cat > %{buildroot}%{_unitdir}/btest.service << 'EOF'
[Unit]
Description=MikroTik Bandwidth Test Server (btest-rs)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
ExecStart=/usr/bin/btest -s
Restart=always
RestartSec=5
DynamicUser=yes
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
AmbientCapabilities=CAP_NET_BIND_SERVICE
CapabilityBoundingSet=CAP_NET_BIND_SERVICE
LimitNOFILE=65535
[Install]
WantedBy=multi-user.target
EOF
%files
%license LICENSE
%{_bindir}/btest
%{_mandir}/man1/btest.1*
%{_unitdir}/btest.service
%post
%systemd_post btest.service
%preun
%systemd_preun btest.service
%postun
%systemd_postun_with_restart btest.service
%changelog
* Mon Mar 30 2026 Siavash Sameni <manwe@manko.yoga> - 0.6.0-1
- Initial RPM package

30
deploy/rpm/build-rpm.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# build-rpm.sh — Build the btest-rs RPM package
set -euo pipefail
SPEC_DIR="$(cd "$(dirname "$0")" && pwd)"
SPEC_FILE="${SPEC_DIR}/btest-rs.spec"
VERSION="0.6.0"
TARBALL="v${VERSION}.tar.gz"
SOURCE_URL="https://github.com/manawenuz/btest-rs/archive/refs/tags/${TARBALL}"
echo "==> Setting up rpmbuild tree"
mkdir -p ~/rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS}
echo "==> Downloading source tarball"
if [ ! -f ~/rpmbuild/SOURCES/"${TARBALL}" ]; then
curl -fSL -o ~/rpmbuild/SOURCES/"${TARBALL}" "${SOURCE_URL}"
else
echo " (already present, skipping download)"
fi
echo "==> Copying spec file"
cp "${SPEC_FILE}" ~/rpmbuild/SPECS/btest-rs.spec
echo "==> Building RPM"
rpmbuild -ba ~/rpmbuild/SPECS/btest-rs.spec
echo ""
echo "==> Build complete. Packages:"
find ~/rpmbuild/RPMS -name '*.rpm' -print
find ~/rpmbuild/SRPMS -name '*.rpm' -print

75
deploy/rpm/test-rpm.sh Executable file
View File

@@ -0,0 +1,75 @@
#!/usr/bin/env bash
# test-rpm.sh — Test the btest-rs RPM build inside a Fedora container
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
IMAGE="fedora:latest"
echo "==> Testing RPM build in ${IMAGE}"
docker run --rm \
-v "${REPO_ROOT}:/workspace:ro" \
"${IMAGE}" \
bash -euxc '
# ── Install build dependencies ──
dnf install -y rpm-build rpmdevtools curl gcc make \
systemd-rpm-macros
# Install Rust toolchain
curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs \
| sh -s -- -y --profile minimal
source "$HOME/.cargo/env"
# ── Set up rpmbuild tree ──
rpmdev-setuptree
VERSION="0.6.0"
TARBALL="v${VERSION}.tar.gz"
# Copy spec
cp /workspace/deploy/rpm/btest-rs.spec ~/rpmbuild/SPECS/
# Create source tarball from workspace
# rpmbuild expects btest-rs-VERSION/ top-level directory
mkdir -p /tmp/btest-rs-${VERSION}
cp -a /workspace/. /tmp/btest-rs-${VERSION}/
tar czf ~/rpmbuild/SOURCES/${TARBALL} -C /tmp btest-rs-${VERSION}
# ── Build RPM ──
rpmbuild -ba ~/rpmbuild/SPECS/btest-rs.spec
# ── Install the RPM ──
RPM=$(find ~/rpmbuild/RPMS -name "btest-rs-*.rpm" | head -1)
echo "Installing: ${RPM}"
dnf install -y "${RPM}"
# ── Verify installation ──
echo "--- btest --version ---"
btest --version
echo "--- Checking systemd unit ---"
systemctl cat btest.service || true
echo "--- Checking man page ---"
test -f /usr/share/man/man1/btest.1* && echo "man page OK" || echo "man page MISSING"
echo "--- Checking license ---"
test -f /usr/share/licenses/btest-rs/LICENSE && echo "license OK" || echo "license MISSING"
# ── Loopback bandwidth test ──
echo "--- Starting loopback test ---"
btest -s &
SERVER_PID=$!
sleep 2
btest -c 127.0.0.1 --duration 3 && echo "Loopback test PASSED" \
|| echo "Loopback test FAILED (exit $?)"
kill "${SERVER_PID}" 2>/dev/null || true
wait "${SERVER_PID}" 2>/dev/null || true
echo "==> All RPM tests completed."
'
echo "==> Fedora container test finished."

View File

@@ -0,0 +1,96 @@
# btest-rs syslog configuration for syslog-ng
# Add this to your syslog-ng.conf or include from conf.d/
#
# Copy to: /var/data/syslogng/config/conf.d/btest.conf
# Or append to your main syslog-ng.conf
#
# Note: uses message-based matching (not program()) because
# MikroTik sources use flags(no-parse) which skips program extraction.
# Filter for btest-rs messages
filter f_btest {
match("btest-rs:" value("MESSAGE"));
};
# Filter subcategories
filter f_btest_auth {
match("btest-rs:" value("MESSAGE")) and (
match("AUTH_SUCCESS" value("MESSAGE")) or
match("AUTH_FAILURE" value("MESSAGE"))
);
};
filter f_btest_test {
match("btest-rs:" value("MESSAGE")) and (
match("TEST_START" value("MESSAGE")) or
match("TEST_END" value("MESSAGE")) or
match("TEST_RESULT" value("MESSAGE"))
);
};
# All btest logs
destination d_btest_all {
file(
"/var/log/remote/btest/all.log"
create_dirs(yes)
dir_perm(0755)
perm(0644)
template(t_mikrotik_format)
);
};
# Auth events (successes + failures)
destination d_btest_auth {
file(
"/var/log/remote/btest/auth.log"
create_dirs(yes)
dir_perm(0755)
perm(0644)
template(t_mikrotik_format)
);
};
# Test events (start/stop/results)
destination d_btest_tests {
file(
"/var/log/remote/btest/tests.log"
create_dirs(yes)
dir_perm(0755)
perm(0644)
template(t_mikrotik_format)
);
};
# Per-day logs
destination d_btest_daily {
file(
"/var/log/remote/btest/${YEAR}-${MONTH}-${DAY}.log"
create_dirs(yes)
dir_perm(0755)
perm(0644)
template(t_mikrotik_format)
);
};
# Log paths
log {
source(s_network_udp);
source(s_network_tcp);
filter(f_btest);
destination(d_btest_all);
destination(d_btest_daily);
};
log {
source(s_network_udp);
source(s_network_tcp);
filter(f_btest_auth);
destination(d_btest_auth);
};
log {
source(s_network_udp);
source(s_network_tcp);
filter(f_btest_test);
destination(d_btest_tests);
};

View File

@@ -1,7 +1,7 @@
services: services:
btest-server: btest-server:
build: . build: .
image: git.manko.yoga/manawenuz/btest-rs:latest image: ghcr.io/manawenuz/btest-rs:latest
container_name: btest-server container_name: btest-server
ports: ports:
- "2000:2000/tcp" - "2000:2000/tcp"
@@ -13,7 +13,7 @@ services:
# Server with authentication enabled # Server with authentication enabled
btest-server-auth: btest-server-auth:
build: . build: .
image: git.manko.yoga/manawenuz/btest-rs:latest image: ghcr.io/manawenuz/btest-rs:latest
container_name: btest-server-auth container_name: btest-server-auth
ports: ports:
- "2010:2000/tcp" - "2010:2000/tcp"

View File

@@ -13,22 +13,31 @@ graph TB
client["client.rs<br/>Client mode"] client["client.rs<br/>Client mode"]
protocol["protocol.rs<br/>Wire protocol types"] protocol["protocol.rs<br/>Wire protocol types"]
auth["auth.rs<br/>MD5 authentication"] auth["auth.rs<br/>MD5 authentication"]
ecsrp5["ecsrp5.rs<br/>EC-SRP5 authentication<br/>(Curve25519 Weierstrass)"]
bandwidth["bandwidth.rs<br/>Rate control & reporting"] bandwidth["bandwidth.rs<br/>Rate control & reporting"]
csv_output["csv_output.rs<br/>CSV result logging"]
syslog["syslog_logger.rs<br/>Remote syslog (RFC 3164)"]
lib["lib.rs<br/>Public API for tests"] lib["lib.rs<br/>Public API for tests"]
main --> server main --> server
main --> client main --> client
main --> bandwidth main --> bandwidth
main --> csv_output
main --> syslog
server --> protocol server --> protocol
server --> auth server --> auth
server --> ecsrp5
server --> bandwidth server --> bandwidth
server --> syslog
client --> protocol client --> protocol
client --> auth client --> auth
client --> ecsrp5
client --> bandwidth client --> bandwidth
lib --> server lib --> server
lib --> client lib --> client
lib --> protocol lib --> protocol
lib --> auth lib --> auth
lib --> ecsrp5
lib --> bandwidth lib --> bandwidth
``` ```
@@ -60,8 +69,8 @@ sequenceDiagram
SRV->>TCP: EC-SRP5 [03 00 00 00] SRV->>TCP: EC-SRP5 [03 00 00 00]
MK->>TCP: [len][username\0][client_pubkey:32][parity:1] MK->>TCP: [len][username\0][client_pubkey:32][parity:1]
SRV->>TCP: [len][server_pubkey:32][parity:1][salt:16] SRV->>TCP: [len][server_pubkey:32][parity:1][salt:16]
MK->>TCP: [len][client_proof:32] MK->>TCP: [len][client_confirmation:32]
SRV->>TCP: [len][server_proof:32] SRV->>TCP: [len][server_confirmation:32]
Note over SRV: Curve25519 Weierstrass EC-SRP5<br/>See docs/ecsrp5-research.md Note over SRV: Curve25519 Weierstrass EC-SRP5<br/>See docs/ecsrp5-research.md
SRV->>TCP: AUTH_OK [01 00 00 00] SRV->>TCP: AUTH_OK [01 00 00 00]
end end
@@ -105,14 +114,18 @@ sequenceDiagram
CLI->>TCP: Command [16 bytes] CLI->>TCP: Command [16 bytes]
Note over CLI: direction bits tell server<br/>what to do (TX/RX/BOTH) Note over CLI: direction bits tell server<br/>what to do (TX/RX/BOTH)
alt Auth response 01 alt Auth response 01 (no auth)
Note over CLI: No auth, proceed Note over CLI: No auth, proceed
else Auth response 02 (MD5) else Auth response 02 (MD5)
MK->>TCP: Challenge MK->>TCP: Challenge [16 random bytes]
CLI->>TCP: MD5 response CLI->>TCP: MD5 response [48 bytes]
MK->>TCP: AUTH_OK MK->>TCP: AUTH_OK
else Auth response 03 (EC-SRP5) else Auth response 03 (EC-SRP5)
Note over CLI: Not supported yet CLI->>TCP: [len][username\0][client_pubkey:32][parity:1]
MK->>TCP: [len][server_pubkey:32][parity:1][salt:16]
CLI->>TCP: [len][client_confirmation:32]
MK->>TCP: [len][server_confirmation:32]
MK->>TCP: AUTH_OK
end end
Note over CLI,MK: Data transfer begins<br/>(TCP or UDP, same as server) Note over CLI,MK: Data transfer begins<br/>(TCP or UDP, same as server)
@@ -156,57 +169,115 @@ graph TB
## Key Design Decisions ## Key Design Decisions
### 1. Tokio async runtime ### 1. Tokio async runtime
All I/O is async via tokio. Each client connection spawns independent tasks for TX, RX, and status exchange. This allows handling hundreds of concurrent connections on a single thread pool. All I/O is async via tokio. Each client connection spawns independent tasks for TX, RX, and status exchange. This allows handling hundreds of concurrent connections on a single thread pool.
### 2. Lock-free shared state ### 2. Lock-free shared state
TX/RX threads and the status loop share bandwidth counters via `AtomicU64`. No mutexes needed — `swap(0)` atomically reads and resets counters each interval.
TX/RX threads and the status loop share bandwidth counters via `AtomicU64`. No mutexes needed -- `swap(0)` atomically reads and resets counters each interval.
### 3. Sequential status loop (matching C pselect) ### 3. Sequential status loop (matching C pselect)
The UDP status exchange uses a sequential timeout-read-then-send pattern rather than `tokio::select!`. This ensures our status messages are sent exactly every 1 second, preventing MikroTik's speed adaptation from seeing irregular feedback. The UDP status exchange uses a sequential timeout-read-then-send pattern rather than `tokio::select!`. This ensures our status messages are sent exactly every 1 second, preventing MikroTik's speed adaptation from seeing irregular feedback.
### 4. Direction bits from server perspective ### 4. Direction bits from server perspective
The direction byte in the protocol means what the **server** should do: The direction byte in the protocol means what the **server** should do:
- `0x01` (CMD_DIR_RX) = server receives - `0x01` (CMD_DIR_RX) = server receives
- `0x02` (CMD_DIR_TX) = server transmits - `0x02` (CMD_DIR_TX) = server transmits
- `0x03` (CMD_DIR_BOTH) = bidirectional - `0x03` (CMD_DIR_BOTH) = bidirectional
The client inverts before sending: client "transmit" `CMD_DIR_RX` (telling server to receive). The client inverts before sending: client "transmit" sends `CMD_DIR_RX` (telling server to receive).
### 5. TCP socket half keepalive ### 5. TCP socket half keepalive
When only one direction is active (e.g., TX only), the unused socket half is kept alive. Dropping `OwnedWriteHalf` sends a TCP FIN, which MikroTik interprets as disconnection. When only one direction is active (e.g., TX only), the unused socket half is kept alive. Dropping `OwnedWriteHalf` sends a TCP FIN, which MikroTik interprets as disconnection.
### 6. Static musl binary ### 6. Static musl binary
Release builds use musl for a fully static binary with zero runtime dependencies. The binary is 2 MB and runs on any Linux.
Release builds use musl for a fully static binary with zero runtime dependencies. The binary is approximately 2 MB and runs on any Linux distribution.
### 7. EC-SRP5 with big integer arithmetic
The EC-SRP5 implementation uses `num-bigint` for Curve25519 Weierstrass-form elliptic curve arithmetic. MikroTik's authentication uses the Weierstrass form (not the more common Montgomery or Edwards forms), requiring direct field arithmetic over the prime `2^255 - 19`. The implementation includes point multiplication, `lift_x`, `redp1` (hash-to-curve), and Montgomery coordinate conversion.
### 8. Global singletons for syslog and CSV
The syslog and CSV modules use `Mutex<Option<...>>` global statics. This avoids threading state through every function call while remaining safe. Both modules are initialized once at startup and used from any async task via their public API functions.
### 9. Shared BandwidthState for client duration timeout
When running with `--duration`, the tokio timeout cancels the client future. To preserve stats accumulated during the test, `BandwidthState` is created in `main()` and passed as an `Arc` into `run_client()`. The state survives cancellation because `main()` holds a reference. The `record_interval()` method accumulates totals that `summary()` returns.
### 10. IPv6 socket handling
IPv6 requires special handling on macOS:
- UDP sockets bind to `[::]` for IPv6 peers, `0.0.0.0` for IPv4
- Socket send/receive buffers set to 4MB via `socket2` before wrapping with tokio
- `SocketAddr::new()` used instead of string formatting (avoids `[addr]:port` parsing issues)
- Connected sockets preferred for single-connection (avoids ENOBUFS on `send_to()`)
- NDP probe packet sent before data blast to populate neighbor cache
- Adaptive backoff on ENOBUFS (200μs→10ms, resets on success)
### 11. CPU usage monitoring
A background OS thread samples system CPU every 1 second via:
- **macOS:** `host_statistics(HOST_CPU_LOAD_INFO)` — returns user/system/idle/nice ticks
- **Linux:** `/proc/stat` — reads aggregate CPU line
The percentage is stored in a global `AtomicU8` and included in every status message at byte 1 using MikroTik's encoding: `0x80 | percentage`. On receive, the remote CPU is decoded with `byte & 0x7F` and capped at 100%. Both local and remote CPU are displayed per interval and logged to CSV/syslog.
## File Layout ## File Layout
``` ```
btest-rs/ btest-rs/
├── src/ ├── src/
│ ├── main.rs # CLI entry point, argument parsing │ ├── main.rs # CLI entry point, argument parsing (clap)
│ ├── lib.rs # Public API (used by integration tests) │ ├── lib.rs # Public API (used by integration tests)
│ ├── protocol.rs # Wire format: Command, StatusMessage, constants │ ├── protocol.rs # Wire format: Command, StatusMessage, constants
│ ├── auth.rs # MD5 challenge-response authentication │ ├── auth.rs # MD5 challenge-response authentication
│ ├── ecsrp5.rs # EC-SRP5 authentication (Curve25519 Weierstrass) │ ├── ecsrp5.rs # EC-SRP5 authentication (Curve25519 Weierstrass)
│ ├── server.rs # Server mode: listener, TCP/UDP handlers │ ├── server.rs # Server mode: listener, TCP/UDP handlers
│ ├── client.rs # Client mode: connector, TCP/UDP handlers │ ├── client.rs # Client mode: connector, TCP/UDP handlers
── bandwidth.rs # Rate limiting, formatting, shared state ── bandwidth.rs # Rate limiting, formatting, shared state
│ ├── cpu.rs # CPU usage sampler (macOS + Linux)
│ ├── csv_output.rs # CSV result logging (append-mode, auto-header)
│ └── syslog_logger.rs # Remote syslog sender (RFC 3164 / BSD format)
├── tests/ ├── tests/
│ └── integration_test.rs # End-to-end server/client tests │ └── integration_test.rs # End-to-end server/client tests
├── scripts/ ├── scripts/
│ ├── build-linux.sh # Cross-compile for x86_64 Linux │ ├── build-linux.sh # Cross-compile for x86_64 Linux (musl)
│ ├── install-service.sh # systemd service installer │ ├── build-macos-release.sh # macOS release build
│ ├── test-local.sh # Loopback self-test │ ├── install-service.sh # systemd service installer
│ ├── test-mikrotik.sh # Test against MikroTik device │ ├── push-docker.sh # Push Docker image to registry
── test-docker.sh # Docker container test ── test-local.sh # Loopback self-test
│ ├── test-mikrotik.sh # Test against MikroTik device
│ ├── test-docker.sh # Docker container test
│ └── debug-capture.sh # Packet capture for debugging
├── docs/ ├── docs/
│ ├── architecture.md # This file │ ├── architecture.md # This file
│ ├── protocol.md # Protocol specification │ ├── protocol.md # Protocol specification
│ ├── user-guide.md # Usage documentation │ ├── user-guide.md # Usage documentation
── docker.md # Docker & deployment guide ── docker.md # Docker & deployment guide
├── Dockerfile # Production Docker image │ ├── ecsrp5-research.md # EC-SRP5 reverse-engineering notes
├── Dockerfile.cross # Cross-compilation for Linux x86_64 │ └── man/
├── docker-compose.yml # Docker Compose configuration │ └── btest.1 # Unix manual page (troff format)
├── Cargo.toml ├── tests/
└── btest-opensource/ # Original C implementation (git submodule) │ ├── integration_test.rs # Basic server/client handshake tests
│ ├── ecsrp5_test.rs # EC-SRP5 authentication tests
│ └── full_integration_test.rs # Comprehensive: all protocols, IPv4/6, CSV, syslog
├── deploy/
│ └── syslog-ng-btest.conf # syslog-ng configuration for btest events
├── proto-test/ # Python EC-SRP5 prototype (research branch)
│ ├── btest_ecsrp5_client.py # Working Python btest EC-SRP5 client
│ ├── btest_mitm.py # MITM proxy for protocol analysis
│ └── elliptic_curves.py # Curve25519 Weierstrass (MarginResearch)
├── KNOWN_ISSUES.md # Known bugs and platform limitations
├── Dockerfile # Production Docker image (multi-stage)
├── Dockerfile.cross # Cross-compilation for Linux x86_64
├── docker-compose.yml # Docker Compose configuration
├── Cargo.toml # Rust package manifest
├── Cargo.lock # Dependency lock file
├── LICENSE # MIT License
└── btest-opensource/ # Original C implementation (git submodule)
``` ```

View File

@@ -1,26 +1,43 @@
# Docker & Deployment Guide # Docker and Deployment Guide
## Container Registry ## Container Registries
Images are published to: Images are published to:
``` ```
git.manko.yoga/manawenuz/btest-rs git.manko.yoga/manawenuz/btest-rs # Gitea registry
ghcr.io/manawenuz/btest-rs # GitHub Container Registry
``` ```
## Quick Run (Ephemeral) ## Quick Start
### Server (one-liner) ### Docker Compose (recommended)
```bash
# Server with no authentication
docker compose up -d
# Server with authentication
docker compose --profile auth up -d
# View logs
docker compose logs -f
```
### One-liner server
```bash ```bash
# Build and run server directly
docker build -t btest-rs . && \ docker build -t btest-rs . && \
docker run --rm -it \ docker run --rm -it \
-p 2000:2000/tcp \ -p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \ -p 2001-2100:2001-2100/udp \
-p 2257-2356:2257-2356/udp \ -p 2257-2356:2257-2356/udp \
btest-rs -s -v btest-rs -s -v
```
# With authentication ### One-liner server with authentication
```bash
docker run --rm -it \ docker run --rm -it \
-p 2000:2000/tcp \ -p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \ -p 2001-2100:2001-2100/udp \
@@ -28,7 +45,28 @@ docker run --rm -it \
btest-rs -s -a admin -p password -v btest-rs -s -a admin -p password -v
``` ```
### Client (one-liner) ### Server with EC-SRP5 authentication
```bash
docker run --rm -it \
-p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \
-p 2257-2356:2257-2356/udp \
btest-rs -s -a admin -p password --ecsrp5 -v
```
### Server with syslog and CSV
```bash
docker run --rm -it \
-p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \
-p 2257-2356:2257-2356/udp \
-v /var/log/btest:/data \
btest-rs -s -a admin -p password --syslog 192.168.1.1:514 --csv /data/results.csv -v
```
### Client mode
```bash ```bash
# TCP download test against MikroTik # TCP download test against MikroTik
@@ -36,36 +74,50 @@ docker run --rm -it btest-rs -c 192.168.88.1 -r
# UDP bidirectional # UDP bidirectional
docker run --rm -it btest-rs -c 192.168.88.1 -t -r -u docker run --rm -it btest-rs -c 192.168.88.1 -t -r -u
# Timed test with CSV output
docker run --rm -it \
-v $(pwd):/data \
btest-rs -c 192.168.88.1 -r -d 30 --csv /data/results.csv
# With authentication
docker run --rm -it btest-rs -c 192.168.88.1 -r -a admin -p password
``` ```
### Using pre-built image from registry ### Using pre-built image from registry
```bash ```bash
# Pull from Gitea registry # Pull from Gitea registry
docker pull git.manko.yoga/manawenuz/btest-rs:latest docker pull ghcr.io/manawenuz/btest-rs:latest
# Run server # Run server
docker run --rm -it \ docker run --rm -it \
-p 2000:2000/tcp \ -p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \ -p 2001-2100:2001-2100/udp \
-p 2257-2356:2257-2356/udp \ -p 2257-2356:2257-2356/udp \
git.manko.yoga/manawenuz/btest-rs:latest -s -v ghcr.io/manawenuz/btest-rs:latest -s -v
``` ```
## Docker Compose ## Docker Compose
### Basic server The `docker-compose.yml` file provides two service profiles:
### Default profile (no auth)
```bash ```bash
docker compose up -d docker compose up -d
``` ```
### Server with authentication Starts a server on port 2000 with verbose logging and no authentication.
### Auth profile
```bash ```bash
docker compose --profile auth up -d docker compose --profile auth up -d
``` ```
Starts an additional server on port 2010 with MD5 authentication (user: admin, password: password).
### docker-compose.yml ### docker-compose.yml
```yaml ```yaml
@@ -94,7 +146,23 @@ services:
- auth - auth
``` ```
## Building ## Dockerfile
The production Dockerfile uses a multi-stage build:
1. **Build stage** -- Rust 1.86 slim image, compiles a release binary
2. **Runtime stage** -- Debian Bookworm slim, copies only the binary
The resulting image is approximately 80 MB. The binary itself is about 2 MB.
Exposed ports:
- `2000/tcp` -- control channel
- `2001-2100/udp` -- server-side data ports
- `2257-2356/udp` -- client-side data ports
Default entrypoint: `btest -s`
## Building Images
### Local build (native) ### Local build (native)
@@ -107,27 +175,26 @@ cargo build --release
```bash ```bash
scripts/build-linux.sh scripts/build-linux.sh
# Binary at: dist/btest (static musl, 2 MB) # Binary at: dist/btest (static musl, ~2 MB)
``` ```
### Docker image build ### Docker image build
```bash ```bash
# Production image (for running) # Production image
docker build -t btest-rs . docker build -t btest-rs .
# With custom tag # With custom tag
docker build -t git.manko.yoga/manawenuz/btest-rs:latest . docker build -t git.manko.yoga/manawenuz/btest-rs:latest .
docker build -t git.manko.yoga/manawenuz/btest-rs:0.1.0 . docker build -t git.manko.yoga/manawenuz/btest-rs:0.6.0 .
``` ```
### Multi-platform build ### Multi-platform build
```bash ```bash
# Build for both ARM64 and x86_64
docker buildx build \ docker buildx build \
--platform linux/amd64,linux/arm64 \ --platform linux/amd64,linux/arm64 \
-t git.manko.yoga/manawenuz/btest-rs:latest \ -t ghcr.io/manawenuz/btest-rs:latest \
--push . --push .
``` ```
@@ -142,14 +209,14 @@ docker build -t git.manko.yoga/manawenuz/btest-rs:latest .
docker push git.manko.yoga/manawenuz/btest-rs:latest docker push git.manko.yoga/manawenuz/btest-rs:latest
# Also tag with version # Also tag with version
docker tag git.manko.yoga/manawenuz/btest-rs:latest \ docker tag ghcr.io/manawenuz/btest-rs:latest \
git.manko.yoga/manawenuz/btest-rs:0.1.0 git.manko.yoga/manawenuz/btest-rs:0.6.0
docker push git.manko.yoga/manawenuz/btest-rs:0.1.0 docker push git.manko.yoga/manawenuz/btest-rs:0.6.0
``` ```
## Deployment on Linux Server ## Deployment Options
### Option 1: Docker ### Option 1: Docker (single container)
```bash ```bash
docker run -d --name btest-server \ docker run -d --name btest-server \
@@ -157,8 +224,8 @@ docker run -d --name btest-server \
-p 2000:2000/tcp \ -p 2000:2000/tcp \
-p 2001-2100:2001-2100/udp \ -p 2001-2100:2001-2100/udp \
-p 2257-2356:2257-2356/udp \ -p 2257-2356:2257-2356/udp \
git.manko.yoga/manawenuz/btest-rs:latest \ ghcr.io/manawenuz/btest-rs:latest \
-s -a admin -p password -v -s -a admin -p password --ecsrp5 -v
``` ```
### Option 2: Static binary + systemd ### Option 2: Static binary + systemd
@@ -167,11 +234,28 @@ docker run -d --name btest-server \
# Copy binary to server # Copy binary to server
scp dist/btest root@server:/usr/local/bin/btest scp dist/btest root@server:/usr/local/bin/btest
# Copy and run installer # Run the installer
scp scripts/install-service.sh root@server:/tmp/ scp scripts/install-service.sh root@server:/tmp/
ssh root@server "bash /tmp/install-service.sh --auth-user admin --auth-pass password" ssh root@server "bash /tmp/install-service.sh --auth-user admin --auth-pass password"
``` ```
The installer script:
- Creates a dedicated `btest` system user
- Installs a hardened systemd unit with security options (NoNewPrivileges, ProtectSystem, PrivateTmp)
- Grants `CAP_NET_BIND_SERVICE` for binding to ports below 1024
- Enables and starts the service
- Supports `--auth-user`, `--auth-pass`, and `--port` options
Useful systemd commands after installation:
```bash
systemctl status btest # Check status
systemctl stop btest # Stop the service
systemctl restart btest # Restart
journalctl -u btest -f # Follow logs
systemctl disable btest # Disable autostart
```
### Option 3: Docker Compose on server ### Option 3: Docker Compose on server
```bash ```bash
@@ -183,9 +267,9 @@ ssh root@server "cd /opt/btest-rs && docker compose up -d"
| Port | Protocol | Purpose | | Port | Protocol | Purpose |
|------|----------|---------| |------|----------|---------|
| 2000 | TCP | Control channel (handshake, auth, status) | | 2000 | TCP | Control channel (handshake, auth, status exchange) |
| 2001-2100 | UDP | Server-side data ports | | 2001-2100 | UDP | Server-side data ports |
| 2257-2356 | UDP | Client-side data ports (2001+256) | | 2257-2356 | UDP | Client-side data ports (server_port + 256) |
### Firewall rules (iptables) ### Firewall rules (iptables)
@@ -203,20 +287,35 @@ ufw allow 2001:2100/udp
ufw allow 2257:2356/udp ufw allow 2257:2356/udp
``` ```
### Firewall rules (nftables)
```bash
nft add rule inet filter input tcp dport 2000 accept
nft add rule inet filter input udp dport 2001-2100 accept
nft add rule inet filter input udp dport 2257-2356 accept
```
## Health Check ## Health Check
```bash ```bash
# Check if server is responding # Check if server is responding (TCP handshake)
nc -zv <server-ip> 2000 nc -zv <server-ip> 2000
# Check Docker container # Check Docker container status
docker logs btest-server docker logs btest-server
docker exec btest-server ps aux docker ps --filter name=btest-server
# Check systemd service
systemctl status btest
journalctl -u btest --since "5 minutes ago"
``` ```
## Resource Usage ## Resource Usage
- **Memory**: ~5 MB base, +1 MB per active connection | Resource | Value |
- **CPU**: Minimal when idle, scales with bandwidth |----------|-------|
- **Binary size**: 2 MB (static musl build) | Memory (idle) | ~5 MB |
- **Docker image**: ~80 MB (Debian slim + binary) | Memory (per active connection) | +1 MB |
| CPU | Minimal when idle, scales with bandwidth |
| Binary size | ~2 MB (static musl build) |
| Docker image | ~80 MB (Debian slim + binary) |

365
docs/man/btest.1 Normal file
View File

@@ -0,0 +1,365 @@
.\" btest-rs manual page
.\" Generated for btest-rs v0.6.0
.TH BTEST 1 "2026-03-31" "btest-rs 0.5.0" "User Commands"
.SH NAME
btest \- MikroTik Bandwidth Test server and client
.SH SYNOPSIS
.B btest
.B \-s
.RI [ OPTIONS ]
.br
.B btest
.B \-c
.I HOST
.RB { \-t | \-r }
.RI [ OPTIONS ]
.SH DESCRIPTION
.B btest
is a Rust reimplementation of the MikroTik Bandwidth Test (btest) protocol.
It can operate as a server (accepting connections from MikroTik RouterOS
devices or other btest clients) or as a client (connecting to a MikroTik
device's built-in bandwidth test server).
.PP
The server listens on TCP port 2000 by default. MikroTik devices connect
to this port for handshake, authentication, and status exchange. UDP data
transfer uses ports 2001 and above.
.PP
Both MD5 challenge-response (RouterOS < 6.43) and EC-SRP5 Curve25519
(RouterOS >= 6.43) authentication are supported.
.SH OPTIONS
.SS "Mode Selection"
.TP
.BR \-s ", " \-\-server
Run in server mode. Listen for incoming connections from MikroTik devices
or other btest clients. Conflicts with
.BR \-c .
.TP
.BI \-c " HOST" "\fR, \fP" \-\-client " HOST"
Run in client mode, connecting to the specified
.IR HOST .
The host can be an IPv4 address, IPv6 address, or hostname. Conflicts with
.BR \-s .
.SS "Test Direction (client mode)"
.TP
.BR \-t ", " \-\-transmit
Client transmits data to the server (upload test). Can be combined with
.B \-r
for bidirectional testing.
.TP
.BR \-r ", " \-\-receive
Client receives data from the server (download test). Can be combined with
.B \-t
for bidirectional testing.
.SS "Protocol and Transfer"
.TP
.BR \-u ", " \-\-udp
Use UDP instead of TCP for data transfer. UDP uses separate data ports
(2001+ server side, 2257+ client side) and exchanges status messages
over the TCP control channel every second.
.TP
.BI \-b " BW" "\fR, \fP" \-\-bandwidth " BW"
Target bandwidth limit for the test. Accepts suffixes:
.B K
(kilobits/sec),
.B M
(megabits/sec),
.B G
(gigabits/sec). Examples:
.BR 100M ", " 1G ", " 500K .
Default is 0 (unlimited).
.TP
.BI \-P " PORT" "\fR, \fP" \-\-port " PORT"
TCP port to listen on in server mode or connect to in client mode.
Default: 2000.
.SS "Network Binding (server mode)"
.TP
.BI \-\-listen " ADDR"
IPv4 address to bind the server listener to. Use
.B none
to disable IPv4 listening entirely (useful with
.B \-\-listen6
for IPv6-only mode). Default: 0.0.0.0.
.TP
.BI \-\-listen6 " \fR[\fPADDR\fR]\fP"
Enable the IPv6 listener. If no address is given, binds to
.BR :: .
Experimental: TCP over IPv6 works fully on all platforms. UDP over IPv6
has issues on macOS due to kernel ENOBUFS limitations. On Linux, IPv6 UDP
works correctly.
.SS "Authentication"
.TP
.BI \-a " USER" "\fR, \fP" \-\-authuser " USER"
Authentication username. In server mode, connecting clients must provide
this username. In client mode, this username is sent to the server.
.TP
.BI \-p " PASS" "\fR, \fP" \-\-authpass " PASS"
Authentication password. In server mode, connecting clients must provide
a matching password. In client mode, this password is used to authenticate
with the server.
.TP
.B \-\-ecsrp5
Use EC-SRP5 authentication (Curve25519 Weierstrass). In server mode, this
causes the server to advertise EC-SRP5 instead of MD5 to connecting clients.
Required for RouterOS >= 6.43 devices. In client mode, the authentication
type is auto-detected from the server's response and this flag is not needed.
.SS "Test Control"
.TP
.BI \-d " SECS" "\fR, \fP" \-\-duration " SECS"
Test duration in seconds (client mode only). The client exits cleanly after
the specified number of seconds. A value of 0 means unlimited (run until
interrupted with Ctrl-C). Default: 0.
.TP
.BR \-n ", " \-\-nat
NAT traversal mode. Sends an empty UDP probe packet to the server before
starting the receive thread, opening a hole in NAT firewalls. Only relevant
for UDP receive tests when the client is behind NAT.
.SS "Logging and Output"
.TP
.BI \-\-csv " FILE"
Output test results to a CSV file. Appends a row for each completed test.
Creates the file with a header row if it does not exist. Columns:
timestamp, host, port, protocol, direction, duration_s, tx_avg_mbps,
rx_avg_mbps, tx_bytes, rx_bytes, lost_packets, auth_type.
.TP
.BR \-q ", " \-\-quiet
Suppress per-second bandwidth output to the terminal. Useful in combination
with
.B \-\-csv
for machine-readable-only output, or when running as a background service.
.TP
.BI \-\-syslog " HOST:PORT"
Send structured log events to a remote syslog server via UDP. Uses RFC 3164
(BSD syslog) format with facility local0. Events include AUTH_SUCCESS,
AUTH_FAILURE, TEST_START, and TEST_END with detailed metadata.
Example:
.BR \-\-syslog\ 192.168.1.1:514 .
.TP
.BR \-v ", " \-\-verbose
Increase log verbosity. Can be repeated for more detail:
.RS
.TP
.B \-v
Debug messages (connection lifecycle, authentication steps).
.TP
.B \-vv
Trace messages (hex dumps of protocol exchange).
.TP
.B \-vvv
Maximum verbosity.
.RE
.TP
.BR \-h ", " \-\-help
Print help information and exit.
.TP
.BR \-V ", " \-\-version
Print version information and exit.
.SH EXAMPLES
.SS "Server Mode"
Start a basic server with no authentication:
.PP
.RS
.nf
btest -s
.fi
.RE
.PP
Server with MD5 authentication:
.PP
.RS
.nf
btest -s -a admin -p password
.fi
.RE
.PP
Server with EC-SRP5 authentication (RouterOS >= 6.43):
.PP
.RS
.nf
btest -s -a admin -p password --ecsrp5
.fi
.RE
.PP
Server with syslog and CSV logging:
.PP
.RS
.nf
btest -s -a admin -p password --syslog 10.0.0.1:514 --csv /var/log/btest.csv
.fi
.RE
.PP
Server listening on IPv4 and IPv6:
.PP
.RS
.nf
btest -s --listen6
.fi
.RE
.PP
Server on a custom port with debug output:
.PP
.RS
.nf
btest -s -P 3000 -v
.fi
.RE
.SS "Client Mode"
TCP download test:
.PP
.RS
.nf
btest -c 192.168.88.1 -r
.fi
.RE
.PP
TCP upload test:
.PP
.RS
.nf
btest -c 192.168.88.1 -t
.fi
.RE
.PP
Bidirectional TCP test:
.PP
.RS
.nf
btest -c 192.168.88.1 -t -r
.fi
.RE
.PP
UDP download test:
.PP
.RS
.nf
btest -c 192.168.88.1 -r -u
.fi
.RE
.PP
UDP bidirectional with bandwidth limit:
.PP
.RS
.nf
btest -c 192.168.88.1 -t -r -u -b 100M
.fi
.RE
.PP
Timed test (30 seconds) with CSV output:
.PP
.RS
.nf
btest -c 192.168.88.1 -r -d 30 --csv results.csv
.fi
.RE
.PP
Quiet mode with CSV only:
.PP
.RS
.nf
btest -c 192.168.88.1 -r -d 60 --csv results.csv -q
.fi
.RE
.PP
With authentication:
.PP
.RS
.nf
btest -c 192.168.88.1 -r -a admin -p password
.fi
.RE
.PP
UDP receive through NAT:
.PP
.RS
.nf
btest -c 192.168.88.1 -r -u -n
.fi
.RE
.SH PORTS
.TP
.B 2000/tcp
Control channel. Used for handshake, authentication, and status exchange.
.TP
.B 2001-2100/udp
Server-side UDP data ports. Each connection uses the next available port
starting from 2001.
.TP
.B 2257-2356/udp
Client-side UDP data ports. Offset from server port by 256.
.SH EXIT STATUS
.TP
.B 0
Success. The test completed normally or the duration expired.
.TP
.B 1
Error. Failed to connect, authentication failed, or invalid arguments.
.SH ENVIRONMENT
.TP
.B RUST_LOG
Override the log filter. When set, takes precedence over the
.B \-v
flag. Example:
.BR RUST_LOG=trace .
.SH FILES
.TP
.I /usr/local/bin/btest
Default installation path for the binary.
.TP
.I /etc/systemd/system/btest.service
systemd unit file created by the install-service.sh script.
.SH AUTHENTICATION
.B btest
supports two authentication schemes:
.TP
.B MD5 (legacy)
Double MD5 challenge-response. Compatible with RouterOS versions before 6.43.
The server sends a 16-byte random challenge. The client responds with
MD5(password + MD5(password + challenge)) and the username.
.TP
.B EC-SRP5 (modern)
Elliptic Curve Secure Remote Password using Curve25519 in Weierstrass form.
Used by RouterOS >= 6.43. Provides zero-knowledge password proof. Enable on
the server with
.BR \-\-ecsrp5 .
Clients auto-detect the authentication type.
.SH MIKROTIK CONFIGURATION
Enable the bandwidth test server on MikroTik for client mode:
.PP
.RS
.nf
/tool/bandwidth-server set enabled=yes
.fi
.RE
.PP
Run a test from MikroTik connecting to a btest-rs server:
.PP
.RS
.nf
/tool/bandwidth-test address=<server-ip> direction=both \\
protocol=udp user=admin password=password
.fi
.RE
.SH SEE ALSO
.BR iperf3 (1),
.BR netperf (1)
.PP
Project documentation:
.I https://github.com/samm-git/btest-opensource
.SH CREDITS
.B btest-opensource
by Alex Samorukov \(em original C implementation and protocol
reverse-engineering (MIT License).
.PP
.B Margin Research
\(em EC-SRP5 authentication reverse-engineering for MikroTik RouterOS
(Apache License 2.0).
.PP
.B MikroTik
\(em creator of the bandwidth test protocol and RouterOS.
.SH LICENSE
MIT License. See the LICENSE file in the source distribution.
.PP
This project is derived from btest-opensource (MIT License, Copyright 2016
Alex Samorukov). The EC-SRP5 implementation is based on research by Margin
Research (Apache License 2.0).
.SH AUTHORS
btest-rs contributors.

View File

@@ -1,6 +1,6 @@
# MikroTik Bandwidth Test Protocol Specification # MikroTik Bandwidth Test Protocol Specification
This document describes the MikroTik btest wire protocol as reverse-engineered from RouterOS traffic captures. Based on the work of [Alex Samorukov](https://github.com/samm-git/btest-opensource). This document describes the MikroTik btest wire protocol as reverse-engineered from RouterOS traffic captures. Based on the work of [Alex Samorukov](https://github.com/samm-git/btest-opensource) and [Margin Research](https://github.com/MarginResearch/mikrotik_authentication).
## Connection Setup ## Connection Setup
@@ -24,7 +24,11 @@ sequenceDiagram
S->>C: OK [01 00 00 00] or FAILED [00 00 00 00] S->>C: OK [01 00 00 00] or FAILED [00 00 00 00]
else EC-SRP5 authentication (RouterOS >= 6.43) else EC-SRP5 authentication (RouterOS >= 6.43)
S->>C: EC_SRP5 [03 00 00 00] S->>C: EC_SRP5 [03 00 00 00]
Note over C,S: Not yet implemented C->>S: MSG1 [len][username\0][client_pubkey:32][parity:1]
S->>C: MSG2 [len][server_pubkey:32][parity:1][salt:16]
C->>S: MSG3 [len][client_confirmation:32]
S->>C: MSG4 [len][server_confirmation:32]
S->>C: OK [01 00 00 00]
end end
Note over C,S: Data transfer begins Note over C,S: Data transfer begins
@@ -32,11 +36,11 @@ sequenceDiagram
## Command Structure (16 bytes) ## Command Structure (16 bytes)
Sent by client after receiving HELLO. Sent by the client after receiving HELLO.
``` ```
Offset Size Type Field Description Offset Size Type Field Description
────── ──── ──── ───── ─────────── ------ ---- ---- ----- -----------
0 1 uint8 protocol 0x00=UDP, 0x01=TCP 0 1 uint8 protocol 0x00=UDP, 0x01=TCP
1 1 uint8 direction Bit flags (server perspective) 1 1 uint8 direction Bit flags (server perspective)
2 1 uint8 random_data 0x00=random, 0x01=zeros 2 1 uint8 random_data 0x00=random, 0x01=zeros
@@ -58,8 +62,8 @@ Direction bits describe what the **server** should do:
| 0x03 | DIR_BOTH | Both directions | Both directions | | 0x03 | DIR_BOTH | Both directions | Both directions |
**Important**: The client inverts when constructing the command: **Important**: The client inverts when constructing the command:
- Client selects "transmit" sends `0x01` (server should receive) - Client selects "transmit" -> sends `0x01` (server should receive)
- Client selects "receive" sends `0x02` (server should transmit) - Client selects "receive" -> sends `0x02` (server should transmit)
### Default TX Sizes ### Default TX Sizes
@@ -124,6 +128,184 @@ Challenge: ad32d6f94d28161625f2f390bb895637 (hex)
Expected: 3c968565bc0314f281a6da1571cf7255 (hex) Expected: 3c968565bc0314f281a6da1571cf7255 (hex)
``` ```
## EC-SRP5 Authentication
EC-SRP5 (Elliptic Curve Secure Remote Password) is used by RouterOS >= 6.43. It provides zero-knowledge password proof using Curve25519 in Weierstrass form.
### Auth Trigger
After the standard btest handshake (HELLO + Command), the server responds with one of:
```
01 00 00 00 -> No auth required
02 00 00 00 -> MD5 challenge-response (RouterOS < 6.43)
03 00 00 00 -> EC-SRP5 (RouterOS >= 6.43)
```
### Message Framing
Unlike Winbox (port 8291) which uses `[len:1][0x06][payload]`, the btest protocol uses a simpler framing:
```
[len:1][payload]
```
The `0x06` handler byte is omitted because the authentication context is implicit after receiving `03 00 00 00`.
| Protocol | Message framing |
|----------|----------------|
| Winbox (port 8291) | `[len:1][0x06][payload]` |
| **btest (port 2000)** | **`[len:1][payload]`** |
### EC-SRP5 Handshake (4 messages)
```mermaid
sequenceDiagram
participant C as Client
participant S as Server
Note over S: Server sent 03 00 00 00
C->>S: MSG1: [len][username\0][client_pubkey:32][parity:1]
Note over C: len = username_len + 1 + 32 + 1
S->>C: MSG2: [len][server_pubkey:32][parity:1][salt:16]
Note over S: len = 49 (0x31)
C->>S: MSG3: [len][client_confirmation:32]
Note over C: len = 32 (0x20)
S->>C: MSG4: [len][server_confirmation:32]
Note over S: len = 32 (0x20)
Note over S: Then continues with normal btest flow:
S->>C: AUTH_OK [01 00 00 00]
S->>C: UDP port [2 bytes BE] (if UDP mode)
```
### Elliptic Curve: Curve25519 in Weierstrass Form
MikroTik's EC-SRP5 uses Curve25519 parameters but operates entirely in Weierstrass form, not the more common Montgomery or Edwards representations.
```
Prime field: p = 2^255 - 19
Curve order: r = 2^252 + 27742317777372353535851937790883648493
Montgomery A: 486662
Weierstrass parameters (converted from Montgomery):
a = 0x2aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa984914a144
b = 0x7b425ed097b425ed097b425ed097b425ed097b425ed097b4260b5e9c7710c864
Generator: lift_x(9) in Montgomery, converted to Weierstrass
Cofactor: 8
```
Public keys are transmitted as Montgomery x-coordinates (32 bytes big-endian) plus a 1-byte y-parity flag.
### Key Derivation
```
inner = SHA256(username + ":" + password)
salt = 16 random bytes (generated by server)
validator_priv (i) = SHA256(salt || inner)
validator_pub (x_gamma) = i * G
```
The server stores `salt` and `x_gamma` (the validator public key) for each user. In btest-rs, these are derived from the username and password at startup.
### Shared Secret Computation
**Client side (ECPESVDP-SRP-A):**
```
v = redp1(x_gamma, parity=1) # hash-to-curve of validator pubkey
w_b = lift_x(server_pubkey) + v # undo verifier blinding
j = SHA256(client_pubkey || server_pubkey)
scalar = (i * j + client_secret) mod r # combined scalar
Z = scalar * w_b # shared secret point
z = to_montgomery(Z).x # Montgomery x-coordinate
```
**Server side (ECPESVDP-SRP-B):**
```
gamma = redp1(x_gamma, parity=0)
w_a = lift_x(client_pubkey)
j = SHA256(client_pubkey || server_pubkey)
Z = server_secret * (w_a + j * gamma) # shared secret point
z = to_montgomery(Z).x
```
### Confirmation Codes
```
client_cc = SHA256(j || z)
server_cc = SHA256(j || client_cc || z)
```
Both sides verify the peer's confirmation code to ensure the shared secret matches. If either code is wrong, authentication fails.
### redp1 (Hash-to-Curve)
```
def redp1(x_bytes, parity):
x = SHA256(x_bytes)
while True:
x2 = SHA256(x)
point = lift_x(int(x2), parity)
if point is valid:
return point
x = (int(x) + 1).to_bytes(32)
```
This deterministically maps a byte string to a valid curve point by repeatedly hashing until a valid x-coordinate is found.
### Captured Exchange (from MITM analysis)
```
CLIENT -> SERVER (40 bytes):
27 61 6e 74 61 72 00 38 8a 37 36 52 6a 32 e9 87
4e 92 f8 c3 aa a1 18 da cd 71 b6 ab 76 fd 72 aa
c3 f6 6a 43 9b c8 a1 01
Decoded:
len=0x27 (39 bytes payload)
username="antar\0"
pubkey=388a373652...c8a1 (32 bytes)
parity=0x01
SERVER -> CLIENT (50 bytes):
31 6c c9 e3 1a 79 43 4a 40 51 de fd 55 cc 8d 6d
3c ec cd 73 19 1f a6 83 15 94 62 52 97 fe 5d 89
1a 00 3c ec 65 b8 34 28 0a 16 c5 48 0d 7b 50 00
e3 80
Decoded:
len=0x31 (49 bytes payload)
server_pubkey=6cc9e31a...5d891a (32 bytes)
parity=0x00
salt=3cec65b834280a16c5480d7b5000e380 (16 bytes)
CLIENT -> SERVER (33 bytes):
20 9b 1f 74 ec 40 31 2c ...
Decoded:
len=0x20 (32 bytes payload)
client_cc=9b1f74ec... (32 bytes, SHA256 proof)
SERVER -> CLIENT (33 bytes):
20 7d 59 b3 2e 28 6e 52 ...
Decoded:
len=0x20 (32 bytes payload)
server_cc=7d59b32e... (32 bytes, SHA256 proof)
POST-AUTH:
01 00 00 00 07 fa
Decoded:
AUTH_OK=01000000
UDP_port=0x07fa (2042)
```
## TCP Data Transfer ## TCP Data Transfer
After handshake, data flows on the **same TCP connection** used for control. After handshake, data flows on the **same TCP connection** used for control.
@@ -163,7 +345,7 @@ graph LR
``` ```
Offset Size Type Field Offset Size Type Field
────── ──── ──── ───── ------ ---- ---- -----
0-3 4 uint32 BE sequence_number 0-3 4 uint32 BE sequence_number
4+ var bytes payload (zeros or random) 4+ var bytes payload (zeros or random)
``` ```
@@ -176,7 +358,7 @@ Exchanged every 1 second over the **TCP control channel** during UDP tests.
``` ```
Offset Size Type Field Byte Order Offset Size Type Field Byte Order
────── ──── ──── ───── ────────── ------ ---- ---- ----- ----------
0 1 uint8 msg_type Always 0x07 0 1 uint8 msg_type Always 0x07
1-4 4 uint32 BE seq_number Big-endian 1-4 4 uint32 BE seq_number Big-endian
5-7 3 bytes padding Always 00 00 00 5-7 3 bytes padding Always 00 00 00
@@ -208,11 +390,11 @@ sequenceDiagram
``` ```
Server sends: 07 00 00 00 01 00 00 00 C0 2D B4 02 Server sends: 07 00 00 00 01 00 00 00 C0 2D B4 02
── ─────────── ──────── ─────────── -- ---------- -------- -----------
type seq=1 padding bytes=45,362,624 type seq=1 padding bytes=45,362,624
Client sends: 07 D9 00 00 01 00 00 00 00 00 00 00 Client sends: 07 D9 00 00 01 00 00 00 00 00 00 00
── ─────────── ──────── ─────────── -- ---------- -------- -----------
type seq padding bytes=0 type seq padding bytes=0
``` ```
@@ -237,7 +419,7 @@ graph TD
For a target speed in bits/sec and packet size in bytes: For a target speed in bits/sec and packet size in bytes:
``` ```
interval_ns = (1,000,000,000 × packet_size × 8) / target_speed_bps interval_ns = (1,000,000,000 * packet_size * 8) / target_speed_bps
``` ```
**Special case**: If interval > 500ms, clamp to exactly 1 second. This replicates a MikroTik behavior where very slow speeds get normalized to 1 packet/second. **Special case**: If interval > 500ms, clamp to exactly 1 second. This replicates a MikroTik behavior where very slow speeds get normalized to 1 packet/second.
@@ -249,16 +431,19 @@ When `-n` / `--nat` flag is set, the client sends an empty UDP packet before sta
## Protocol Constants ## Protocol Constants
``` ```
BTEST_PORT = 2000 TCP control port BTEST_PORT = 2000 TCP control port
BTEST_UDP_PORT_START = 2001 First UDP data port BTEST_UDP_PORT_START = 2001 First UDP data port
BTEST_PORT_CLIENT_OFFSET = 256 Client UDP port offset BTEST_PORT_CLIENT_OFFSET = 256 Client UDP port offset
HELLO = [01 00 00 00] HELLO = [01 00 00 00]
AUTH_OK = [01 00 00 00] AUTH_OK = [01 00 00 00]
AUTH_REQUIRED = [02 00 00 00] AUTH_REQUIRED = [02 00 00 00]
AUTH_EC_SRP5 = [03 00 00 00] AUTH_EC_SRP5 = [03 00 00 00]
AUTH_FAILED = [00 00 00 00] AUTH_FAILED = [00 00 00 00]
STATUS_MSG_TYPE = 0x07 STATUS_MSG_TYPE = 0x07
STATUS_MSG_SIZE = 12 bytes STATUS_MSG_SIZE = 12 bytes
DEFAULT_TCP_TX_SIZE = 32768 (0x8000)
DEFAULT_UDP_TX_SIZE = 1500 (0x05DC)
``` ```

View File

@@ -14,21 +14,29 @@ btest -c 192.168.88.1 -r
Run btest-rs as a server and let MikroTik devices connect for bandwidth testing. Run btest-rs as a server and let MikroTik devices connect for bandwidth testing.
### Basic Server ### Basic Server (No Authentication)
```bash ```bash
btest -s btest -s
``` ```
Listens on TCP port 2000 (default). Any MikroTik device can connect without authentication. Listens on all IPv4 interfaces, TCP port 2000. Any MikroTik device can connect without credentials.
### Server with Authentication ### Server with MD5 Authentication
```bash ```bash
btest -s -a admin -p mysecretpassword btest -s -a admin -p mysecretpassword
``` ```
MikroTik devices must provide matching credentials. Uses MD5 challenge-response authentication. Requires connecting devices to provide matching credentials. Uses MD5 double-hash challenge-response authentication, compatible with RouterOS versions before 6.43.
### Server with EC-SRP5 Authentication
```bash
btest -s -a admin -p mysecretpassword --ecsrp5
```
Advertises EC-SRP5 (Curve25519 Weierstrass) authentication to connecting clients. Required for RouterOS >= 6.43 devices that use the modern authentication protocol.
### Custom Port ### Custom Port
@@ -36,25 +44,90 @@ MikroTik devices must provide matching credentials. Uses MD5 challenge-response
btest -s -P 3000 btest -s -P 3000
``` ```
### Custom Listen Address
```bash
# Listen only on a specific interface
btest -s --listen 10.0.0.1
# Disable IPv4, listen only on IPv6
btest -s --listen none --listen6
# Listen on both IPv4 and IPv6
btest -s --listen6
```
### IPv6 Listener (Experimental)
```bash
# IPv6 on default address (::)
btest -s --listen6
# IPv6 on a specific address
btest -s --listen6 fd00::1
```
TCP over IPv6 works fully on all platforms. UDP over IPv6 has issues on macOS due to kernel ENOBUFS limitations with `send_to()`. On Linux, IPv6 UDP works correctly.
### Syslog Integration
```bash
btest -s --syslog 192.168.1.1:514
```
Sends structured log events to a remote syslog server via UDP (RFC 3164 / BSD syslog format, facility local0). Events include:
- `AUTH_SUCCESS` -- successful authentication with peer address, username, and auth type
- `AUTH_FAILURE` -- failed authentication with peer address, username, auth type, and reason
- `TEST_START` -- test initiated with peer address, protocol, direction, and connection count
- `TEST_END` -- test completed with peer address, protocol, direction, duration, average speeds, bytes transferred, and lost packets
### CSV Output
```bash
btest -s --csv /var/log/btest-results.csv
```
Appends a row for each completed test to the specified CSV file. Creates the file with headers if it does not exist. CSV columns:
```
timestamp,host,port,protocol,direction,duration_s,tx_avg_mbps,rx_avg_mbps,tx_bytes,rx_bytes,lost_packets,auth_type
```
### Quiet Mode
```bash
btest -s --csv /var/log/btest.csv -q
```
Suppresses per-second terminal output. Useful when running as a background service with CSV or syslog logging only.
### Verbose/Debug Output ### Verbose/Debug Output
```bash ```bash
btest -s -v # Show connection info and debug messages btest -s -v # Debug messages (connection lifecycle, auth steps)
btest -s -vv # Show hex dumps of status exchange (for debugging) btest -s -vv # Trace messages (hex dumps of status exchange)
btest -s -vvv # Maximum verbosity
``` ```
### MikroTik Configuration (connecting to our server) ### Combined Example
**Important: Always set Connection Count to 1.** Multi-connection mode is not supported and will cause severely degraded speeds. ```bash
btest -s -a admin -p secret --ecsrp5 --syslog 10.0.0.1:514 --csv /var/log/btest.csv -v
```
This runs a server with EC-SRP5 authentication, sends events to syslog, logs results to CSV, and prints debug output to the terminal.
### MikroTik Configuration (Connecting to Our Server)
On the MikroTik device (WinBox or CLI): On the MikroTik device (WinBox or CLI):
``` ```
# CLI — always include connection-count=1 /tool/bandwidth-test address=<server-ip> direction=both protocol=udp \
/tool/bandwidth-test address=<server-ip> direction=both protocol=udp user=admin password=mysecretpassword connection-count=1 user=admin password=mysecretpassword
``` ```
Or via WinBox: **Tools Bandwidth Test**, enter server address, credentials, **set Connection Count to 1**, and click Start. Or via WinBox: **Tools > Bandwidth Test**, enter the server address and credentials, and click Start.
## Client Mode ## Client Mode
@@ -62,28 +135,27 @@ Connect to a MikroTik device's built-in bandwidth test server.
### Prerequisites ### Prerequisites
Enable btest server on MikroTik: Enable the btest server on the MikroTik device:
``` ```
/tool/bandwidth-server set enabled=yes /tool/bandwidth-server set enabled=yes
``` ```
**Note**: If the MikroTik uses RouterOS >= 6.43 with authentication enabled, you'll need to either disable auth or use credentials. EC-SRP5 auth is not yet supported; MD5 auth works on older RouterOS versions. ### Download Test (Receive)
### Download Test (receive)
```bash ```bash
btest -c 192.168.88.1 -r btest -c 192.168.88.1 -r
``` ```
Measures download speed from MikroTik to your machine. Measures download speed from the MikroTik device to your machine. The server transmits, the client receives.
### Upload Test (transmit) ### Upload Test (Transmit)
```bash ```bash
btest -c 192.168.88.1 -t btest -c 192.168.88.1 -t
``` ```
Measures upload speed from your machine to MikroTik. Measures upload speed from your machine to the MikroTik device. The client transmits, the server receives.
### Bidirectional Test ### Bidirectional Test
@@ -101,6 +173,8 @@ btest -c 192.168.88.1 -t -u # UDP upload
btest -c 192.168.88.1 -t -r -u # UDP bidirectional btest -c 192.168.88.1 -t -r -u # UDP bidirectional
``` ```
UDP mode uses separate data ports (2001+ on the server side, 2257+ on the client side) and exchanges status messages every second over the TCP control channel.
### Bandwidth Limiting ### Bandwidth Limiting
```bash ```bash
@@ -109,15 +183,7 @@ btest -c 192.168.88.1 -t -b 1G # Limit to 1 Gbps
btest -c 192.168.88.1 -r -b 500K # Limit to 500 Kbps btest -c 192.168.88.1 -r -b 500K # Limit to 500 Kbps
``` ```
### NAT Traversal Suffixes: `K` (kilobits/sec), `M` (megabits/sec), `G` (gigabits/sec). Values are in bits per second.
If you're behind NAT and need to receive UDP data:
```bash
btest -c 192.168.88.1 -r -u -n
```
The `-n` flag sends a probe packet to open the NAT firewall hole.
### With Authentication ### With Authentication
@@ -125,62 +191,187 @@ The `-n` flag sends a probe packet to open the NAT firewall hole.
btest -c 192.168.88.1 -r -a admin -p password btest -c 192.168.88.1 -r -a admin -p password
``` ```
The client auto-detects the authentication type (MD5 or EC-SRP5) from the server's response and handles it accordingly.
### NAT Traversal
```bash
btest -c 192.168.88.1 -r -u -n
```
The `-n` flag sends an empty UDP probe packet before starting the receive thread. This opens a hole in NAT firewalls so the server's UDP data packets can reach the client.
### Timed Tests
```bash
btest -c 192.168.88.1 -r -d 30 # Run for 30 seconds, then stop
btest -c 192.168.88.1 -t -r -d 60 # 60-second bidirectional test
```
The default duration is 0 (unlimited). When the duration expires, the client exits cleanly.
### CSV Output (Client Mode)
```bash
btest -c 192.168.88.1 -r -d 30 --csv results.csv
```
Appends a summary row after the test completes with the host, port, protocol, direction, duration, and auth type.
### Quiet Mode (Client)
```bash
btest -c 192.168.88.1 -r -d 10 --csv results.csv -q
```
Suppresses per-second bandwidth output to the terminal. Useful for scripted or automated testing where only the CSV file matters.
### Custom Port
```bash
btest -c 192.168.88.1 -r -P 3000
```
## Reading the Output ## Reading the Output
``` ```
[ 1] TX 264.50 Mbps (33062912 bytes) [ 1] TX 264.50 Mbps (33062912 bytes) cpu: 12%/0%
[ 2] TX 263.98 Mbps (32997376 bytes) [ 2] TX 263.98 Mbps (32997376 bytes) cpu: 15%/33%
[ 2] RX 263.98 Mbps (32997012 bytes) [ 2] RX 263.98 Mbps (32997012 bytes) cpu: 15%/33%
[ 3] RX 430.51 Mbps (53813376 bytes) lost: 5 [ 3] RX 430.51 Mbps (53813376 bytes) lost: 5 cpu: 18%/45%
[ 4] RX 450.00 Mbps (56250000 bytes) cpu: 72%/85% !
``` ```
| Field | Meaning | | Field | Meaning |
|-------|---------| |-------|---------|
| `[ N]` | Interval number (1 per second) | | `[ N]` | Interval number (1 per second) |
| `TX` | Data we sent (upload) | | `TX` | Data sent (upload from your perspective) |
| `RX` | Data we received (download) | | `RX` | Data received (download from your perspective) |
| `Mbps` | Megabits per second | | `Mbps` | Megabits per second |
| `bytes` | Raw bytes transferred in this interval | | `bytes` | Raw bytes transferred in this interval |
| `lost: N` | UDP packets lost (UDP mode only) | | `lost: N` | UDP packets lost in this interval (UDP mode only) |
| `cpu: L%/R%` | Local CPU / Remote CPU usage percentage |
| `!` | Warning: CPU usage exceeds 70% on either side |
## CLI Reference ## Complete CLI Reference
``` ```
btest-rs MikroTik Bandwidth Test server & client in Rust btest-rs -- MikroTik Bandwidth Test server & client in Rust
Usage: btest [OPTIONS] Usage: btest [OPTIONS]
Options: Options:
-s, --server Run in server mode -s, --server
-c, --client <HOST> Run in client mode, connect to HOST Run in server mode. Listens for incoming connections from MikroTik
-t, --transmit Client: upload test devices or other btest clients. Conflicts with -c.
-r, --receive Client: download test
-u, --udp Use UDP instead of TCP -c, --client <HOST>
-b, --bandwidth <BW> Bandwidth limit (e.g., 100M, 1G, 500K) Run in client mode, connecting to the specified host. The host can be
-P, --port <PORT> Port number [default: 2000] an IPv4 address, IPv6 address, or hostname. Conflicts with -s.
-a, --authuser <USER> Authentication username
-p, --authpass <PASS> Authentication password -t, --transmit
-n, --nat NAT traversal mode Client transmits data (upload test). Tells the server to receive.
-v, --verbose Increase log verbosity (-v, -vv) Can be combined with -r for bidirectional testing.
-h, --help Show help
-V, --version Show version -r, --receive
Client receives data (download test). Tells the server to transmit.
Can be combined with -t for bidirectional testing.
-u, --udp
Use UDP instead of TCP for the data transfer. UDP uses separate data
ports (2001+ server side, 2257+ client side) and exchanges status
messages over the TCP control channel every second.
-b, --bandwidth <BW>
Target bandwidth limit for the test. Accepts suffixes: K (kilobits),
M (megabits), G (gigabits). Examples: 100M, 1G, 500K. Default is 0
(unlimited).
-P, --port <PORT>
TCP port to listen on (server mode) or connect to (client mode).
[default: 2000]
--listen <ADDR>
IPv4 address to bind the server listener to. Use "none" to disable
IPv4 listening entirely (useful with --listen6 for IPv6-only mode).
[default: 0.0.0.0]
--listen6 [<ADDR>]
Enable the IPv6 listener. If no address is given, binds to [::].
Experimental: TCP over IPv6 works fully on all platforms. UDP over
IPv6 has issues on macOS due to kernel ENOBUFS limitations.
-a, --authuser <USER>
Authentication username. In server mode, clients must provide this
username. In client mode, this is sent to the server.
-p, --authpass <PASS>
Authentication password. In server mode, clients must provide a
matching password. In client mode, this is used to authenticate.
--ecsrp5
Use EC-SRP5 authentication (Curve25519 Weierstrass). In server mode,
this advertises EC-SRP5 instead of MD5 to connecting clients.
Required for RouterOS >= 6.43. In client mode, auth type is
auto-detected and this flag is not needed.
-n, --nat
NAT traversal mode. Sends an empty UDP probe packet to the server
before starting the receive thread, opening a hole in NAT firewalls.
Only relevant for UDP receive tests behind NAT.
-d, --duration <SECS>
Test duration in seconds (client mode only). The client exits cleanly
after the specified time. A value of 0 means unlimited (run until
interrupted with Ctrl-C). [default: 0]
--csv <FILE>
Output test results to a CSV file. Appends a row per completed test.
Creates the file with a header row if it does not exist. Columns:
timestamp, host, port, protocol, direction, duration_s, tx_avg_mbps,
rx_avg_mbps, tx_bytes, rx_bytes, lost_packets, auth_type.
-q, --quiet
Suppress per-second bandwidth output to the terminal. Useful in
combination with --csv for machine-readable-only output, or when
running as a background service.
--syslog <HOST:PORT>
Send structured log events to a remote syslog server via UDP. Uses
RFC 3164 (BSD syslog) format with facility local0. Events include
AUTH_SUCCESS, AUTH_FAILURE, TEST_START, and TEST_END with detailed
metadata. Example: --syslog 192.168.1.1:514
-v, --verbose...
Increase log verbosity. Can be repeated:
-v debug messages (connection lifecycle, auth steps)
-vv trace messages (hex dumps of protocol exchange)
-vvv maximum verbosity
-h, --help
Print help information
-V, --version
Print version information
``` ```
## Tips ## Tips
- **Connection Count MUST be 1** when MikroTik connects to your server. Multi-connection mode is not supported and will cause speeds to drop to near zero. Single-connection performance is excellent (1+ Gbps).
- **TCP mode** generally gives more stable results than UDP due to TCP flow control. - **TCP mode** generally gives more stable results than UDP due to TCP flow control.
- **UDP mode** is better for measuring raw link capacity without TCP overhead. - **UDP mode** is better for measuring raw link capacity without TCP overhead.
- **First interval** may show higher or lower numbers as the connection stabilizes. Look at intervals 3+ for steady-state throughput. - **First interval** may show higher or lower numbers as the connection stabilizes. Look at intervals 3+ for steady-state throughput.
- **WiFi testing**: bidirectional tests on WiFi will show lower per-direction speeds because WiFi is half-duplex at the MAC layer. - **WiFi testing**: bidirectional tests on WiFi will show lower per-direction speeds because WiFi is half-duplex at the MAC layer.
- **Bandwidth limiting** applies to the direction you specify. In bidirectional mode with `-b 100M`, both directions are limited to 100 Mbps each.
## Troubleshooting ## Troubleshooting
| Problem | Solution | | Problem | Solution |
|---------|----------| |---------|----------|
| `EC-SRP5 authentication not supported` | Disable auth on MikroTik btest server, or use older RouterOS | | Connection refused | Check that port 2000 is open and the server is running |
| `Connection refused` | Check port 2000 is open, firewall allows it | | Auth failure with EC-SRP5 | Ensure `--ecsrp5` is set on the server if the MikroTik client uses RouterOS >= 6.43 |
| Server shows 0 RX | Check MikroTik is actually sending (direction setting) | | Auth failure with MD5 | Verify username and password match exactly (case-sensitive) |
| Speed drops over time (server mode) | Set Connection Count to 1 on MikroTik. Multi-connection is not supported | | Server shows 0 RX | Check that the MikroTik direction setting includes sending to the server |
| Very low speed with multiple connections | Multi-connection mode is broken — set Connection Count to 1 | | Very low UDP speed | Network congestion or MTU issues; try reducing bandwidth with `-b` |
| UDP `lost` packets high | Network congestion or MTU issues, try reducing bandwidth with `-b` | | IPv6 UDP fails on macOS | Known macOS kernel limitation; use Linux for IPv6 UDP tests |
| Syslog messages not arriving | Verify the syslog server address and port, and check firewall rules for UDP 514 |
| CSV file not created | Check write permissions on the directory; the file is created on first use |

50
scripts/push-docker-all.sh Executable file
View File

@@ -0,0 +1,50 @@
#!/usr/bin/env bash
# Build and push Docker image to both Gitea and GitHub Container Registry.
#
# Prerequisites:
# docker login git.manko.yoga (Gitea — your username + token)
# docker login ghcr.io (GitHub — your username + PAT with packages:write)
#
# Usage:
# ./scripts/push-docker-all.sh v0.6.0
set -euo pipefail
cd "$(dirname "$0")/.."
if [[ -f .env ]]; then
set -a; source .env; set +a
fi
TAG="${1:?Usage: $0 <tag> (e.g. v0.6.0)}"
GITEA_IMAGE="git.manko.yoga/manawenuz/btest-rs"
GHCR_IMAGE="ghcr.io/manawenuz/btest-rs"
echo "=== Building Docker image ==="
docker build \
-t "${GITEA_IMAGE}:${TAG}" \
-t "${GITEA_IMAGE}:latest" \
-t "${GHCR_IMAGE}:${TAG}" \
-t "${GHCR_IMAGE}:latest" \
.
echo ""
echo "=== Pushing to Gitea ==="
docker push "${GITEA_IMAGE}:${TAG}"
docker push "${GITEA_IMAGE}:latest"
echo ""
echo "=== Pushing to GitHub Container Registry ==="
docker push "${GHCR_IMAGE}:${TAG}"
docker push "${GHCR_IMAGE}:latest"
echo ""
echo "Done! Images pushed:"
echo " ${GITEA_IMAGE}:${TAG}"
echo " ${GITEA_IMAGE}:latest"
echo " ${GHCR_IMAGE}:${TAG}"
echo " ${GHCR_IMAGE}:latest"
echo ""
echo "Pull with:"
echo " docker pull ${GHCR_IMAGE}:${TAG}"
echo " docker run --rm -p 2000:2000 -p 2001-2100:2001-2100/udp ${GHCR_IMAGE}:${TAG} -s -v"

120
scripts/sync-github-release.sh Executable file
View File

@@ -0,0 +1,120 @@
#!/usr/bin/env bash
# Sync a release from Gitea to GitHub.
# Downloads all binaries from Gitea release, creates GitHub release, uploads them.
#
# Prerequisites:
# gh auth login (GitHub CLI authenticated)
#
# Usage:
# ./scripts/sync-github-release.sh v0.6.0
set -euo pipefail
cd "$(dirname "$0")/.."
if [[ -f .env ]]; then
set -a; source .env; set +a
fi
TAG="${1:?Usage: $0 <tag> (e.g. v0.6.0)}"
GITEA_URL="https://git.manko.yoga"
GITEA_REPO="manawenuz/btest-rs"
GITHUB_REPO="manawenuz/btest-rs"
echo "=== Downloading assets from Gitea release ${TAG} ==="
mkdir -p /tmp/btest-release-${TAG}
cd /tmp/btest-release-${TAG}
rm -f *.tar.gz *.zip *.txt
# Get asset list from Gitea API
ASSETS=$(curl -sf "${GITEA_URL}/api/v1/repos/${GITEA_REPO}/releases/tags/${TAG}" | \
python3 -c "import sys,json; [print(a['browser_download_url']) for a in json.load(sys.stdin).get('assets',[])]")
if [ -z "$ASSETS" ]; then
echo "No assets found for ${TAG} on Gitea. Check if the release exists."
exit 1
fi
for url in $ASSETS; do
FILENAME=$(basename "$url")
echo " Downloading: $FILENAME"
curl -sLO "$url"
done
# Merge all separate .sha256 files into checksums-sha256.txt
# and remove the individual .sha256 files
echo ""
echo "=== Merging checksums ==="
for sha_file in *.sha256; do
[ -f "$sha_file" ] || continue
echo " Merging: $sha_file"
cat "$sha_file" >> checksums-sha256.txt
rm "$sha_file"
done
# Add checksums for any files not yet in checksums-sha256.txt
for f in *.tar.gz *.zip; do
[ -f "$f" ] || continue
if ! grep -q "$f" checksums-sha256.txt 2>/dev/null; then
echo " Adding checksum for: $f"
shasum -a 256 "$f" >> checksums-sha256.txt
fi
done
# Sort and deduplicate
sort -u -k2 checksums-sha256.txt > checksums-sha256.tmp && mv checksums-sha256.tmp checksums-sha256.txt
echo ""
echo "Checksums:"
cat checksums-sha256.txt
echo ""
echo "Files to upload:"
ls -lh *.tar.gz *.zip checksums-sha256.txt 2>/dev/null
echo ""
echo "=== Creating GitHub release ${TAG} ==="
gh release create "${TAG}" \
--repo "${GITHUB_REPO}" \
--title "btest-rs ${TAG}" \
--notes "## Downloads
| Platform | Architecture | File |
|----------|-------------|------|
| Linux | x86_64 | btest-linux-x86_64.tar.gz |
| Linux | aarch64 (RPi 64-bit) | btest-linux-aarch64.tar.gz |
| Linux | armv7 (RPi 32-bit) | btest-linux-armv7.tar.gz |
| Windows | x86_64 | btest-windows-x86_64.zip |
| macOS | aarch64 (Apple Silicon) | btest-darwin-aarch64.tar.gz |
| Docker | x86_64 | \`docker pull ghcr.io/manawenuz/btest-rs:${TAG}\` |
### Quick Install (Linux)
\`\`\`bash
curl -LO https://github.com/${GITHUB_REPO}/releases/download/${TAG}/btest-linux-x86_64.tar.gz
tar xzf btest-linux-x86_64.tar.gz
sudo mv btest /usr/local/bin/
\`\`\`
### Raspberry Pi
\`\`\`bash
# 64-bit
curl -LO https://github.com/${GITHUB_REPO}/releases/download/${TAG}/btest-linux-aarch64.tar.gz
tar xzf btest-linux-aarch64.tar.gz
sudo mv btest /usr/local/bin/
# 32-bit
curl -LO https://github.com/${GITHUB_REPO}/releases/download/${TAG}/btest-linux-armv7.tar.gz
tar xzf btest-linux-armv7.tar.gz
sudo mv btest /usr/local/bin/
\`\`\`
" \
./*.tar.gz ./*.zip ./*.txt 2>/dev/null || true
echo ""
echo "=== Done! ==="
echo "https://github.com/${GITHUB_REPO}/releases/tag/${TAG}"
# Cleanup
cd -
rm -rf /tmp/btest-release-${TAG}

64
scripts/test-aur-remote.sh Executable file
View File

@@ -0,0 +1,64 @@
#!/usr/bin/env bash
# Test the AUR package on a remote x86_64 Linux server using Docker.
#
# Usage:
# ./scripts/test-aur-remote.sh [user@host]
#
# Spins up an Arch container, installs btest-rs via yay (like a real user),
# runs loopback tests, cleans up.
set -euo pipefail
REMOTE="${1:-}"
TEST_SCRIPT='
docker run --rm archlinux:latest bash -c "
set -euo pipefail
echo \"[1/4] Installing yay...\"
pacman -Syu --noconfirm base-devel git sudo >/dev/null 2>&1
useradd -m builder
echo \"builder ALL=(ALL) NOPASSWD: ALL\" >> /etc/sudoers
su builder -c \"
cd /tmp
git clone https://aur.archlinux.org/yay-bin.git 2>/dev/null
cd yay-bin
makepkg -si --noconfirm 2>&1 | tail -3
\"
echo \"[2/4] Installing btest-rs from AUR via yay...\"
su builder -c \"yay -S btest-rs --noconfirm 2>&1 | tail -10\"
echo \"\"
echo \"[3/4] Verify installation...\"
btest --version
which btest
man -w btest.1 2>/dev/null && echo \"Man page: installed\" || echo \"Man page: not found\"
systemctl cat btest.service 2>/dev/null | head -3 && echo \"Systemd unit: installed\" || echo \"Systemd unit: not found\"
echo \"\"
echo \"[4/4] Loopback tests...\"
echo \"--- TCP (3s) ---\"
btest -s -P 19876 &
sleep 2
btest -c 127.0.0.1 -P 19876 -r -d 3
kill %1 2>/dev/null; wait 2>/dev/null || true
echo \"--- UDP (3s) ---\"
btest -s -P 19877 &
sleep 2
btest -c 127.0.0.1 -P 19877 -r -u -d 3
kill %1 2>/dev/null; wait 2>/dev/null || true
echo \"\"
echo \"=== ALL TESTS PASSED ===\"
"
'
if [ -n "$REMOTE" ]; then
echo "=== Testing AUR package on $REMOTE ==="
ssh "$REMOTE" "$TEST_SCRIPT"
else
echo "=== Testing AUR package locally ==="
eval "$TEST_SCRIPT"
fi

View File

@@ -1,4 +1,4 @@
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64}; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -13,6 +13,13 @@ pub struct BandwidthState {
pub rx_packets: AtomicU64, pub rx_packets: AtomicU64,
pub rx_lost_packets: AtomicU64, pub rx_lost_packets: AtomicU64,
pub last_udp_seq: AtomicU32, pub last_udp_seq: AtomicU32,
/// Cumulative totals (never reset by swap)
pub total_tx_bytes: AtomicU64,
pub total_rx_bytes: AtomicU64,
pub total_lost_packets: AtomicU64,
pub intervals: AtomicU32,
/// Remote peer's CPU usage (received via status messages)
pub remote_cpu: AtomicU8,
} }
impl BandwidthState { impl BandwidthState {
@@ -26,8 +33,33 @@ impl BandwidthState {
rx_packets: AtomicU64::new(0), rx_packets: AtomicU64::new(0),
rx_lost_packets: AtomicU64::new(0), rx_lost_packets: AtomicU64::new(0),
last_udp_seq: AtomicU32::new(0), last_udp_seq: AtomicU32::new(0),
total_tx_bytes: AtomicU64::new(0),
total_rx_bytes: AtomicU64::new(0),
total_lost_packets: AtomicU64::new(0),
intervals: AtomicU32::new(0),
remote_cpu: AtomicU8::new(0),
}) })
} }
/// Record an interval's stats into cumulative totals.
pub fn record_interval(&self, tx: u64, rx: u64, lost: u64) {
use std::sync::atomic::Ordering::Relaxed;
self.total_tx_bytes.fetch_add(tx, Relaxed);
self.total_rx_bytes.fetch_add(rx, Relaxed);
self.total_lost_packets.fetch_add(lost, Relaxed);
self.intervals.fetch_add(1, Relaxed);
}
/// Get summary for syslog reporting.
pub fn summary(&self) -> (u64, u64, u64, u32) {
use std::sync::atomic::Ordering::Relaxed;
(
self.total_tx_bytes.load(Relaxed),
self.total_rx_bytes.load(Relaxed),
self.total_lost_packets.load(Relaxed),
self.intervals.load(Relaxed),
)
}
} }
/// Calculate the sleep interval between packets to achieve target bandwidth. /// Calculate the sleep interval between packets to achieve target bandwidth.
@@ -48,6 +80,34 @@ pub fn calc_send_interval(tx_speed_bps: u32, tx_size: u16) -> Option<Duration> {
} }
} }
/// Advance `next_send` by one interval and clamp drift.
///
/// When the sender falls behind (e.g., the write blocked longer than the
/// inter-packet interval), `next_send` accumulates a debt. Once the path
/// clears, the loop would fire packets with *no* delay until the debt is
/// repaid, producing a burst that overshoots the target rate.
///
/// This helper resets `next_send` to `now` whenever it has drifted more
/// than 2x the interval behind the current wall-clock time, bounding the
/// maximum burst to at most one extra interval's worth of packets.
pub fn advance_next_send(
next_send: &mut std::time::Instant,
iv: Duration,
now: std::time::Instant,
) -> Option<Duration> {
*next_send += iv;
// If we have fallen more than 2x the interval behind, reset to now
// to prevent a compensating burst.
if *next_send + iv < now {
*next_send = now;
}
if *next_send > now {
Some(*next_send - now)
} else {
None
}
}
/// Format a bandwidth value in human-readable form. /// Format a bandwidth value in human-readable form.
pub fn format_bandwidth(bits_per_sec: f64) -> String { pub fn format_bandwidth(bits_per_sec: f64) -> String {
if bits_per_sec >= 1_000_000_000.0 { if bits_per_sec >= 1_000_000_000.0 {
@@ -94,6 +154,22 @@ pub fn print_status(
elapsed: Duration, elapsed: Duration,
lost_packets: Option<u64>, lost_packets: Option<u64>,
) { ) {
print_status_with_cpu(interval_num, direction, bytes, elapsed, lost_packets, None, None);
}
pub fn print_status_with_cpu(
interval_num: u32,
direction: &str,
bytes: u64,
elapsed: Duration,
lost_packets: Option<u64>,
local_cpu: Option<u8>,
remote_cpu: Option<u8>,
) {
if crate::csv_output::is_quiet() {
return;
}
let secs = elapsed.as_secs_f64(); let secs = elapsed.as_secs_f64();
let bits = bytes as f64 * 8.0; let bits = bytes as f64 * 8.0;
let bw = if secs > 0.0 { bits / secs } else { 0.0 }; let bw = if secs > 0.0 { bits / secs } else { 0.0 };
@@ -103,13 +179,26 @@ pub fn print_status(
_ => String::new(), _ => String::new(),
}; };
let cpu_str = match (local_cpu, remote_cpu) {
(Some(l), Some(r)) => {
let warn = if l > 70 || r > 70 { " !" } else { "" };
format!(" cpu: {}%/{}%{}", l, r, warn)
}
(Some(l), None) => {
let warn = if l > 70 { " !" } else { "" };
format!(" cpu: {}%{}", l, warn)
}
_ => String::new(),
};
println!( println!(
"[{:4}] {:>3} {} ({} bytes){}", "[{:4}] {:>3} {} ({} bytes){}{}",
interval_num, interval_num,
direction, direction,
format_bandwidth(bw), format_bandwidth(bw),
bytes, bytes,
loss_str, loss_str,
cpu_str,
); );
} }

127
src/bin/client_only.rs Normal file
View File

@@ -0,0 +1,127 @@
//! btest-client: minimal bandwidth test client for embedded/OpenWrt systems.
//!
//! Stripped-down client that connects to MikroTik btest servers.
//! No server mode, no syslog, smaller binary footprint.
//!
//! Build: cargo build --profile release-small --bin btest-client
use clap::Parser;
use std::sync::atomic::Ordering;
#[derive(Parser)]
#[command(name = "btest-client", about = "MikroTik Bandwidth Test client", version)]
struct Cli {
/// Server address to connect to
#[arg(short = 'c', long = "client", required = true)]
host: String,
/// Transmit data (upload)
#[arg(short = 't', long = "transmit")]
transmit: bool,
/// Receive data (download)
#[arg(short = 'r', long = "receive")]
receive: bool,
/// Use UDP
#[arg(short = 'u', long = "udp")]
udp: bool,
/// Bandwidth limit (e.g., 100M)
#[arg(short = 'b', long = "bandwidth")]
bandwidth: Option<String>,
/// Port
#[arg(short = 'P', long = "port", default_value_t = 2000)]
port: u16,
/// Username
#[arg(short = 'a', long = "authuser")]
auth_user: Option<String>,
/// Password
#[arg(short = 'p', long = "authpass")]
auth_pass: Option<String>,
/// NAT mode
#[arg(short = 'n', long = "nat")]
nat: bool,
/// Duration in seconds (0=unlimited)
#[arg(short = 'd', long = "duration", default_value_t = 0)]
duration: u64,
/// Verbose
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let filter = match cli.verbose {
0 => "info",
1 => "debug",
_ => "trace",
};
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(filter)),
)
.with_target(false)
.init();
btest_rs::cpu::start_sampler();
if !cli.transmit && !cli.receive {
eprintln!("Error: specify -t (transmit) and/or -r (receive)");
std::process::exit(1);
}
let direction = match (cli.transmit, cli.receive) {
(true, false) => btest_rs::protocol::CMD_DIR_RX,
(false, true) => btest_rs::protocol::CMD_DIR_TX,
(true, true) => btest_rs::protocol::CMD_DIR_BOTH,
_ => unreachable!(),
};
let bw = match &cli.bandwidth {
Some(b) => btest_rs::bandwidth::parse_bandwidth(b)?,
None => 0,
};
let (tx_speed, rx_speed) = match direction {
btest_rs::protocol::CMD_DIR_TX => (bw, 0),
btest_rs::protocol::CMD_DIR_RX => (0, bw),
_ => (bw, bw),
};
let state = btest_rs::bandwidth::BandwidthState::new();
let state_clone = state.clone();
let host = cli.host.clone();
let client_fut = btest_rs::client::run_client(
&host, cli.port, direction, cli.udp,
tx_speed, rx_speed,
cli.auth_user, cli.auth_pass, cli.nat,
state_clone,
);
if cli.duration > 0 {
match tokio::time::timeout(
std::time::Duration::from_secs(cli.duration),
client_fut,
).await {
Ok(r) => { let _ = r?; }
Err(_) => {
state.running.store(false, Ordering::SeqCst);
}
}
} else {
let _ = client_fut.await?;
}
Ok(())
}

62
src/bin/server_only.rs Normal file
View File

@@ -0,0 +1,62 @@
//! btest-server: minimal bandwidth test server for embedded/OpenWrt systems.
//!
//! Stripped-down server that accepts MikroTik client connections.
//! No client mode, no syslog, no CSV, smaller binary footprint.
//!
//! Build: cargo build --profile release-small --bin btest-server
use clap::Parser;
#[derive(Parser)]
#[command(name = "btest-server", about = "MikroTik Bandwidth Test server", version)]
struct Cli {
/// Port
#[arg(short = 'P', long = "port", default_value_t = 2000)]
port: u16,
/// IPv4 listen address
#[arg(long = "listen", default_value = "0.0.0.0")]
listen_addr: String,
/// Username
#[arg(short = 'a', long = "authuser")]
auth_user: Option<String>,
/// Password
#[arg(short = 'p', long = "authpass")]
auth_pass: Option<String>,
/// Use EC-SRP5 authentication
#[arg(long = "ecsrp5")]
ecsrp5: bool,
/// Verbose
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbose: u8,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
let filter = match cli.verbose {
0 => "info",
1 => "debug",
_ => "trace",
};
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(filter)),
)
.with_target(false)
.init();
btest_rs::cpu::start_sampler();
let v4 = if cli.listen_addr.eq_ignore_ascii_case("none") { None } else { Some(cli.listen_addr) };
tracing::info!("btest-server starting on port {}", cli.port);
btest_rs::server::run_server(cli.port, cli.auth_user, cli.auth_pass, cli.ecsrp5, v4, None).await?;
Ok(())
}

View File

@@ -20,6 +20,7 @@ pub async fn run_client(
auth_user: Option<String>, auth_user: Option<String>,
auth_pass: Option<String>, auth_pass: Option<String>,
nat_mode: bool, nat_mode: bool,
shared_state: Arc<BandwidthState>,
) -> Result<()> { ) -> Result<()> {
let addr = format!("{}:{}", host, port); let addr = format!("{}:{}", host, port);
tracing::info!("Connecting to {}...", addr); tracing::info!("Connecting to {}...", addr);
@@ -90,16 +91,15 @@ pub async fn run_client(
); );
if use_udp { if use_udp {
run_udp_test_client(&mut stream, host, &cmd, nat_mode).await run_udp_test_client(&mut stream, host, &cmd, nat_mode, shared_state).await
} else { } else {
run_tcp_test_client(stream, cmd).await run_tcp_test_client(stream, cmd, shared_state).await
} }
} }
// --- TCP Test Client --- // --- TCP Test Client ---
async fn run_tcp_test_client(stream: TcpStream, cmd: Command) -> Result<()> { async fn run_tcp_test_client(stream: TcpStream, cmd: Command, state: Arc<BandwidthState>) -> Result<()> {
let state = BandwidthState::new();
let tx_size = cmd.tx_size as usize; let tx_size = cmd.tx_size as usize;
let client_should_tx = cmd.client_tx(); let client_should_tx = cmd.client_tx();
let client_should_rx = cmd.client_rx(); let client_should_rx = cmd.client_rx();
@@ -167,10 +167,9 @@ async fn tcp_client_tx_loop(
match interval { match interval {
Some(iv) => { Some(iv) => {
next_send += iv;
let now = Instant::now(); let now = Instant::now();
if next_send > now { if let Some(delay) = bandwidth::advance_next_send(&mut next_send, iv, now) {
tokio::time::sleep(next_send - now).await; tokio::time::sleep(delay).await;
} }
} }
None => { None => {
@@ -202,6 +201,7 @@ async fn run_udp_test_client(
host: &str, host: &str,
cmd: &Command, cmd: &Command,
nat_mode: bool, nat_mode: bool,
state: Arc<BandwidthState>,
) -> Result<()> { ) -> Result<()> {
let mut port_buf = [0u8; 2]; let mut port_buf = [0u8; 2];
stream.read_exact(&mut port_buf).await?; stream.read_exact(&mut port_buf).await?;
@@ -233,7 +233,6 @@ async fn run_udp_test_client(
udp.send(&[]).await?; udp.send(&[]).await?;
} }
let state = BandwidthState::new();
let tx_size = cmd.tx_size as usize; let tx_size = cmd.tx_size as usize;
let client_should_tx = cmd.client_tx(); let client_should_tx = cmd.client_tx();
let client_should_rx = cmd.client_rx(); let client_should_rx = cmd.client_rx();
@@ -289,13 +288,19 @@ async fn udp_client_tx_loop(
state.tx_bytes.fetch_add(n as u64, Ordering::Relaxed); state.tx_bytes.fetch_add(n as u64, Ordering::Relaxed);
consecutive_errors = 0; consecutive_errors = 0;
} }
Err(_) => { Err(e) => {
consecutive_errors += 1; consecutive_errors += 1;
if consecutive_errors > 1000 { if consecutive_errors == 1 {
tracing::debug!("UDP TX send error: {} (target)", e);
}
if consecutive_errors > 50000 {
tracing::warn!("UDP TX: too many consecutive send errors, stopping"); tracing::warn!("UDP TX: too many consecutive send errors, stopping");
break; break;
} }
tokio::time::sleep(Duration::from_micros(200)).await; let backoff = Duration::from_micros(
(200 + consecutive_errors.min(5000) as u64 * 10).min(10000)
);
tokio::time::sleep(backoff).await;
continue; continue;
} }
} }
@@ -311,10 +316,9 @@ async fn udp_client_tx_loop(
match interval { match interval {
Some(iv) => { Some(iv) => {
next_send += iv;
let now = Instant::now(); let now = Instant::now();
if next_send > now { if let Some(delay) = bandwidth::advance_next_send(&mut next_send, iv, now) {
tokio::time::sleep(next_send - now).await; tokio::time::sleep(delay).await;
} }
} }
None => { None => {
@@ -372,14 +376,17 @@ async fn client_status_loop(cmd: &Command, state: &BandwidthState) {
seq += 1; seq += 1;
if cmd.client_tx() { let tx = if cmd.client_tx() { state.tx_bytes.swap(0, Ordering::Relaxed) } else { 0 };
let tx = state.tx_bytes.swap(0, Ordering::Relaxed); let rx = if cmd.client_rx() { state.rx_bytes.swap(0, Ordering::Relaxed) } else { 0 };
bandwidth::print_status(seq, "TX", tx, Duration::from_secs(1), None); state.record_interval(tx, rx, 0);
}
let local_cpu = crate::cpu::get();
let remote_cpu = state.remote_cpu.load(Ordering::Relaxed);
if cmd.client_tx() {
bandwidth::print_status_with_cpu(seq, "TX", tx, Duration::from_secs(1), None, Some(local_cpu), Some(remote_cpu));
}
if cmd.client_rx() { if cmd.client_rx() {
let rx = state.rx_bytes.swap(0, Ordering::Relaxed); bandwidth::print_status_with_cpu(seq, "RX", rx, Duration::from_secs(1), None, Some(local_cpu), Some(remote_cpu));
bandwidth::print_status(seq, "RX", rx, Duration::from_secs(1), None);
} }
} }
} }
@@ -413,6 +420,7 @@ async fn udp_client_status_loop(
match tokio::time::timeout(wait_time, reader.read_exact(&mut status_buf)).await { match tokio::time::timeout(wait_time, reader.read_exact(&mut status_buf)).await {
Ok(Ok(_)) => { Ok(Ok(_)) => {
let server_status = StatusMessage::deserialize(&status_buf); let server_status = StatusMessage::deserialize(&status_buf);
state.remote_cpu.store(server_status.cpu_load, Ordering::Relaxed);
if server_status.bytes_received > 0 && cmd.client_tx() { if server_status.bytes_received > 0 && cmd.client_tx() {
let new_speed = let new_speed =
@@ -444,8 +452,9 @@ async fn udp_client_status_loop(
let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed); let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed);
let tx_bytes = state.tx_bytes.swap(0, Ordering::Relaxed); let tx_bytes = state.tx_bytes.swap(0, Ordering::Relaxed);
let lost = state.rx_lost_packets.swap(0, Ordering::Relaxed); let lost = state.rx_lost_packets.swap(0, Ordering::Relaxed);
state.record_interval(tx_bytes, rx_bytes, lost);
let status = StatusMessage { let status = StatusMessage { cpu_load: crate::cpu::get(),
seq, seq,
bytes_received: rx_bytes as u32, bytes_received: rx_bytes as u32,
}; };
@@ -455,11 +464,13 @@ async fn udp_client_status_loop(
} }
let _ = writer.flush().await; let _ = writer.flush().await;
let local_cpu = crate::cpu::get();
let remote_cpu = state.remote_cpu.load(Ordering::Relaxed);
if cmd.client_tx() { if cmd.client_tx() {
bandwidth::print_status(seq, "TX", tx_bytes, Duration::from_secs(1), None); bandwidth::print_status_with_cpu(seq, "TX", tx_bytes, Duration::from_secs(1), None, Some(local_cpu), Some(remote_cpu));
} }
if cmd.client_rx() { if cmd.client_rx() {
bandwidth::print_status(seq, "RX", rx_bytes, Duration::from_secs(1), Some(lost)); bandwidth::print_status_with_cpu(seq, "RX", rx_bytes, Duration::from_secs(1), Some(lost), Some(local_cpu), Some(remote_cpu));
} }
} }
} }

212
src/cpu.rs Normal file
View File

@@ -0,0 +1,212 @@
//! Lightweight CPU usage measurement.
//!
//! Returns the system-wide CPU usage as a percentage (0-100).
//! Works on macOS, Linux, Windows, and FreeBSD without external dependencies.
use std::sync::atomic::{AtomicU8, Ordering};
use std::time::Duration;
static CURRENT_CPU: AtomicU8 = AtomicU8::new(0);
/// Start a background thread that samples CPU usage every second.
pub fn start_sampler() {
std::thread::spawn(|| {
let mut prev = get_cpu_times();
loop {
std::thread::sleep(Duration::from_secs(1));
let curr = get_cpu_times();
let usage = compute_usage(&prev, &curr);
CURRENT_CPU.store(usage, Ordering::Relaxed);
prev = curr;
}
});
}
/// Get the current CPU usage percentage (0-100).
pub fn get() -> u8 {
CURRENT_CPU.load(Ordering::Relaxed)
}
// --- Platform-specific implementation ---
#[cfg(target_os = "linux")]
fn get_cpu_times() -> (u64, u64) {
// Read /proc/stat: cpu user nice system idle iowait irq softirq steal
if let Ok(content) = std::fs::read_to_string("/proc/stat") {
if let Some(line) = content.lines().next() {
let parts: Vec<u64> = line
.split_whitespace()
.skip(1) // skip "cpu"
.filter_map(|s| s.parse().ok())
.collect();
if parts.len() >= 4 {
let idle = parts[3];
let total: u64 = parts.iter().sum();
return (total, idle);
}
}
}
(0, 0)
}
#[cfg(target_os = "macos")]
fn get_cpu_times() -> (u64, u64) {
// Use host_statistics to get CPU ticks
use std::mem::MaybeUninit;
extern "C" {
fn mach_host_self() -> u32;
fn host_statistics(
host: u32,
flavor: i32,
info: *mut i32,
count: *mut u32,
) -> i32;
}
const HOST_CPU_LOAD_INFO: i32 = 3;
const CPU_STATE_MAX: usize = 4;
unsafe {
let host = mach_host_self();
let mut info = MaybeUninit::<[u32; CPU_STATE_MAX]>::uninit();
let mut count: u32 = CPU_STATE_MAX as u32;
let ret = host_statistics(
host,
HOST_CPU_LOAD_INFO,
info.as_mut_ptr() as *mut i32,
&mut count,
);
if ret == 0 {
let ticks = info.assume_init();
// ticks: [user, system, idle, nice]
let user = ticks[0] as u64;
let system = ticks[1] as u64;
let idle = ticks[2] as u64;
let nice = ticks[3] as u64;
let total = user + system + idle + nice;
return (total, idle);
}
}
(0, 0)
}
#[cfg(target_os = "windows")]
fn get_cpu_times() -> (u64, u64) {
#[repr(C)]
#[derive(Default)]
struct FILETIME {
dwLowDateTime: u32,
dwHighDateTime: u32,
}
impl FILETIME {
fn to_u64(&self) -> u64 {
(self.dwHighDateTime as u64) << 32 | self.dwLowDateTime as u64
}
}
extern "system" {
fn GetSystemTimes(
lpIdleTime: *mut FILETIME,
lpKernelTime: *mut FILETIME,
lpUserTime: *mut FILETIME,
) -> i32;
}
let mut idle = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
// SAFETY: We pass valid pointers to stack-allocated FILETIME structs.
// GetSystemTimes is a well-documented Win32 API that writes into these
// output parameters. A non-zero return value indicates success.
let ret = unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) };
if ret != 0 {
let idle_ticks = idle.to_u64();
// Kernel time includes idle time on Windows, so total = kernel + user.
let total_ticks = kernel.to_u64() + user.to_u64();
(total_ticks, idle_ticks)
} else {
(0, 0)
}
}
#[cfg(target_os = "freebsd")]
fn get_cpu_times() -> (u64, u64) {
// kern.cp_time returns: user nice system interrupt idle
if let Ok(output) = std::process::Command::new("sysctl")
.arg("-n")
.arg("kern.cp_time")
.output()
{
if output.status.success() {
let text = String::from_utf8_lossy(&output.stdout);
let parts: Vec<u64> = text
.split_whitespace()
.filter_map(|s| s.parse().ok())
.collect();
if parts.len() >= 5 {
let user = parts[0];
let nice = parts[1];
let system = parts[2];
let interrupt = parts[3];
let idle = parts[4];
let total = user + nice + system + interrupt + idle;
return (total, idle);
}
}
}
(0, 0)
}
#[cfg(not(any(
target_os = "linux",
target_os = "macos",
target_os = "windows",
target_os = "freebsd",
)))]
fn get_cpu_times() -> (u64, u64) {
(0, 0) // Unsupported platform
}
fn compute_usage(prev: &(u64, u64), curr: &(u64, u64)) -> u8 {
let total_diff = curr.0.saturating_sub(prev.0);
let idle_diff = curr.1.saturating_sub(prev.1);
if total_diff == 0 {
return 0;
}
let busy = total_diff - idle_diff;
((busy * 100) / total_diff).min(100) as u8
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cpu_times_returns_nonzero() {
let (total, idle) = get_cpu_times();
// On supported platforms, total should be > 0
if cfg!(any(
target_os = "linux",
target_os = "macos",
target_os = "windows",
target_os = "freebsd",
)) {
assert!(total > 0, "CPU total ticks should be > 0");
assert!(idle <= total, "idle should be <= total");
}
}
#[test]
fn test_compute_usage() {
assert_eq!(compute_usage(&(0, 0), &(100, 20)), 80);
assert_eq!(compute_usage(&(0, 0), &(100, 100)), 0);
assert_eq!(compute_usage(&(0, 0), &(100, 0)), 100);
assert_eq!(compute_usage(&(0, 0), &(0, 0)), 0);
}
}

86
src/csv_output.rs Normal file
View File

@@ -0,0 +1,86 @@
//! CSV output for machine-readable test results.
//!
//! Appends a row per test to the specified CSV file.
//! Creates the file with headers if it doesn't exist.
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;
use std::sync::Mutex;
use std::time::SystemTime;
static CSV_FILE: Mutex<Option<String>> = Mutex::new(None);
static QUIET: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
const HEADER: &str = "timestamp,host,port,protocol,direction,duration_s,tx_avg_mbps,rx_avg_mbps,tx_bytes,rx_bytes,lost_packets,local_cpu_pct,remote_cpu_pct,auth_type";
/// Initialize CSV output. Creates file with headers if needed.
pub fn init(path: &str) -> std::io::Result<()> {
let needs_header = !Path::new(path).exists() || std::fs::metadata(path)?.len() == 0;
if needs_header {
let mut f = OpenOptions::new().create(true).write(true).open(path)?;
writeln!(f, "{}", HEADER)?;
}
*CSV_FILE.lock().unwrap() = Some(path.to_string());
Ok(())
}
pub fn set_quiet(q: bool) {
QUIET.store(q, std::sync::atomic::Ordering::Relaxed);
}
pub fn is_quiet() -> bool {
QUIET.load(std::sync::atomic::Ordering::Relaxed)
}
/// Write a test result row to the CSV file.
pub fn write_result(
host: &str,
port: u16,
protocol: &str,
direction: &str,
duration_secs: u64,
tx_bytes: u64,
rx_bytes: u64,
lost_packets: u64,
local_cpu: u8,
remote_cpu: u8,
auth_type: &str,
) {
let guard = CSV_FILE.lock().unwrap();
if let Some(ref path) = *guard {
let tx_mbps = if duration_secs > 0 {
tx_bytes as f64 * 8.0 / duration_secs as f64 / 1_000_000.0
} else {
0.0
};
let rx_mbps = if duration_secs > 0 {
rx_bytes as f64 * 8.0 / duration_secs as f64 / 1_000_000.0
} else {
0.0
};
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let row = format!(
"{},{},{},{},{},{},{:.2},{:.2},{},{},{},{},{},{}",
now, host, port, protocol, direction, duration_secs,
tx_mbps, rx_mbps, tx_bytes, rx_bytes, lost_packets,
local_cpu, remote_cpu, auth_type,
);
if let Ok(mut f) = OpenOptions::new().append(true).open(path) {
let _ = writeln!(f, "{}", row);
}
}
}
/// Check if CSV output is enabled.
pub fn is_enabled() -> bool {
CSV_FILE.lock().unwrap().is_some()
}

View File

@@ -1,6 +1,8 @@
pub mod auth; pub mod auth;
pub mod bandwidth; pub mod bandwidth;
pub mod client; pub mod client;
pub mod cpu;
pub mod csv_output;
pub mod ecsrp5; pub mod ecsrp5;
pub mod protocol; pub mod protocol;
pub mod server; pub mod server;

View File

@@ -1,6 +1,8 @@
mod auth; mod auth;
mod bandwidth; mod bandwidth;
mod client; mod client;
mod cpu;
pub mod csv_output;
mod ecsrp5; mod ecsrp5;
mod protocol; mod protocol;
mod server; mod server;
@@ -74,6 +76,18 @@ struct Cli {
#[arg(short = 'n', long = "nat")] #[arg(short = 'n', long = "nat")]
nat: bool, nat: bool,
/// Test duration in seconds (client mode, 0=unlimited)
#[arg(short = 'd', long = "duration", default_value_t = 0)]
duration: u64,
/// Output results to CSV file (appends if exists)
#[arg(long = "csv")]
csv: Option<String>,
/// Suppress terminal output (use with --csv for machine-readable only)
#[arg(long = "quiet", short = 'q')]
quiet: bool,
/// Send logs to remote syslog server (e.g., 192.168.1.1:514) /// Send logs to remote syslog server (e.g., 192.168.1.1:514)
#[arg(long = "syslog")] #[arg(long = "syslog")]
syslog: Option<String>, syslog: Option<String>,
@@ -87,6 +101,9 @@ struct Cli {
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let cli = Cli::parse(); let cli = Cli::parse();
// Start CPU usage sampler
cpu::start_sampler();
// Set up logging based on verbosity // Set up logging based on verbosity
let filter = match cli.verbose { let filter = match cli.verbose {
0 => "info", 0 => "info",
@@ -107,6 +124,14 @@ async fn main() -> anyhow::Result<()> {
} }
} }
// Initialize CSV output if requested
if let Some(ref csv_path) = cli.csv {
if let Err(e) = csv_output::init(csv_path) {
eprintln!("Warning: failed to initialize CSV output to {}: {}", csv_path, e);
}
}
csv_output::set_quiet(cli.quiet);
if cli.server { if cli.server {
// Server mode // Server mode
let v4 = if cli.listen_addr.eq_ignore_ascii_case("none") { None } else { Some(cli.listen_addr) }; let v4 = if cli.listen_addr.eq_ignore_ascii_case("none") { None } else { Some(cli.listen_addr) };
@@ -143,18 +168,71 @@ async fn main() -> anyhow::Result<()> {
_ => (0, 0), _ => (0, 0),
}; };
client::run_client( let dir_str = match direction {
CMD_DIR_RX => "send",
CMD_DIR_TX => "receive",
CMD_DIR_BOTH => "both",
_ => "unknown",
};
let proto_str = if cli.udp { "UDP" } else { "TCP" };
// Create shared state that survives timeout cancellation
let shared_state = bandwidth::BandwidthState::new();
// Log test start
syslog_logger::test_start(&host, proto_str, dir_str, 0);
// Run client with optional duration timeout
let start = std::time::Instant::now();
let client_fut = client::run_client(
&host, &host,
cli.port, cli.port,
direction, direction,
cli.udp, cli.udp,
tx_speed, tx_speed,
rx_speed, rx_speed,
cli.auth_user, cli.auth_user.clone(),
cli.auth_pass, cli.auth_pass.clone(),
cli.nat, cli.nat,
) shared_state.clone(),
.await?; );
if cli.duration > 0 {
match tokio::time::timeout(
std::time::Duration::from_secs(cli.duration),
client_fut,
)
.await
{
Ok(result) => { let _ = result?; },
Err(_) => {
// Timeout — signal stop
shared_state.running.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
} else {
let _ = client_fut.await?;
}
let elapsed = start.elapsed().as_secs();
let (total_tx, total_rx, total_lost, _intervals) = shared_state.summary();
// Log test end to syslog
syslog_logger::test_end(
&host, proto_str, dir_str,
total_tx, total_rx, total_lost, elapsed as u32,
);
// Write CSV if enabled
if csv_output::is_enabled() {
let auth_type = if cli.auth_user.is_some() { "auth" } else { "none" };
let local_cpu = cpu::get();
let remote_cpu = shared_state.remote_cpu.load(std::sync::atomic::Ordering::Relaxed);
csv_output::write_result(
&host, cli.port, proto_str, dir_str,
elapsed, total_tx, total_rx, total_lost, local_cpu, remote_cpu, auth_type,
);
}
} else { } else {
eprintln!("Error: Must specify either -s (server) or -c <host> (client)"); eprintln!("Error: Must specify either -s (server) or -c <host> (client)");
eprintln!("Run with --help for usage information."); eprintln!("Run with --help for usage information.");

View File

@@ -137,23 +137,31 @@ impl Command {
pub struct StatusMessage { pub struct StatusMessage {
pub seq: u32, pub seq: u32,
pub bytes_received: u32, pub bytes_received: u32,
pub cpu_load: u8,
} }
impl StatusMessage { impl StatusMessage {
pub fn serialize(&self) -> [u8; STATUS_MSG_SIZE] { pub fn serialize(&self) -> [u8; STATUS_MSG_SIZE] {
let mut buf = [0u8; STATUS_MSG_SIZE]; let mut buf = [0u8; STATUS_MSG_SIZE];
buf[0] = STATUS_MSG_TYPE; buf[0] = STATUS_MSG_TYPE;
buf[1..5].copy_from_slice(&self.seq.to_be_bytes()); // Byte 1: CPU load with high bit set (MikroTik format: 0x80 | percentage)
buf[5] = 0; buf[1] = 0x80 | (self.cpu_load & 0x7F);
buf[6] = 0; buf[2] = 0;
buf[7] = 0; buf[3] = 0;
// Bytes 4-7: sequence number (LE)
buf[4..8].copy_from_slice(&self.seq.to_le_bytes());
// Bytes 8-11: bytes received (LE)
buf[8..12].copy_from_slice(&self.bytes_received.to_le_bytes()); buf[8..12].copy_from_slice(&self.bytes_received.to_le_bytes());
buf buf
} }
pub fn deserialize(buf: &[u8; STATUS_MSG_SIZE]) -> Self { pub fn deserialize(buf: &[u8; STATUS_MSG_SIZE]) -> Self {
// MikroTik encodes CPU with high bit set: actual = byte & 0x7F
let raw_cpu = buf[1];
let cpu = if raw_cpu > 128 { raw_cpu & 0x7F } else { raw_cpu };
Self { Self {
seq: u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]), cpu_load: cpu.min(100),
seq: u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]),
bytes_received: u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]), bytes_received: u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]),
} }
} }

View File

@@ -346,13 +346,27 @@ async fn handle_client(
run_tcp_test_server(stream, cmd).await run_tcp_test_server(stream, cmd).await
}; };
crate::syslog_logger::test_end(&peer.to_string(), proto_str, dir_str); let (total_tx, total_rx, total_lost, intervals) = match &result {
result Ok(summary) => *summary,
Err(_) => (0, 0, 0, 0),
};
crate::syslog_logger::test_end(
&peer.to_string(), proto_str, dir_str,
total_tx, total_rx, total_lost, intervals,
);
if crate::csv_output::is_enabled() {
crate::csv_output::write_result(
&peer.ip().to_string(), peer.port(), proto_str, dir_str,
intervals as u64, total_tx, total_rx, total_lost,
crate::cpu::get(), 0, auth_type,
);
}
result.map(|_| ())
} }
// --- TCP Test Server --- // --- TCP Test Server ---
async fn run_tcp_test_server(stream: TcpStream, cmd: Command) -> Result<()> { async fn run_tcp_test_server(stream: TcpStream, cmd: Command) -> Result<(u64, u64, u64, u32)> {
let state = BandwidthState::new(); let state = BandwidthState::new();
let tx_size = cmd.tx_size as usize; let tx_size = cmd.tx_size as usize;
let server_should_tx = cmd.server_tx(); let server_should_tx = cmd.server_tx();
@@ -420,11 +434,11 @@ async fn run_tcp_test_server(stream: TcpStream, cmd: Command) -> Result<()> {
state.running.store(false, Ordering::SeqCst); state.running.store(false, Ordering::SeqCst);
if let Some(h) = tx_handle { let _ = h.await; } if let Some(h) = tx_handle { let _ = h.await; }
if let Some(h) = rx_handle { let _ = h.await; } if let Some(h) = rx_handle { let _ = h.await; }
Ok(()) Ok(state.summary())
} }
/// TCP multi-connection. /// TCP multi-connection.
async fn run_tcp_multiconn_server(streams: Vec<TcpStream>, cmd: Command) -> Result<()> { async fn run_tcp_multiconn_server(streams: Vec<TcpStream>, cmd: Command) -> Result<(u64, u64, u64, u32)> {
let state = BandwidthState::new(); let state = BandwidthState::new();
let tx_size = cmd.tx_size as usize; let tx_size = cmd.tx_size as usize;
let server_should_tx = cmd.server_tx(); let server_should_tx = cmd.server_tx();
@@ -480,7 +494,7 @@ async fn run_tcp_multiconn_server(streams: Vec<TcpStream>, cmd: Command) -> Resu
for h in tx_handles { let _ = h.await; } for h in tx_handles { let _ = h.await; }
for h in rx_handles { let _ = h.await; } for h in rx_handles { let _ = h.await; }
tracing::info!("TCP multi-connection test ended"); tracing::info!("TCP multi-connection test ended");
Ok(()) Ok(state.summary())
} }
async fn tcp_tx_loop( async fn tcp_tx_loop(
@@ -523,7 +537,7 @@ async fn tcp_tx_loop_inner(
if send_status && Instant::now() >= next_status { if send_status && Instant::now() >= next_status {
status_seq += 1; status_seq += 1;
let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed); let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed);
let status = StatusMessage { let status = StatusMessage { cpu_load: crate::cpu::get(),
seq: status_seq, seq: status_seq,
bytes_received: rx_bytes as u32, bytes_received: rx_bytes as u32,
}; };
@@ -531,6 +545,7 @@ async fn tcp_tx_loop_inner(
state.running.store(false, Ordering::SeqCst); state.running.store(false, Ordering::SeqCst);
break; break;
} }
state.record_interval(0, rx_bytes, 0);
bandwidth::print_status(status_seq, "RX", rx_bytes, Duration::from_secs(1), None); bandwidth::print_status(status_seq, "RX", rx_bytes, Duration::from_secs(1), None);
next_status = Instant::now() + Duration::from_secs(1); next_status = Instant::now() + Duration::from_secs(1);
} }
@@ -550,10 +565,9 @@ async fn tcp_tx_loop_inner(
match interval { match interval {
Some(iv) => { Some(iv) => {
next_send += iv;
let now = Instant::now(); let now = Instant::now();
if next_send > now { if let Some(delay) = bandwidth::advance_next_send(&mut next_send, iv, now) {
tokio::time::sleep(next_send - now).await; tokio::time::sleep(delay).await;
} }
} }
None => { None => {
@@ -601,7 +615,7 @@ async fn tcp_status_sender(
// Swap to get bytes received this interval (atomic reset) // Swap to get bytes received this interval (atomic reset)
let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed); let rx_bytes = state.rx_bytes.swap(0, Ordering::Relaxed);
let status = StatusMessage { let status = StatusMessage { cpu_load: crate::cpu::get(),
seq, seq,
bytes_received: rx_bytes as u32, bytes_received: rx_bytes as u32,
}; };
@@ -612,7 +626,7 @@ async fn tcp_status_sender(
} }
let _ = writer.flush().await; let _ = writer.flush().await;
// Also print locally state.record_interval(0, rx_bytes, 0);
bandwidth::print_status(seq, "RX", rx_bytes, Duration::from_secs(1), None); bandwidth::print_status(seq, "RX", rx_bytes, Duration::from_secs(1), None);
} }
} }
@@ -624,7 +638,7 @@ async fn run_udp_test_server(
peer: SocketAddr, peer: SocketAddr,
cmd: &Command, cmd: &Command,
udp_port_offset: Arc<std::sync::atomic::AtomicU16>, udp_port_offset: Arc<std::sync::atomic::AtomicU16>,
) -> Result<()> { ) -> Result<(u64, u64, u64, u32)> {
let offset = udp_port_offset.fetch_add(1, Ordering::SeqCst); let offset = udp_port_offset.fetch_add(1, Ordering::SeqCst);
let server_udp_port = BTEST_UDP_PORT_START + offset; let server_udp_port = BTEST_UDP_PORT_START + offset;
let client_udp_port = server_udp_port + BTEST_PORT_CLIENT_OFFSET; let client_udp_port = server_udp_port + BTEST_PORT_CLIENT_OFFSET;
@@ -729,7 +743,7 @@ async fn run_udp_test_server(
state.running.store(false, Ordering::SeqCst); state.running.store(false, Ordering::SeqCst);
if let Some(h) = tx_handle { let _ = h.await; } if let Some(h) = tx_handle { let _ = h.await; }
if let Some(h) = rx_handle { let _ = h.await; } if let Some(h) = rx_handle { let _ = h.await; }
Ok(()) Ok(state.summary())
} }
async fn udp_tx_loop( async fn udp_tx_loop(
@@ -790,10 +804,9 @@ async fn udp_tx_loop(
match interval { match interval {
Some(iv) => { Some(iv) => {
next_send += iv;
let now = Instant::now(); let now = Instant::now();
if next_send > now { if let Some(delay) = bandwidth::advance_next_send(&mut next_send, iv, now) {
tokio::time::sleep(next_send - now).await; tokio::time::sleep(delay).await;
} }
} }
None => { None => {
@@ -863,14 +876,15 @@ async fn status_report_loop(cmd: &Command, state: &BandwidthState) {
seq += 1; seq += 1;
let tx = if cmd.server_tx() { state.tx_bytes.swap(0, Ordering::Relaxed) } else { 0 };
let rx = if cmd.server_rx() { state.rx_bytes.swap(0, Ordering::Relaxed) } else { 0 };
let lost = if cmd.server_rx() { state.rx_lost_packets.swap(0, Ordering::Relaxed) } else { 0 };
state.record_interval(tx, rx, lost);
if cmd.server_tx() { if cmd.server_tx() {
let tx = state.tx_bytes.swap(0, Ordering::Relaxed);
bandwidth::print_status(seq, "TX", tx, Duration::from_secs(1), None); bandwidth::print_status(seq, "TX", tx, Duration::from_secs(1), None);
} }
if cmd.server_rx() { if cmd.server_rx() {
let rx = state.rx_bytes.swap(0, Ordering::Relaxed);
let lost = state.rx_lost_packets.swap(0, Ordering::Relaxed);
let lost_opt = if cmd.is_udp() { Some(lost) } else { None }; let lost_opt = if cmd.is_udp() { Some(lost) } else { None };
bandwidth::print_status(seq, "RX", rx, Duration::from_secs(1), lost_opt); bandwidth::print_status(seq, "RX", rx, Duration::from_secs(1), lost_opt);
} }
@@ -910,9 +924,10 @@ async fn udp_status_loop(
match tokio::time::timeout(wait_time, reader.read_exact(&mut status_buf)).await { match tokio::time::timeout(wait_time, reader.read_exact(&mut status_buf)).await {
Ok(Ok(_)) => { Ok(Ok(_)) => {
let client_status = StatusMessage::deserialize(&status_buf); let client_status = StatusMessage::deserialize(&status_buf);
state.remote_cpu.store(client_status.cpu_load, Ordering::Relaxed);
tracing::debug!( tracing::debug!(
"RECV status: raw={:02x?} seq={} bytes_received={}", "RECV status: raw={:02x?} seq={} bytes_received={} cpu={}%",
&status_buf, client_status.seq, client_status.bytes_received, &status_buf, client_status.seq, client_status.bytes_received, client_status.cpu_load,
); );
if client_status.bytes_received > 0 && cmd.server_tx() { if client_status.bytes_received > 0 && cmd.server_tx() {
@@ -957,7 +972,7 @@ async fn udp_status_loop(
} else { } else {
rx_bytes rx_bytes
}; };
let status = StatusMessage { let status = StatusMessage { cpu_load: crate::cpu::get(),
seq, seq,
bytes_received: report_bytes as u32, bytes_received: report_bytes as u32,
}; };
@@ -972,12 +987,17 @@ async fn udp_status_loop(
} }
let _ = writer.flush().await; let _ = writer.flush().await;
// Print local stats // Print local stats and record totals
state.record_interval(tx_bytes, rx_bytes, lost);
if cmd.server_tx() { if cmd.server_tx() {
bandwidth::print_status(seq, "TX", tx_bytes, Duration::from_secs(1), None); let local_cpu = crate::cpu::get();
let remote_cpu = state.remote_cpu.load(Ordering::Relaxed);
bandwidth::print_status_with_cpu(seq, "TX", tx_bytes, Duration::from_secs(1), None, Some(local_cpu), Some(remote_cpu));
} }
if cmd.server_rx() { if cmd.server_rx() {
bandwidth::print_status(seq, "RX", rx_bytes, Duration::from_secs(1), Some(lost)); let local_cpu = crate::cpu::get();
let remote_cpu = state.remote_cpu.load(Ordering::Relaxed);
bandwidth::print_status_with_cpu(seq, "RX", rx_bytes, Duration::from_secs(1), Some(lost), Some(local_cpu), Some(remote_cpu));
} }
} }
} }

View File

@@ -38,25 +38,58 @@ pub fn init(target: &str) -> std::io::Result<()> {
fn send(severity: u8, msg: &str) { fn send(severity: u8, msg: &str) {
let guard = SYSLOG.lock().unwrap(); let guard = SYSLOG.lock().unwrap();
if let Some(ref sender) = *guard { if let Some(ref sender) = *guard {
// RFC 5424 facility=1 (user), severity as given // RFC 3164 (BSD syslog): <priority>Mon DD HH:MM:SS hostname program: message
let priority = 8 + severity; // facility=1 (user-level) * 8 + severity // facility=16 (local0) * 8 + severity
let timestamp = chrono_lite_now(); let priority = 128 + severity;
let timestamp = bsd_timestamp();
let syslog_msg = format!( let syslog_msg = format!(
"<{}>1 {} {} btest-rs - - - {}", "<{}>{} {} btest-rs: {}",
priority, timestamp, sender.hostname, msg, priority, timestamp, sender.hostname, msg,
); );
let _ = sender.socket.send_to(syslog_msg.as_bytes(), &sender.target); let _ = sender.socket.send_to(syslog_msg.as_bytes(), &sender.target);
} }
} }
fn chrono_lite_now() -> String { fn bsd_timestamp() -> String {
// Simple ISO 8601 timestamp without chrono dependency // RFC 3164 format: "Mon DD HH:MM:SS" (no year)
let now = std::time::SystemTime::now() use std::time::{SystemTime, UNIX_EPOCH};
.duration_since(std::time::UNIX_EPOCH) let now = SystemTime::now()
.unwrap_or_default(); .duration_since(UNIX_EPOCH)
let secs = now.as_secs(); .unwrap_or_default()
// Good enough for syslog — not perfect but functional .as_secs();
format!("{}", secs)
// Simple conversion — good enough for syslog
let secs_in_day = 86400u64;
let days = now / secs_in_day;
let time_of_day = now % secs_in_day;
let hours = time_of_day / 3600;
let minutes = (time_of_day % 3600) / 60;
let seconds = time_of_day % 60;
// Day of year calculation (approximate months)
let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
let days_in_months = [31u64,28,31,30,31,30,31,31,30,31,30,31];
// Days since epoch to year/month/day
let mut y = 1970u64;
let mut remaining = days;
loop {
let leap = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 366 } else { 365 };
if remaining < leap { break; }
remaining -= leap;
y += 1;
}
let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
let mut m = 0usize;
for i in 0..12 {
let mut d = days_in_months[i];
if i == 1 && leap { d += 1; }
if remaining < d { m = i; break; }
remaining -= d;
}
let day = remaining + 1;
format!("{} {:2} {:02}:{:02}:{:02}", months[m], day, hours, minutes, seconds)
} }
// --- Public logging functions --- // --- Public logging functions ---
@@ -88,24 +121,28 @@ pub fn test_start(peer: &str, proto: &str, direction: &str, conn_count: u8) {
send(6, &msg); send(6, &msg);
} }
pub fn test_end(peer: &str, proto: &str, direction: &str) { pub fn test_end(
let msg = format!(
"TEST_END peer={} proto={} dir={}",
peer, proto, direction,
);
tracing::info!("{}", msg);
send(6, &msg);
}
pub fn test_result(
peer: &str, peer: &str,
proto: &str,
direction: &str, direction: &str,
avg_mbps: f64, total_tx: u64,
total_rx: u64,
total_lost: u64,
duration_secs: u32, duration_secs: u32,
) { ) {
let tx_mbps = if duration_secs > 0 {
total_tx as f64 * 8.0 / duration_secs as f64 / 1_000_000.0
} else {
0.0
};
let rx_mbps = if duration_secs > 0 {
total_rx as f64 * 8.0 / duration_secs as f64 / 1_000_000.0
} else {
0.0
};
let msg = format!( let msg = format!(
"TEST_RESULT peer={} dir={} avg_mbps={:.2} duration={}s", "TEST_END peer={} proto={} dir={} duration={}s tx_avg={:.2}Mbps rx_avg={:.2}Mbps tx_bytes={} rx_bytes={} lost={}",
peer, direction, avg_mbps, duration_secs, peer, proto, direction, duration_secs, tx_mbps, rx_mbps, total_tx, total_rx, total_lost,
); );
tracing::info!("{}", msg); tracing::info!("{}", msg);
send(6, &msg); send(6, &msg);

View File

@@ -85,6 +85,7 @@ async fn test_ecsrp5_full_client_auth() {
Some("testuser".into()), Some("testuser".into()),
Some("testpass".into()), Some("testpass".into()),
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -109,6 +110,7 @@ async fn test_ecsrp5_wrong_password_fails() {
Some("testuser".into()), Some("testuser".into()),
Some("wrongpass".into()), Some("wrongpass".into()),
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await; .await;
@@ -131,6 +133,7 @@ async fn test_md5_auth_still_works() {
Some("testuser".into()), Some("testuser".into()),
Some("testpass".into()), Some("testpass".into()),
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -155,6 +158,7 @@ async fn test_noauth_still_works() {
None, None,
None, None,
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -179,6 +183,7 @@ async fn test_ecsrp5_udp_bidirectional() {
Some("testuser".into()), Some("testuser".into()),
Some("testpass".into()), Some("testpass".into()),
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });

View File

@@ -0,0 +1,338 @@
//! Comprehensive integration tests covering all modes, protocols, and output formats.
//! Each test starts a server, runs a client, verifies data flows, and checks CSV/stats.
use std::net::UdpSocket as StdUdpSocket;
use std::sync::atomic::Ordering;
use std::time::Duration;
const BASE_PORT: u16 = 14000;
// --- Helpers ---
async fn start_server(port: u16, ecsrp5: bool) {
let auth_user = Some("testuser".into());
let auth_pass = Some("testpass".into());
tokio::spawn(async move {
let _ = btest_rs::server::run_server(
port, auth_user, auth_pass, ecsrp5,
Some("127.0.0.1".into()), None,
).await;
});
tokio::time::sleep(Duration::from_millis(200)).await;
}
async fn start_server_noauth(port: u16) {
tokio::spawn(async move {
let _ = btest_rs::server::run_server(
port, None, None, false,
Some("127.0.0.1".into()), None,
).await;
});
tokio::time::sleep(Duration::from_millis(200)).await;
}
async fn start_server_v6(port: u16) {
tokio::spawn(async move {
let _ = btest_rs::server::run_server(
port, None, None, false,
None, Some("::1".into()),
).await;
});
tokio::time::sleep(Duration::from_millis(200)).await;
}
async fn run_client_test(
host: &str, port: u16, transmit: bool, receive: bool, udp: bool,
user: Option<&str>, pass: Option<&str>,
) -> (u64, u64, u64, u32) {
let direction = match (transmit, receive) {
(true, false) => btest_rs::protocol::CMD_DIR_RX,
(false, true) => btest_rs::protocol::CMD_DIR_TX,
(true, true) => btest_rs::protocol::CMD_DIR_BOTH,
_ => panic!("must specify direction"),
};
let state = btest_rs::bandwidth::BandwidthState::new();
let state_clone = state.clone();
let host = host.to_string();
let user = user.map(String::from);
let pass = pass.map(String::from);
let handle = tokio::spawn(async move {
btest_rs::client::run_client(
&host, port, direction, udp,
0, 0, user, pass, false, state_clone,
).await
});
tokio::time::sleep(Duration::from_secs(2)).await;
state.running.store(false, Ordering::SeqCst);
tokio::time::sleep(Duration::from_millis(500)).await;
handle.abort();
state.summary()
}
// --- TCP IPv4 Tests ---
#[tokio::test]
async fn test_tcp4_receive() {
let port = BASE_PORT;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, false, true, false, None, None).await;
assert!(_rx > 0, "TCP4 receive: expected rx > 0, got {}", _rx);
assert!(_intervals > 0, "TCP4 receive: expected intervals > 0");
}
#[tokio::test]
async fn test_tcp4_send() {
let port = BASE_PORT + 1;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, true, false, false, None, None).await;
assert!(_tx > 0, "TCP4 send: expected tx > 0, got {}", _tx);
assert!(_intervals > 0, "TCP4 send: expected intervals > 0");
}
#[tokio::test]
async fn test_tcp4_both() {
let port = BASE_PORT + 2;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, true, true, false, None, None).await;
assert!(_tx > 0, "TCP4 both: expected tx > 0, got {}", _tx);
assert!(_rx > 0, "TCP4 both: expected rx > 0, got {}", _rx);
}
// --- UDP IPv4 Tests ---
#[tokio::test]
async fn test_udp4_receive() {
let port = BASE_PORT + 3;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, false, true, true, None, None).await;
assert!(_rx > 0, "UDP4 receive: expected rx > 0, got {}", _rx);
}
#[tokio::test]
async fn test_udp4_send() {
let port = BASE_PORT + 4;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, true, false, true, None, None).await;
assert!(_tx > 0, "UDP4 send: expected tx > 0, got {}", _tx);
}
#[tokio::test]
async fn test_udp4_both() {
let port = BASE_PORT + 5;
start_server_noauth(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("127.0.0.1", port, true, true, true, None, None).await;
assert!(_tx > 0, "UDP4 both: expected tx > 0, got {}", _tx);
assert!(_rx > 0, "UDP4 both: expected rx > 0, got {}", _rx);
}
// --- TCP IPv6 Tests ---
#[tokio::test]
async fn test_tcp6_receive() {
let port = BASE_PORT + 6;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, false, true, false, None, None).await;
assert!(_rx > 0, "TCP6 receive: expected rx > 0, got {}", _rx);
}
#[tokio::test]
async fn test_tcp6_send() {
let port = BASE_PORT + 7;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, true, false, false, None, None).await;
assert!(_tx > 0, "TCP6 send: expected tx > 0, got {}", _tx);
}
#[tokio::test]
async fn test_tcp6_both() {
let port = BASE_PORT + 8;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, true, true, false, None, None).await;
assert!(_tx > 0, "TCP6 both: expected tx > 0, got {}", _tx);
assert!(_rx > 0, "TCP6 both: expected rx > 0, got {}", _rx);
}
// --- UDP IPv6 Tests (loopback, no ENOBUFS issues) ---
#[tokio::test]
async fn test_udp6_receive() {
let port = BASE_PORT + 9;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, false, true, true, None, None).await;
assert!(_rx > 0, "UDP6 receive: expected rx > 0, got {}", _rx);
}
#[tokio::test]
async fn test_udp6_send() {
let port = BASE_PORT + 10;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, true, false, true, None, None).await;
assert!(_tx > 0, "UDP6 send: expected tx > 0, got {}", _tx);
}
#[tokio::test]
async fn test_udp6_both() {
let port = BASE_PORT + 11;
start_server_v6(port).await;
let (_tx, _rx, _, _intervals) = run_client_test("::1", port, true, true, true, None, None).await;
assert!(_tx > 0, "UDP6 both: expected tx > 0, got {}", _tx);
assert!(_rx > 0, "UDP6 both: expected rx > 0, got {}", _rx);
}
// --- Authentication Tests ---
#[tokio::test]
async fn test_md5_auth_works() {
let port = BASE_PORT + 12;
start_server(port, false).await;
let (_tx, _rx, _, _) = run_client_test(
"127.0.0.1", port, false, true, false,
Some("testuser"), Some("testpass"),
).await;
assert!(_rx > 0, "MD5 auth: expected data flow");
}
#[tokio::test]
async fn test_ecsrp5_auth_works() {
let port = BASE_PORT + 13;
start_server(port, true).await;
let (_tx, _rx, _, _) = run_client_test(
"127.0.0.1", port, false, true, false,
Some("testuser"), Some("testpass"),
).await;
assert!(_rx > 0, "EC-SRP5 auth: expected data flow");
}
#[tokio::test]
async fn test_ecsrp5_wrong_password() {
let port = BASE_PORT + 14;
start_server(port, true).await;
let state = btest_rs::bandwidth::BandwidthState::new();
let result = btest_rs::client::run_client(
"127.0.0.1", port,
btest_rs::protocol::CMD_DIR_TX,
false, 0, 0,
Some("testuser".into()), Some("wrongpass".into()),
false, state,
).await;
assert!(result.is_err(), "Wrong password should fail");
}
// --- CSV Output Tests ---
#[tokio::test]
async fn test_csv_created_client() {
let port = BASE_PORT + 15;
start_server_noauth(port).await;
let csv_path = format!("/tmp/btest_test_csv_{}.csv", port);
let _ = std::fs::remove_file(&csv_path);
// Initialize CSV
btest_rs::csv_output::init(&csv_path).unwrap();
let (tx, rx, lost, intervals) = run_client_test(
"127.0.0.1", port, false, true, false, None, None,
).await;
// Write result like main.rs does
btest_rs::csv_output::write_result(
"127.0.0.1", port, "TCP", "receive",
2, tx, rx, lost, 0, 0, "none",
);
// Verify CSV exists and has data
let content = std::fs::read_to_string(&csv_path).unwrap();
let lines: Vec<&str> = content.lines().collect();
assert!(lines.len() >= 2, "CSV should have header + at least 1 row, got {} lines", lines.len());
assert!(lines[0].starts_with("timestamp,"), "CSV header missing");
assert!(lines[1].contains("TCP"), "CSV row should contain protocol");
// Check that tx or rx bytes are non-zero (the 7th or 8th CSV field)
let fields: Vec<&str> = lines[1].split(',').collect();
assert!(fields.len() >= 10, "CSV row should have enough fields");
let tx_bytes: u64 = fields[8].parse().unwrap_or(0);
let rx_bytes: u64 = fields[9].parse().unwrap_or(0);
assert!(tx_bytes > 0 || rx_bytes > 0, "CSV should have non-zero bytes: tx={} rx={}", tx_bytes, rx_bytes);
let _ = std::fs::remove_file(&csv_path);
}
#[tokio::test]
async fn test_csv_created_server() {
let port = BASE_PORT + 16;
let csv_path = format!("/tmp/btest_test_server_csv_{}.csv", port);
let _ = std::fs::remove_file(&csv_path);
btest_rs::csv_output::init(&csv_path).unwrap();
start_server_noauth(port).await;
let _ = run_client_test("127.0.0.1", port, false, true, false, None, None).await;
tokio::time::sleep(Duration::from_millis(500)).await;
let content = std::fs::read_to_string(&csv_path).unwrap_or_default();
let lines: Vec<&str> = content.lines().collect();
assert!(lines.len() >= 2, "Server CSV should have header + rows, got {}", lines.len());
let _ = std::fs::remove_file(&csv_path);
}
// --- Syslog Tests ---
#[tokio::test]
async fn test_syslog_emits_events() {
// Bind a local UDP socket to receive syslog messages
let syslog_sock = StdUdpSocket::bind("127.0.0.1:0").unwrap();
let syslog_addr = syslog_sock.local_addr().unwrap();
syslog_sock.set_nonblocking(true).unwrap();
// Initialize syslog to our test socket
btest_rs::syslog_logger::init(&syslog_addr.to_string()).unwrap();
let port = BASE_PORT + 17;
start_server_noauth(port).await;
let _ = run_client_test("127.0.0.1", port, false, true, false, None, None).await;
tokio::time::sleep(Duration::from_millis(500)).await;
// Read all syslog messages
let mut messages = Vec::new();
let mut buf = [0u8; 4096];
loop {
match syslog_sock.recv(&mut buf) {
Ok(n) => messages.push(String::from_utf8_lossy(&buf[..n]).to_string()),
Err(_) => break,
}
}
let all = messages.join("\n");
assert!(all.contains("AUTH_SUCCESS") || all.contains("TEST_START"),
"Syslog should contain auth or test events, got: {}", all);
assert!(all.contains("TEST_START"), "Syslog should contain TEST_START");
assert!(all.contains("TEST_END"), "Syslog should contain TEST_END");
}
// --- Bandwidth State Tests ---
#[tokio::test]
async fn test_bandwidth_state_record_interval() {
let state = btest_rs::bandwidth::BandwidthState::new();
state.record_interval(1000, 2000, 5);
state.record_interval(3000, 4000, 10);
let (tx, rx, lost, intervals) = state.summary();
assert_eq!(tx, 4000);
assert_eq!(rx, 6000);
assert_eq!(lost, 15);
assert_eq!(intervals, 2);
}
#[tokio::test]
async fn test_bandwidth_state_running_flag() {
let state = btest_rs::bandwidth::BandwidthState::new();
assert!(state.running.load(Ordering::Relaxed));
state.running.store(false, Ordering::SeqCst);
assert!(!state.running.load(Ordering::Relaxed));
}

View File

@@ -153,6 +153,7 @@ async fn test_loopback_tcp_rx() {
None, None,
None, None,
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -177,6 +178,7 @@ async fn test_loopback_tcp_tx() {
None, None,
None, None,
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -201,6 +203,7 @@ async fn test_loopback_tcp_both() {
None, None,
None, None,
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });
@@ -225,6 +228,7 @@ async fn test_loopback_tcp_with_auth() {
Some("admin".into()), Some("admin".into()),
Some("secret".into()), Some("secret".into()),
false, false,
btest_rs::bandwidth::BandwidthState::new(),
) )
.await .await
}); });