From 772270c7e6307170fc8ac7f5476a45f4ce5bab87 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 22:05:42 +0330 Subject: [PATCH] fix(xray): refuse a config whose new socket the core cannot bind at all The guard that keeps a working core from being replaced by a config it cannot bind only knew one reason: another process holds the port. An inbound whose listen address the host does not have, or whose port the panel is not allowed to bind, went the same way as that one did: the new core exited at start and the watchdog restarted it every two seconds with every inbound down. The probe now names those two failures as well. A tproxy inbound is excused from the address check: IP_TRANSPARENT lets the core bind an address the host does not hold, which the probe cannot do. The permission check assumes what the shipped units give: the core is the panel's child with the same privileges. A core granted file capabilities the panel lacks would be refused a port it could bind. Checked against the pinned core on its own: it exits 255 on a missing address and on a denied port, and starts on the missing address with tproxy. On a running panel an inbound on 192.0.2.1 was refused with the core's PID and the other inbound untouched, and came up by hot apply once its listen was fixed. The case that left a missing address to the core is replaced: that was the previous commit's scope, not a rule. --- internal/web/service/xray.go | 2 +- internal/web/service/xray_bind_conflict.go | 43 +++++++++++++------ .../web/service/xray_bind_conflict_test.go | 34 +++++++++++++-- internal/xray/hot_diff.go | 8 ++-- 4 files changed, 65 insertions(+), 22 deletions(-) diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index dca7ca6ae..ed1a6f5d4 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -1601,7 +1601,7 @@ func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin, // start exits the core, and the watchdog would then loop on it forever. conflicts := bindConflicts(xrayConfig, process.GetConfig()) if len(conflicts) == 0 { - conflicts = socketsHeldElsewhere(xrayConfig, process.GetConfig()) + conflicts = unbindableSockets(xrayConfig, process.GetConfig()) } if len(conflicts) > 0 { refused := fmt.Sprintf("config refused: %s", conflicts[0]) diff --git a/internal/web/service/xray_bind_conflict.go b/internal/web/service/xray_bind_conflict.go index cc25c585f..acc857adc 100644 --- a/internal/web/service/xray_bind_conflict.go +++ b/internal/web/service/xray_bind_conflict.go @@ -24,20 +24,22 @@ type bindConflict struct { listenB string port int shared transportBits + // refusal is why the kernel will not give one inbound its socket; empty for a pair. + refusal string } func (c bindConflict) String() string { - if c.tagB == "" { - return fmt.Sprintf("inbound %q cannot bind %s:%d (%s): another process holds it", - c.tagA, displayListen(c.listen), c.port, transportTagSuffix(c.shared)) + if c.refusal != "" { + return fmt.Sprintf("inbound %q cannot bind %s:%d (%s): %s", + c.tagA, displayListen(c.listen), c.port, transportTagSuffix(c.shared), c.refusal) } return fmt.Sprintf("inbounds %q and %q both bind %s:%d (%s)", c.tagA, c.tagB, displayListen(c.listen), c.port, transportTagSuffix(c.shared)) } -// socketsHeldElsewhere reports sockets newCfg adds that another process already holds. +// unbindableSockets reports sockets newCfg adds that the kernel will not give the core. // Sockets the running config serves are the core's own and are never probed. -func socketsHeldElsewhere(newCfg, runningCfg *xray.Config) []bindConflict { +func unbindableSockets(newCfg, runningCfg *xray.Config) []bindConflict { if newCfg == nil { return nil } @@ -55,14 +57,18 @@ func socketsHeldElsewhere(newCfg, runningCfg *xray.Config) []bindConflict { } } } - var held transportBits + conflict := bindConflict{tagA: ib.Tag, listen: bind.listen, port: ib.Port} for _, transport := range []transportBits{transportTCP, transportUDP} { - if wanted&transport != 0 && heldByAnotherProcess(bind, ib.Port, transport) { - held |= transport + if wanted&transport == 0 { + continue + } + if refusal := bindRefusal(bind, ib.Port, transport, xray.InboundUsesTproxy(ib)); refusal != "" { + conflict.shared |= transport + conflict.refusal = refusal } } - if held != 0 { - conflicts = append(conflicts, bindConflict{tagA: ib.Tag, listen: bind.listen, port: ib.Port, shared: held}) + if conflict.refusal != "" { + conflicts = append(conflicts, conflict) } } slices.SortFunc(conflicts, func(a, b bindConflict) int { @@ -71,9 +77,9 @@ func socketsHeldElsewhere(newCfg, runningCfg *xray.Config) []bindConflict { return conflicts } -// heldByAnotherProcess binds the socket the way the core will and lets it go again. -// Only "address in use" counts: any other failure is the core's own to report. -func heldByAnotherProcess(bind bindAddr, port int, transport transportBits) bool { +// bindRefusal binds the socket the way the core will and lets it go again. It names the +// failures the core, as the panel's child, is sure to share; any other is the core's to report. +func bindRefusal(bind bindAddr, port int, transport transportBits, transparent bool) string { host := bind.listen if host == "" { host = "0.0.0.0" @@ -96,7 +102,16 @@ func heldByAnotherProcess(bind bindAddr, port int, transport transportBits) bool _ = listener.Close() } } - return errors.Is(err, syscall.EADDRINUSE) + switch { + case errors.Is(err, syscall.EADDRINUSE): + return "another process holds it" + // IP_TRANSPARENT lets a tproxy inbound bind an address the host does not hold. + case errors.Is(err, syscall.EADDRNOTAVAIL) && !transparent: + return "this host has no such address" + case errors.Is(err, syscall.EACCES): + return "the panel may not bind it" + } + return "" } // bindConflicts reports inbounds of newCfg whose sockets collide. A collision the diff --git a/internal/web/service/xray_bind_conflict_test.go b/internal/web/service/xray_bind_conflict_test.go index d5c33c08c..1a6b52928 100644 --- a/internal/web/service/xray_bind_conflict_test.go +++ b/internal/web/service/xray_bind_conflict_test.go @@ -2,11 +2,13 @@ package service import ( "encoding/json" + "errors" "net" "os" goruntime "runtime" "strconv" "strings" + "syscall" "testing" "github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet" @@ -316,7 +318,7 @@ func TestRestartKeepsTheCoreWhenAnotherProcessHoldsANewInboundsPort(t *testing.T } } -func TestSocketsHeldElsewhere(t *testing.T) { +func TestUnbindableSockets(t *testing.T) { // Held the way the core listens on a 0.0.0.0 listen, so every OS refuses a second bind. tcp, err := net.Listen("tcp", "0.0.0.0:0") if err != nil { @@ -366,7 +368,12 @@ func TestSocketsHeldElsewhere(t *testing.T) { }, {name: "an IPv6-only inbound beside an IPv4 holder", wanted: inbound("v6-only", "::", tcp4Port, "vless", `{"network":"tcp","sockopt":{"v6only":true}}`)}, {name: "a port its holder shares through SO_REUSEPORT", wanted: inbound("shared", "0.0.0.0", sharedPort, "vless", `{"network":"tcp"}`), unixOnly: true}, - {name: "a listen address this host does not have is the core's to report", wanted: inbound("elsewhere", "192.0.2.1", tcpPort, "vless", `{"network":"tcp"}`)}, + { + name: "a listen address this host does not have", wanted: inbound("elsewhere", "192.0.2.1", tcpPort, "vless", `{"network":"tcp"}`), + want: `inbound "elsewhere" cannot bind 192.0.2.1:` + strconv.Itoa(tcpPort) + ` (tcp): this host has no such address`, unixOnly: true, + }, + // IP_TRANSPARENT lets the core bind an address the host does not hold; the probe cannot. + {name: "the same address behind a transparent proxy", wanted: inbound("transparent", "192.0.2.1", tcpPort, "dokodemo-door", `{"network":"tcp","sockopt":{"tproxy":"tproxy"}}`)}, } { t.Run(tc.name, func(t *testing.T) { if tc.unixOnly && goruntime.GOOS == "windows" { @@ -377,7 +384,7 @@ func TestSocketsHeldElsewhere(t *testing.T) { running = configFromInbounds(t, tc.running) } got := "" - for _, conflict := range socketsHeldElsewhere(configFromInbounds(t, tc.wanted), running) { + for _, conflict := range unbindableSockets(configFromInbounds(t, tc.wanted), running) { got += conflict.String() } if got != tc.want { @@ -386,3 +393,24 @@ func TestSocketsHeldElsewhere(t *testing.T) { }) } } + +// Only a host that denies the test a privileged port can show this: root, macOS and a +// container with ip_unprivileged_port_start=0 all let the bind through. +func TestUnbindableSocketsRefusesAPortThePanelMayNotBind(t *testing.T) { + const privilegedPort = 81 + listener, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(privilegedPort)) + if err == nil { + _ = listener.Close() + } + if !errors.Is(err, syscall.EACCES) { + t.Skipf("this host does not deny port %d to the test process: %v", privilegedPort, err) + } + cfg := configFromInbounds(t, `{"tag":"low","listen":"0.0.0.0","port":81,"protocol":"vless","settings":{"clients":[]},"streamSettings":{"network":"tcp"}}`) + got := "" + for _, conflict := range unbindableSockets(cfg, nil) { + got += conflict.String() + } + if want := `inbound "low" cannot bind *:81 (tcp): the panel may not bind it`; got != want { + t.Fatalf("conflicts = %q, want %q", got, want) + } +} diff --git a/internal/xray/hot_diff.go b/internal/xray/hot_diff.go index 0e6ddcbdc..8b946dec2 100644 --- a/internal/xray/hot_diff.go +++ b/internal/xray/hot_diff.go @@ -176,7 +176,7 @@ func diffInbounds(oldCfg, newCfg *Config, diff *HotDiff) bool { logger.Debug("hot diff: inbound [", oldIb.Tag, "] REALITY configuration changed; a gRPC remove+add does not reliably rebuild the REALITY authenticator, forcing a full restart") return false } - if exists && (inboundUsesTproxy(oldIb) || inboundUsesTproxy(newIb)) { + if exists && (InboundUsesTproxy(oldIb) || InboundUsesTproxy(newIb)) { logger.Debug("hot diff: inbound [", oldIb.Tag, "] is a TPROXY target; a gRPC add reports success but does not reliably bind a working listener, forcing a full restart instead of a hot swap") return false } @@ -205,7 +205,7 @@ func diffInbounds(oldCfg, newCfg *Config, diff *HotDiff) bool { diff.TuicRelayChanges = append(diff.TuicRelayChanges, InboundReplacement{Next: newIb}) continue } - if inboundUsesTproxy(newIb) { + if InboundUsesTproxy(newIb) { logger.Debug("hot diff: new inbound [", newIb.Tag, "] is a TPROXY target (e.g. internal/amneziawg's Xray egress bridge); a gRPC add reports success but does not reliably bind a working listener, forcing a full restart instead of a hot add") return false } @@ -389,9 +389,9 @@ func inboundUsesReality(ib *InboundConfig) bool { return stream.Security == "reality" } -// inboundUsesTproxy: a sockopt.tproxy inbound (the tunnel protocol's TProxy +// InboundUsesTproxy: a sockopt.tproxy inbound (the tunnel protocol's TProxy // mode) hot-adds over gRPC "successfully" but binds no listener — restart. -func inboundUsesTproxy(ib *InboundConfig) bool { +func InboundUsesTproxy(ib *InboundConfig) bool { if ib == nil || len(ib.StreamSettings) == 0 { return false }