From 22ffae302fcbb1ea0b93ec6e44d24c7b8d04441e Mon Sep 17 00:00:00 2001 From: Sanaei Date: Thu, 26 Nov 2026 13:18:21 +0330 Subject: [PATCH] fix(inbounds): keep the running handler when its replacement cannot be added A save that has to rebuild an inbound's handler removed the running one through the Xray API and then added the new one. xray-core's API server reads requests of at most 4 MiB, which a VLESS inbound passes at about 46,000 clients, so the add was refused after the removal had gone through. The inbound then stayed down until the periodic restart picked the change up: 12 s on a 100,000-client inbound in a lab run, up to the restart interval in general. The add request is now built and measured before anything is sent, and the save asks the local runtime for that check before it removes the old handler. When the replacement cannot go through the API the old handler keeps serving and the save asks for the restart it needed anyway, with a warning that names the size. In the same lab run the inbound's port was closed only for the restart itself. Refs #7207 --- internal/web/runtime/local.go | 14 ++++ internal/web/service/inbound.go | 9 +++ .../service/inbound_update_oversized_test.go | 72 +++++++++++++++++++ internal/xray/api.go | 54 ++++++++++---- 4 files changed, 135 insertions(+), 14 deletions(-) create mode 100644 internal/web/service/inbound_update_oversized_test.go diff --git a/internal/web/runtime/local.go b/internal/web/runtime/local.go index a2e80bfd9..1ef764945 100644 --- a/internal/web/runtime/local.go +++ b/internal/web/runtime/local.go @@ -118,6 +118,20 @@ func (l *Local) AddInbound(_ context.Context, ib *model.Inbound) error { return err } +// CheckAddInbound reports why AddInbound could not hand ib to the core, without +// touching the core: a replace asks it before removing the handler that still serves. +func (l *Local) CheckAddInbound(ib *model.Inbound) error { + switch ib.Protocol { + case model.MTProto, model.AmneziaWG, model.TUIC: + return nil + } + body, err := json.MarshalIndent(ib.GenXrayInboundConfig(), "", " ") + if err != nil { + return err + } + return xray.CheckAddInbound(body) +} + func (l *Local) DelInbound(_ context.Context, ib *model.Inbound) error { if ib.Protocol == model.MTProto { mtproto.GetManager().Remove(ib.Id) diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index d871cb49e..b962941f2 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2312,6 +2312,15 @@ func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, if runningInbound != nil && applyInboundUserOps(rt, runningInbound, runtimeInbound) { return } + // Removed first, a handler whose replacement the core's API cannot + // take would leave the inbound down until the restart. + if checker, ok := rt.(interface{ CheckAddInbound(*model.Inbound) error }); ok && runtimeInbound != nil { + if err2 := checker.CheckAddInbound(runtimeInbound); err2 != nil { + logger.Warning("Inbound", oldInbound.Tag, "cannot be replaced on", rt.Name(), "without a restart:", err2) + needRestart = true + return + } + } if err2 := rt.DelInbound(context.Background(), &oldSnapshot); err2 == nil { logger.Debug("Old inbound deleted on", rt.Name(), ":", tag) } diff --git a/internal/web/service/inbound_update_oversized_test.go b/internal/web/service/inbound_update_oversized_test.go new file mode 100644 index 000000000..eff358fee --- /dev/null +++ b/internal/web/service/inbound_update_oversized_test.go @@ -0,0 +1,72 @@ +package service + +import ( + "fmt" + "strings" + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +// oversizedVlessSettings holds enough clients that the core's 4 MiB API limit +// refuses the inbound as one request, as it does past about 46,000 users. +func oversizedVlessSettings() string { + var b strings.Builder + b.WriteString(`{"decryption":"none","clients":[`) + for i := range 50000 { + if i > 0 { + b.WriteByte(',') + } + fmt.Fprintf(&b, `{"id":"%08d-0000-4000-8000-000000000000","email":"user-%05d@oversized","enable":true,"created_at":1,"updated_at":1}`, i, i) + } + b.WriteString(`]}`) + return b.String() +} + +// runOversizedInbound starts a core already serving the inbound, stores its row +// and makes that core the panel's local runtime. +func runOversizedInbound(t *testing.T) (*model.Inbound, func() any) { + t.Helper() + setupBulkDB(t) + ib := &model.Inbound{ + Tag: "oversized", Listen: "127.0.0.1", Port: freeLoopbackPort(t), Protocol: model.VLESS, Enable: true, + Settings: oversizedVlessSettings(), + StreamSettings: `{"network":"tcp","security":"none"}`, + Sniffing: `{"enabled":false}`, + } + if err := database.GetDB().Create(ib).Error; err != nil { + t.Fatalf("create inbound: %v", err) + } + instance, _, local := localRuntimeOnCore(t, withInbound(isolationConfig(t), ib)) + mgr := runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }}) + mgr.SetLocalRuntimeOverride(local) + runtime.SetManager(mgr) + t.Cleanup(func() { runtime.SetManager(nil) }) + return ib, func() any { return coreInboundHandler(t, instance, ib.Tag) } +} + +// A save that rebuilds the handler cannot send a 50,000-client inbound through +// the core's API; the handler it serves from must stay up until the restart. +func TestInboundSaveKeepsAHandlerItCannotReplaceLive(t *testing.T) { + ib, handler := runOversizedInbound(t) + serving := handler() + if serving == nil { + t.Fatal("the core did not start with the inbound") + } + + form := *ib + form.Settings = `{"decryption":"none"}` + form.Sniffing = `{"enabled":true,"destOverride":["http","tls"]}` + _, needRestart, err := (&InboundService{}).UpdateInbound(&form) + if err != nil { + t.Fatalf("UpdateInbound: %v", err) + } + if !needRestart { + t.Fatal("needRestart = false: nothing would apply the new sniffing") + } + if handler() != serving { + t.Fatal("the save removed the running handler and could not add its replacement: the inbound is down until the next restart") + } +} diff --git a/internal/xray/api.go b/internal/xray/api.go index 99d2d9211..7b7781ebb 100644 --- a/internal/xray/api.go +++ b/internal/xray/api.go @@ -49,6 +49,7 @@ import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" ) // Compiled once at package load: GetTraffic runs on every traffic-stats tick, @@ -154,6 +155,43 @@ func (x *XrayAPI) Close() { // for example while the process restart lock is held. const handlerRPCTimeout = 10 * time.Second +// maxAPIRequestBytes is the largest request xray-core's API server reads: it keeps +// grpc-go's 4 MiB default, which a VLESS inbound passes at about 46,000 clients. +const maxAPIRequestBytes = 4 << 20 + +// ErrAPIRequestTooLarge marks an inbound only a restart can load into the core. +var ErrAPIRequestTooLarge = errors.New("request exceeds the xray API message limit") + +func buildAddInboundRequest(inbound []byte) (*command.AddInboundRequest, error) { + conf := new(conf.InboundDetourConfig) + err := json.Unmarshal(inbound, conf) + if err != nil { + logger.Debug("Failed to unmarshal inbound:", err) + return nil, err + } + if err := checkUntrustedBuildInput(conf.StreamSetting, inbound); err != nil { + return nil, err + } + localizeNoiseScripts(conf.StreamSetting) + config, err := conf.Build() + if err != nil { + logger.Debug("Failed to build inbound Detur:", err) + return nil, err + } + request := &command.AddInboundRequest{Inbound: config} + if size := proto.Size(request); size > maxAPIRequestBytes { + return nil, fmt.Errorf("%w: inbound %q takes %d bytes of the %d the core reads", ErrAPIRequestTooLarge, conf.Tag, size, maxAPIRequestBytes) + } + return request, nil +} + +// CheckAddInbound reports what would stop AddInbound before the request reaches the +// core, so a caller replacing a running handler can ask before it removes that one. +func CheckAddInbound(inbound []byte) error { + _, err := buildAddInboundRequest(inbound) + return err +} + // AddInbound adds a new inbound configuration to the Xray core via gRPC. func (x *XrayAPI) AddInbound(inbound []byte) error { if x.HandlerServiceClient == nil { @@ -161,26 +199,14 @@ func (x *XrayAPI) AddInbound(inbound []byte) error { } client := *x.HandlerServiceClient - conf := new(conf.InboundDetourConfig) - err := json.Unmarshal(inbound, conf) + request, err := buildAddInboundRequest(inbound) if err != nil { - logger.Debug("Failed to unmarshal inbound:", err) return err } - if err := checkUntrustedBuildInput(conf.StreamSetting, inbound); err != nil { - return err - } - localizeNoiseScripts(conf.StreamSetting) - config, err := conf.Build() - if err != nil { - logger.Debug("Failed to build inbound Detur:", err) - return err - } - inboundConfig := command.AddInboundRequest{Inbound: config} ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout) defer cancel() - _, err = client.AddInbound(ctx, &inboundConfig) + _, err = client.AddInbound(ctx, request) return err }