Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
186 changes: 129 additions & 57 deletions libv2ray_main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package libv2ray

import (
"context"
"fmt"
"io"
"log"
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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())
Expand All @@ -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
Expand Down
Loading