Files
mirror-3x-ui/internal/web/service/xray_bind_conflict.go
T
Sanaei 772270c7e6 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.
2026-11-29 22:05:42 +03:30

238 lines
7.6 KiB
Go

package service
import (
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"slices"
"strconv"
"syscall"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/util/json_util"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// bindConflict names two generated inbounds whose listens cannot coexist.
type bindConflict struct {
tagA string
tagB string
listen string
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.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))
}
// 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 unbindableSockets(newCfg, runningCfg *xray.Config) []bindConflict {
if newCfg == nil {
return nil
}
var conflicts []bindConflict
for i := range newCfg.InboundConfigs {
ib := &newCfg.InboundConfigs[i]
bind := bindAddr{listen: configListen(ib.Listen), v6only: streamV6Only(string(ib.StreamSettings))}
wanted := configTransports(ib)
if runningCfg != nil {
for j := range runningCfg.InboundConfigs {
running := &runningCfg.InboundConfigs[j]
runningBind := bindAddr{listen: configListen(running.Listen), v6only: streamV6Only(string(running.StreamSettings))}
if running.Port == ib.Port && listenOverlaps(bind, runningBind) {
wanted &^= configTransports(running)
}
}
}
conflict := bindConflict{tagA: ib.Tag, listen: bind.listen, port: ib.Port}
for _, transport := range []transportBits{transportTCP, transportUDP} {
if wanted&transport == 0 {
continue
}
if refusal := bindRefusal(bind, ib.Port, transport, xray.InboundUsesTproxy(ib)); refusal != "" {
conflict.shared |= transport
conflict.refusal = refusal
}
}
if conflict.refusal != "" {
conflicts = append(conflicts, conflict)
}
}
slices.SortFunc(conflicts, func(a, b bindConflict) int {
return cmp.Or(cmp.Compare(a.port, b.port), cmp.Compare(a.tagA, b.tagA))
})
return conflicts
}
// 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"
}
suffix := ""
if bind.v6only {
suffix = "6"
}
address := net.JoinHostPort(host, strconv.Itoa(port))
listen := net.ListenConfig{Control: coreListenControl}
var err error
if transport == transportUDP {
var conn net.PacketConn
if conn, err = listen.ListenPacket(context.Background(), "udp"+suffix, address); err == nil {
_ = conn.Close()
}
} else {
var listener net.Listener
if listener, err = listen.Listen(context.Background(), "tcp"+suffix, address); err == nil {
_ = listener.Close()
}
}
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
// running config already serves is excused: it is demonstration, not a guess.
func bindConflicts(newCfg, runningCfg *xray.Config) []bindConflict {
conflicts := rawBindConflicts(newCfg)
if len(conflicts) == 0 {
return nil
}
excused := runningBindPairs(runningCfg)
if len(excused) == 0 {
return conflicts
}
kept := make([]bindConflict, 0, len(conflicts))
for _, c := range conflicts {
if _, ok := excused[bindPairKey(c)]; !ok {
kept = append(kept, c)
}
}
return kept
}
// rawBindConflicts groups inbounds by port first: only a port two inbounds share
// is worth parsing transports for, which keeps the probe free on clean configs.
func rawBindConflicts(cfg *xray.Config) []bindConflict {
if cfg == nil {
return nil
}
byPort := make(map[int][]*xray.InboundConfig, len(cfg.InboundConfigs))
for i := range cfg.InboundConfigs {
ib := &cfg.InboundConfigs[i]
if ib.Port > 0 {
byPort[ib.Port] = append(byPort[ib.Port], ib)
}
}
var conflicts []bindConflict
for port, group := range byPort {
for i := range group {
for j := i + 1; j < len(group); j++ {
left, right := group[i], group[j]
listenLeft, listenRight := configListen(left.Listen), configListen(right.Listen)
bindLeft := bindAddr{listen: listenLeft, v6only: streamV6Only(string(left.StreamSettings))}
bindRight := bindAddr{listen: listenRight, v6only: streamV6Only(string(right.StreamSettings))}
if !listenOverlaps(bindLeft, bindRight) {
continue
}
// One port carrying tcp on one inbound and udp on another is a
// supported deployment (vless/tcp + hysteria2/udp), never a clash.
shared := configTransports(left) & configTransports(right)
if shared == 0 {
continue
}
conflicts = append(conflicts, bindConflict{
tagA: left.Tag,
tagB: right.Tag,
listen: listenLeft,
listenB: listenRight,
port: port,
shared: shared,
})
}
}
}
// Port grouping iterates a map: order the report so the first conflict the
// caller shows is the same on every restart.
slices.SortFunc(conflicts, func(a, b bindConflict) int {
return cmp.Or(cmp.Compare(a.port, b.port), cmp.Compare(a.tagA, b.tagA), cmp.Compare(a.tagB, b.tagB))
})
return conflicts
}
// runningBindPairs is what the core is demonstrably binding right now, keyed the
// way a new config's conflicts are, so only the identical one is excused.
func runningBindPairs(cfg *xray.Config) map[string]struct{} {
conflicts := rawBindConflicts(cfg)
if len(conflicts) == 0 {
return nil
}
pairs := make(map[string]struct{}, len(conflicts))
for _, c := range conflicts {
pairs[bindPairKey(c)] = struct{}{}
}
return pairs
}
// bindPairKey is the socket set an excuse was granted for: the two listens, the
// port and the shared transports, never the tags, which the generator reorders.
func bindPairKey(c bindConflict) string {
left, right := c.listen, c.listenB
if left > right {
left, right = right, left
}
return fmt.Sprintf("%d\x00%s\x00%s\x00%d", c.port, left, right, c.shared)
}
func displayListen(listen string) string {
if isAnyListen(listen) {
return "*"
}
return listen
}
// configListen decodes a generated inbound's listen field: absent or empty means
// every address, which is what the core does with an empty listen too.
func configListen(raw json_util.RawMessage) string {
var listen string
if len(raw) == 0 || json.Unmarshal(raw, &listen) != nil {
return ""
}
return listen
}
// configTransports reads a generated inbound's transports through the same rule
// the save-time guards use, so the two cannot drift apart.
func configTransports(ib *xray.InboundConfig) transportBits {
// "socks" is the panel's own bridge shape (injectAmneziawgnetSocks and
// friends): its udp flag lives in settings like a mixed inbound's.
if ib.Protocol == "socks" {
return inboundTransports(model.Mixed, string(ib.StreamSettings), string(ib.Settings))
}
return inboundTransports(model.Protocol(ib.Protocol), string(ib.StreamSettings), string(ib.Settings))
}