diff --git a/libv2ray_main.go b/libv2ray_main.go index 68af7eff..fefa9580 100644 --- a/libv2ray_main.go +++ b/libv2ray_main.go @@ -33,13 +33,22 @@ const ( // CoreController represents a controller for managing Xray core instance lifecycle type CoreController struct { - CallbackHandler CoreCallbackHandler - statsManager corestats.Manager - coreMutex sync.Mutex - coreInstance *core.Instance - IsRunning bool + mu sync.Mutex + callback CoreCallbackHandler + instance *core.Instance + stats corestats.Manager + notifications []lifecycleNotification + notifying bool } +type lifecycleNotification struct { + callback CoreCallbackHandler + running bool +} + +// Xray reads process-wide environment settings during instance initialization. +var coreInitMu sync.Mutex + // CoreCallbackHandler defines interface for receiving callbacks and notifications from the core service type CoreCallbackHandler interface { Startup() int @@ -64,6 +73,9 @@ func setEnvVariable(key, value string) { // It sets up asset path, certificate path, XUDP base key and customizes the file reader // to support Android asset system func InitCoreEnv(envPath string, key string) { + coreInitMu.Lock() + defer coreInitMu.Unlock() + // Set asset/cert paths if len(envPath) > 0 { setEnvVariable(coreAsset, envPath) @@ -98,43 +110,109 @@ func NewCoreController(s CoreCallbackHandler) *CoreController { log.Printf("Failed to register log handler: %v", err) } - return &CoreController{ - CallbackHandler: s, - } + return &CoreController{callback: s} } -// StartLoop initializes and starts the core processing loop -// Thread-safe method that configures and runs the Xray core with the provided configuration -// Returns immediately if the core is already running -func (x *CoreController) StartLoop(configContent string, tunFd int32) (err error) { - // Set TUN fd key, 0 means do not use TUN - setEnvVariable(tunFdKey, strconv.Itoa(int(tunFd))) +// GetCallbackHandler returns the handler for future lifecycle notifications. +func (x *CoreController) GetCallbackHandler() CoreCallbackHandler { + x.mu.Lock() + defer x.mu.Unlock() + return x.callback +} + +// SetCallbackHandler replaces the handler for future lifecycle notifications. +func (x *CoreController) SetCallbackHandler(callback CoreCallbackHandler) { + x.mu.Lock() + defer x.mu.Unlock() + x.callback = callback +} - x.coreMutex.Lock() - defer x.coreMutex.Unlock() +// GetIsRunning reports whether the controller has a started core. +func (x *CoreController) GetIsRunning() bool { + x.mu.Lock() + defer x.mu.Unlock() + return x.instance != nil +} - if x.IsRunning { - log.Println("Core is already running") +// SetIsRunning retains the existing Java binding and has no effect. +// +// Deprecated: Use StartLoop and StopLoop to change the running state. +func (x *CoreController) SetIsRunning(_ bool) {} + +// StartLoop starts the core unless it is already running. +func (x *CoreController) StartLoop(configContent string, tunFd int32) error { + x.mu.Lock() + defer x.unlockAndNotify() + if x.instance != nil { return nil } - return x.doStartLoop(configContent) + instance, err := startCore(configContent, tunFd) + if err != nil { + return err + } + x.instance = instance + x.stats, _ = instance.GetFeature(corestats.ManagerType()).(corestats.Manager) + x.queueNotification(true) + return nil } -// StopLoop safely stops the core processing loop and releases resources -// Thread-safe method that shuts down the core instance and triggers necessary callbacks +// StopLoop shuts down the core and releases its resources. func (x *CoreController) StopLoop() error { - x.coreMutex.Lock() - defer x.coreMutex.Unlock() + x.mu.Lock() + defer x.unlockAndNotify() + if x.instance == nil { + return nil + } - if x.IsRunning { - x.doShutdown() - x.CallbackHandler.Shutdown() - x.CallbackHandler.OnEmitStatus(0, "Core stopped") + if err := x.instance.Close(); err != nil { + log.Printf("core shutdown error: %v", err) } + x.instance, x.stats = nil, nil + x.queueNotification(false) return nil } +// queueNotification snapshots the handler at the transition, with mu held. +func (x *CoreController) queueNotification(running bool) { + if x.callback != nil { + x.notifications = append(x.notifications, lifecycleNotification{ + callback: x.callback, + running: running, + }) + } +} + +// unlockAndNotify takes ownership of the queue before releasing mu. Reentrant +// and concurrent transitions can enqueue while the callback is running. +func (x *CoreController) unlockAndNotify() { + defer x.mu.Unlock() + if x.notifying { + return + } + x.notifying = true + defer func() { x.notifying = false }() + for len(x.notifications) > 0 { + notification := x.notifications[0] + x.notifications[0] = lifecycleNotification{} + x.notifications = x.notifications[1:] + x.notify(notification) + } + x.notifications = nil +} + +func (x *CoreController) notify(notification lifecycleNotification) { + x.mu.Unlock() + defer x.mu.Lock() + if notification.running { + notification.callback.Startup() + notification.callback.OnEmitStatus(0, "Started successfully, running") + return + } + notification.callback.Shutdown() + notification.callback.OnEmitStatus(0, "Core stopped") +} + // CheckVersionX returns the library and Xray versions func CheckVersionX() string { return fmt.Sprintf("Lib v%d, Xray-core v%s", libVersion, core.Version()) @@ -147,44 +225,28 @@ func ReconcileBrowserDialer(dialerAddr string) { browser_dialer.Reload() } -// doShutdown shuts down the Xray instance and cleans up resources -func (x *CoreController) doShutdown() { - if x.coreInstance != nil { - if err := x.coreInstance.Close(); err != nil { - log.Printf("core shutdown error: %v", err) - } - x.coreInstance = nil - } - x.IsRunning = false - x.statsManager = nil -} +func startCore(configContent string, tunFd int32) (*core.Instance, error) { + coreInitMu.Lock() + defer coreInitMu.Unlock() -// doStartLoop sets up and starts the Xray core -func (x *CoreController) doStartLoop(configContent string) error { - log.Println("initializing core...") config, err := coreserial.LoadJSONConfig(strings.NewReader(configContent)) if err != nil { - return fmt.Errorf("config error: %w", err) + return nil, fmt.Errorf("config error: %w", err) } - x.coreInstance, err = core.New(config) + // Xray reads this process-wide descriptor when starting its TUN inbound. + setEnvVariable(tunFdKey, strconv.FormatInt(int64(tunFd), 10)) + instance, err := core.New(config) if err != nil { - return fmt.Errorf("core init failed: %w", err) + return nil, fmt.Errorf("core init failed: %w", err) } - x.statsManager = x.coreInstance.GetFeature(corestats.ManagerType()).(corestats.Manager) - - log.Println("starting core...") - x.IsRunning = true - if err := x.coreInstance.Start(); err != nil { - x.doShutdown() - return fmt.Errorf("startup failed: %w", err) + if err := instance.Start(); err != nil { + if closeErr := instance.Close(); closeErr != nil { + log.Printf("core startup cleanup error: %v", closeErr) + } + return nil, fmt.Errorf("startup failed: %w", err) } - - x.CallbackHandler.Startup() - x.CallbackHandler.OnEmitStatus(0, "Started successfully, running") - - log.Println("Starting core successfully") - return nil + return instance, nil } // Log writer implementation diff --git a/libv2ray_utils.go b/libv2ray_utils.go index 342e516f..0821f79d 100644 --- a/libv2ray_utils.go +++ b/libv2ray_utils.go @@ -22,13 +22,15 @@ import ( // Returns a single-line text in format: tag,direction,value;tag,direction,value; // Returns an empty string if the stats manager is not initialized or no counters exist. func (x *CoreController) QueryAllOutboundTrafficStats() string { - if x.statsManager == nil { + x.mu.Lock() + defer x.mu.Unlock() + if x.stats == nil { return "" } var b strings.Builder - x.statsManager.VisitCounters(func(name string, counter corestats.Counter) bool { + x.stats.VisitCounters(func(name string, counter corestats.Counter) bool { parts := strings.Split(name, ">>>") if len(parts) != 4 || parts[0] != "outbound" || parts[2] != "traffic" { return true @@ -59,7 +61,10 @@ func (x *CoreController) MeasureDelay(url string) (int64, error) { ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) defer cancel() - return measureInstDelay(ctx, x.coreInstance, url) + x.mu.Lock() + instance := x.instance + x.mu.Unlock() + return measureInstDelay(ctx, instance, url) } // MeasureOutboundDelay measures the outbound delay for a given configuration and URL