Files
mirror-3x-ui/internal/web/service/xray_bind_conflict_test.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

417 lines
15 KiB
Go

package service
import (
"encoding/json"
"errors"
"net"
"os"
goruntime "runtime"
"strconv"
"strings"
"syscall"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/amneziawgnet"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// configFromInbounds builds the config the way the panel does, from raw JSON:
// the probe is only worth anything if it parses what is really written.
func configFromInbounds(t *testing.T, inbounds string) *xray.Config {
t.Helper()
var cfg xray.Config
if err := json.Unmarshal([]byte(`{"inbounds":[`+inbounds+`]}`), &cfg); err != nil {
t.Fatalf("build config: %v", err)
}
return &cfg
}
func TestBindConflicts(t *testing.T) {
const (
relay = `{"listen":"127.0.0.1","port":65101,"protocol":"socks","tag":"relay","settings":{"auth":"password","udp":true,"accounts":[]}}`
user = `{"listen":"0.0.0.0","port":65101,"protocol":"vless","tag":"user","streamSettings":{"network":"tcp"}}`
)
cases := []struct {
name string
inbounds string
running string
want int
}{
{
"same listen, port and tcp",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a"},
{"listen":"0.0.0.0","port":443,"protocol":"vmess","tag":"b"}`,
``, 1,
},
{
"tcp and udp on one port are legal",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a"},
{"listen":"0.0.0.0","port":443,"protocol":"hysteria","tag":"b"}`,
``, 0,
},
{
"kcp moves vless to udp and frees the port",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a","streamSettings":{"network":"kcp"}},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"b","streamSettings":{"network":"tcp"}}`,
``, 0,
},
{
"ipv4 and ipv6 wildcards bind one dual-stack socket",
`{"listen":"::","port":443,"protocol":"vless","tag":"ipv6"},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"ipv4"}`,
``, 1,
},
{
"dual-stack ipv6 wildcard takes an ipv4 address",
`{"listen":"::","port":443,"protocol":"vless","tag":"ipv6"},
{"listen":"10.5.0.200","port":443,"protocol":"vless","tag":"ipv4"}`,
``, 1,
},
{
"v6only ipv6 wildcard leaves an ipv4 address free",
`{"listen":"::","port":443,"protocol":"vless","tag":"ipv6","streamSettings":{"network":"tcp","sockopt":{"v6only":true}}},
{"listen":"10.5.0.200","port":443,"protocol":"vless","tag":"ipv4"}`,
``, 0,
},
{
"v6only ipv6 wildcard still collides with the dual-stack 0.0.0.0",
`{"listen":"::","port":443,"protocol":"vless","tag":"ipv6","streamSettings":{"network":"tcp","sockopt":{"v6only":true}}},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"ipv4"}`,
``, 1,
},
{
"wildcard listen overlaps a loopback one",
`{"listen":"0.0.0.0","port":8443,"protocol":"vless","tag":"a"},
{"listen":"127.0.0.1","port":8443,"protocol":"trojan","tag":"b"}`,
``, 1,
},
{
"absent listen means wildcard",
`{"port":8443,"protocol":"vless","tag":"a"},
{"listen":"127.0.0.1","port":8443,"protocol":"trojan","tag":"b"}`,
``, 1,
},
{
"distinct loopback addresses do not overlap",
`{"listen":"127.0.0.1","port":8443,"protocol":"vless","tag":"a"},
{"listen":"127.0.0.2","port":8443,"protocol":"vless","tag":"b"}`,
``, 0,
},
{
"port zero is not a bind",
`{"listen":"0.0.0.0","port":0,"protocol":"tunnel","tag":"a"},
{"listen":"0.0.0.0","port":0,"protocol":"vless","tag":"b"}`,
``, 0,
},
{
"clean config",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a"},
{"listen":"127.0.0.1","port":62789,"protocol":"tunnel","tag":"api"},
` + relay,
``, 0,
},
{
// The relay the AmneziaWG family lives on: loopback tcp+udp, on the
// same port as a user inbound's tcp.
"amneziawg relay against a tcp inbound",
relay + "," + user, ``, 1,
},
{
"amneziawg relay against a udp inbound",
relay + `,{"listen":"0.0.0.0","port":65101,"protocol":"hysteria","tag":"user"}`,
``, 1,
},
{
// Proves the relay's transports come from settings.udp and not from a
// blanket "loopback owns everything" rule.
"socks bridge without udp coexists with a udp inbound",
`{"listen":"127.0.0.1","port":65101,"protocol":"socks","tag":"bridge","settings":{"auth":"noauth"}},
{"listen":"0.0.0.0","port":65101,"protocol":"hysteria","tag":"user"}`,
``, 0,
},
{
"reserved api inbound against a user inbound",
`{"listen":"127.0.0.1","port":62789,"protocol":"tunnel","tag":"api","settings":{"rewriteAddress":"127.0.0.1"}},
{"listen":"0.0.0.0","port":62789,"protocol":"vless","tag":"user"}`,
``, 1,
},
{
// The core is running this pair right now, so whatever a static read
// says about it, it binds: an established setup is never refused.
"collision the running config already serves",
relay + "," + user, relay + "," + user, 0,
},
{
"collision the running config does not have",
relay + "," + user, user, 1,
},
{
// `::` and `0.0.0.0` on one port is what bindv6only=1 makes legal, so the
// running config excuses it -- but moving one onto the other is not it.
"excused pair whose listen changed into a real collision",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a"},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"b"}`,
`{"listen":"::","port":443,"protocol":"vless","tag":"a"},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"b"}`,
1,
},
{
// The same pair of sockets is the same evidence, whichever order the
// generator happened to emit them in.
"excused pair with its listens swapped stays excused",
`{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"a"},
{"listen":"::","port":443,"protocol":"vless","tag":"b"}`,
`{"listen":"::","port":443,"protocol":"vless","tag":"a"},
{"listen":"0.0.0.0","port":443,"protocol":"vless","tag":"b"}`,
0,
},
{
"same pair on another port is still new",
`{"listen":"127.0.0.1","port":65102,"protocol":"socks","tag":"relay","settings":{"auth":"password","udp":true,"accounts":[]}},
{"listen":"0.0.0.0","port":65102,"protocol":"vless","tag":"user","streamSettings":{"network":"tcp"}}`,
relay + "," + user, 1,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var running *xray.Config
if tc.running != "" {
running = configFromInbounds(t, tc.running)
}
got := bindConflicts(configFromInbounds(t, tc.inbounds), running)
if len(got) != tc.want {
t.Fatalf("bindConflicts = %v, want %d conflict(s)", got, tc.want)
}
for _, c := range got {
if c.tagA == "" || c.tagB == "" || c.tagA == c.tagB {
t.Fatalf("a conflict must name both tags, got %+v", c)
}
}
})
}
}
func TestBindConflicts_MessageNamesBothSides(t *testing.T) {
conflicts := bindConflicts(configFromInbounds(t, `
{"listen":"127.0.0.1","port":65101,"protocol":"socks","tag":"relay","settings":{"auth":"password","udp":true,"accounts":[]}},
{"listen":"0.0.0.0","port":65101,"protocol":"vless","tag":"user","streamSettings":{"network":"tcp"}}`), nil)
if len(conflicts) != 1 {
t.Fatalf("want exactly one conflict, got %v", conflicts)
}
msg := conflicts[0].String()
for _, want := range []string{`"relay"`, `"user"`, "127.0.0.1", "65101"} {
if !strings.Contains(msg, want) {
t.Fatalf("conflict message %q must contain %q", msg, want)
}
}
}
// The probe must read what the panel really emits: the AmneziaWG relay is a
// loopback "socks" inbound whose udp flag lives in settings, not streamSettings.
func TestBindConflicts_GeneratedConfig(t *testing.T) {
cases := []struct {
name string
portOff int
running bool
want int
}{
{"user inbound on the relay port", 0, false, 1},
{"already running config", 0, true, 0},
{"user inbound on a free port", 1, false, 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
setupSettingTestDB(t)
seedInboundConflict(t, "awg-1", "0.0.0.0", 51820, model.AmneziaWG, ``, amneziawgRoutedSettings)
var awg model.Inbound
if err := database.GetDB().Where("tag = ?", "awg-1").First(&awg).Error; err != nil {
t.Fatalf("read seeded row: %v", err)
}
relayPort := amneziawgnet.SOCKSPortForInbound(awg.Id)
seedInboundConflict(t, "user", "0.0.0.0", relayPort+tc.portOff, model.VLESS, `{"network":"tcp"}`, `{}`)
svc := &XrayService{}
cfg, err := svc.GetXrayConfig()
if err != nil {
t.Fatalf("GetXrayConfig: %v", err)
}
running := (*xray.Config)(nil)
if tc.running {
if running, err = svc.GetXrayConfig(); err != nil {
t.Fatalf("second GetXrayConfig: %v", err)
}
}
got := bindConflicts(cfg, running)
if len(got) != tc.want {
t.Fatalf("bindConflicts = %v, want %d", got, tc.want)
}
if tc.want == 0 {
return
}
msg := got[0].String()
for _, want := range []string{`"awg-1"`, `"user"`, strconv.Itoa(relayPort)} {
if !strings.Contains(msg, want) {
t.Fatalf("conflict message %q must contain %q", msg, want)
}
}
})
}
}
// A port another process holds makes the new core exit at start, and the watchdog then
// restarts it every two seconds with every inbound down: the working core must stay.
func TestRestartKeepsTheCoreWhenAnotherProcessHoldsANewInboundsPort(t *testing.T) {
if goruntime.GOOS == "windows" {
t.Skip("the fake core is a shell script")
}
setupConflictDB(t)
stopped := isManuallyStopped.Swap(false)
pending := pendingXrayRestart.Swap(nil)
queued := pendingXraySessionDrop.Swap(false)
t.Cleanup(func() {
isManuallyStopped.Store(stopped)
pendingXrayRestart.Store(pending)
pendingXraySessionDrop.Store(queued)
})
t.Setenv("XUI_BIN_FOLDER", t.TempDir())
t.Setenv("XUI_LOG_FOLDER", t.TempDir())
if err := os.WriteFile(xray.GetBinaryPath(), []byte(fakeXrayCore("26.10.21", true)), 0o755); err != nil {
t.Fatal(err)
}
useFreeXrayAPIPort(t)
before := startFakeCore(t)
// Held the way the core listens on an empty or 0.0.0.0 listen, so every OS refuses a second bind.
held, err := net.Listen("tcp", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = held.Close() })
port := held.Addr().(*net.TCPAddr).Port
seedInboundConflict(t, "busy", "0.0.0.0", port, model.VLESS, `{"network":"tcp"}`,
`{"clients":[{"email":"busy@example.com","id":"5f2eb9d6-3a2f-4a55-9812-6ea1e2f7a666","enable":true}],"decryption":"none"}`)
svc := new(XrayService)
err = svc.RestartXray(false)
if err == nil || !strings.Contains(err.Error(), "config refused") || !strings.Contains(err.Error(), strconv.Itoa(port)) {
t.Fatalf("restart error = %v, want a refusal naming port %d", err, port)
}
if XrayProcess() != before || !before.IsRunning() {
t.Fatal("the working core was replaced by a config it cannot bind")
}
if err := held.Close(); err != nil {
t.Fatal(err)
}
if err := svc.RestartXray(false); err != nil {
t.Fatalf("restart with the port free: %v", err)
}
if after := XrayProcess(); after == before || after == nil || !after.IsRunning() {
t.Fatal("the core did not take the inbound once its port was free")
}
}
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 {
t.Fatal(err)
}
t.Cleanup(func() { _ = tcp.Close() })
udp, err := net.ListenPacket("udp", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = udp.Close() })
tcp4, err := net.Listen("tcp4", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = tcp4.Close() })
// A holder that sets what the core sets shares its port with the core, as the kernel allows.
shared, err := (&net.ListenConfig{Control: coreListenControl}).Listen(t.Context(), "tcp", "0.0.0.0:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = shared.Close() })
tcpPort, udpPort, tcp4Port := tcp.Addr().(*net.TCPAddr).Port, udp.LocalAddr().(*net.UDPAddr).Port, tcp4.Addr().(*net.TCPAddr).Port
sharedPort := shared.Addr().(*net.TCPAddr).Port
inbound := func(tag, listen string, port int, protocol, stream string) string {
return `{"tag":"` + tag + `","listen":"` + listen + `","port":` + strconv.Itoa(port) + `,"protocol":"` + protocol +
`","settings":{"clients":[]},"streamSettings":` + stream + `}`
}
vlessOnTCP := inbound("held-tcp", "0.0.0.0", tcpPort, "vless", `{"network":"tcp"}`)
for _, tc := range []struct {
name string
running, wanted string
want string
unixOnly bool
}{
{
name: "a new tcp inbound on a tcp port another process holds", wanted: vlessOnTCP,
want: `inbound "held-tcp" cannot bind *:` + strconv.Itoa(tcpPort) + ` (tcp): another process holds it`,
},
{name: "the same socket when the running core already serves it", running: vlessOnTCP, wanted: vlessOnTCP},
{name: "a tcp inbound on a port held only for udp", wanted: inbound("tcp-beside-udp", "0.0.0.0", udpPort, "vless", `{"network":"tcp"}`)},
{
name: "a udp inbound on a udp port another process holds", wanted: inbound("held-udp", "0.0.0.0", udpPort, "wireguard", `{}`),
want: `inbound "held-udp" cannot bind *:` + strconv.Itoa(udpPort) + ` (udp): another process holds it`,
},
{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", 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" {
t.Skip("Windows has no SO_REUSEPORT; the core sets nothing there either")
}
var running *xray.Config
if tc.running != "" {
running = configFromInbounds(t, tc.running)
}
got := ""
for _, conflict := range unbindableSockets(configFromInbounds(t, tc.wanted), running) {
got += conflict.String()
}
if got != tc.want {
t.Fatalf("conflicts = %q, want %q", got, tc.want)
}
})
}
}
// 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)
}
}