diff --git a/libv2ray_main.go b/libv2ray_main.go index 68af7eff..6d096ed4 100644 --- a/libv2ray_main.go +++ b/libv2ray_main.go @@ -1,6 +1,7 @@ package libv2ray import ( + "context" "fmt" "io" "log" @@ -33,13 +34,25 @@ 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 + probeContext context.Context + cancelProbes context.CancelFunc + probes sync.WaitGroup + 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 +77,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 +114,115 @@ 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.probeContext, x.cancelProbes = context.WithCancel(context.Background()) + 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") + // Keep new probes out until the active probes release the instance. + x.cancelProbes() + x.probes.Wait() + x.probeContext, x.cancelProbes = nil, nil + + 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 +235,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..c1e57662 100644 --- a/libv2ray_utils.go +++ b/libv2ray_utils.go @@ -18,17 +18,21 @@ import ( coreserial "github.com/xtls/xray-core/infra/conf/serial" ) +const delayProbeTimeout = 12 * time.Second + // QueryAllOutboundTrafficStats retrieves and resets all outbound traffic counters. // 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 @@ -56,17 +60,52 @@ func (x *CoreController) QueryAllOutboundTrafficStats() string { // Uses a 12-second timeout context and returns the round-trip time in milliseconds // An error is returned if the connection fails or returns an unexpected status func (x *CoreController) MeasureDelay(url string) (int64, error) { - ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) + x.mu.Lock() + instance := x.instance + if instance == nil { + x.mu.Unlock() + return -1, errors.New("core instance is nil") + } + ctx, cancel := context.WithTimeout(x.probeContext, delayProbeTimeout) + x.probes.Add(1) + x.mu.Unlock() + defer x.probes.Done() defer cancel() - return measureInstDelay(ctx, x.coreInstance, url) + return measureInstDelay(ctx, instance, url) } // MeasureOutboundDelay measures the outbound delay for a given configuration and URL func MeasureOutboundDelay(ConfigureFileContent string, url string) (int64, error) { - config, err := coreserial.LoadJSONConfig(strings.NewReader(ConfigureFileContent)) + ctx, cancel := context.WithTimeout(context.Background(), delayProbeTimeout) + inst, err := newProbeInstance(ctx, ConfigureFileContent) + if err != nil { + cancel() + return -1, err + } + defer func() { + cancel() + inst.Close() + }() + if err := ctx.Err(); err != nil { + return -1, err + } + if err := inst.Start(); err != nil { + return -1, fmt.Errorf("startup failed: %w", err) + } + return measureInstDelay(ctx, inst, url) +} + +func newProbeInstance(ctx context.Context, configContent string) (*core.Instance, error) { + coreInitMu.Lock() + defer coreInitMu.Unlock() + + if err := ctx.Err(); err != nil { + return nil, err + } + config, err := coreserial.LoadJSONConfig(strings.NewReader(configContent)) if err != nil { - return -1, fmt.Errorf("config load error: %w", err) + return nil, fmt.Errorf("config load error: %w", err) } config.Inbound = nil @@ -80,24 +119,18 @@ func MeasureOutboundDelay(ConfigureFileContent string, url string) (int64, error } config.App = essentialApp - inst, err := core.New(config) - if err != nil { - return -1, fmt.Errorf("instance creation failed: %w", err) + if err := ctx.Err(); err != nil { + return nil, err } - - if err := inst.Start(); err != nil { - return -1, fmt.Errorf("startup failed: %w", err) + inst, err := core.NewWithContext(ctx, config) + if err != nil { + return nil, fmt.Errorf("instance creation failed: %w", err) } - defer inst.Close() - return measureInstDelay(context.Background(), inst, url) + return inst, nil } // measureInstDelay measures the delay for an instance to a given URL func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int64, error) { - if inst == nil { - return -1, errors.New("core instance is nil") - } - if url == "" { url = "https://www.google.com/generate_204" } @@ -105,7 +138,12 @@ func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int tr := &http.Transport{ TLSHandshakeTimeout: 6 * time.Second, DisableKeepAlives: false, - DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + DialContext: func(_ context.Context, network, addr string) (net.Conn, error) { + // Dials can outlive individual HTTP requests. Bind Xray's + // connection to the shared probe context. + if err := ctx.Err(); err != nil { + return nil, err + } dest, err := corenet.ParseDestination(fmt.Sprintf("%s:%s", network, addr)) if err != nil { return nil, err @@ -114,10 +152,7 @@ func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int }, } - client := &http.Client{ - Transport: tr, - Timeout: 12 * time.Second, - } + client := &http.Client{Transport: tr} var minDuration int64 = -1 success := false @@ -127,19 +162,13 @@ func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int const attempts = 2 for i := 0; i < attempts; i++ { - select { - case <-ctx.Done(): - if !success { - return -1, ctx.Err() - } - return minDuration, nil - default: + if ctx.Err() != nil { + break } - req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { - lastErr = fmt.Errorf("failed to create HTTP request: %w", err) - continue + return -1, fmt.Errorf("failed to create HTTP request: %w", err) } start := time.Now() @@ -149,14 +178,14 @@ func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int continue } - _, err = io.Copy(io.Discard, resp.Body) - resp.Body.Close() - if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + resp.Body.Close() lastErr = fmt.Errorf("invalid status: %s", resp.Status) continue } + _, err = io.Copy(io.Discard, resp.Body) + resp.Body.Close() if err != nil { lastErr = fmt.Errorf("failed to read response body: %w", err) continue @@ -169,6 +198,9 @@ func measureInstDelay(ctx context.Context, inst *core.Instance, url string) (int success = true } + if err := ctx.Err(); err != nil && (!success || errors.Is(err, context.Canceled)) { + return -1, err + } if !success { return -1, lastErr }