Skip to content
Yuu518Public

About

No description, website, or topics provided.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Repository files navigation

ports-box

A TCP/UDP port forwarder for Linux with per-user traffic quotas.

  • Users as groups: each username is a group that can hold multiple port-forwarding rules, and every rule can be enabled/disabled individually; for single-user setups, just write rules at the top level
  • Failover (fallback): each rule can have multiple backup targets — when the primary target is unavailable it automatically switches by priority and switches back once the primary recovers; rules that include TCP detect recovery via background health checks (every 10 seconds by default)
  • Domain name resolution: forwarding targets can be domain names, resolved using the host's DNS configuration (/etc/resolv.conf, /etc/hosts) and cached according to record TTL — after a domain's records change, new connections automatically use the new address without a restart
  • Traffic quotas (optional): quotas can be set per user, or a single total_quota can be split evenly among users without an individual quota; if neither is set, that user is unlimited (usage is recorded but not enforced); usage follows the carrier billing model — each local wall-clock hour is a billing period charged as the larger of inbound and outbound in that hour (max(upload, download)), and billed usage is the sum over hours
  • Remote sync (optional): instead of a fixed local quota, keep a balance per user that is reconciled against the provider's traffic packages (currently Volcengine shared traffic packages), so the remaining traffic matches the provider console; new packages are credited to all users or to one user, and balances can be transferred between users (see "Remote sync" below)
  • Hard stop on quota exhaustion: new connections are rejected, in-flight connections are closed immediately, UDP packets are dropped; service resumes as soon as the quota is raised in the config (no restart needed)
  • Usage persistence (optional): with state_file configured, used traffic is stored in a SQLite database (flushed every 10 seconds by default and on exit), so counters survive restarts; without it, usage is kept in memory only and resets to zero on restart
  • Config auto-reload: edits to the config file are picked up automatically without a restart; an invalid config is rejected and the running one is kept (see "Config auto-reload" below)
  • Web panel (optional, off by default): a built-in dashboard at /dashboard shows usage, rules, and target health, and edits users, rules, and quotas; it can sit behind an entry token, a username and password, both, or neither when an authenticating proxy such as Cloudflare Access guards it (see "Web panel" below)
  • Query API: an HTTP interface returns each user's total/used/remaining traffic; compatible with Sub-Store (subscription-userinfo response header)

Build and run

cargo build --release
./target/release/ports-box -c /etc/ports-box/config.json -d /var/lib/ports-box
Option Description
-c, --config <FILE> Path to the config file, defaults to ./config.json; parsed as YAML when the extension is .yaml/.yml, otherwise as JSON
-d, --dir <DIR> Working directory, changed into at startup (relative paths in the config such as state_file.path are resolved against it)
--no-reload Do not watch the config file; changes then take effect only after a restart

The log level is controlled via RUST_LOG (default ports_box=info). On SIGTERM / SIGINT, usage is written to the database before exiting.

Every forwarded TCP connection holds two file descriptors, plus two more per direction that is actively moving data (the splice pipe, see "Performance"), and every UDP session one; at startup the process raises its soft open-file limit (RLIMIT_NOFILE) to the hard limit. The bundled systemd unit sets LimitNOFILE=1048576.

Docker image

The image is built by GitHub Actions and pushed to Docker Hub. The repository needs the following Secrets:

Secret Description
DOCKERHUB_USERNAME Docker Hub username
DOCKERHUB_TOKEN Docker Hub access token

After pushing to main / master, or manually running the Docker workflow, two tags are built and pushed:

<DOCKERHUB_USERNAME>/ports-box:<version from Cargo.toml>
<DOCKERHUB_USERNAME>/ports-box:latest

The current version number comes from package.version in Cargo.toml; when the workflow runs on a v* tag, the tag must match that version.

Docker Compose

First prepare the config file and data directory:

cp config.example.json config.json
mkdir -p data
sudo chown 10001:10001 data

The container runs as the unprivileged user ports-box (UID/GID 10001), so the data directory must be writable by that UID, otherwise state.db cannot be created. The binary carries the cap_net_bind_service file capability, so it can bind ports below 1024 even under host networking; if you run the container with --cap-drop ALL, add --cap-add NET_BIND_SERVICE back or the binary will fail to start.

