sing-box/box.go

453 lines
13 KiB
Go
Raw Normal View History

2022-06-30 21:27:56 +08:00
package box
import (
"context"
"fmt"
2022-07-12 15:17:29 +08:00
"io"
"os"
"runtime/debug"
2022-07-04 19:34:45 +08:00
"time"
2022-06-30 21:27:56 +08:00
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/inbound"
"github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/common/taskmonitor"
C "github.com/sagernet/sing-box/constant"
2022-07-20 07:12:40 +08:00
"github.com/sagernet/sing-box/experimental"
2023-11-28 12:00:28 +08:00
"github.com/sagernet/sing-box/experimental/cachefile"
2023-02-28 19:02:27 +08:00
"github.com/sagernet/sing-box/experimental/libbox/platform"
2022-06-30 21:27:56 +08:00
"github.com/sagernet/sing-box/log"
2022-07-02 14:07:50 +08:00
"github.com/sagernet/sing-box/option"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing-box/protocol/direct"
"github.com/sagernet/sing-box/route"
2022-07-08 23:03:57 +08:00
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
F "github.com/sagernet/sing/common/format"
2023-08-29 13:43:42 +08:00
"github.com/sagernet/sing/service"
2023-08-07 17:46:51 +08:00
"github.com/sagernet/sing/service/pause"
2022-06-30 21:27:56 +08:00
)
2022-07-07 21:47:21 +08:00
var _ adapter.Service = (*Box)(nil)
2022-06-30 21:27:56 +08:00
2022-07-07 21:47:21 +08:00
type Box struct {
2023-03-18 20:26:58 +08:00
createdAt time.Time
router adapter.Router
inbound *inbound.Manager
outbound *outbound.Manager
2024-11-10 12:11:21 +08:00
network *route.NetworkManager
2023-03-18 20:26:58 +08:00
logFactory log.Factory
logger log.ContextLogger
2023-11-28 12:00:28 +08:00
preServices1 map[string]adapter.Service
preServices2 map[string]adapter.Service
2023-03-18 20:26:58 +08:00
postServices map[string]adapter.Service
done chan struct{}
2022-06-30 21:27:56 +08:00
}
2023-04-03 18:24:20 +08:00
type Options struct {
option.Options
Context context.Context
2023-11-15 13:05:33 +08:00
PlatformLogWriter log.PlatformWriter
2023-04-03 18:24:20 +08:00
}
2023-03-17 14:51:09 +08:00
2024-11-02 00:39:02 +08:00
func Context(ctx context.Context, inboundRegistry adapter.InboundRegistry, outboundRegistry adapter.OutboundRegistry) context.Context {
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)
}
return ctx
}
2023-04-03 18:24:20 +08:00
func New(options Options) (*Box, error) {
2023-11-28 12:00:28 +08:00
createdAt := time.Now()
2023-04-03 18:24:20 +08:00
ctx := options.Context
if ctx == nil {
ctx = context.Background()
}
ctx = service.ContextWithDefaultRegistry(ctx)
2024-11-02 00:39:02 +08:00
inboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)
if inboundRegistry == nil {
return nil, E.New("missing inbound registry in context")
}
outboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)
if outboundRegistry == nil {
return nil, E.New("missing outbound registry in context")
}
2023-12-16 15:40:14 +08:00
ctx = pause.WithDefaultManager(ctx)
2023-03-17 14:51:09 +08:00
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
2023-11-28 12:00:28 +08:00
var needCacheFile bool
2022-07-19 22:16:49 +08:00
var needClashAPI bool
2022-09-26 19:37:06 +08:00
var needV2RayAPI bool
2023-11-28 12:00:28 +08:00
if experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled || options.PlatformLogWriter != nil {
needCacheFile = true
}
2023-11-20 23:41:10 +08:00
if experimentalOptions.ClashAPI != nil || options.PlatformLogWriter != nil {
2023-03-17 14:51:09 +08:00
needClashAPI = true
}
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
needV2RayAPI = true
2022-07-19 22:16:49 +08:00
}
2024-11-02 00:39:02 +08:00
platformInterface := service.FromContext[platform.Interface](ctx)
2023-04-03 18:24:20 +08:00
var defaultLogWriter io.Writer
2024-11-02 00:39:02 +08:00
if platformInterface != nil {
2023-04-03 18:24:20 +08:00
defaultLogWriter = io.Discard
}
logFactory, err := log.New(log.Options{
2023-04-21 17:29:00 +08:00
Context: ctx,
2023-04-03 18:24:20 +08:00
Options: common.PtrValueOrDefault(options.Log),
Observable: needClashAPI,
DefaultWriter: defaultLogWriter,
BaseTime: createdAt,
2023-11-15 13:05:33 +08:00
PlatformWriter: options.PlatformLogWriter,
2023-04-03 18:24:20 +08:00
})
if err != nil {
return nil, E.Cause(err, "create log factory")
2022-06-30 21:27:56 +08:00
}
routeOptions := common.PtrValueOrDefault(options.Route)
2024-11-10 12:11:21 +08:00
inboundManager := inbound.NewManager(logFactory.NewLogger("inbound"), inboundRegistry)
outboundManager := outbound.NewManager(logFactory.NewLogger("outbound"), outboundRegistry, routeOptions.Final)
ctx = service.ContextWith[adapter.InboundManager](ctx, inboundManager)
ctx = service.ContextWith[adapter.OutboundManager](ctx, outboundManager)
2024-11-10 12:11:21 +08:00
networkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger("network"), routeOptions)
2022-07-02 14:07:50 +08:00
if err != nil {
2024-11-10 12:11:21 +08:00
return nil, E.Cause(err, "initialize network manager")
}
ctx = service.ContextWith[adapter.NetworkManager](ctx, networkManager)
router, err := route.NewRouter(ctx, logFactory, routeOptions, common.PtrValueOrDefault(options.DNS), common.PtrValueOrDefault(options.NTP))
if err != nil {
return nil, E.Cause(err, "initialize router")
2022-06-30 21:27:56 +08:00
}
2024-11-02 00:39:02 +08:00
//nolint:staticcheck
if len(options.LegacyInbounds) > 0 {
for _, legacyInbound := range options.LegacyInbounds {
options.Inbounds = append(options.Inbounds, option.Inbound{
Type: legacyInbound.Type,
Tag: legacyInbound.Tag,
Options: common.Must1(legacyInbound.RawOptions()),
})
}
}
//nolint:staticcheck
if len(options.LegacyOutbounds) > 0 {
for _, legacyOutbound := range options.LegacyOutbounds {
options.Outbounds = append(options.Outbounds, option.Outbound{
Type: legacyOutbound.Type,
Tag: legacyOutbound.Tag,
Options: common.Must1(legacyOutbound.RawOptions()),
})
}
}
2022-07-02 22:55:10 +08:00
for i, inboundOptions := range options.Inbounds {
2022-07-12 15:17:29 +08:00
var tag string
if inboundOptions.Tag != "" {
tag = inboundOptions.Tag
} else {
tag = F.ToString(i)
}
err = inboundManager.Create(ctx,
2022-07-12 15:17:29 +08:00
router,
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
2024-06-11 21:16:33 +08:00
tag,
2024-11-02 00:39:02 +08:00
inboundOptions.Type,
inboundOptions.Options,
2022-07-12 15:17:29 +08:00
)
2022-07-02 22:55:10 +08:00
if err != nil {
return nil, E.Cause(err, "initialize inbound[", i, "]")
2022-06-30 21:27:56 +08:00
}
}
for i, outboundOptions := range options.Outbounds {
2022-07-12 15:17:29 +08:00
var tag string
if outboundOptions.Tag != "" {
tag = outboundOptions.Tag
} else {
tag = F.ToString(i)
}
2024-11-02 00:39:02 +08:00
outboundCtx := ctx
if tag != "" {
// TODO: remove this
outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
Outbound: tag,
})
}
err = outboundManager.Create(
2024-11-02 00:39:02 +08:00
outboundCtx,
2022-07-12 15:17:29 +08:00
router,
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
2023-04-08 08:58:01 +08:00
tag,
2024-11-02 00:39:02 +08:00
outboundOptions.Type,
outboundOptions.Options,
)
2022-06-30 21:27:56 +08:00
if err != nil {
return nil, E.Cause(err, "initialize outbound[", i, "]")
2022-06-30 21:27:56 +08:00
}
2022-07-02 14:07:50 +08:00
}
outboundManager.Initialize(common.Must1(
direct.NewOutbound(
ctx,
router,
logFactory.NewLogger("outbound/direct"),
"direct",
option.DirectOutboundOptions{},
),
))
2024-11-02 00:39:02 +08:00
if platformInterface != nil {
2024-11-10 12:11:21 +08:00
err = platformInterface.Initialize(networkManager)
2023-04-18 14:04:09 +08:00
if err != nil {
return nil, E.Cause(err, "initialize platform interface")
}
}
2023-11-28 12:00:28 +08:00
preServices1 := make(map[string]adapter.Service)
preServices2 := make(map[string]adapter.Service)
2023-03-18 20:26:58 +08:00
postServices := make(map[string]adapter.Service)
2023-11-28 12:00:28 +08:00
if needCacheFile {
2023-12-16 15:40:14 +08:00
cacheFile := service.FromContext[adapter.CacheFile](ctx)
if cacheFile == nil {
cacheFile = cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
service.MustRegister[adapter.CacheFile](ctx, cacheFile)
}
2023-11-28 12:00:28 +08:00
preServices1["cache file"] = cacheFile
}
2022-07-19 22:16:49 +08: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-20 07:12:40 +08:00
if err != nil {
return nil, E.Cause(err, "create clash api server")
}
2022-09-10 14:09:47 +08:00
router.SetClashServer(clashServer)
2023-11-28 12:00:28 +08:00
preServices2["clash api"] = clashServer
2022-07-19 22:16:49 +08:00
}
2022-09-26 19:37:06 +08:00
if needV2RayAPI {
v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
2022-09-26 19:37:06 +08:00
if err != nil {
return nil, E.Cause(err, "create v2ray api server")
}
router.SetV2RayServer(v2rayServer)
2023-11-28 12:00:28 +08:00
preServices2["v2ray api"] = v2rayServer
2022-09-26 19:37:06 +08:00
}
2022-07-07 21:47:21 +08:00
return &Box{
2023-03-18 20:26:58 +08:00
router: router,
inbound: inboundManager,
outbound: outboundManager,
2024-11-10 12:11:21 +08:00
network: networkManager,
2023-03-18 20:26:58 +08:00
createdAt: createdAt,
logFactory: logFactory,
logger: logFactory.Logger(),
2023-11-28 12:00:28 +08:00
preServices1: preServices1,
preServices2: preServices2,
2023-03-18 20:26:58 +08:00
postServices: postServices,
done: make(chan struct{}),
2022-07-02 14:07:50 +08:00
}, nil
2022-06-30 21:27:56 +08:00
}
2023-03-18 20:26:58 +08: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 13:10:25 +08:00
println(err.Error())
2023-03-18 20:26:58 +08: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 21:47:21 +08:00
func (s *Box) Start() error {
2022-08-22 12:43:21 +08:00
err := s.start()
if err != nil {
// TODO: remove catch error
defer func() {
v := recover()
if v != nil {
2024-06-25 13:10:25 +08:00
println(err.Error())
debug.PrintStack()
2024-06-25 13:10:25 +08:00
println("panic on early start: " + fmt.Sprint(v))
}
}()
2022-08-22 12:43:21 +08:00
s.Close()
2023-03-18 20:26:58 +08:00
return err
2022-08-22 12:43:21 +08:00
}
2023-03-18 20:26:58 +08:00
s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
return nil
2022-08-22 12:43:21 +08:00
}
2023-03-18 20:26:58 +08:00
func (s *Box) preStart() error {
2024-04-02 23:07:26 +08: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")
}
2023-11-28 12:00:28 +08:00
for serviceName, service := range s.preServices1 {
if preService, isPreService := service.(adapter.LegacyPreStarter); isPreService {
monitor.Start("pre-start ", serviceName)
2023-11-28 12:00:28 +08:00
err := preService.PreStart()
monitor.Finish()
2023-11-28 12:00:28 +08:00
if err != nil {
return E.Cause(err, "pre-start ", serviceName)
2023-11-28 12:00:28 +08:00
}
}
}
for serviceName, service := range s.preServices2 {
if preService, isPreService := service.(adapter.LegacyPreStarter); isPreService {
monitor.Start("pre-start ", serviceName)
2023-07-02 16:45:30 +08:00
err := preService.PreStart()
monitor.Finish()
2023-07-02 16:45:30 +08:00
if err != nil {
return E.Cause(err, "pre-start ", serviceName)
2023-07-02 16:45:30 +08:00
}
2023-03-05 11:05:30 +08:00
}
}
2024-11-10 12:11:21 +08:00
err = s.network.Start(adapter.StartStateInitialize)
if err != nil {
return E.Cause(err, "initialize network manager")
}
err = s.router.Start(adapter.StartStateInitialize)
if err != nil {
return E.Cause(err, "initialize router")
}
err = s.outbound.Start(adapter.StartStateStart)
2023-06-13 22:38:05 +08:00
if err != nil {
return err
2022-06-30 21:27:56 +08:00
}
2024-11-10 12:11:21 +08:00
err = s.network.Start(adapter.StartStateStart)
if err != nil {
return err
}
return s.router.Start(adapter.StartStateStart)
2023-03-18 20:26:58 +08:00
}
func (s *Box) start() error {
err := s.preStart()
2022-08-20 09:13:00 +08:00
if err != nil {
return err
}
2023-11-28 12:00:28 +08:00
for serviceName, service := range s.preServices1 {
err = service.Start()
if err != nil {
return E.Cause(err, "start ", serviceName)
}
}
for serviceName, service := range s.preServices2 {
2023-03-18 20:26:58 +08:00
err = service.Start()
if err != nil {
return E.Cause(err, "start ", serviceName)
}
}
err = s.inbound.Start(adapter.StartStateStart)
2024-06-07 15:55:21 +08:00
if err != nil {
return err
}
2023-03-18 20:26:58 +08:00
for serviceName, service := range s.postServices {
2023-07-02 16:45:30 +08:00
err := service.Start()
2023-03-18 20:26:58 +08:00
if err != nil {
return E.Cause(err, "start ", serviceName)
}
}
err = s.outbound.Start(adapter.StartStatePostStart)
if err != nil {
return err
2023-07-02 16:45:30 +08:00
}
2024-11-10 12:11:21 +08:00
err = s.network.Start(adapter.StartStatePostStart)
if err != nil {
return err
}
err = s.router.Start(adapter.StartStatePostStart)
2024-06-07 15:55:21 +08:00
if err != nil {
return err
}
err = s.inbound.Start(adapter.StartStatePostStart)
if err != nil {
return err
}
2024-11-10 12:11:21 +08:00
err = s.network.Start(adapter.StartStateStarted)
if err != nil {
return err
}
err = s.router.Start(adapter.StartStateStarted)
if err != nil {
return err
}
err = s.outbound.Start(adapter.StartStateStarted)
if err != nil {
return err
}
err = s.inbound.Start(adapter.StartStateStarted)
if err != nil {
return err
2024-06-07 15:55:21 +08:00
}
return nil
2022-06-30 21:27:56 +08:00
}
2022-07-07 21:47:21 +08:00
func (s *Box) Close() error {
2022-08-12 12:13:57 +08:00
select {
case <-s.done:
return os.ErrClosed
default:
close(s.done)
}
2024-04-02 23:07:26 +08:00
monitor := taskmonitor.New(s.logger, C.StopTimeout)
2022-10-25 12:55:00 +08:00
var errors error
2023-03-18 20:26:58 +08:00
for serviceName, service := range s.postServices {
monitor.Start("close ", serviceName)
2023-03-18 20:26:58 +08:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
})
monitor.Finish()
2023-03-18 20:26:58 +08:00
}
errors = E.Errors(errors, s.inbound.Close())
errors = E.Errors(errors, s.outbound.Close())
2024-11-10 12:11:21 +08:00
errors = E.Errors(errors, s.network.Close())
errors = E.Errors(errors, s.router.Close())
2023-11-28 12:00:28 +08:00
for serviceName, service := range s.preServices1 {
monitor.Start("close ", serviceName)
2023-11-28 12:00:28 +08:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
})
monitor.Finish()
2023-11-28 12:00:28 +08:00
}
for serviceName, service := range s.preServices2 {
monitor.Start("close ", serviceName)
2023-03-18 20:26:58 +08:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
2022-10-25 12:55:00 +08:00
})
monitor.Finish()
2022-10-25 12:55:00 +08:00
}
2023-03-18 20:26:58 +08:00
if err := common.Close(s.logFactory); err != nil {
2022-10-25 12:55:00 +08:00
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close logger")
2022-10-25 12:55:00 +08:00
})
}
return errors
2022-06-30 21:27:56 +08:00
}
2022-09-26 19:37:06 +08:00
func (s *Box) Inbound() adapter.InboundManager {
return s.inbound
}
func (s *Box) Outbound() adapter.OutboundManager {
return s.outbound
}
2024-11-10 12:11:21 +08:00
func (s *Box) Network() adapter.NetworkManager {
return s.network
}
2022-09-26 19:37:06 +08:00
func (s *Box) Router() adapter.Router {
return s.router
}