sing-box/box.go

422 lines
12 KiB
Go
Raw Normal View History

2022-06-30 13:27:56 +00:00
package box
import (
"context"
"fmt"
2022-07-12 07:17:29 +00:00
"io"
"os"
"runtime/debug"
2022-07-04 11:34:45 +00:00
"time"
2022-06-30 13:27:56 +00:00
"github.com/sagernet/sing-box/adapter"
2024-11-21 10:10:41 +00:00
"github.com/sagernet/sing-box/adapter/endpoint"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
2024-11-10 08:46:59 +00:00
"github.com/sagernet/sing-box/common/dialer"
"github.com/sagernet/sing-box/common/taskmonitor"
C "github.com/sagernet/sing-box/constant"
2022-07-19 23:12:40 +00:00
"github.com/sagernet/sing-box/experimental"
2023-11-28 04:00:28 +00:00
"github.com/sagernet/sing-box/experimental/cachefile"
2023-02-28 11:02:27 +00:00
"github.com/sagernet/sing-box/experimental/libbox/platform"
2022-06-30 13:27:56 +00:00
"github.com/sagernet/sing-box/log"
2022-07-02 06:07:50 +00:00
"github.com/sagernet/sing-box/option"
2024-11-01 16:39:02 +00:00
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/route"
2022-07-08 15:03:57 +00:00
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
2024-11-10 08:46:59 +00:00
"github.com/sagernet/sing/common/ntp"
2023-08-29 05:43:42 +00:00
"github.com/sagernet/sing/service"
2023-08-07 09:46:51 +00:00
"github.com/sagernet/sing/service/pause"
2022-06-30 13:27:56 +00:00
)
2022-07-07 13:47:21 +00:00
var _ adapter.Service = (*Box)(nil)
2022-06-30 13:27:56 +00:00
2022-07-07 13:47:21 +00:00
type Box struct {
2024-11-10 08:46:59 +00:00
createdAt time.Time
logFactory log.Factory
logger log.ContextLogger
network *route.NetworkManager
2024-11-21 10:10:41 +00:00
endpoint *endpoint.Manager
2024-11-10 08:46:59 +00:00
inbound *inbound.Manager
outbound *outbound.Manager
2024-11-20 03:32:02 +00:00
connection *route.ConnectionManager
router *route.Router
2024-11-10 08:46:59 +00:00
services []adapter.LifecycleService
done chan struct{}
2022-06-30 13:27:56 +00:00
}
2023-04-03 10:24:20 +00:00
type Options struct {
option.Options
Context context.Context
2023-11-15 05:05:33 +00:00
PlatformLogWriter log.PlatformWriter
2023-04-03 10:24:20 +00:00
}
2023-03-17 06:51:09 +00:00
2024-11-10 08:46:59 +00:00
func Context(
ctx context.Context,
inboundRegistry adapter.InboundRegistry,
outboundRegistry adapter.OutboundRegistry,
2024-11-21 10:10:41 +00:00
endpointRegistry adapter.EndpointRegistry,
2024-11-10 08:46:59 +00:00
) context.Context {
2024-11-01 16:39:02 +00:00
if service.FromContext[option.InboundOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.InboundRegistry](ctx) == nil {
ctx = service.ContextWith[option.InboundOptionsRegistry](ctx, inboundRegistry)
ctx = service.ContextWith[adapter.InboundRegistry](ctx, inboundRegistry)
}
if service.FromContext[option.OutboundOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.OutboundRegistry](ctx) == nil {
ctx = service.ContextWith[option.OutboundOptionsRegistry](ctx, outboundRegistry)
ctx = service.ContextWith[adapter.OutboundRegistry](ctx, outboundRegistry)
}
2024-11-21 10:10:41 +00:00
if service.FromContext[option.EndpointOptionsRegistry](ctx) == nil ||
service.FromContext[adapter.EndpointRegistry](ctx) == nil {
ctx = service.ContextWith[option.EndpointOptionsRegistry](ctx, endpointRegistry)
ctx = service.ContextWith[adapter.EndpointRegistry](ctx, endpointRegistry)
}
2024-11-01 16:39:02 +00:00
return ctx
}
2023-04-03 10:24:20 +00:00
func New(options Options) (*Box, error) {
2023-11-28 04:00:28 +00:00
createdAt := time.Now()
2023-04-03 10:24:20 +00:00
ctx := options.Context
if ctx == nil {
ctx = context.Background()
}
ctx = service.ContextWithDefaultRegistry(ctx)
2024-11-10 08:46:59 +00:00
2024-11-21 10:10:41 +00:00
endpointRegistry := service.FromContext[adapter.EndpointRegistry](ctx)
2024-11-01 16:39:02 +00:00
inboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)
2024-11-21 10:10:41 +00:00
outboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)
if endpointRegistry == nil {
return nil, E.New("missing endpoint registry in context")
}
2024-11-01 16:39:02 +00:00
if inboundRegistry == nil {
return nil, E.New("missing inbound registry in context")
}
if outboundRegistry == nil {
return nil, E.New("missing outbound registry in context")
}
2024-11-10 08:46:59 +00:00
2023-12-16 07:40:14 +00:00
ctx = pause.WithDefaultManager(ctx)
2023-03-17 06:51:09 +00:00
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
2023-11-28 04:00:28 +00:00
var needCacheFile bool
2022-07-19 14:16:49 +00:00
var needClashAPI bool
2022-09-26 11:37:06 +00:00
var needV2RayAPI bool
2023-11-28 04:00:28 +00:00
if experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled || options.PlatformLogWriter != nil {
needCacheFile = true
}
2023-11-20 15:41:10 +00:00
if experimentalOptions.ClashAPI != nil || options.PlatformLogWriter != nil {
2023-03-17 06:51:09 +00:00
needClashAPI = true
}
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
needV2RayAPI = true
2022-07-19 14:16:49 +00:00
}
2024-11-01 16:39:02 +00:00
platformInterface := service.FromContext[platform.Interface](ctx)
2023-04-03 10:24:20 +00:00
var defaultLogWriter io.Writer
2024-11-01 16:39:02 +00:00
if platformInterface != nil {
2023-04-03 10:24:20 +00:00
defaultLogWriter = io.Discard
}
logFactory, err := log.New(log.Options{
2023-04-21 09:29:00 +00:00
Context: ctx,
2023-04-03 10:24:20 +00:00
Options: common.PtrValueOrDefault(options.Log),
Observable: needClashAPI,
DefaultWriter: defaultLogWriter,
BaseTime: createdAt,
2023-11-15 05:05:33 +00:00
PlatformWriter: options.PlatformLogWriter,
2023-04-03 10:24:20 +00:00
})
if err != nil {
return nil, E.Cause(err, "create log factory")
2022-06-30 13:27:56 +00:00
}
2024-11-10 08:46:59 +00:00
routeOptions := common.PtrValueOrDefault(options.Route)
2024-11-21 10:10:41 +00:00
endpointManager := endpoint.NewManager(logFactory.NewLogger("endpoint"), endpointRegistry)
inboundManager := inbound.NewManager(logFactory.NewLogger("inbound"), inboundRegistry, endpointManager)
outboundManager := outbound.NewManager(logFactory.NewLogger("outbound"), outboundRegistry, endpointManager, routeOptions.Final)
service.MustRegister[adapter.EndpointManager](ctx, endpointManager)
2024-11-10 08:46:59 +00:00
service.MustRegister[adapter.InboundManager](ctx, inboundManager)
service.MustRegister[adapter.OutboundManager](ctx, outboundManager)
2024-11-10 04:11:21 +00:00
networkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger("network"), routeOptions)
2022-07-02 06:07:50 +00:00
if err != nil {
2024-11-10 04:11:21 +00:00
return nil, E.Cause(err, "initialize network manager")
}
2024-11-10 08:46:59 +00:00
service.MustRegister[adapter.NetworkManager](ctx, networkManager)
2024-11-20 03:32:02 +00:00
connectionManager := route.NewConnectionManager(logFactory.NewLogger("connection"))
service.MustRegister[adapter.ConnectionManager](ctx, connectionManager)
2024-11-10 08:46:59 +00:00
router, err := route.NewRouter(ctx, logFactory, routeOptions, common.PtrValueOrDefault(options.DNS))
2024-11-10 04:11:21 +00:00
if err != nil {
return nil, E.Cause(err, "initialize router")
2022-06-30 13:27:56 +00:00
}
2024-11-21 10:10:41 +00:00
for i, endpointOptions := range options.Endpoints {
var tag string
if endpointOptions.Tag != "" {
tag = endpointOptions.Tag
} else {
tag = F.ToString(i)
}
err = endpointManager.Create(ctx,
router,
logFactory.NewLogger(F.ToString("endpoint/", endpointOptions.Type, "[", tag, "]")),
tag,
endpointOptions.Type,
endpointOptions.Options,
)
if err != nil {
return nil, E.Cause(err, "initialize inbound[", i, "]")
}
}
2022-07-02 14:55:10 +00:00
for i, inboundOptions := range options.Inbounds {
2022-07-12 07:17:29 +00:00
var tag string
if inboundOptions.Tag != "" {
tag = inboundOptions.Tag
} else {
tag = F.ToString(i)
}
err = inboundManager.Create(ctx,
2022-07-12 07:17:29 +00:00
router,
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
2024-06-11 13:16:33 +00:00
tag,
2024-11-01 16:39:02 +00:00
inboundOptions.Type,
inboundOptions.Options,
2022-07-12 07:17:29 +00:00
)
2022-07-02 14:55:10 +00:00
if err != nil {
return nil, E.Cause(err, "initialize inbound[", i, "]")
2022-06-30 13:27:56 +00:00
}
}
for i, outboundOptions := range options.Outbounds {
2022-07-12 07:17:29 +00:00
var tag string
if outboundOptions.Tag != "" {
tag = outboundOptions.Tag
} else {
tag = F.ToString(i)
}
2024-11-01 16:39:02 +00:00
outboundCtx := ctx
if tag != "" {
// TODO: remove this
outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
Outbound: tag,
})
}
err = outboundManager.Create(
2024-11-01 16:39:02 +00:00
outboundCtx,
2022-07-12 07:17:29 +00:00
router,
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
2023-04-08 00:58:01 +00:00
tag,
2024-11-01 16:39:02 +00:00
outboundOptions.Type,
outboundOptions.Options,
)
2022-06-30 13:27:56 +00:00
if err != nil {
return nil, E.Cause(err, "initialize outbound[", i, "]")
2022-06-30 13:27:56 +00:00
}
2022-07-02 06:07:50 +00:00
}
outboundManager.Initialize(common.Must1(
direct.NewOutbound(
ctx,
router,
logFactory.NewLogger("outbound/direct"),
"direct",
option.DirectOutboundOptions{},
),
))
2024-11-01 16:39:02 +00:00
if platformInterface != nil {
2024-11-10 04:11:21 +00:00
err = platformInterface.Initialize(networkManager)
2023-04-18 06:04:09 +00:00
if err != nil {
return nil, E.Cause(err, "initialize platform interface")
}
}
2024-11-10 08:46:59 +00:00
var services []adapter.LifecycleService
2023-11-28 04:00:28 +00:00
if needCacheFile {
2024-11-10 08:46:59 +00:00
cacheFile := cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
service.MustRegister[adapter.CacheFile](ctx, cacheFile)
services = append(services, cacheFile)
2023-11-28 04:00:28 +00:00
}
2022-07-19 14:16:49 +00:00
if needClashAPI {
clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI)
clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
clashServer, err := experimental.NewClashServer(ctx, logFactory.(log.ObservableFactory), clashAPIOptions)
2022-07-19 23:12:40 +00:00
if err != nil {
2024-11-10 08:46:59 +00:00
return nil, E.Cause(err, "create clash-server")
2022-07-19 23:12:40 +00:00
}
2024-11-10 08:46:59 +00:00
router.SetTracker(clashServer)
service.MustRegister[adapter.ClashServer](ctx, clashServer)
services = append(services, clashServer)
2022-07-19 14:16:49 +00:00
}
2022-09-26 11:37:06 +00:00
if needV2RayAPI {
v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
2022-09-26 11:37:06 +00:00
if err != nil {
2024-11-10 08:46:59 +00:00
return nil, E.Cause(err, "create v2ray-server")
}
if v2rayServer.StatsService() != nil {
router.SetTracker(v2rayServer.StatsService())
services = append(services, v2rayServer)
service.MustRegister[adapter.V2RayServer](ctx, v2rayServer)
}
}
ntpOptions := common.PtrValueOrDefault(options.NTP)
if ntpOptions.Enabled {
ntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions)
if err != nil {
return nil, E.Cause(err, "create NTP service")
2022-09-26 11:37:06 +00:00
}
2024-11-10 08:46:59 +00:00
timeService := ntp.NewService(ntp.Options{
Context: ctx,
Dialer: ntpDialer,
Logger: logFactory.NewLogger("ntp"),
Server: ntpOptions.ServerOptions.Build(),
Interval: time.Duration(ntpOptions.Interval),
WriteToSystem: ntpOptions.WriteToSystem,
})
service.MustRegister[ntp.TimeService](ctx, timeService)
services = append(services, adapter.NewLifecycleService(timeService, "ntp service"))
2022-09-26 11:37:06 +00:00
}
2022-07-07 13:47:21 +00:00
return &Box{
2024-11-10 08:46:59 +00:00
network: networkManager,
2024-11-21 10:10:41 +00:00
endpoint: endpointManager,
2024-11-10 08:46:59 +00:00
inbound: inboundManager,
outbound: outboundManager,
2024-11-20 03:32:02 +00:00
connection: connectionManager,
router: router,
2024-11-10 08:46:59 +00:00
createdAt: createdAt,
logFactory: logFactory,
logger: logFactory.Logger(),
services: services,
done: make(chan struct{}),
2022-07-02 06:07:50 +00:00
}, nil
2022-06-30 13:27:56 +00:00
}
2023-03-18 12:26:58 +00:00
func (s *Box) PreStart() error {
err := s.preStart()
if err != nil {
// TODO: remove catch error
defer func() {
v := recover()
if v != nil {
2024-06-25 05:10:25 +00:00
println(err.Error())
2023-03-18 12:26:58 +00:00
debug.PrintStack()
panic("panic on early close: " + fmt.Sprint(v))
}
}()
s.Close()
return err
}
s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil
}
2022-07-07 13:47:21 +00:00
func (s *Box) Start() error {
2022-08-22 04:43:21 +00:00
err := s.start()
if err != nil {
// TODO: remove catch error
defer func() {
v := recover()
if v != nil {
2024-06-25 05:10:25 +00:00
println(err.Error())
debug.PrintStack()
2024-06-25 05:10:25 +00:00
println("panic on early start: " + fmt.Sprint(v))
}
}()
2022-08-22 04:43:21 +00:00
s.Close()
2023-03-18 12:26:58 +00:00
return err
2022-08-22 04:43:21 +00:00
}
2023-03-18 12:26:58 +00:00
s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil
2022-08-22 04:43:21 +00:00
}
2023-03-18 12:26:58 +00:00
func (s *Box) preStart() error {
2024-04-02 15:07:26 +00:00
monitor := taskmonitor.New(s.logger, C.StartTimeout)
monitor.Start("start logger")
err := s.logFactory.Start()
monitor.Finish()
if err != nil {
return E.Cause(err, "start logger")
}
2024-11-10 08:46:59 +00:00
err = adapter.StartNamed(adapter.StartStateInitialize, s.services) // cache-file clash-api v2ray-api
if err != nil {
2024-11-10 08:46:59 +00:00
return err
}
2024-11-21 10:10:41 +00:00
err = adapter.Start(adapter.StartStateInitialize, s.network, s.connection, s.router, s.outbound, s.inbound, s.endpoint)
2023-06-13 14:38:05 +00:00
if err != nil {
return err
2022-06-30 13:27:56 +00:00
}
2024-11-20 03:32:02 +00:00
err = adapter.Start(adapter.StartStateStart, s.outbound, s.network, s.connection, s.router)
2024-11-10 04:11:21 +00:00
if err != nil {
return err
}
2024-11-10 08:46:59 +00:00
return nil
2023-03-18 12:26:58 +00:00
}
func (s *Box) start() error {
err := s.preStart()
2022-08-20 01:13:00 +00:00
if err != nil {
return err
}
2024-11-10 08:46:59 +00:00
err = adapter.StartNamed(adapter.StartStateStart, s.services)
2024-06-07 07:55:21 +00:00
if err != nil {
return err
}
2024-11-10 08:46:59 +00:00
err = s.inbound.Start(adapter.StartStateStart)
if err != nil {
return err
}
2024-11-21 10:10:41 +00:00
err = adapter.Start(adapter.StartStateStart, s.endpoint)
if err != nil {
return err
}
err = adapter.Start(adapter.StartStatePostStart, s.outbound, s.network, s.connection, s.router, s.inbound, s.endpoint)
2024-11-10 04:11:21 +00:00
if err != nil {
return err
}
2024-11-10 08:46:59 +00:00
err = adapter.StartNamed(adapter.StartStatePostStart, s.services)
if err != nil {
return err
}
2024-11-21 10:10:41 +00:00
err = adapter.Start(adapter.StartStateStarted, s.network, s.connection, s.router, s.outbound, s.inbound, s.endpoint)
if err != nil {
return err
}
2024-11-10 08:46:59 +00:00
err = adapter.StartNamed(adapter.StartStateStarted, s.services)
if err != nil {
return err
2024-06-07 07:55:21 +00:00
}
return nil
2022-06-30 13:27:56 +00:00
}
2022-07-07 13:47:21 +00:00
func (s *Box) Close() error {
2022-08-12 04:13:57 +00:00
select {
case <-s.done:
return os.ErrClosed
default:
close(s.done)
}
2024-11-10 08:46:59 +00:00
err := common.Close(
2024-11-20 03:32:02 +00:00
s.inbound, s.outbound, s.router, s.connection, s.network,
2024-11-10 08:46:59 +00:00
)
for _, lifecycleService := range s.services {
err = E.Append(err, lifecycleService.Close(), func(err error) error {
return E.Cause(err, "close ", lifecycleService.Name())
2022-10-25 04:55:00 +00:00
})
}
2024-11-10 08:46:59 +00:00
err = E.Append(err, s.logFactory.Close(), func(err error) error {
return E.Cause(err, "close logger")
})
return err
}
2024-11-10 04:11:21 +00:00
func (s *Box) Network() adapter.NetworkManager {
return s.network
}
2022-09-26 11:37:06 +00:00
func (s *Box) Router() adapter.Router {
return s.router
}
2024-11-10 08:46:59 +00:00
func (s *Box) Inbound() adapter.InboundManager {
return s.inbound
}
func (s *Box) Outbound() adapter.OutboundManager {
return s.outbound
}