[PR #6547] [MERGED] fix(xray): refuse a config the running core cannot bind #6345

Closed
opened 2026-11-02 04:08:05 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/MHSanaei/3x-ui/pull/6547
Author: @BlindMaster24
Created: 9/15/2026
Status: ✅ Merged
Merged: 9/15/2026
Merged by: @BlindMaster24

Base: main ← Head: fix/xray-refuse-config-with-duplicate-binds


📝 Commits (2)

  • 8e50b2c fix(xray): refuse a config the running core cannot bind
  • a4f32ca fix(xray): surface a refused config and re-key the bind excuse set

📊 Changes

5 files changed (+431 additions, -2 deletions)

View changed files

📝 frontend/src/pages/index/OverviewActionBar.tsx (+7 -1)
📝 internal/web/service/server.go (+3 -1)
📝 internal/web/service/xray.go (+37 -0)
➕ internal/web/service/xray_bind_conflict.go (+147 -0)
➕ internal/web/service/xray_bind_conflict_test.go (+237 -0)

📄 Description

What breaks today

XrayService.RestartXray hands the newly generated config to the core after stopping the working one:

_ = process.Stop()          // xray.go:1381
process = xray.NewProcess(xrayConfig)
err = process.Start()       // xray.go:1401

If any inbound in that config cannot bind its listen, the core does not skip that inbound — it exits the whole process (main/run.go:94 → os.Exit(-1) after Failed to start). CheckXrayRunningJob then runs every second and restarts Xray on the same config, so the panel settles into a ~3-second spawn-crash loop: every protocol on the host is dead (not just the colliding one) while the cause stays in the logs.

The save-time port guards cannot cover this. They run on inbound save, and several paths reach a colliding config without one:

  • SetInboundEnable flips enable with no port check at all;
  • adding a client to an AmneziaWG inbound creates its Xray-side relay inbound (a loopback port derived from the row id) with no port check on that path;
  • editing the config template, an egress bridge, or any future generator has the same shape.

This is the same family as #6537/#6539/#6540/#6542/#6544, which each closed one path. This one closes the funnel: every state-changing op goes through RestartXray (runtime/local.go:336), and process.Start() exists nowhere else in the service layer (verified by grep).

The rule

bindConflicts(newCfg, runningCfg) reports two inbounds that would bind one socket: same port, overlapping listens (listenOverlaps, so 0.0.0.0/empty/:: count as wildcard) and a shared transport. vless/tcp + hysteria2/udp on one port is a supported deployment and is already pinned by tests — so the check is transport-aware and reuses inboundTransports, the exact rule the save-time guards use.

Two decisions worth your eye:

1. It refuses only when a working core is being replaced. With nothing running, the config is started and the core's own error names the port (logger.Warning). Refusing there would let a wrong static read leave the panel with no core at all, which is worse than the loop it removes.

2. A collision the running core already serves is excused. The running config is proof of what the core can bind: if two tags collide in the new config and collided in the config this process is serving right now, they demonstrably bind and the pair is not reported. This is what makes the guard safe to put on the synchronization path — a config that works today can never be refused by a static analysis being wrong about it. Only a collision the running config does not have is refused.

Rejected: making the "restart Xray" button bypass the check. That would re-open the exact loop the change removes, and the error message already names both tags and the port, which is what an operator needs to fix it.

Speed on the sync path

The probe buckets inbounds by port first, so transports are parsed only for a port two inbounds share — a clean config does zero JSON unmarshals beyond the listen fields, and the running-config pass only runs when the new config actually produced a collision.

Measured on a 500-inbound config (ad-hoc benchmark, not committed):

BenchmarkBindConflictsClean-12        500    44122 ns/op   45757 B/op    508 allocs/op
BenchmarkBindConflictsColliding-12    500    98097 ns/op   93472 B/op   1060 allocs/op

~44 µs against GetXrayConfig()'s own per-restart work (template parse + DB rows + injectors), and the excuse rule costs nothing on a config that has no collision.

Red first, with the exact output

1. The transport rule — probe: treat any same-port overlap as a clash. Exactly the three coexistence cases fail, nothing else:

--- FAIL: TestBindConflicts/tcp_and_udp_on_one_port_are_legal
--- FAIL: TestBindConflicts/kcp_moves_vless_to_udp_and_frees_the_port
--- FAIL: TestBindConflicts/socks_bridge_without_udp_coexists_with_a_udp_inbound

2. The excuse rule — probe: report raw collisions. Exactly the two "already running" cases fail:

--- FAIL: TestBindConflicts/collision_the_running_config_already_serves
--- FAIL: TestBindConflicts_GeneratedConfig/already_running_config

3. The relay's own shape. The relay is emitted as protocol: "socks" with settings.udp = true (xray.go:768-775, SocksInboundSettings), which inboundTransports does not model for a bare "socks" — the probe maps it onto the mixed shape so its UDP bit is not lost. Probe: drop that mapping and only this case fails:

--- FAIL: TestBindConflicts/amneziawg_relay_against_a_udp_inbound

4. The probe reads real generated configs, not fixtures. TestBindConflicts_GeneratedConfig seeds an AmneziaWG row with one qualifying peer plus a user inbound written straight to the DB on the derived relay port — the path the save-time guards cannot see — then calls GetXrayConfig() and asserts the refusal names awg-1, user and 65101, that the same config is excused when it is the running one, and that a free port stays clean. This one pins the real emitted shape and the derived port; the two probes above are what prove the rule it applies.

Gate

  • go test ./internal/web/service -shuffle=on — green, 196 s, all DB-backed tests included (local run with a pure-Go SQLite driver via -overlay; the tree's own go.mod/go.sum are unchanged).
  • gofmt -l and go vet on the package — clean.
  • CI: go-test, golangci, race on this head.

Unverified here: PostgreSQL and the Xray gRPC end-to-end tests (XUI_TEST_PG_DSN, XRAY_E2E_BINARY are unset). The guard's call site in RestartXray is one line at a single funnel and is not covered by a test — it cannot be exercised without a real core process, so it is verified by reading; the decision it makes is what the tests above cover.


🔄 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/6547 **Author:** [@BlindMaster24](https://github.com/BlindMaster24) **Created:** 9/15/2026 **Status:** ✅ Merged **Merged:** 9/15/2026 **Merged by:** [@BlindMaster24](https://github.com/BlindMaster24) **Base:** `main` ← **Head:** `fix/xray-refuse-config-with-duplicate-binds` --- ### 📝 Commits (2) - [`8e50b2c`](https://github.com/MHSanaei/3x-ui/commit/8e50b2ca1a0bdc91b469a57291149a5fabdbe1f2) fix(xray): refuse a config the running core cannot bind - [`a4f32ca`](https://github.com/MHSanaei/3x-ui/commit/a4f32ca1bc97e3bfa955c0ff7819089ede6b9bed) fix(xray): surface a refused config and re-key the bind excuse set ### 📊 Changes **5 files changed** (+431 additions, -2 deletions) <details> <summary>View changed files</summary> 📝 `frontend/src/pages/index/OverviewActionBar.tsx` (+7 -1) 📝 `internal/web/service/server.go` (+3 -1) 📝 `internal/web/service/xray.go` (+37 -0) ➕ `internal/web/service/xray_bind_conflict.go` (+147 -0) ➕ `internal/web/service/xray_bind_conflict_test.go` (+237 -0) </details> ### 📄 Description ## What breaks today `XrayService.RestartXray` hands the newly generated config to the core *after* stopping the working one: ```go _ = process.Stop() // xray.go:1381 process = xray.NewProcess(xrayConfig) err = process.Start() // xray.go:1401 ``` If any inbound in that config cannot bind its listen, the core does not skip that inbound — it exits the whole process (`main/run.go:94` → `os.Exit(-1)` after `Failed to start`). `CheckXrayRunningJob` then runs every second and restarts Xray on the same config, so the panel settles into a ~3-second spawn-crash loop: every protocol on the host is dead (not just the colliding one) while the cause stays in the logs. The save-time port guards cannot cover this. They run on inbound *save*, and several paths reach a colliding config without one: * `SetInboundEnable` flips `enable` with no port check at all; * adding a client to an AmneziaWG inbound creates its Xray-side relay inbound (a loopback port derived from the row id) with no port check on that path; * editing the config template, an egress bridge, or any future generator has the same shape. This is the same family as #6537/#6539/#6540/#6542/#6544, which each closed one *path*. This one closes the **funnel**: every state-changing op goes through `RestartXray` (`runtime/local.go:336`), and `process.Start()` exists nowhere else in the service layer (verified by grep). ## The rule `bindConflicts(newCfg, runningCfg)` reports two inbounds that would bind one socket: same port, overlapping listens (`listenOverlaps`, so `0.0.0.0`/empty/`::` count as wildcard) **and** a shared transport. `vless/tcp` + `hysteria2/udp` on one port is a supported deployment and is already pinned by tests — so the check is transport-aware and reuses `inboundTransports`, the exact rule the save-time guards use. Two decisions worth your eye: **1. It refuses only when a working core is being replaced.** With nothing running, the config is started and the core's own error names the port (`logger.Warning`). Refusing there would let a wrong static read leave the panel with no core at all, which is worse than the loop it removes. **2. A collision the running core already serves is excused.** The running config is proof of what the core can bind: if two tags collide in the new config *and* collided in the config this process is serving right now, they demonstrably bind and the pair is not reported. This is what makes the guard safe to put on the synchronization path — a config that works today can never be refused by a static analysis being wrong about it. Only a collision the running config does not have is refused. Rejected: making the "restart Xray" button bypass the check. That would re-open the exact loop the change removes, and the error message already names both tags and the port, which is what an operator needs to fix it. ## Speed on the sync path The probe buckets inbounds by port first, so transports are parsed only for a port two inbounds share — a clean config does zero JSON unmarshals beyond the listen fields, and the running-config pass only runs when the new config actually produced a collision. Measured on a 500-inbound config (ad-hoc benchmark, not committed): ``` BenchmarkBindConflictsClean-12 500 44122 ns/op 45757 B/op 508 allocs/op BenchmarkBindConflictsColliding-12 500 98097 ns/op 93472 B/op 1060 allocs/op ``` ~44 µs against `GetXrayConfig()`'s own per-restart work (template parse + DB rows + injectors), and the excuse rule costs nothing on a config that has no collision. ## Red first, with the exact output **1. The transport rule** — probe: treat any same-port overlap as a clash. Exactly the three coexistence cases fail, nothing else: ``` --- FAIL: TestBindConflicts/tcp_and_udp_on_one_port_are_legal --- FAIL: TestBindConflicts/kcp_moves_vless_to_udp_and_frees_the_port --- FAIL: TestBindConflicts/socks_bridge_without_udp_coexists_with_a_udp_inbound ``` **2. The excuse rule** — probe: report raw collisions. Exactly the two "already running" cases fail: ``` --- FAIL: TestBindConflicts/collision_the_running_config_already_serves --- FAIL: TestBindConflicts_GeneratedConfig/already_running_config ``` **3. The relay's own shape.** The relay is emitted as `protocol: "socks"` with `settings.udp = true` (`xray.go:768-775`, `SocksInboundSettings`), which `inboundTransports` does not model for a bare `"socks"` — the probe maps it onto the mixed shape so its UDP bit is not lost. Probe: drop that mapping and only this case fails: ``` --- FAIL: TestBindConflicts/amneziawg_relay_against_a_udp_inbound ``` **4. The probe reads real generated configs, not fixtures.** `TestBindConflicts_GeneratedConfig` seeds an AmneziaWG row with one qualifying peer plus a user inbound written *straight to the DB* on the derived relay port — the path the save-time guards cannot see — then calls `GetXrayConfig()` and asserts the refusal names `awg-1`, `user` and `65101`, that the same config is excused when it is the running one, and that a free port stays clean. This one pins the real emitted shape and the derived port; the two probes above are what prove the rule it applies. ## Gate * `go test ./internal/web/service -shuffle=on` — **green**, 196 s, all DB-backed tests included (local run with a pure-Go SQLite driver via `-overlay`; the tree's own `go.mod`/`go.sum` are unchanged). * `gofmt -l` and `go vet` on the package — clean. * CI: `go-test`, `golangci`, `race` on this head. Unverified here: PostgreSQL and the Xray gRPC end-to-end tests (`XUI_TEST_PG_DSN`, `XRAY_E2E_BINARY` are unset). The guard's call site in `RestartXray` is one line at a single funnel and is *not* covered by a test — it cannot be exercised without a real core process, so it is verified by reading; the decision it makes is what the tests above cover. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-02 04:08:05 +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#6345
No description provided.