Create compose.yaml:

services:
  ports-box:
    image: yuu518/ports-box:latest
    container_name: ports-box
    restart: unless-stopped
    network_mode: host
    environment:
      RUST_LOG: ports_box=info
    volumes:
      - ./config.json:/etc/ports-box/config.json:ro
      - ./data:/var/lib/ports-box
    command: ["-c", "/etc/ports-box/config.json", "-d", "/var/lib/ports-box"]

Start, follow logs, and stop:

docker compose up -d
docker compose logs -f
docker compose down

Restart after upgrading the image:

docker compose pull
docker compose up -d

network_mode: host suits Linux server deployments: the listen ports in the config bind directly on the host, so there is no need to write a ports mapping for every TCP/UDP rule. If you don't use host networking, every forwarding port and the API port must be mapped explicitly, for example:

ports:
  - "8080:8080/tcp"
  - "5353:5353/udp"
  - "7070:7070/tcp"

To build the image locally from source, replace image with:

build: .
image: ports-box:local

Configuration

Both JSON and YAML formats are supported, distinguished by file extension (.yaml/.yml for YAML, anything else for JSON), with identical fields. JSON is parsed as JSON5 (a superset of strict JSON): comments (//, /* */), trailing commas, unquoted keys, and single-quoted strings are all allowed.

Minimal config — single user, plain forwarding, no traffic limit: just write rules at the top level (internally equivalent to a user named default; mutually exclusive with users; if total_quota is set, it becomes that user's quota):

{
  "rules": [
    { "listen": "0.0.0.0:8080", "target": "10.0.0.2:80" },
    { "listen": "0.0.0.0:9000", "target": "192.168.1.5:9000", "protocol": "tcp" }
  ]
}

Full example:

{
  "state_file": {
    "enabled": true,
    "path": "state.db",
    "flush_secs": 10
  },
  "api": {
    "listen": "127.0.0.1:7070",
    "token": "changeme"
  },
  "panel": {
    "enabled": true,
    "listen": "127.0.0.1:8888",
    "token": "changeme",
    "username": "admin",
    "password": "changeme"
  },
  "total_quota": "100GB",
  "users": [
    {
      "name": "alice",
      "quota": "30GB",
      "rules": [
        { "listen": "0.0.0.0:8080", "target": "10.0.0.2:80", "fallback": "10.0.0.3:80", "tag": "web" },
        { "listen": "0.0.0.0:5353", "target": "10.0.0.2:53", "protocol": "udp" }
      ]
    },
    {
      "name": "bob",
      "rules": [
        { "listen": "0.0.0.0:9000", "target": "192.168.1.5:9000", "protocol": "tcp" },
        { "listen": "0.0.0.0:9001", "target": "192.168.1.5:9001", "enabled": false }
      ]
    }
  ]
}

The equivalent YAML (config.yaml):

state_file:
  enabled: true
  path: state.db
  flush_secs: 10
api:
  listen: 127.0.0.1:7070
  token: changeme
panel:
  enabled: true
  listen: 127.0.0.1:8888
  token: changeme
  username: admin
  password: changeme
total_quota: 100GB
users:
  - name: alice
    quota: 30GB
    rules:
      - listen: 0.0.0.0:8080
        target: 10.0.0.2:80
        fallback: 10.0.0.3:80
        tag: web
      - listen: 0.0.0.0:5353
        target: 10.0.0.2:53
        protocol: udp
  - name: bob
    rules:
      - listen: 0.0.0.0:9000
        target: 192.168.1.5:9000
        protocol: tcp
      - listen: 0.0.0.0:9001
        target: 192.168.1.5:9001
        enabled: false
Field Description
state_file Optional; omit the whole section to disable usage persistence (counters reset on restart). Subfields: enabled (default true, set false to disable temporarily), path (SQLite database path, default state.db, relative to the working directory), flush_secs (flush interval in seconds, default 10)
api Optional; omit to not start the query API. token is also optional; when set, every request must carry the token
panel Optional; the web panel only starts when enabled is explicitly true (default false). Subfields: listen (default 127.0.0.1:8888), token (entry token), username, password — all optional, but username and password go together — and path (where the panel stores its changes, default panel.json, relative to the working directory). See "Web panel" below
total_quota Optional; users without their own quota split this total evenly (offline accounting)
accounting Optional; how usage turns into limits. Subfields: mode (offline, the default, or remote), metering (max, the default, bills the larger direction of each hour; sum bills upload plus download; download bills only traffic sent back to clients) and remote (see "Remote sync" below)
rules Single-user shorthand: a top-level rule list, equivalent to a user named default; mutually exclusive with users. rules or users is required unless the panel is enabled
users[].quota Optional; this user's quota, taking precedence over the total_quota share. When neither quota nor total_quota is set, the user is unlimited. Offline accounting only
users[].packages Optional; traffic package ids credited to this user alone. Remote accounting only
rules[].listen Listen address (IP:port)
rules[].target Forwarding target (host:port, domain names supported — see "Domain name resolution" below)
rules[].fallback Optional; backup target(s), a single string or a list (in order as second, third priority, …); switches over automatically when target is unavailable and switches back on recovery
rules[].check_secs Optional, default 10; health check interval in seconds. Rules that include TCP probe each target with a TCP connection; udp rules cannot be probed, so a failed target instead cools down for this duration before being retried
rules[].protocol both (default, forwards TCP and UDP on the same port) / tcp / udp
rules[].enabled Default true; set false to disable the port
rules[].tag Optional label (e.g. "web") for annotating and categorizing rules

Traffic values can be written as integers (bytes) or strings: "500MB", "10GB", "1.5TB" (base 1024, case-insensitive).

Fallback behavior: targets are tried in priority order target → fallback[0] → fallback[1] …, and the first healthy one is used. A connection failure (including the 5-second timeout) immediately moves to the next target; once a higher-priority target recovers (detected by health checks), new connections automatically switch back — established TCP connections are not interrupted and finish naturally, while UDP sessions are actively terminated so the client's next packet goes back to the primary target. When all targets are down, the primary target keeps being retried. Pure udp rules cannot be probed (the target may not listen on TCP), so they fall back to a passive mode: a failed target cools down for check_secs seconds and is retried by new sessions, making the switch-back granularity roughly equal to that cooldown. Health checks for all rules run in parallel, with at most 16 probes in flight at once.

UDP sessions: each client address gets its own upstream session, closed after 60 seconds without traffic. Sessions are established in the background, so a slow DNS lookup or dead target never delays other clients; packets arriving meanwhile are queued (up to 32) and sent in order once connected. Each listen address keeps at most 4096 concurrent sessions; packets from new clients beyond that are dropped.

{ "listen": "0.0.0.0:8080", "target": "10.0.0.2:80", "fallback": ["10.0.0.3:80", "10.0.0.4:80"] }

Domain name resolution: the host part of target / fallback may be a domain name, resolved on every new TCP connection, UDP session, and health check. A built-in resolver reads the host's DNS configuration (nameservers from /etc/resolv.conf and /etc/hosts), with no glibc dependency — it works the same in musl static builds. Results are cached according to the DNS record's TTL: repeated lookups within the TTL hit the cache, and expired entries are re-queried automatically — after a domain's records change, new connections/sessions use the new address once the old TTL expires, no restart needed; established connections are unaffected and finish naturally. IP literals (including IPv6 in the [::1]:80 form) bypass DNS. Invalid domain names or ports are reported as errors at startup.

Quota changes (including adding traffic) take effect as soon as the config file is saved (see "Config auto-reload"); used traffic is kept. With state_file enabled, used traffic is also restored from the database after a restart, so restarting does not reset the counters.

Remote sync

Offline accounting compares lifetime usage with a fixed total_quota. When the provider sells traffic as packages that never reset, that drifts away from the console: packages are bought and expire, the provider may bill a relay differently from what ports-box measures, and other resources in the region draw from the same packages. Remote accounting fixes this by keeping a balance per user and reconciling it with the provider on every sync.

"accounting": {
  "mode": "remote",
  "metering": "sum",
  "remote": {
    "provider": "volcengine",
    "access_key": "AK...",
    "secret_key": "SK...",
    "regions": ["cn-shanghai"],
    "interval_secs": 600,
    "packages": ["tfp-aaaa"]
  }
},
"users": [
  { "name": "eric", "packages": ["tfp-bbbb"], "rules": [ ... ] }
]
Field Description
provider volcengine (shared traffic packages, read through the billing API ListResourcePackages)
access_key, secret_key Required in remote mode. Use a sub-account key that can only read billing
regions Required in remote mode. Only packages whose region is listed are counted; packages elsewhere are reported in the panel and ignored
interval_secs Default 600, at least 60; a failed sync is retried after a minute
packages Package ids split evenly among all users when they are credited

How a sync works:

  • First sync (migration). Every package that exists at that moment is marked as already counted, and each user's opening balance is their offline remaining traffic scaled so that the balances add up to the provider's remaining traffic. Migration waits until at least one user exists; until the first sync succeeds, offline limits stay in effect.
  • New packages are credited once, only if listed. A package listed under remote.packages is split evenly among the current users; a package listed under a user's packages goes to that user in full. Unlisted packages are shown as unallocated until you list them. Listing a package again, moving it, or removing it after it was credited changes nothing; transfer balances instead.
  • Single-user mode needs no lists. With top-level rules (or single-user mode in the panel), every package in the configured regions is credited to the one user automatically, and every sync settles any difference into that user, so the balance always equals the provider's remaining traffic.
  • Consumption is calibrated. The drop in the provider's remaining traffic since the last sync is charged to users in proportion to the traffic ports-box metered for each of them, so the balances keep adding up to the console. If nothing was metered, the drop is not charged and shows up as negative unallocated traffic.
  • Expired leftovers are forfeited by balance. The provider drains packages in expiry order across the whole region, so a package's leftover at expiry cannot be traced to a user; it is taken from users in proportion to their balances.
  • Limits between syncs. Each user may use their balance as of the last sync; local metering stops them in real time, and the next sync corrects the difference. A user with no balance (for example one just added) is stopped until they receive some.
  • Transfers. The panel moves balance between users; a user can only give what they have left.
  • Allocating unallocated traffic. When the provider holds more than the balances add up to (an unlisted package, or a user added after migration), the overview offers to split the unallocated traffic among all users or give it to one, in full or in part.

Balances, package snapshots, and a ledger of every credit, transfer, and forfeit are kept in state_file. Without it they live in memory and the next start migrates again. Switching back to offline uses total_quota and quota again; the ledger is kept and resumes when remote mode is turned back on.

Config auto-reload

The config file is checked every 3 seconds; when its content changes (and stays the same for another 0.5 seconds, so a half-written file is never picked up), it is reloaded without a restart:

  • The new config is fully parsed and validated, and every newly needed port is bound, before anything changes. If any step fails (syntax error, invalid field, duplicate listen address, port already in use, …), the reload is rejected with an ERROR log line and the running config stays in effect. Fixing the file triggers the next reload automatically.
  • Unchanged rules keep running untouched, including their established connections.
  • Removed or disabled rules stop listening, and their TCP connections and UDP sessions are closed.
  • A changed rule (different target, fallback, protocol, check_secs, or owner) is restarted: its existing connections are closed and new ones use the new settings. The listening socket is handed over, not rebound, so the port never goes away.
  • Quota changes (quota, total_quota) apply immediately and keep used traffic: raising a quota re-enables an exhausted user, lowering it below the used amount stops that user's traffic at once.
  • accounting changes apply immediately; a change to the remote settings or to any package list triggers a sync right away.
  • New users start from the usage stored in state_file (if any); removed users have their usage flushed to it first.
  • Changes to api, panel, and state_file are not applied live; a warning is logged and they take effect after a restart.

With Docker, a single-file bind mount (./config.json:/etc/ports-box/config.json) only sees edits that overwrite the file in place (e.g. cp new.json config.json); editors that save by writing a new file and renaming it replace the host file, which the container no longer sees. Mount the directory instead if you edit the config that way. Pass --no-reload to turn auto-reload off.

Web panel

The panel is off unless the config says "panel": { "enabled": true, ... }. It listens on 127.0.0.1:8888 by default and can use a token, a username and password, both, or neither; startup fails if only one of username and password is set. With neither, anyone who can reach the panel can change users and rules, so only do this behind an authenticating proxy such as Cloudflare Zero Trust (Access); a warning is logged at startup.

  1. With a token, open http://127.0.0.1:8888/?token=<token>. A correct token redirects to /dashboard; without it every path on the panel port answers 404, including /dashboard and the sign-in endpoint. Without a token, open http://127.0.0.1:8888/dashboard directly.
  2. With a username and password, sign in with them. With a token alone, the token link signs you in. With neither, the dashboard opens straight away and has no sign-out button.
  3. For the next 7 days the browser can open /dashboard directly. Sessions live in memory, so a restart requires the token link or a new sign-in.

Overview shows each user's quota, billed usage, current-hour usage, and raw upload/download, plus every rule with its targets: which one is in use, which are on standby, and which are down. It refreshes every 3 seconds. In remote mode it also shows the provider's remaining traffic, the sum of balances, unallocated traffic, the last sync and its result, a Sync now button, and a form to transfer balance between users; each user shows their balance instead of a quota.

Traffic packages lists the packages in the configured regions after a sync, with their remaining traffic, expiry, status, and how they were credited. An uncredited package can be split among all users or given to one user from here, which adds it to the matching list and syncs at once.

Ledger lists opening balances, credited packages, forfeited leftovers, and transfers, filterable by user.

Settings starts with the User mode: Multiple users or Single user (exclusive). In single-user mode all rules are owned by one implicit user (named default when created here), so total_quota or the traffic packages cover the whole server. This is the same as writing top-level rules in the config file, which opens in single-user mode; switching to it requires keeping at most one user. The panel is simplified to match: the tabs are Overview, Traffic packages, Rules, and Settings (no Ledger), the overview shows the provider's remaining traffic and the rules without a user name, transfers and allocation are hidden, and packages are credited automatically.

The rest of Settings edits accounting and total_quota: the accounting mode, metering, and the remote provider, keys, regions, interval, and evenly split packages. The secret key is never sent back to the browser; leave it empty to keep the saved one. Test connection queries the provider with the values in the form and changes nothing. Changes to the provider, keys, or regions, and switching to remote mode, can only be saved after a successful test with exactly those values: the remote sync section's Save button stays grey until then, and so does the main save button. The evenly split packages are picked from a dropdown of uncredited packages (a whitelist); a user's own packages are picked the same way under Users and rules, and a package already given to someone else cannot be picked twice. In single-user mode no list is needed.

Users and rules (Rules in single-user mode) edits users, quotas, own packages, and rules; in single-user mode it is just a list of rules. Saving validates the result, binds any new ports, and applies it immediately (it works with --no-reload too); if anything fails, nothing changes and the error is shown. Things to know:

  • With the panel enabled, the config file may leave out users and rules entirely: the process starts with nothing forwarded, and users and rules are added from the panel.
  • Saving never touches the config file. The panel keeps its changes in its own store, panel.path (default panel.json, relative to the working directory), and they survive restarts. The store holds the remote secret key in plain text; on Unix it is written with mode 0600.
  • Editing the config file takes over again. Whoever changed things last wins: as soon as the config file's content changes — while running, or while the process was stopped — the file is used as written, the panel's saved changes are dropped, and panel.json is deleted. Any change to the file counts, even one outside users, total_quota, and accounting.
  • If a changed config file is rejected (syntax error, port in use, …), the running config, including the panel's changes, stays in effect until the file is fixed.
  • The api, state_file, and panel sections always come from the config file and cannot be edited from the panel.
  • The working directory must be writable (as it already is for state.db); the config file itself can stay read-only, so a Docker :ro mount keeps working. Without host networking, set panel.listen to 0.0.0.0:8888 and map the port.

The panel speaks plain HTTP and the token and password are stored in the config file as written. To reach it from another machine, use an SSH tunnel or put it behind an HTTPS reverse proxy; a warning is logged when it listens on a non-loopback address.

Query API

The token is carried via the Authorization: Bearer <token> header or the ?token=<token> query parameter. If the API listens on a non-loopback address without a token, a warning is logged at startup.

Endpoint Description
GET /api/users Usage for all users
GET /api/users/{name} Usage for a single user
GET /sub/{name} Sub-Store-compatible endpoint
$ curl "http://127.0.0.1:7070/api/users/alice?token=changeme"
{"name":"alice","total":"30.00GB","used":"1.00MB","hour_used":"120.00KB","remaining":"29.99GB"}

used is the billed total (sum of each hour's larger direction); hour_used is the current hour's billed traffic so far.

For unlimited users, total / remaining return "unlimited"; the Sub-Store endpoint omits the total= field.

Sub-Store usage: use http://<host>:7070/sub/alice?token=changeme as the subscription URL; Sub-Store reads traffic information from the subscription-userinfo: upload=…; download=…; total=… response header. Sub-Store treats upload + download as used traffic, so the endpoint reports the billed usage split between the two directions in proportion to the raw traffic: upload + download always equals used, and the remaining amount Sub-Store shows matches the API.

Deploying to Linux (/opt/forwarder)

Cross-compile a fully static Linux binary on Windows/macOS (requires zig):

rustup target add x86_64-unknown-linux-musl
cargo install cargo-zigbuild
cargo zigbuild --release --target x86_64-unknown-linux-musl
# Output: target/x86_64-unknown-linux-musl/release/ports-box

On Linux, a plain cargo build --release works. Copy the binary and config to the server:

scp target/x86_64-unknown-linux-musl/release/ports-box root@server:/opt/forwarder/
scp config.json root@server:/opt/forwarder/
scp deploy/ports-box.service root@server:/etc/systemd/system/

Enable it on the server (see deploy/ports-box.service for the systemd unit; the working directory is /opt/forwarder, and state.db lives there too):

chmod +x /opt/forwarder/ports-box
systemctl daemon-reload
systemctl enable --now ports-box
systemctl status ports-box      # check status
journalctl -u ports-box -f      # follow logs

Config changes (rules, quotas) are applied automatically, see "Config auto-reload"; changes to api / panel / state_file need systemctl restart ports-box; stopping/restarting writes usage to state.db first, so no counters are lost.

Performance

On Linux the data path uses kernel features while keeping byte-exact accounting and the instant hard stop:

  • TCP zero-copy: data moves socket → pipe → socket with splice(2) and never enters user space. A pipe is borrowed only while a direction is moving data and returned to a small per-thread pool when it goes idle or the connection ends, so idle connections hold none. A direction that keeps the pipe busy grows it from the default 64 KiB to 256 KiB, so bulk transfers need fewer system calls while light connections stay small. When no pipe of at least 64 KiB can be created (for example once the process user passes fs.pipe-user-pages-soft), that direction falls back to a plain 64 KiB buffer copy.
  • UDP on every core: each UDP listen port opens one socket per CPU (up to 8) with SO_REUSEPORT; the kernel hashes each client to a fixed socket, so every socket keeps its own sessions without lock contention. A side effect is that a second ports-box process running as the same user can bind the same UDP port and silently share its traffic instead of failing with "address in use".
  • UDP batching: packets are received in batches of up to 16 (recvmmsg) with UDP GRO, and coalesced packets are sent back out with UDP GSO, keeping the original datagram boundaries; if the NIC or path rejects GSO, the packets are sent one by one. IP fragmentation behaviour is left at the kernel default.
  • Socket buffers: UDP sockets ask for 4 MiB send and receive buffers; the kernel caps the request at net.core.wmem_max / net.core.rmem_max.

Suggested sysctls for high-traffic hosts:

net.core.default_qdisc = fq
net.ipv4.tcp_congestion_control = bbr
net.core.rmem_max = 4194304
net.core.wmem_max = 4194304
net.ipv4.tcp_rmem = 4096 131072 33554432
net.ipv4.tcp_wmem = 4096 65536 33554432
net.core.netdev_max_backlog = 16384
net.core.somaxconn = 4096

Other platforms use the same code paths with a buffer copy for TCP and a single UDP socket per port.


🤖 AI-Assisted Development

This project is an exploration of AI's project-level coding capabilities. Code generated using Claude Code(Fable 5) models via Visual Studio Code.

About

No description, website, or topics provided.

Resources

Stars

9 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages