Files
MeshPort/engines/singbox/bridge/engine.go
T
shenandshen c7cc2aa865 Fix VPN internet connectivity and simplify client setup
Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
2026-10-12 06:51:25 -07:00

249 lines
7.2 KiB
Go

// Package bridge provides an explicitly managed sing-box lifecycle. Platform
// TUN integration and ordinary internet proxy profiles are separate milestones.
package bridge
import (
"context"
"errors"
"fmt"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/common/control"
"github.com/sagernet/sing/service"
"net"
"os"
"path/filepath"
"runtime"
"sync"
"time"
box "github.com/sagernet/sing-box"
"github.com/sagernet/sing-box/adapter/certificate"
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
boxservice "github.com/sagernet/sing-box/adapter/service"
"github.com/sagernet/sing-box/dns"
"github.com/sagernet/sing-box/dns/transport"
"github.com/sagernet/sing-box/dns/transport/fakeip"
"github.com/sagernet/sing-box/dns/transport/local"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/protocol/http"
"github.com/sagernet/sing-box/protocol/shadowsocks"
"github.com/sagernet/sing-box/protocol/trojan"
"github.com/sagernet/sing-box/protocol/tun"
"github.com/sagernet/sing-box/protocol/vless"
"github.com/sagernet/sing-box/protocol/vmess"
sjson "github.com/sagernet/sing/common/json"
)
func registryContext(ctx context.Context) context.Context {
in := inbound.NewRegistry()
registerTrackedInbound(in)
tun.RegisterInbound(in)
out := outbound.NewRegistry()
registerMeshOutbound(out)
shadowsocks.RegisterOutbound(out)
vmess.RegisterOutbound(out)
vless.RegisterOutbound(out)
trojan.RegisterOutbound(out)
http.RegisterOutbound(out)
direct.RegisterOutbound(out) // Required for sing-box's internal defaults.
dnsRegistry := dns.NewTransportRegistry()
local.RegisterTransport(dnsRegistry)
transport.RegisterUDP(dnsRegistry)
transport.RegisterHTTPS(dnsRegistry)
transport.RegisterTLS(dnsRegistry)
fakeip.RegisterTransport(dnsRegistry)
return box.Context(ctx, in, out, endpoint.NewRegistry(), dnsRegistry,
boxservice.NewRegistry(), certificate.NewRegistry())
}
type Snapshot struct {
State string `json:"state"`
Version string `json:"version"`
RuntimeEvents []RuntimeEvent `json:"runtime_events,omitempty"`
}
type Engine struct {
runtimeLogs runtimeLogs
selfTestTrace bool
startupCause error // Private diagnostic for package tests; never returned over ABI.
// Protector must be installed before starting a host TUN.
CacheRoot string
cacheDir string
Protect func(int) error
mu sync.Mutex
box *box.Box
state string
cancel context.CancelFunc
ctx context.Context
desktopTun bool
}
func (e *Engine) Snapshot() Snapshot {
e.mu.Lock()
defer e.mu.Unlock()
state := e.state
if state == "" {
state = "Stopped"
}
if state == "Running" && e.ctx.Err() != nil {
state = "Failed"
}
return Snapshot{State: state, Version: "1.14.3", RuntimeEvents: e.runtimeLogs.snapshot()}
}
func (e *Engine) Start(parent context.Context, config Config) error {
e.mu.Lock()
defer e.mu.Unlock()
if e.box != nil {
return errors.New("engine already started; stop before applying configuration")
}
if parent.Err() != nil {
return errors.New("engine context is canceled")
}
if config.DesktopTun && (runtime.GOOS != "darwin" || os.Geteuid() != 0) {
return errors.New("desktop TUN requires macOS privileged helper")
}
if config.DesktopTun {
attached, err := desktopTunAddressAttached()
if err != nil {
return errors.New("cannot inspect desktop TUN address")
}
if attached {
return errors.New("desktop TUN address already in use")
}
}
data, err := config.managedJSON()
if err != nil {
return err
}
e.selfTestTrace = config.selfTestTrace()
e.desktopTun = config.DesktopTun
e.state = "Starting"
ctx, cancel := context.WithCancel(parent)
ctx = registryContext(ctx)
if config.Tun != nil {
if e.Protect == nil {
cancel()
e.state = "Failed"
return errors.New("platform socket protection required")
}
physical := &control.Interface{Name: config.Tun.Interface, Index: config.Tun.Index, MTU: 1500, Flags: net.FlagUp}
ctx = service.ContextWith[adapter.PlatformInterface](ctx, &hostPlatform{config: *config.Tun, protect: e.Protect, monitor: &hostMonitor{physical: physical}})
}
options, err := sjson.UnmarshalExtendedContext[option.Options](ctx, data)
if err != nil {
cancel()
e.state = "Failed"
return startupFailure("decode_configuration", err)
}
if config.FakeIP || len(config.RuleSets) > 0 {
if e.cacheDir == "" {
e.cacheDir, err = os.MkdirTemp(e.CacheRoot, "meshport-fakeip-")
if err != nil {
cancel()
e.state = "Failed"
return errors.New("cannot create private DNS cache")
}
}
options.Experimental = &option.ExperimentalOptions{CacheFile: &option.CacheFileOptions{Enabled: true, Path: filepath.Join(e.cacheDir, "fakeip.db"), StoreFakeIP: config.FakeIP}}
}
e.runtimeLogs.configure(config.Proxy)
// Collect bounded, credential-redacted warning/error events in memory.
// Raw upstream logs must never go to stderr or a user's log file.
if !e.selfTestTrace {
options.Log = &option.LogOptions{Level: "warn", Output: os.DevNull}
}
instance, err := box.New(box.Options{Options: options, Context: ctx})
if err != nil {
e.startupCause = err
cancel()
e.state = "Failed"
return startupFailure("initialize_engine", err)
}
instance.LogFactory().AttachPlatformWriter(&e.runtimeLogs)
if err = instance.Start(); err != nil {
e.startupCause = err
_ = instance.Close()
cancel()
e.state = "Failed"
return startupFailure("start_engine", err)
}
e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running"
return nil
}
func (e *Engine) Stop() error {
e.mu.Lock()
defer e.mu.Unlock()
if e.box == nil {
e.state = "Stopped"
return nil
}
e.state = "Stopping"
err := e.box.Close()
e.cancel()
e.box, e.cancel, e.ctx = nil, nil, nil
if e.desktopTun && err == nil {
// Darwin can retain the utun address until its last kernel reference
// drains. Reusing that address immediately can attach the new routes
// to the retiring interface and remove them when it finally disappears.
deadline := time.Now().Add(2 * time.Second)
for {
attached, inspectErr := desktopTunAddressAttached()
if inspectErr != nil {
err = inspectErr
break
}
if !attached {
break
}
if time.Now().After(deadline) {
err = errors.New("desktop TUN address did not detach")
break
}
time.Sleep(20 * time.Millisecond)
}
}
if err != nil {
e.state = "Failed"
if e.selfTestTrace {
fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err)
}
return errors.New("proxy engine cleanup failed")
}
e.state = "Stopped"
return nil
}
func desktopTunAddressAttached() (bool, error) {
addresses, err := net.InterfaceAddrs()
if err != nil {
return false, err
}
for _, address := range addresses {
ip, _, err := net.ParseCIDR(address.String())
if err == nil && ip.Equal(net.ParseIP("172.19.0.1")) {
return true, nil
}
}
return false, nil
}
// Close releases the session's private cache only after the engine is stopped.
func (e *Engine) Close() error {
err := e.Stop()
e.mu.Lock()
defer e.mu.Unlock()
if e.cacheDir != "" {
removeErr := os.RemoveAll(e.cacheDir)
e.cacheDir = ""
if err == nil {
err = removeErr
}
}
return err
}