mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[PR #3958] [CLOSED] fix: prevent multi-GB traffic overages after bandwidth limit is reached #5568
Labels
No labels
backlog
bug
clarification needed
documentation
duplicate
enhancement
github_actions
good first issue
invalid
javascript
New Feature
PR welcomed
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
MHSanaei/3x-ui#5568
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 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)
bef6b45fix: prevent multi-GB traffic overages after bandwidth limit is reached44ec6cfMerge branch 'main' into fix/traffic-overage-enforcement1bafa1ffix0c037beMerge 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 andRemoveUser()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=trueis 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— NewFlushTrafficToDB()method that fetches current Xray stats and persists them viainboundService.AddTraffic().web/web.go— CallFlushTrafficToDB()inside the 30 s restart cron beforeRestartXray(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— NewDrainUserTraffic(email)method that callsGetStatswithReset_: truefor bothuser>>>email>>>traffic>>>uplinkand>>>downlink, capturing bytes accumulated since the last bulk reset.web/service/inbound.godisableInvalidClients()— After a successfulRemoveUser(), callsDrainUserTrafficand adds the delta to the client's DB row withgorm.Expr("up + ?", ...).Fix 3 — iptables DROP block for active TCP connections (Bucket B)
util/iptables/iptables.go(new) — Utility package managing a dedicated3X-UI-BLOCKiptables chain:EnsureChain()— creates the chain and adds a jump fromINPUT(idempotent)FlushChain()— removes all rules (used on startup)BlockIP(ip, port)— inserts a DROP rule with a3xui:block:<timestamp>commentUnblockIP(ip, port)— removes the DROP ruleListRules()— parsesiptables -S 3X-UI-BLOCKinto structuredRuleEntryvaluesAll rules are isolated to the custom chain — no OS/admin rules are touched. If
iptablesis not available, functions log a warning and return gracefully.web/job/unblock_ips_job.go(new) — Background job scheduled@every 5mthat enumerates rules in3X-UI-BLOCKand removes any older thanmaxBlockAgeSecs(10 minutes).web/service/inbound.go— Two helpers:blockClientIPs(email)— reads known IPs frominbound_client_ips, gets the inbound port, callsiptables.BlockIPfor each IP. Called after a successfulRemoveUser()indisableInvalidClients().unblockClientIPs(email)— mirror of the above usingiptables.UnblockIP. Called after a successfulAddUser()inautoRenewClients()so renewed clients can reconnect.web/web.go— On startup callsiptables.EnsureChain()theniptables.FlushChain()to initialize the chain and clear any stale rules from a prior crash. RegistersNewUnblockIPsJob()at@every 5m.Testing
client_traffics.enable = 0in DBiptables -L 3X-UI-BLOCK -nshows DROP rules for the client's IPs on the inbound portRemoveUser()gRPC failure → verifyclient_trafficstotals are accurate after the subsequent Xray restart (no bytes permanently lost).Notes
iptablesto 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.ip6tables) can be added as a follow-up.maxBlockAgeSecsconstant inunblock_ips_job.gocontrols the auto-expiry window (default: 10 minutes).🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.