mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-29 22:14:50 +03:00
fix(inbounds): refuse an inbound on a socket the panel itself listens on
The panel binds its web and subscription sockets before Xray starts, so a local inbound on either leaves Xray unable to listen at all. Nothing compared an inbound with those two sockets. Restoring a backup with this machine's settings kept could therefore import a tunnel on the panel's own port: the database was swapped first, and the failure only showed when Xray would not start. The rule is now stated once and every writer goes through it: - A restore reads the backup's inbounds and the settings that will be in force afterwards (this machine's for kept keys, the backup's for the rest, XUI_PORT over both) and is refused before Xray is stopped or the database touched. All three paths do this: a SQLite file, a SQLite file imported into PostgreSQL, and a pg_dump archive, whose two tables pg_restore prints as a data script without a connection. Only enabled rows refuse a restore, so a backup holding a disabled leftover stays usable; enabling that row later is refused by the port check. - Adding, editing and enabling an inbound run the same check. - Saving panel settings, and x-ui setting -port / -listenIP, refuse to move a panel socket onto an inbound. A collision that already exists does not block later saves. The x-ui menu no longer reports a refused port or listen address as set. One existing test put its inbound on 2053, the default panel port, for no reason of its own; it now uses 2083. Not covered: x-ui setting -reset and a changed XUI_PORT can still put the panel on an inbound's port. The PostgreSQL paths were run against PostgreSQL 18 with its pg_dump and pg_restore; CI skips those tests. make node-e2e passes. Closes #7115
This commit is contained in:
@@ -3805,6 +3805,29 @@ func BackupSQLite(dstPath string) (err error) {
|
||||
})
|
||||
}
|
||||
|
||||
// ReadSQLiteInboundsAndSettings reads a panel database file that is not the live one,
|
||||
// so a restore can be judged before it replaces anything.
|
||||
func ReadSQLiteInboundsAndSettings(dbPath string) ([]*model.Inbound, []model.Setting, error) {
|
||||
gdb, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{Logger: logger.Discard})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
sqlDB, err := gdb.DB()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer sqlDB.Close()
|
||||
var inbounds []*model.Inbound
|
||||
if err := gdb.Order("id").Find(&inbounds).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
var settings []model.Setting
|
||||
if err := gdb.Find(&settings).Error; err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return inbounds, settings, nil
|
||||
}
|
||||
|
||||
func ValidateSQLiteDB(dbPath string) error {
|
||||
if _, err := os.Stat(dbPath); err != nil {
|
||||
return err
|
||||
|
||||
@@ -74,7 +74,7 @@ func onlyHost(t *testing.T, inboundId int) model.Host {
|
||||
// externalProxy kept handing out its port and security after the update.
|
||||
func TestUpdateInbound_ExternalProxyChangeRetargetsImportedHost(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
created := addExternalProxyInbound(t, "edge-tls", 2053, `{"network":"ws","security":"tls",
|
||||
created := addExternalProxyInbound(t, "edge-tls", 2083, `{"network":"ws","security":"tls",
|
||||
"tlsSettings":{"certificates":[{"certificateFile":"/etc/ssl/edge.pem","keyFile":"/etc/ssl/edge.key"}]},
|
||||
"wsSettings":{"path":"/ws"},
|
||||
"externalProxy":[{"forceTls":"same","dest":"edge.example","port":2053}]}`)
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/entity"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// panelListener is a TCP socket the panel itself holds on the host it runs on.
|
||||
type panelListener struct {
|
||||
name string
|
||||
bind bindAddr
|
||||
port int
|
||||
}
|
||||
|
||||
const (
|
||||
webListenerName = "web listener"
|
||||
subListenerName = "subscription listener"
|
||||
)
|
||||
|
||||
// settingLookup returns a setting's stored value; "" stands for its default.
|
||||
type settingLookup func(key string) (string, error)
|
||||
|
||||
// panelListenersFrom derives the sockets a set of settings opens the way web.Server
|
||||
// and sub.Server read them: XUI_PORT beats webPort, subEnable gates the second.
|
||||
func panelListenersFrom(get settingLookup) ([]panelListener, error) {
|
||||
read := func(key string) (string, error) {
|
||||
value, err := get(key)
|
||||
return effectiveSettingValue(key, value), err
|
||||
}
|
||||
webListen, err := get("webListen")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
webPort, overridden, overrideErr := config.GetPortOverride()
|
||||
if !overridden || overrideErr != nil {
|
||||
stored, err := read("webPort")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if webPort, err = strconv.Atoi(stored); err != nil {
|
||||
return nil, common.NewErrorf("panel port %q is not a number", stored)
|
||||
}
|
||||
}
|
||||
listeners := []panelListener{{name: webListenerName, bind: bindAddr{listen: webListen}, port: webPort}}
|
||||
|
||||
subEnable, err := read("subEnable")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if enabled, err := strconv.ParseBool(subEnable); err != nil || !enabled {
|
||||
return listeners, nil
|
||||
}
|
||||
subListen, err := get("subListen")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stored, err := read("subPort")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
subPort, err := strconv.Atoi(stored)
|
||||
if err != nil {
|
||||
return nil, common.NewErrorf("subscription port %q is not a number", stored)
|
||||
}
|
||||
return append(listeners, panelListener{name: subListenerName, bind: bindAddr{listen: subListen}, port: subPort}), nil
|
||||
}
|
||||
|
||||
func livePanelListeners() ([]panelListener, error) {
|
||||
return panelListenersFrom((&SettingService{}).getString)
|
||||
}
|
||||
|
||||
// claims reports whether the TCP bind of an inbound hosted on this panel lands on
|
||||
// the listener's socket; a node-hosted row binds on another machine.
|
||||
func (l panelListener) claims(ib *model.Inbound) bool {
|
||||
return ib.NodeID == nil && ib.Port == l.port &&
|
||||
inboundTransports(ib.Protocol, ib.StreamSettings, ib.Settings)&transportTCP != 0 &&
|
||||
listenOverlaps(l.bind, inboundBindAddr(ib))
|
||||
}
|
||||
|
||||
func (l panelListener) conflict() *portConflictDetail {
|
||||
return &portConflictDetail{PanelListener: l.name, Listen: l.bind.listen, Port: l.port, Transports: transportTCP}
|
||||
}
|
||||
|
||||
func panelListenerClaiming(listeners []panelListener, ib *model.Inbound) *panelListener {
|
||||
for i := range listeners {
|
||||
if listeners[i].claims(ib) {
|
||||
return &listeners[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkPanelListenersFree refuses settings that put a panel socket on a local inbound
|
||||
// row it did not already share one with. Disabled rows count: jobs re-enable them unchecked.
|
||||
func checkPanelListenersFree(db *gorm.DB, next []panelListener) error {
|
||||
current, err := livePanelListeners()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ports := make([]int, 0, len(next))
|
||||
for _, l := range next {
|
||||
ports = append(ports, l.port)
|
||||
}
|
||||
var rows []*model.Inbound
|
||||
if err := db.Model(model.Inbound{}).Where("node_id IS NULL AND port IN ?", ports).
|
||||
Order("id").Find(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
// A collision that predates the change must not hold every later save hostage.
|
||||
if panelListenerClaiming(current, row) != nil {
|
||||
continue
|
||||
}
|
||||
if l := panelListenerClaiming(next, row); l != nil {
|
||||
return common.NewErrorf("the panel's %s cannot use port %d: it is already used by inbound %s on %s",
|
||||
l.name, l.port, inboundLabel(row.Remark, row.Tag, row.Id), listenLabel(row.Listen))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func allSettingListeners(all *entity.AllSetting) ([]panelListener, error) {
|
||||
values := map[string]string{
|
||||
"webListen": all.WebListen,
|
||||
"webPort": strconv.Itoa(all.WebPort),
|
||||
"subEnable": strconv.FormatBool(all.SubEnable),
|
||||
"subListen": all.SubListen,
|
||||
"subPort": strconv.Itoa(all.SubPort),
|
||||
}
|
||||
return panelListenersFrom(func(key string) (string, error) { return values[key], nil })
|
||||
}
|
||||
|
||||
// checkListenerSetting is checkPanelListenersFree for one stored key about to change.
|
||||
func (s *SettingService) checkListenerSetting(key, value string) error {
|
||||
next, err := panelListenersFrom(func(k string) (string, error) {
|
||||
if k == key {
|
||||
return value, nil
|
||||
}
|
||||
return s.getString(k)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkPanelListenersFree(database.GetDB(), next)
|
||||
}
|
||||
|
||||
// restoredSettingLookup answers with the value in force once a restore finishes:
|
||||
// this machine's for a kept host-bound key, the backup's for everything else.
|
||||
func restoredSettingLookup(imported map[string]string, kept hostBoundSnapshot) settingLookup {
|
||||
hostBound := make(map[string]struct{}, len(hostBoundSettingKeys))
|
||||
for _, key := range hostBoundSettingKeys {
|
||||
hostBound[key] = struct{}{}
|
||||
}
|
||||
return func(key string) (string, error) {
|
||||
if _, bound := hostBound[key]; bound && kept.taken {
|
||||
return kept.values[key], nil
|
||||
}
|
||||
return imported[key], nil
|
||||
}
|
||||
}
|
||||
|
||||
// restoreListenerConflict refuses a backup whose enabled local inbound would bind a
|
||||
// socket the restored panel holds: Xray cannot start beside it. Disabled rows pass.
|
||||
func restoreListenerConflict(inbounds []*model.Inbound, settings map[string]string, kept hostBoundSnapshot) error {
|
||||
listeners, err := panelListenersFrom(restoredSettingLookup(settings, kept))
|
||||
if err != nil {
|
||||
return common.NewErrorf("This file cannot be imported: %v", err)
|
||||
}
|
||||
for _, ib := range inbounds {
|
||||
if !ib.Enable {
|
||||
continue
|
||||
}
|
||||
if l := panelListenerClaiming(listeners, ib); l != nil {
|
||||
return common.NewErrorf("Restore refused: inbound %s in this backup cannot start, %s. "+
|
||||
"Change the inbound's port or the panel's port, then restore again.",
|
||||
inboundLabel(ib.Remark, ib.Tag, ib.Id), l.conflict().String())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func settingRowsByKey(rows []model.Setting) map[string]string {
|
||||
values := make(map[string]string, len(rows))
|
||||
for _, row := range rows {
|
||||
values[row.Key] = row.Value
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
// checkSQLiteRestoreListeners runs restoreListenerConflict over a staged SQLite file.
|
||||
func checkSQLiteRestoreListeners(dbPath string, kept hostBoundSnapshot) error {
|
||||
inbounds, settings, err := database.ReadSQLiteInboundsAndSettings(dbPath)
|
||||
if err != nil {
|
||||
return common.NewErrorf("This file cannot be imported: %v", err)
|
||||
}
|
||||
return restoreListenerConflict(inbounds, settingRowsByKey(settings), kept)
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
const (
|
||||
rawTCPStream = `{"network":"tcp"}`
|
||||
vlessNoUsers = `{"clients":[],"decryption":"none"}`
|
||||
)
|
||||
|
||||
func seedPanelSettings(t *testing.T, values map[string]string) {
|
||||
t.Helper()
|
||||
for key, value := range values {
|
||||
if err := (&SettingService{}).saveSetting(key, value); err != nil {
|
||||
t.Fatalf("seed setting %s: %v", key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A local inbound on a socket the panel itself listens on leaves Xray unable to
|
||||
// bind it; each case below isolates one condition of that rule.
|
||||
func TestPortConflictWithPanelListeners(t *testing.T) {
|
||||
node := 7
|
||||
cases := []struct {
|
||||
name string
|
||||
settings map[string]string
|
||||
xuiPort string
|
||||
inbound model.Inbound
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "web listener on the default port",
|
||||
inbound: model.Inbound{Port: 2053, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
want: "port 2053 (tcp) already used by this panel's own web listener on *",
|
||||
},
|
||||
{
|
||||
name: "subscription listener on the default port",
|
||||
inbound: model.Inbound{Port: 2096, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
want: "port 2096 (tcp) already used by this panel's own subscription listener on *",
|
||||
},
|
||||
{
|
||||
name: "disabled subscription server holds no socket",
|
||||
settings: map[string]string{"subEnable": "false"},
|
||||
inbound: model.Inbound{Port: 2096, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
},
|
||||
{
|
||||
name: "udp inbound shares the port number",
|
||||
inbound: model.Inbound{Port: 2053, Protocol: model.Hysteria},
|
||||
},
|
||||
{
|
||||
name: "node-hosted inbound binds on another host",
|
||||
inbound: model.Inbound{Port: 2053, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers, NodeID: &node},
|
||||
},
|
||||
{
|
||||
name: "panel and inbound on different addresses",
|
||||
settings: map[string]string{"webListen": "127.0.0.2"},
|
||||
inbound: model.Inbound{Listen: "127.0.0.3", Port: 2053, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
},
|
||||
{
|
||||
name: "panel on one address, inbound on every address",
|
||||
settings: map[string]string{"webListen": "127.0.0.2"},
|
||||
inbound: model.Inbound{Listen: "0.0.0.0", Port: 2053, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
want: "port 2053 (tcp) already used by this panel's own web listener on 127.0.0.2",
|
||||
},
|
||||
{
|
||||
name: "XUI_PORT moves the web listener off the stored port",
|
||||
xuiPort: "9000",
|
||||
inbound: model.Inbound{Port: 2053, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
},
|
||||
{
|
||||
name: "XUI_PORT is the port the web listener holds",
|
||||
xuiPort: "9000",
|
||||
inbound: model.Inbound{Port: 9000, Protocol: model.VLESS, StreamSettings: rawTCPStream, Settings: vlessNoUsers},
|
||||
want: "port 9000 (tcp) already used by this panel's own web listener on *",
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
t.Setenv("XUI_PORT", tc.xuiPort)
|
||||
seedPanelSettings(t, tc.settings)
|
||||
|
||||
conflict, err := (&InboundService{}).checkPortConflict(&tc.inbound, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("checkPortConflict: %v", err)
|
||||
}
|
||||
got := ""
|
||||
if conflict != nil {
|
||||
got = conflict.String()
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Fatalf("conflict = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Moving a panel listener onto a socket a local inbound owns breaks the same rule
|
||||
// from the other side: after the restart one of the two cannot bind.
|
||||
func TestPanelListenerCannotMoveOntoAnInbound(t *testing.T) {
|
||||
seedTunnel := func(t *testing.T, enable bool) {
|
||||
t.Helper()
|
||||
row := &model.Inbound{
|
||||
Tag: "tunnel-443", Remark: "office tunnel", Enable: true, Listen: "0.0.0.0", Port: 443,
|
||||
Protocol: model.Tunnel, Settings: `{"address":"10.0.0.2","port":443,"allowedNetwork":"tcp"}`,
|
||||
}
|
||||
if err := database.GetDB().Create(row).Error; err != nil {
|
||||
t.Fatalf("seed inbound: %v", err)
|
||||
}
|
||||
if !enable {
|
||||
if err := database.GetDB().Model(row).Update("enable", false).Error; err != nil {
|
||||
t.Fatalf("disable inbound: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("panel settings: web port", func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedTunnel(t, true)
|
||||
s := &SettingService{}
|
||||
all, err := s.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllSetting: %v", err)
|
||||
}
|
||||
all.WebPort = 443
|
||||
err = s.UpdateAllSetting(all, SecretClears{})
|
||||
want := "the panel's web listener cannot use port 443: it is already used by inbound 'office tunnel' (#1) on *"
|
||||
if err == nil || err.Error() != want {
|
||||
t.Fatalf("UpdateAllSetting error = %v, want %q", err, want)
|
||||
}
|
||||
if port, _ := s.GetPort(); port != 2053 {
|
||||
t.Fatalf("webPort = %d after a refused save, want 2053", port)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("panel settings: subscription port, inbound disabled", func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedTunnel(t, false)
|
||||
s := &SettingService{}
|
||||
all, err := s.GetAllSetting()
|
||||
if err != nil {
|
||||
t.Fatalf("GetAllSetting: %v", err)
|
||||
}
|
||||
all.SubPort = 443
|
||||
err = s.UpdateAllSetting(all, SecretClears{})
|
||||
want := "the panel's subscription listener cannot use port 443: it is already used by inbound 'office tunnel' (#1) on *"
|
||||
if err == nil || err.Error() != want {
|
||||
t.Fatalf("UpdateAllSetting error = %v, want %q", err, want)
|
||||
}
|
||||
})
|
||||
|
||||
// Binding the panel to one address of a socket it already shared with a row
|
||||
// creates no new collision, so the narrowing is allowed.
|
||||
t.Run("cli: narrowing a listener an older row already shares", func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedTunnel(t, false)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "443"})
|
||||
s := &SettingService{}
|
||||
if err := s.SetListen("127.0.0.1"); err != nil {
|
||||
t.Fatalf("SetListen narrowing the shared socket: %v", err)
|
||||
}
|
||||
if listen, _ := s.GetListen(); listen != "127.0.0.1" {
|
||||
t.Fatalf("webListen = %q, want 127.0.0.1", listen)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cli: port", func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedTunnel(t, true)
|
||||
s := &SettingService{}
|
||||
err := s.SetPort(443)
|
||||
want := "the panel's web listener cannot use port 443: it is already used by inbound 'office tunnel' (#1) on *"
|
||||
if err == nil || err.Error() != want {
|
||||
t.Fatalf("SetPort error = %v, want %q", err, want)
|
||||
}
|
||||
if port, _ := s.GetPort(); port != 2053 {
|
||||
t.Fatalf("webPort = %d after a refused SetPort, want 2053", port)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cli: listen address", func(t *testing.T) {
|
||||
setupConflictDB(t)
|
||||
seedTunnel(t, true)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "443", "webListen": "127.0.0.2"})
|
||||
if err := database.GetDB().Model(&model.Inbound{}).Where("tag = ?", "tunnel-443").
|
||||
Update("listen", "127.0.0.3").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := &SettingService{}
|
||||
err := s.SetListen("127.0.0.3")
|
||||
want := "the panel's web listener cannot use port 443: it is already used by inbound 'office tunnel' (#1) on 127.0.0.3"
|
||||
if err == nil || err.Error() != want {
|
||||
t.Fatalf("SetListen error = %v, want %q", err, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// restoreBackupBytes builds a real panel database in its own folder and returns
|
||||
// the file an operator would download from Back Up.
|
||||
func restoreBackupBytes(t *testing.T, settings map[string]string, inbounds ...*model.Inbound) []byte {
|
||||
t.Helper()
|
||||
t.Setenv("XUI_DB_FOLDER", t.TempDir())
|
||||
path := config.GetDBPath()
|
||||
dbtest.InitDB(t, path)
|
||||
seedPanelSettings(t, settings)
|
||||
for _, ib := range inbounds {
|
||||
enable := ib.Enable
|
||||
if err := database.GetDB().Create(ib).Error; err != nil {
|
||||
t.Fatalf("seed backup inbound: %v", err)
|
||||
}
|
||||
if !enable {
|
||||
if err := database.GetDB().Model(ib).Update("enable", false).Error; err != nil {
|
||||
t.Fatalf("disable backup inbound: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := database.CloseDB(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func backupTunnel(enable bool) *model.Inbound {
|
||||
return &model.Inbound{
|
||||
UserId: 1, Tag: "tunnel-443", Remark: "office tunnel", Enable: enable, Listen: "0.0.0.0", Port: 443,
|
||||
Protocol: model.Tunnel, Settings: `{"address":"10.0.0.2","port":443,"allowedNetwork":"tcp"}`,
|
||||
}
|
||||
}
|
||||
|
||||
func openUpload(t *testing.T, data []byte) *os.File {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "backup.db")
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
upload, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = upload.Close() })
|
||||
return upload
|
||||
}
|
||||
|
||||
func inboundTagCount(t *testing.T, tag string) int64 {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := database.GetDB().Model(&model.Inbound{}).Where("tag = ?", tag).Count(&count).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// The backup's tunnel listens where this machine's panel does. Restoring it with
|
||||
// this machine's settings kept must be refused while the live database is intact.
|
||||
func TestImportDBRefusesInboundOnThePanelListener(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the isolated core executable fixture requires a POSIX environment")
|
||||
}
|
||||
const refusal = "Restore refused: inbound 'office tunnel' (#1) in this backup cannot start, " +
|
||||
"port 443 (tcp) already used by this panel's own web listener on *. " +
|
||||
"Change the inbound's port or the panel's port, then restore again."
|
||||
|
||||
destination := func(t *testing.T) {
|
||||
t.Helper()
|
||||
setupConflictDB(t)
|
||||
sqliteImportTestCore(t)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "443"})
|
||||
seedInboundConflict(t, "destination-inbound", "", 62002, model.VLESS, rawTCPStream, vlessNoUsers)
|
||||
}
|
||||
|
||||
t.Run("kept panel port collides: refused before the swap", func(t *testing.T) {
|
||||
backup := restoreBackupBytes(t, map[string]string{"webPort": "2053"}, backupTunnel(true))
|
||||
destination(t)
|
||||
|
||||
err := (&ServerService{}).ImportDB(openUpload(t, backup), true)
|
||||
if err == nil || err.Error() != refusal {
|
||||
t.Fatalf("ImportDB error = %v, want %q", err, refusal)
|
||||
}
|
||||
if n := inboundTagCount(t, "destination-inbound"); n != 1 {
|
||||
t.Fatalf("destination inbound rows = %d, want 1: the live database was replaced", n)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 0 {
|
||||
t.Fatalf("backup inbound rows = %d, want 0: the refused backup was imported", n)
|
||||
}
|
||||
if _, statErr := os.Stat(config.GetDBPath() + ".backup"); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("fallback file stat = %v, want not-exist: the live database was moved aside", statErr)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("panel port comes from the backup: restored", func(t *testing.T) {
|
||||
backup := restoreBackupBytes(t, map[string]string{"webPort": "2053"}, backupTunnel(true))
|
||||
destination(t)
|
||||
|
||||
if err := (&ServerService{}).ImportDB(openUpload(t, backup), false); err != nil {
|
||||
t.Fatalf("ImportDB without kept settings: %v", err)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 1 {
|
||||
t.Fatalf("backup inbound rows = %d, want 1", n)
|
||||
}
|
||||
})
|
||||
|
||||
// A disabled row binds nothing; enabling it later is what the port check refuses.
|
||||
t.Run("colliding inbound is disabled: restored", func(t *testing.T) {
|
||||
backup := restoreBackupBytes(t, map[string]string{"webPort": "2053"}, backupTunnel(false))
|
||||
destination(t)
|
||||
|
||||
if err := (&ServerService{}).ImportDB(openUpload(t, backup), true); err != nil {
|
||||
t.Fatalf("ImportDB with a disabled colliding inbound: %v", err)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 1 {
|
||||
t.Fatalf("backup inbound rows = %d, want 1", n)
|
||||
}
|
||||
})
|
||||
|
||||
// Whether the subscription server runs is carried by the backup, not kept: one
|
||||
// that switches it off frees the port this machine's subscription server held.
|
||||
t.Run("backup switches the subscription server off: restored", func(t *testing.T) {
|
||||
onSubPort := backupTunnel(true)
|
||||
onSubPort.Port = 2096
|
||||
backup := restoreBackupBytes(t, map[string]string{"subEnable": "false"}, onSubPort)
|
||||
destination(t)
|
||||
|
||||
if err := (&ServerService{}).ImportDB(openUpload(t, backup), true); err != nil {
|
||||
t.Fatalf("ImportDB with the subscription server switched off: %v", err)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 1 {
|
||||
t.Fatalf("backup inbound rows = %d, want 1", n)
|
||||
}
|
||||
})
|
||||
|
||||
// The backup's own panel port is the one in force when settings are not kept.
|
||||
t.Run("backup collides with its own panel port: refused", func(t *testing.T) {
|
||||
backup := restoreBackupBytes(t, map[string]string{"webPort": "443"}, backupTunnel(true))
|
||||
destination(t)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "8443"})
|
||||
|
||||
err := (&ServerService{}).ImportDB(openUpload(t, backup), false)
|
||||
if err == nil || err.Error() != refusal {
|
||||
t.Fatalf("ImportDB error = %v, want %q", err, refusal)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -205,31 +205,46 @@ type portConflictDetail struct {
|
||||
// ForwardedBy is the peer whose port forward holds Port, when that is the
|
||||
// reason for the conflict.
|
||||
ForwardedBy string
|
||||
Transports transportBits
|
||||
// PanelListener names the panel's own socket holding Port, when no inbound does.
|
||||
PanelListener string
|
||||
Transports transportBits
|
||||
}
|
||||
|
||||
// inboundLabel is how a conflict message names an inbound: remark, else tag, with its id.
|
||||
func inboundLabel(remark, tag string, id int) string {
|
||||
name := remark
|
||||
if name == "" {
|
||||
name = tag
|
||||
}
|
||||
switch {
|
||||
case name == "":
|
||||
return fmt.Sprintf("#%d", id)
|
||||
case id > 0:
|
||||
return fmt.Sprintf("'%s' (#%d)", name, id)
|
||||
}
|
||||
// reserved/system inbounds (e.g. the Xray API) have no DB id.
|
||||
return fmt.Sprintf("'%s'", name)
|
||||
}
|
||||
|
||||
func listenLabel(listen string) string {
|
||||
if isAnyListen(listen) {
|
||||
return "*"
|
||||
}
|
||||
return listen
|
||||
}
|
||||
|
||||
// String renders the detail as a single-line, user-facing summary.
|
||||
func (d *portConflictDetail) String() string {
|
||||
name := d.Remark
|
||||
if name == "" {
|
||||
name = d.Tag
|
||||
}
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("#%d", d.InboundID)
|
||||
} else if d.InboundID > 0 {
|
||||
name = fmt.Sprintf("'%s' (#%d)", name, d.InboundID)
|
||||
} else {
|
||||
// reserved/system inbounds (e.g. the Xray API) have no DB id.
|
||||
name = fmt.Sprintf("'%s'", name)
|
||||
}
|
||||
listen := d.Listen
|
||||
if isAnyListen(listen) {
|
||||
listen = "*"
|
||||
}
|
||||
name := inboundLabel(d.Remark, d.Tag, d.InboundID)
|
||||
listen := listenLabel(d.Listen)
|
||||
port := fmt.Sprintf("port %d", d.Port)
|
||||
if d.Relay {
|
||||
port = fmt.Sprintf("relay port %d", d.Port)
|
||||
}
|
||||
if d.PanelListener != "" {
|
||||
return fmt.Sprintf("%s (%s) already used by this panel's own %s on %s",
|
||||
port, transportTagSuffix(d.Transports), d.PanelListener, listen)
|
||||
}
|
||||
if d.ForwardedBy != "" {
|
||||
return fmt.Sprintf("%s (%s) already forwarded on inbound %s on %s by its client %s",
|
||||
port, transportTagSuffix(d.Transports), name, listen, d.ForwardedBy)
|
||||
@@ -302,6 +317,16 @@ func checkPortConflictTx(db *gorm.DB, inbound *model.Inbound, ignoreId int) (*po
|
||||
}, nil
|
||||
}
|
||||
|
||||
// The panel binds its web and subscription sockets before Xray starts, so an
|
||||
// inbound on either leaves Xray unable to listen at all.
|
||||
listeners, err := livePanelListeners()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if held := panelListenerClaiming(listeners, inbound); held != nil {
|
||||
return held.conflict(), nil
|
||||
}
|
||||
|
||||
// Local embedded inbounds reserve an automatically assigned Xray SOCKS relay port.
|
||||
if inbound.NodeID == nil && listenOverlaps(loopbackBind, inboundBindAddr(inbound)) {
|
||||
conflict, err := checkAmneziawgnetSocksConflict(db, inbound, ignoreId, newBits)
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
|
||||
)
|
||||
|
||||
// pg_restore prints one such header per table, schema-qualified, then its rows.
|
||||
var pgCopyHeaderPattern = regexp.MustCompile(`^COPY (?:"?[^".\s]+"?\.)?"?([^".\s(]+)"? \((.*)\) FROM stdin;$`)
|
||||
|
||||
// pgCopyRows parses the COPY blocks of a pg_restore data script: per table, one
|
||||
// column-to-value map per row. A NULL column is left out of its row.
|
||||
func pgCopyRows(r io.Reader) (map[string][]map[string]string, error) {
|
||||
tables := make(map[string][]map[string]string)
|
||||
reader := bufio.NewReader(r)
|
||||
var table string
|
||||
var columns []string
|
||||
for {
|
||||
line, readErr := reader.ReadString('\n')
|
||||
if readErr != nil && !errors.Is(readErr, io.EOF) {
|
||||
return nil, readErr
|
||||
}
|
||||
atEOF := errors.Is(readErr, io.EOF)
|
||||
line = strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r")
|
||||
switch {
|
||||
case atEOF && line == "":
|
||||
case table == "":
|
||||
if header := pgCopyHeaderPattern.FindStringSubmatch(line); header != nil {
|
||||
table = header[1]
|
||||
columns = columns[:0]
|
||||
for column := range strings.SplitSeq(header[2], ",") {
|
||||
columns = append(columns, strings.Trim(strings.TrimSpace(column), `"`))
|
||||
}
|
||||
}
|
||||
case line == `\.`:
|
||||
table = ""
|
||||
default:
|
||||
fields := strings.Split(line, "\t")
|
||||
if len(fields) != len(columns) {
|
||||
return nil, common.NewErrorf("table %s: a row has %d fields for %d columns", table, len(fields), len(columns))
|
||||
}
|
||||
row := make(map[string]string, len(columns))
|
||||
for i, field := range fields {
|
||||
if field == `\N` {
|
||||
continue
|
||||
}
|
||||
row[columns[i]] = pgCopyUnescape(field)
|
||||
}
|
||||
tables[table] = append(tables[table], row)
|
||||
}
|
||||
if atEOF {
|
||||
return tables, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var pgCopyEscapes = map[byte]byte{'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v'}
|
||||
|
||||
// pgCopyUnescape undoes COPY's text-format backslash escapes; COPY TO writes only
|
||||
// the named ones and a doubled backslash, any other escaped byte stands for itself.
|
||||
func pgCopyUnescape(field string) string {
|
||||
if !strings.Contains(field, `\`) {
|
||||
return field
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(field))
|
||||
for i := 0; i < len(field); i++ {
|
||||
if field[i] != '\\' || i+1 == len(field) {
|
||||
out.WriteByte(field[i])
|
||||
continue
|
||||
}
|
||||
i++
|
||||
if replacement, named := pgCopyEscapes[field[i]]; named {
|
||||
out.WriteByte(replacement)
|
||||
continue
|
||||
}
|
||||
out.WriteByte(field[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func inboundFromPgCopyRow(row map[string]string) (*model.Inbound, error) {
|
||||
id, err := strconv.Atoi(row["id"])
|
||||
if err != nil {
|
||||
return nil, common.NewErrorf("inbound id %q is not a number", row["id"])
|
||||
}
|
||||
port, err := strconv.Atoi(row["port"])
|
||||
if err != nil {
|
||||
return nil, common.NewErrorf("inbound #%d: port %q is not a number", id, row["port"])
|
||||
}
|
||||
inbound := &model.Inbound{
|
||||
Id: id, Remark: row["remark"], Tag: row["tag"], Enable: row["enable"] == "t",
|
||||
Listen: row["listen"], Port: port, Protocol: model.Protocol(row["protocol"]),
|
||||
Settings: row["settings"], StreamSettings: row["stream_settings"],
|
||||
}
|
||||
if raw, hosted := row["node_id"]; hosted {
|
||||
nodeID, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return nil, common.NewErrorf("inbound #%d: node id %q is not a number", id, raw)
|
||||
}
|
||||
inbound.NodeID = &nodeID
|
||||
}
|
||||
return inbound, nil
|
||||
}
|
||||
|
||||
// checkPgDumpRestoreListeners runs restoreListenerConflict over a pg_dump archive:
|
||||
// pg_restore writes the two tables as a data script, which needs no connection.
|
||||
func checkPgDumpRestoreListeners(bin, dumpPath string, kept hostBoundSnapshot) error {
|
||||
script, err := os.CreateTemp("", "x-ui-pg-preflight-*.sql")
|
||||
if err != nil {
|
||||
return common.NewErrorf("Error creating temporary file: %v", err)
|
||||
}
|
||||
scriptPath := script.Name()
|
||||
defer os.Remove(scriptPath)
|
||||
if err := script.Close(); err != nil {
|
||||
return common.NewErrorf("Error creating temporary file: %v", err)
|
||||
}
|
||||
|
||||
cmd := exec.CommandContext(context.Background(), bin,
|
||||
"--data-only", "--table=inbounds", "--table=settings", "--file="+scriptPath, dumpPath)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
if err := cmd.Run(); err != nil {
|
||||
return common.NewErrorf("pg_restore cannot read the inbounds of this dump file: %v: %s", err, strings.TrimSpace(stderr.String()))
|
||||
}
|
||||
data, err := os.Open(scriptPath)
|
||||
if err != nil {
|
||||
return common.NewErrorf("Error reading the dump's inbounds: %v", err)
|
||||
}
|
||||
defer data.Close()
|
||||
tables, err := pgCopyRows(data)
|
||||
if err != nil {
|
||||
return common.NewErrorf("Error reading the dump's inbounds: %v", err)
|
||||
}
|
||||
|
||||
inbounds := make([]*model.Inbound, 0, len(tables["inbounds"]))
|
||||
for _, row := range tables["inbounds"] {
|
||||
inbound, err := inboundFromPgCopyRow(row)
|
||||
if err != nil {
|
||||
return common.NewErrorf("Error reading the dump's inbounds: %v", err)
|
||||
}
|
||||
inbounds = append(inbounds, inbound)
|
||||
}
|
||||
slices.SortFunc(inbounds, func(a, b *model.Inbound) int { return a.Id - b.Id })
|
||||
settings := make(map[string]string, len(tables["settings"]))
|
||||
for _, row := range tables["settings"] {
|
||||
settings[row["key"]] = row["value"]
|
||||
}
|
||||
return restoreListenerConflict(inbounds, settings, kept)
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
gormlogger "gorm.io/gorm/logger"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
// The script is what pg_restore --data-only prints: tab-separated rows, \N for
|
||||
// NULL, and backslash escapes inside values such as a pretty-printed settings JSON.
|
||||
func TestPgCopyRowsReadsARestoreScript(t *testing.T) {
|
||||
script := strings.Join([]string{
|
||||
`--`,
|
||||
`-- Data for Name: inbounds; Type: TABLE DATA; Schema: public; Owner: -`,
|
||||
`--`,
|
||||
``,
|
||||
`COPY public.inbounds (id, remark, enable, listen, port, protocol, settings, node_id) FROM stdin;`,
|
||||
"3\toffice\\ttunnel\tt\t\t443\ttunnel\t{\\n \"path\": \"C:\\\\\\\\x\"\\n}\t\\N",
|
||||
"4\t\tf\t0.0.0.0\t8443\tvless\t{}\t12",
|
||||
`\.`,
|
||||
``,
|
||||
`COPY "import_host_1".settings (id, key, value) FROM stdin;`,
|
||||
"1\twebPort\t443",
|
||||
"2\twebListen\t",
|
||||
`\.`,
|
||||
``,
|
||||
}, "\n")
|
||||
|
||||
tables, err := pgCopyRows(strings.NewReader(script))
|
||||
if err != nil {
|
||||
t.Fatalf("pgCopyRows: %v", err)
|
||||
}
|
||||
if got := len(tables["inbounds"]); got != 2 {
|
||||
t.Fatalf("inbounds rows = %d, want 2", got)
|
||||
}
|
||||
first := tables["inbounds"][0]
|
||||
if first["remark"] != "office\ttunnel" {
|
||||
t.Errorf("remark = %q, want the escaped tab restored", first["remark"])
|
||||
}
|
||||
if want := "{\n \"path\": \"C:\\\\x\"\n}"; first["settings"] != want {
|
||||
t.Errorf("settings = %q, want %q", first["settings"], want)
|
||||
}
|
||||
if _, present := first["node_id"]; present {
|
||||
t.Errorf("node_id = %q, want a NULL column left out", first["node_id"])
|
||||
}
|
||||
if listen, present := first["listen"]; !present || listen != "" {
|
||||
t.Errorf("listen = %q (present=%t), want an empty string, which is not NULL", listen, present)
|
||||
}
|
||||
if got := tables["inbounds"][1]["node_id"]; got != "12" {
|
||||
t.Errorf("second row node_id = %q, want 12", got)
|
||||
}
|
||||
if got := tables["settings"][0]["value"]; got != "443" {
|
||||
t.Errorf("schema-qualified, quoted table: webPort = %q, want 443", got)
|
||||
}
|
||||
|
||||
if _, err := pgCopyRows(strings.NewReader("COPY public.settings (id, key, value) FROM stdin;\n1\twebPort\n\\.\n")); err == nil ||
|
||||
err.Error() != "table settings: a row has 2 fields for 3 columns" {
|
||||
t.Errorf("short row error = %v, want the field-count mismatch", err)
|
||||
}
|
||||
}
|
||||
|
||||
// pgThrowawayDatabase creates a database of its own on the test server and returns
|
||||
// a URL DSN for it: pg_dump and pg_restore act on whole databases.
|
||||
func pgThrowawayDatabase(t *testing.T, adminDSN, name string) string {
|
||||
t.Helper()
|
||||
parsed, err := url.Parse(adminDSN)
|
||||
if err != nil || (parsed.Scheme != "postgres" && parsed.Scheme != "postgresql") {
|
||||
t.Skip("XUI_TEST_PG_DSN must be a postgres:// URL for the pg_dump restore test")
|
||||
}
|
||||
admin, err := gorm.Open(postgres.Open(adminDSN), &gorm.Config{Logger: gormlogger.Discard})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool, err := admin.DB()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dbname := fmt.Sprintf("%s_%d", name, time.Now().UnixNano())
|
||||
if err := admin.Exec("CREATE DATABASE " + dbname).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = database.CloseDB()
|
||||
if err := admin.Exec("DROP DATABASE " + dbname + " WITH (FORCE)").Error; err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
_ = pool.Close()
|
||||
})
|
||||
parsed.Path = "/" + dbname
|
||||
return parsed.String()
|
||||
}
|
||||
|
||||
func openPgPanelDatabase(t *testing.T, dsn string) {
|
||||
t.Helper()
|
||||
_ = database.CloseDB()
|
||||
t.Setenv("XUI_DB_TYPE", "postgres")
|
||||
t.Setenv("XUI_DB_DSN", dsn)
|
||||
if err := database.InitDB(""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A pg_dump archive cannot be opened like a SQLite file; the refusal must still
|
||||
// come before Xray is stopped and the destination database is replaced.
|
||||
func TestRestorePostgresDumpRefusesInboundOnThePanelListener(t *testing.T) {
|
||||
adminDSN := strings.TrimSpace(os.Getenv("XUI_TEST_PG_DSN"))
|
||||
if adminDSN == "" {
|
||||
t.Skip("set XUI_TEST_PG_DSN to run real PostgreSQL restores")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the isolated core executable fixture requires a POSIX environment")
|
||||
}
|
||||
for _, tool := range []string{"pg_dump", "pg_restore"} {
|
||||
if _, err := exec.LookPath(tool); err != nil {
|
||||
t.Skipf("%s is not installed", tool)
|
||||
}
|
||||
}
|
||||
sourceDSN := pgThrowawayDatabase(t, adminDSN, "xui_restore_source")
|
||||
openPgPanelDatabase(t, sourceDSN)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "2053", "remarkTemplate": "line one\n\tline two \\ end"})
|
||||
if err := database.GetDB().Create(&model.User{Username: "source-user", Password: "test-password"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tunnel := backupTunnel(true)
|
||||
if err := database.GetDB().Create(tunnel).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
refusal := fmt.Sprintf("Restore refused: inbound 'office tunnel' (#%d) in this backup cannot start, "+
|
||||
"port 443 (tcp) already used by this panel's own web listener on *. "+
|
||||
"Change the inbound's port or the panel's port, then restore again.", tunnel.Id)
|
||||
dump, err := (&ServerService{}).exportPostgresDB()
|
||||
if err != nil {
|
||||
t.Fatalf("exportPostgresDB: %v", err)
|
||||
}
|
||||
|
||||
destination := func(t *testing.T) {
|
||||
t.Helper()
|
||||
openPgPanelDatabase(t, pgThrowawayDatabase(t, adminDSN, "xui_restore_destination"))
|
||||
sqliteImportTestCore(t)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "443"})
|
||||
if err := database.GetDB().Create(&model.User{Username: "destination-user", Password: "test-password"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seedInboundConflict(t, "destination-inbound", "", 62002, model.VLESS, rawTCPStream, vlessNoUsers)
|
||||
}
|
||||
upload := func(t *testing.T) *os.File {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "backup.dump")
|
||||
if err := os.WriteFile(path, dump, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = file.Close() })
|
||||
return file
|
||||
}
|
||||
|
||||
t.Run("kept panel port collides: refused before the restore", func(t *testing.T) {
|
||||
destination(t)
|
||||
err := (&ServerService{}).ImportDB(upload(t), true)
|
||||
if err == nil || err.Error() != refusal {
|
||||
t.Fatalf("ImportDB error = %v, want %q", err, refusal)
|
||||
}
|
||||
if n := inboundTagCount(t, "destination-inbound"); n != 1 {
|
||||
t.Fatalf("destination inbound rows = %d, want 1: the database was restored over", n)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 0 {
|
||||
t.Fatalf("backup inbound rows = %d, want 0: the refused dump was restored", n)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("panel port comes from the dump: restored", func(t *testing.T) {
|
||||
destination(t)
|
||||
if err := (&ServerService{}).ImportDB(upload(t), false); err != nil {
|
||||
t.Fatalf("ImportDB without kept settings: %v", err)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 1 {
|
||||
t.Fatalf("backup inbound rows = %d, want 1", n)
|
||||
}
|
||||
template, err := (&SettingService{}).getString("remarkTemplate")
|
||||
if err != nil || template != "line one\n\tline two \\ end" {
|
||||
t.Fatalf("remarkTemplate = %q, error=%v: the dump did not restore intact", template, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The SQLite-into-PostgreSQL path reads the same staged file the SQLite restore does.
|
||||
func TestImportSQLiteIntoPostgresRefusesInboundOnThePanelListener(t *testing.T) {
|
||||
dsn := strings.TrimSpace(os.Getenv("XUI_TEST_PG_DSN"))
|
||||
if dsn == "" {
|
||||
t.Skip("set XUI_TEST_PG_DSN to run real SQLite-to-PostgreSQL imports")
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("the isolated core executable fixture requires a POSIX environment")
|
||||
}
|
||||
t.Setenv("XUI_DB_TYPE", "sqlite")
|
||||
t.Setenv("XUI_DB_DSN", "")
|
||||
backup := restoreBackupBytes(t, map[string]string{"webPort": "2053"}, backupTunnel(true))
|
||||
|
||||
sqliteImportPostgresDestination(t, dsn)
|
||||
sqliteImportTestCore(t)
|
||||
seedPanelSettings(t, map[string]string{"webPort": "443"})
|
||||
seedInboundConflict(t, "destination-inbound", "", 62002, model.VLESS, rawTCPStream, vlessNoUsers)
|
||||
|
||||
err := (&ServerService{}).ImportDB(openUpload(t, backup), true)
|
||||
const refusal = "Restore refused: inbound 'office tunnel' (#1) in this backup cannot start, " +
|
||||
"port 443 (tcp) already used by this panel's own web listener on *. " +
|
||||
"Change the inbound's port or the panel's port, then restore again."
|
||||
if err == nil || err.Error() != refusal {
|
||||
t.Fatalf("ImportDB error = %v, want %q", err, refusal)
|
||||
}
|
||||
if n := inboundTagCount(t, "destination-inbound"); n != 1 {
|
||||
t.Fatalf("destination inbound rows = %d, want 1: the database was imported over", n)
|
||||
}
|
||||
if n := inboundTagCount(t, "tunnel-443"); n != 0 {
|
||||
t.Fatalf("backup inbound rows = %d, want 0: the refused backup was imported", n)
|
||||
}
|
||||
}
|
||||
@@ -1953,6 +1953,14 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
|
||||
return common.NewErrorf("This file cannot be imported: %v", err)
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
if err = checkSQLiteRestoreListeners(tempPath, keptSettings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
xrayStopped := true
|
||||
defer func() {
|
||||
if xrayStopped {
|
||||
@@ -1965,11 +1973,6 @@ func (s *ServerService) ImportDB(file multipart.File, keepHostSettings bool) err
|
||||
logger.Warningf("Failed to stop Xray before DB import: %v", errStop)
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
|
||||
if errClose := database.CloseDB(); errClose != nil {
|
||||
logger.Warningf("Failed to close existing DB before replacement: %v", errClose)
|
||||
}
|
||||
@@ -2237,6 +2240,14 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting
|
||||
return err
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
if err := checkPgDumpRestoreListeners(bin, tempPath, keptSettings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
xrayStopped := true
|
||||
defer func() {
|
||||
if xrayStopped {
|
||||
@@ -2249,11 +2260,6 @@ func (s *ServerService) restorePostgresDump(file multipart.File, keepHostSetting
|
||||
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
|
||||
if errClose := database.CloseDB(); errClose != nil {
|
||||
logger.Warningf("Failed to close existing DB before restore: %v", errClose)
|
||||
}
|
||||
@@ -2314,6 +2320,14 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump
|
||||
return common.NewErrorf("This file cannot be imported: %v", err)
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
if err := checkSQLiteRestoreListeners(dbPath, keptSettings); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
xrayStopped := true
|
||||
defer func() {
|
||||
if xrayStopped {
|
||||
@@ -2326,11 +2340,6 @@ func (s *ServerService) migrateSQLiteIntoPostgres(file multipart.File, isSQLDump
|
||||
logger.Warningf("Failed to stop Xray before DB restore: %v", errStop)
|
||||
}
|
||||
|
||||
var keptSettings hostBoundSnapshot
|
||||
if keepHostSettings {
|
||||
keptSettings = captureHostBoundSettings()
|
||||
}
|
||||
|
||||
if errClose := database.CloseDB(); errClose != nil {
|
||||
logger.Warningf("Failed to close existing DB before restore: %v", errClose)
|
||||
}
|
||||
|
||||
@@ -555,6 +555,9 @@ func (s *SettingService) GetListen() (string, error) {
|
||||
}
|
||||
|
||||
func (s *SettingService) SetListen(ip string) error {
|
||||
if err := s.checkListenerSetting("webListen", ip); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.setString("webListen", ip)
|
||||
}
|
||||
|
||||
@@ -749,6 +752,9 @@ func (s *SettingService) GetListenPort() (int, error) {
|
||||
}
|
||||
|
||||
func (s *SettingService) SetPort(port int) error {
|
||||
if err := s.checkListenerSetting("webPort", strconv.Itoa(port)); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.setInt("webPort", port)
|
||||
}
|
||||
|
||||
@@ -1795,6 +1801,13 @@ func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting, clears
|
||||
if err := allSetting.CheckValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
listeners, err := allSettingListeners(allSetting)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := checkPanelListenersFree(database.GetDB(), listeners); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(allSetting).Elem()
|
||||
t := reflect.TypeFor[entity.AllSetting]()
|
||||
|
||||
@@ -592,7 +592,15 @@ set_port() {
|
||||
LOGD "Cancelled"
|
||||
before_show_menu
|
||||
else
|
||||
${xui_folder}/x-ui setting -port ${port}
|
||||
local output
|
||||
output=$(${xui_folder}/x-ui setting -port "${port}" 2>&1)
|
||||
echo "${output}"
|
||||
# The panel refuses a port one of its own inbounds listens on.
|
||||
if ! grep -Fxq "Port set successfully: ${port}" <<< "${output}"; then
|
||||
LOGE "The port was not changed."
|
||||
before_show_menu
|
||||
return
|
||||
fi
|
||||
echo -e "The port is set, Please restart the panel now, and use the new port ${green}${port}${plain} to access web panel"
|
||||
confirm_restart
|
||||
fi
|
||||
@@ -2924,9 +2932,16 @@ SSH_port_forwarding() {
|
||||
fi
|
||||
;;
|
||||
2)
|
||||
${xui_folder}/x-ui setting -listenIP 0.0.0.0 > /dev/null 2>&1
|
||||
echo -e "${green}Listen IP has been cleared.${plain}"
|
||||
restart
|
||||
local cleared
|
||||
cleared=$(${xui_folder}/x-ui setting -listenIP 0.0.0.0 2>&1)
|
||||
# Listening on every address is refused when an inbound holds the panel's port on one.
|
||||
if grep -Fxq "listen 0.0.0.0 set successfully" <<< "${cleared}"; then
|
||||
echo -e "${green}Listen IP has been cleared.${plain}"
|
||||
restart
|
||||
else
|
||||
echo "${cleared}"
|
||||
LOGE "The listen IP was not cleared."
|
||||
fi
|
||||
;;
|
||||
0)
|
||||
show_menu
|
||||
|
||||
Reference in New Issue
Block a user