[PR #3958] [CLOSED] fix: prevent multi-GB traffic overages after bandwidth limit is reached #5568

Closed
opened 2026-10-31 20:47:53 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/3958
Author: @WatchDogsDev
Created: 3/22/2026
Status: ❌ Closed

Base: main ← Head: fix/traffic-overage-enforcement


📝 Commits (4)

  • bef6b45 fix: prevent multi-GB traffic overages after bandwidth limit is reached
  • 44ec6cf Merge branch 'main' into fix/traffic-overage-enforcement
  • 1bafa1f fix
  • 0c037be Merge branch 'main' into fix/traffic-overage-enforcement

📊 Changes

6 files changed (+371 additions, -6 deletions)

View changed files

➕ util/iptables/iptables.go (+209 -0)
➕ web/job/unblock_ips_job.go (+40 -0)
📝 web/service/inbound.go (+72 -6)
📝 web/service/xray.go (+13 -0)
📝 web/web.go (+15 -0)
📝 xray/api.go (+22 -0)

📄 Description

Problem

When a client exceeds their bandwidth limit, the 10-second traffic check job often fails to stop them in time. Clients can overshoot their limit by 10 GB or more. There are three distinct causes:

Bucket A — in-flight gap (~10 s of traffic):
Between GetTraffic(reset=true) zeroing the Xray counter and RemoveUser() taking effect, the client keeps generating traffic. Those bytes land in the freshly-zeroed counter and are counted one cycle late — a minor but real overage.

Bucket B — active TCP connections survive removal (primary cause of multi-GB overages):
RemoveUser() removes the client from Xray's auth table but does not close existing established connections. A mid-download client on a persistent TLS tunnel keeps transferring until the connection closes naturally.

Bucket C — restart race (catastrophic, permanent data loss):
When RemoveUser() fails, needRestart=true is set and Xray restarts up to 30 seconds later. On restart all in-memory stats counters are zeroed — bytes transferred during that window are permanently lost and never credited to the client.


Changes

Fix 1 — Flush traffic to DB before Xray restart (Bucket C)

web/service/xray.go — New FlushTrafficToDB() method that fetches current Xray stats and persists them via inboundService.AddTraffic().

web/web.go — Call FlushTrafficToDB() inside the 30 s restart cron before RestartXray(false), so in-memory counters are saved before Xray zeros them.

Fix 2 — Drain residual per-user traffic after RemoveUser (Bucket A)

xray/api.go — New DrainUserTraffic(email) method that calls GetStats with Reset_: true for both user>>>email>>>traffic>>>uplink and >>>downlink, capturing bytes accumulated since the last bulk reset.

web/service/inbound.go disableInvalidClients() — After a successful RemoveUser(), calls DrainUserTraffic and adds the delta to the client's DB row with gorm.Expr("up + ?", ...).

Fix 3 — iptables DROP block for active TCP connections (Bucket B)

util/iptables/iptables.go (new) — Utility package managing a dedicated 3X-UI-BLOCK iptables chain:

  • EnsureChain() — creates the chain and adds a jump from INPUT (idempotent)
  • FlushChain() — removes all rules (used on startup)
  • BlockIP(ip, port) — inserts a DROP rule with a 3xui:block:<timestamp> comment
  • UnblockIP(ip, port) — removes the DROP rule
  • ListRules() — parses iptables -S 3X-UI-BLOCK into structured RuleEntry values

All rules are isolated to the custom chain — no OS/admin rules are touched. If iptables is not available, functions log a warning and return gracefully.

web/job/unblock_ips_job.go (new) — Background job scheduled @every 5m that enumerates rules in 3X-UI-BLOCK and removes any older than maxBlockAgeSecs (10 minutes).

web/service/inbound.go — Two helpers:

  • blockClientIPs(email) — reads known IPs from inbound_client_ips, gets the inbound port, calls iptables.BlockIP for each IP. Called after a successful RemoveUser() in disableInvalidClients().
  • unblockClientIPs(email) — mirror of the above using iptables.UnblockIP. Called after a successful AddUser() in autoRenewClients() so renewed clients can reconnect.

web/web.go — On startup calls iptables.EnsureChain() then iptables.FlushChain() to initialize the chain and clear any stale rules from a prior crash. Registers NewUnblockIPsJob() at @every 5m.


Testing

  1. Create a client with a small total limit (e.g. 50 MB).
  2. Start a large download through that client.
  3. Within one 10-second cycle of hitting the limit, verify:
    • client_traffics.enable = 0 in DB
    • iptables -L 3X-UI-BLOCK -n shows DROP rules for the client's IPs on the inbound port
    • Download stalls / connection is dropped
  4. Reset or renew the client:
    • Verify iptables rules are removed
    • Verify the client can reconnect
  5. Simulate a RemoveUser() gRPC failure → verify client_traffics totals are accurate after the subsequent Xray restart (no bytes permanently lost).

Notes

  • Requires iptables to be available on the host (standard on all Linux distributions used with 3x-ui). Absence is handled gracefully — normal disable logic continues, only the IP block step is skipped with a warning log.
  • IPv6 support (ip6tables) can be added as a follow-up.
  • The maxBlockAgeSecs constant in unblock_ips_job.go controls the auto-expiry window (default: 10 minutes).

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/MHSanaei/3x-ui/pull/3958 **Author:** [@WatchDogsDev](https://github.com/WatchDogsDev) **Created:** 3/22/2026 **Status:** ❌ Closed **Base:** `main` ← **Head:** `fix/traffic-overage-enforcement` --- ### 📝 Commits (4) - [`bef6b45`](https://github.com/MHSanaei/3x-ui/commit/bef6b45848ea5a07148e4c108b6b169f31d5531b) fix: prevent multi-GB traffic overages after bandwidth limit is reached - [`44ec6cf`](https://github.com/MHSanaei/3x-ui/commit/44ec6cf04c651cd8c8dcfc11ce76403344aa9885) Merge branch 'main' into fix/traffic-overage-enforcement - [`1bafa1f`](https://github.com/MHSanaei/3x-ui/commit/1bafa1fc3759762e0920056cdc91ae97e0a49d1f) fix - [`0c037be`](https://github.com/MHSanaei/3x-ui/commit/0c037be40a0752e5890a6a1e46be3be4a78c67ae) Merge branch 'main' into fix/traffic-overage-enforcement ### 📊 Changes **6 files changed** (+371 additions, -6 deletions) <details> <summary>View changed files</summary> ➕ `util/iptables/iptables.go` (+209 -0) ➕ `web/job/unblock_ips_job.go` (+40 -0) 📝 `web/service/inbound.go` (+72 -6) 📝 `web/service/xray.go` (+13 -0) 📝 `web/web.go` (+15 -0) 📝 `xray/api.go` (+22 -0) </details> ### 📄 Description ## Problem When a client exceeds their bandwidth limit, the 10-second traffic check job often fails to stop them in time. Clients can overshoot their limit by 10 GB or more. There are three distinct causes: **Bucket A — in-flight gap (~10 s of traffic):** Between `GetTraffic(reset=true)` zeroing the Xray counter and `RemoveUser()` taking effect, the client keeps generating traffic. Those bytes land in the freshly-zeroed counter and are counted one cycle late — a minor but real overage. **Bucket B — active TCP connections survive removal (primary cause of multi-GB overages):** `RemoveUser()` removes the client from Xray's auth table but does **not** close existing established connections. A mid-download client on a persistent TLS tunnel keeps transferring until the connection closes naturally. **Bucket C — restart race (catastrophic, permanent data loss):** When `RemoveUser()` fails, `needRestart=true` is set and Xray restarts up to 30 seconds later. On restart all in-memory stats counters are zeroed — bytes transferred during that window are **permanently lost** and never credited to the client. --- ## Changes ### Fix 1 — Flush traffic to DB before Xray restart (Bucket C) **`web/service/xray.go`** — New `FlushTrafficToDB()` method that fetches current Xray stats and persists them via `inboundService.AddTraffic()`. **`web/web.go`** — Call `FlushTrafficToDB()` inside the 30 s restart cron before `RestartXray(false)`, so in-memory counters are saved before Xray zeros them. ### Fix 2 — Drain residual per-user traffic after RemoveUser (Bucket A) **`xray/api.go`** — New `DrainUserTraffic(email)` method that calls `GetStats` with `Reset_: true` for both `user>>>email>>>traffic>>>uplink` and `>>>downlink`, capturing bytes accumulated since the last bulk reset. **`web/service/inbound.go`** `disableInvalidClients()` — After a successful `RemoveUser()`, calls `DrainUserTraffic` and adds the delta to the client's DB row with `gorm.Expr("up + ?", ...)`. ### Fix 3 — iptables DROP block for active TCP connections (Bucket B) **`util/iptables/iptables.go`** (new) — Utility package managing a dedicated `3X-UI-BLOCK` iptables chain: - `EnsureChain()` — creates the chain and adds a jump from `INPUT` (idempotent) - `FlushChain()` — removes all rules (used on startup) - `BlockIP(ip, port)` — inserts a DROP rule with a `3xui:block:<timestamp>` comment - `UnblockIP(ip, port)` — removes the DROP rule - `ListRules()` — parses `iptables -S 3X-UI-BLOCK` into structured `RuleEntry` values All rules are isolated to the custom chain — no OS/admin rules are touched. If `iptables` is not available, functions log a warning and return gracefully. **`web/job/unblock_ips_job.go`** (new) — Background job scheduled `@every 5m` that enumerates rules in `3X-UI-BLOCK` and removes any older than `maxBlockAgeSecs` (10 minutes). **`web/service/inbound.go`** — Two helpers: - `blockClientIPs(email)` — reads known IPs from `inbound_client_ips`, gets the inbound port, calls `iptables.BlockIP` for each IP. Called after a successful `RemoveUser()` in `disableInvalidClients()`. - `unblockClientIPs(email)` — mirror of the above using `iptables.UnblockIP`. Called after a successful `AddUser()` in `autoRenewClients()` so renewed clients can reconnect. **`web/web.go`** — On startup calls `iptables.EnsureChain()` then `iptables.FlushChain()` to initialize the chain and clear any stale rules from a prior crash. Registers `NewUnblockIPsJob()` at `@every 5m`. --- ## Testing 1. Create a client with a small total limit (e.g. 50 MB). 2. Start a large download through that client. 3. Within one 10-second cycle of hitting the limit, verify: - `client_traffics.enable = 0` in DB - `iptables -L 3X-UI-BLOCK -n` shows DROP rules for the client's IPs on the inbound port - Download stalls / connection is dropped 4. Reset or renew the client: - Verify iptables rules are removed - Verify the client can reconnect 5. Simulate a `RemoveUser()` gRPC failure → verify `client_traffics` totals are accurate after the subsequent Xray restart (no bytes permanently lost). --- ## Notes - Requires `iptables` to be available on the host (standard on all Linux distributions used with 3x-ui). Absence is handled gracefully — normal disable logic continues, only the IP block step is skipped with a warning log. - IPv6 support (`ip6tables`) can be added as a follow-up. - The `maxBlockAgeSecs` constant in `unblock_ips_job.go` controls the auto-expiry window (default: 10 minutes). --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-31 20:47:53 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#5568
No description provided.