sing-box/box.go

389 lines
10 KiB
Go
Raw Permalink 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"
"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"
"github.com/sagernet/sing-box/inbound"
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"
"github.com/sagernet/sing-box/outbound"
"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"
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 {
2023-03-18 12:26:58 +00:00
createdAt time.Time
router adapter.Router
inbounds []adapter.Inbound
outbounds []adapter.Outbound
logFactory log.Factory
logger log.ContextLogger
2023-11-28 04:00:28 +00:00
preServices1 map[string]adapter.Service
preServices2 map[string]adapter.Service
2023-03-18 12:26:58 +00:00
postServices map[string]adapter.Service
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
PlatformInterface platform.Interface
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
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()
}
2023-08-29 05:43:42 +00:00
ctx = service.ContextWithDefaultRegistry(ctx)
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
}
2023-04-03 10:24:20 +00:00
var defaultLogWriter io.Writer
if options.PlatformInterface != nil {
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
}
2022-07-12 07:17:29 +00:00
router, err := route.NewRouter(
ctx,
2022-11-28 05:10:56 +00:00
logFactory,
2022-07-12 07:17:29 +00:00
common.PtrValueOrDefault(options.Route),
common.PtrValueOrDefault(options.DNS),
2023-02-21 06:53:00 +00:00
common.PtrValueOrDefault(options.NTP),
2022-08-04 14:01:20 +00:00
options.Inbounds,
2023-04-03 10:24:20 +00:00
options.PlatformInterface,
2022-07-12 07:17:29 +00:00
)
2022-07-02 06:07:50 +00:00
if err != nil {
2022-07-02 17:57:04 +00:00
return nil, E.Cause(err, "parse route options")
2022-06-30 13:27:56 +00:00
}
2022-07-02 14:55:10 +00:00
inbounds := make([]adapter.Inbound, 0, len(options.Inbounds))
outbounds := make([]adapter.Outbound, 0, len(options.Outbounds))
for i, inboundOptions := range options.Inbounds {
var in adapter.Inbound
2022-07-12 07:17:29 +00:00
var tag string
if inboundOptions.Tag != "" {
tag = inboundOptions.Tag
} else {
tag = F.ToString(i)
}
in, err = inbound.New(
ctx,
router,
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
inboundOptions,
2023-04-03 10:24:20 +00:00
options.PlatformInterface,
2022-07-12 07:17:29 +00:00
)
2022-07-02 14:55:10 +00:00
if err != nil {
2022-07-02 17:57:04 +00:00
return nil, E.Cause(err, "parse inbound[", i, "]")
2022-06-30 13:27:56 +00:00
}
inbounds = append(inbounds, in)
2022-06-30 13:27:56 +00:00
}
for i, outboundOptions := range options.Outbounds {
var out adapter.Outbound
2022-07-12 07:17:29 +00:00
var tag string
if outboundOptions.Tag != "" {
tag = outboundOptions.Tag
} else {
tag = F.ToString(i)
}
out, err = outbound.New(
2022-07-29 16:29:22 +00:00
ctx,
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,
2022-07-12 07:17:29 +00:00
outboundOptions)
2022-06-30 13:27:56 +00:00
if err != nil {
2022-07-02 17:57:04 +00:00
return nil, E.Cause(err, "parse outbound[", i, "]")
2022-06-30 13:27:56 +00:00
}
outbounds = append(outbounds, out)
2022-07-02 06:07:50 +00:00
}
2022-08-29 11:43:13 +00:00
err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
2023-04-08 00:58:01 +00:00
out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), "direct", option.Outbound{Type: "direct", Tag: "default"})
common.Must(oErr)
outbounds = append(outbounds, out)
return out
})
if err != nil {
return nil, err
2022-06-30 13:27:56 +00:00
}
2023-04-18 06:04:09 +00:00
if options.PlatformInterface != nil {
err = options.PlatformInterface.Initialize(ctx, router)
if err != nil {
return nil, E.Cause(err, "initialize platform interface")
}
}
2023-11-28 04:00:28 +00:00
preServices1 := make(map[string]adapter.Service)
preServices2 := make(map[string]adapter.Service)
2023-03-18 12:26:58 +00:00
postServices := make(map[string]adapter.Service)
2023-11-28 04:00:28 +00:00
if needCacheFile {
2023-12-16 07:40:14 +00: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 04:00:28 +00:00
preServices1["cache file"] = cacheFile
}
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, router, logFactory.(log.ObservableFactory), clashAPIOptions)
2022-07-19 23:12:40 +00:00
if err != nil {
return nil, E.Cause(err, "create clash api server")
}
2022-09-10 06:09:47 +00:00
router.SetClashServer(clashServer)
2023-11-28 04:00:28 +00:00
preServices2["clash api"] = 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 {
return nil, E.Cause(err, "create v2ray api server")
}
router.SetV2RayServer(v2rayServer)
2023-11-28 04:00:28 +00:00
preServices2["v2ray api"] = v2rayServer
2022-09-26 11:37:06 +00:00
}
2022-07-07 13:47:21 +00:00
return &Box{
2023-03-18 12:26:58 +00:00
router: router,
inbounds: inbounds,
outbounds: outbounds,
createdAt: createdAt,
logFactory: logFactory,
logger: logFactory.Logger(),
2023-11-28 04:00:28 +00:00
preServices1: preServices1,
preServices2: preServices2,
2023-03-18 12:26:58 +00:00
postServices: postServices,
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 {
log.Error(E.Cause(err, "origin error"))
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 {
log.Error(E.Cause(err, "origin error"))
debug.PrintStack()
panic("panic on early close: " + 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")
}
2023-11-28 04:00:28 +00:00
for serviceName, service := range s.preServices1 {
if preService, isPreService := service.(adapter.PreStarter); isPreService {
monitor.Start("pre-start ", serviceName)
2023-11-28 04:00:28 +00:00
err := preService.PreStart()
monitor.Finish()
2023-11-28 04:00:28 +00:00
if err != nil {
return E.Cause(err, "pre-start ", serviceName)
2023-11-28 04:00:28 +00:00
}
}
}
for serviceName, service := range s.preServices2 {
2023-07-02 08:45:30 +00:00
if preService, isPreService := service.(adapter.PreStarter); isPreService {
monitor.Start("pre-start ", serviceName)
2023-07-02 08:45:30 +00:00
err := preService.PreStart()
monitor.Finish()
2023-07-02 08:45:30 +00:00
if err != nil {
return E.Cause(err, "pre-start ", serviceName)
2023-07-02 08:45:30 +00:00
}
2023-03-05 03:05:30 +00:00
}
}
err = s.router.PreStart()
if err != nil {
return E.Cause(err, "pre-start router")
}
err = s.startOutbounds()
2023-06-13 14:38:05 +00:00
if err != nil {
return err
2022-06-30 13:27:56 +00:00
}
2023-03-18 12:26:58 +00:00
return s.router.Start()
}
func (s *Box) start() error {
err := s.preStart()
2022-08-20 01:13:00 +00:00
if err != nil {
return err
}
2023-11-28 04:00:28 +00: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 12:26:58 +00:00
err = service.Start()
if err != nil {
return E.Cause(err, "start ", serviceName)
}
}
2022-08-20 01:13:00 +00:00
for i, in := range s.inbounds {
2023-04-08 00:09:28 +00:00
var tag string
if in.Tag() == "" {
tag = F.ToString(i)
} else {
tag = in.Tag()
}
2022-08-20 01:13:00 +00:00
err = in.Start()
if err != nil {
return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
}
}
2023-12-02 09:47:57 +00:00
return s.postStart()
2023-07-02 08:45:30 +00:00
}
func (s *Box) postStart() error {
2023-03-18 12:26:58 +00:00
for serviceName, service := range s.postServices {
2023-07-02 08:45:30 +00:00
err := service.Start()
2023-03-18 12:26:58 +00:00
if err != nil {
return E.Cause(err, "start ", serviceName)
}
}
2023-12-02 09:47:57 +00:00
for _, outbound := range s.outbounds {
if lateOutbound, isLateOutbound := outbound.(adapter.PostStarter); isLateOutbound {
err := lateOutbound.PostStart()
2023-07-02 08:45:30 +00:00
if err != nil {
2023-12-02 09:47:57 +00:00
return E.Cause(err, "post-start outbound/", outbound.Tag())
2023-07-02 08:45:30 +00:00
}
}
}
2023-12-02 09:47:57 +00:00
return s.router.PostStart()
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-04-02 15:07:26 +00:00
monitor := taskmonitor.New(s.logger, C.StopTimeout)
2022-10-25 04:55:00 +00:00
var errors error
2023-03-18 12:26:58 +00:00
for serviceName, service := range s.postServices {
monitor.Start("close ", serviceName)
2023-03-18 12:26:58 +00:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
})
monitor.Finish()
2023-03-18 12:26:58 +00:00
}
2022-10-25 04:55:00 +00:00
for i, in := range s.inbounds {
monitor.Start("close inbound/", in.Type(), "[", i, "]")
2022-10-25 04:55:00 +00:00
errors = E.Append(errors, in.Close(), func(err error) error {
return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
})
monitor.Finish()
2022-10-25 04:55:00 +00:00
}
for i, out := range s.outbounds {
monitor.Start("close outbound/", out.Type(), "[", i, "]")
2022-10-25 04:55:00 +00:00
errors = E.Append(errors, common.Close(out), func(err error) error {
2023-04-05 13:41:06 +00:00
return E.Cause(err, "close outbound/", out.Type(), "[", i, "]")
2022-10-25 04:55:00 +00:00
})
monitor.Finish()
2022-06-30 13:27:56 +00:00
}
monitor.Start("close router")
2022-10-25 04:55:00 +00:00
if err := common.Close(s.router); err != nil {
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close router")
})
2022-06-30 13:27:56 +00:00
}
monitor.Finish()
2023-11-28 04:00:28 +00:00
for serviceName, service := range s.preServices1 {
monitor.Start("close ", serviceName)
2023-11-28 04:00:28 +00:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
})
monitor.Finish()
2023-11-28 04:00:28 +00:00
}
for serviceName, service := range s.preServices2 {
monitor.Start("close ", serviceName)
2023-03-18 12:26:58 +00:00
errors = E.Append(errors, service.Close(), func(err error) error {
return E.Cause(err, "close ", serviceName)
2022-10-25 04:55:00 +00:00
})
monitor.Finish()
2022-10-25 04:55:00 +00:00
}
2023-03-18 12:26:58 +00:00
if err := common.Close(s.logFactory); err != nil {
2022-10-25 04:55:00 +00:00
errors = E.Append(errors, err, func(err error) error {
return E.Cause(err, "close logger")
2022-10-25 04:55:00 +00:00
})
}
return errors
2022-06-30 13:27:56 +00:00
}
2022-09-26 11:37:06 +00:00
func (s *Box) Router() adapter.Router {
return s.router
}