box.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package box
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "os"
  7. "runtime/debug"
  8. "time"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/adapter/inbound"
  11. "github.com/sagernet/sing-box/adapter/outbound"
  12. "github.com/sagernet/sing-box/common/dialer"
  13. "github.com/sagernet/sing-box/common/taskmonitor"
  14. C "github.com/sagernet/sing-box/constant"
  15. "github.com/sagernet/sing-box/experimental"
  16. "github.com/sagernet/sing-box/experimental/cachefile"
  17. "github.com/sagernet/sing-box/experimental/libbox/platform"
  18. "github.com/sagernet/sing-box/log"
  19. "github.com/sagernet/sing-box/option"
  20. "github.com/sagernet/sing-box/protocol/direct"
  21. "github.com/sagernet/sing-box/route"
  22. "github.com/sagernet/sing/common"
  23. E "github.com/sagernet/sing/common/exceptions"
  24. F "github.com/sagernet/sing/common/format"
  25. "github.com/sagernet/sing/common/ntp"
  26. "github.com/sagernet/sing/service"
  27. "github.com/sagernet/sing/service/pause"
  28. )
  29. var _ adapter.Service = (*Box)(nil)
  30. type Box struct {
  31. createdAt time.Time
  32. logFactory log.Factory
  33. logger log.ContextLogger
  34. network *route.NetworkManager
  35. router *route.Router
  36. inbound *inbound.Manager
  37. outbound *outbound.Manager
  38. services []adapter.LifecycleService
  39. done chan struct{}
  40. }
  41. type Options struct {
  42. option.Options
  43. Context context.Context
  44. PlatformLogWriter log.PlatformWriter
  45. }
  46. func Context(
  47. ctx context.Context,
  48. inboundRegistry adapter.InboundRegistry,
  49. outboundRegistry adapter.OutboundRegistry,
  50. ) context.Context {
  51. if service.FromContext[option.InboundOptionsRegistry](ctx) == nil ||
  52. service.FromContext[adapter.InboundRegistry](ctx) == nil {
  53. ctx = service.ContextWith[option.InboundOptionsRegistry](ctx, inboundRegistry)
  54. ctx = service.ContextWith[adapter.InboundRegistry](ctx, inboundRegistry)
  55. }
  56. if service.FromContext[option.OutboundOptionsRegistry](ctx) == nil ||
  57. service.FromContext[adapter.OutboundRegistry](ctx) == nil {
  58. ctx = service.ContextWith[option.OutboundOptionsRegistry](ctx, outboundRegistry)
  59. ctx = service.ContextWith[adapter.OutboundRegistry](ctx, outboundRegistry)
  60. }
  61. return ctx
  62. }
  63. func New(options Options) (*Box, error) {
  64. createdAt := time.Now()
  65. ctx := options.Context
  66. if ctx == nil {
  67. ctx = context.Background()
  68. }
  69. ctx = service.ContextWithDefaultRegistry(ctx)
  70. inboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)
  71. if inboundRegistry == nil {
  72. return nil, E.New("missing inbound registry in context")
  73. }
  74. outboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)
  75. if outboundRegistry == nil {
  76. return nil, E.New("missing outbound registry in context")
  77. }
  78. ctx = pause.WithDefaultManager(ctx)
  79. experimentalOptions := common.PtrValueOrDefault(options.Experimental)
  80. applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
  81. var needCacheFile bool
  82. var needClashAPI bool
  83. var needV2RayAPI bool
  84. if experimentalOptions.CacheFile != nil && experimentalOptions.CacheFile.Enabled || options.PlatformLogWriter != nil {
  85. needCacheFile = true
  86. }
  87. if experimentalOptions.ClashAPI != nil || options.PlatformLogWriter != nil {
  88. needClashAPI = true
  89. }
  90. if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
  91. needV2RayAPI = true
  92. }
  93. platformInterface := service.FromContext[platform.Interface](ctx)
  94. var defaultLogWriter io.Writer
  95. if platformInterface != nil {
  96. defaultLogWriter = io.Discard
  97. }
  98. logFactory, err := log.New(log.Options{
  99. Context: ctx,
  100. Options: common.PtrValueOrDefault(options.Log),
  101. Observable: needClashAPI,
  102. DefaultWriter: defaultLogWriter,
  103. BaseTime: createdAt,
  104. PlatformWriter: options.PlatformLogWriter,
  105. })
  106. if err != nil {
  107. return nil, E.Cause(err, "create log factory")
  108. }
  109. routeOptions := common.PtrValueOrDefault(options.Route)
  110. inboundManager := inbound.NewManager(logFactory.NewLogger("inbound"), inboundRegistry)
  111. outboundManager := outbound.NewManager(logFactory.NewLogger("outbound"), outboundRegistry, routeOptions.Final)
  112. service.MustRegister[adapter.InboundManager](ctx, inboundManager)
  113. service.MustRegister[adapter.OutboundManager](ctx, outboundManager)
  114. networkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger("network"), routeOptions)
  115. if err != nil {
  116. return nil, E.Cause(err, "initialize network manager")
  117. }
  118. service.MustRegister[adapter.NetworkManager](ctx, networkManager)
  119. router, err := route.NewRouter(ctx, logFactory, routeOptions, common.PtrValueOrDefault(options.DNS))
  120. if err != nil {
  121. return nil, E.Cause(err, "initialize router")
  122. }
  123. for i, inboundOptions := range options.Inbounds {
  124. var tag string
  125. if inboundOptions.Tag != "" {
  126. tag = inboundOptions.Tag
  127. } else {
  128. tag = F.ToString(i)
  129. }
  130. err = inboundManager.Create(ctx,
  131. router,
  132. logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
  133. tag,
  134. inboundOptions.Type,
  135. inboundOptions.Options,
  136. )
  137. if err != nil {
  138. return nil, E.Cause(err, "initialize inbound[", i, "]")
  139. }
  140. }
  141. for i, outboundOptions := range options.Outbounds {
  142. var tag string
  143. if outboundOptions.Tag != "" {
  144. tag = outboundOptions.Tag
  145. } else {
  146. tag = F.ToString(i)
  147. }
  148. outboundCtx := ctx
  149. if tag != "" {
  150. // TODO: remove this
  151. outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
  152. Outbound: tag,
  153. })
  154. }
  155. err = outboundManager.Create(
  156. outboundCtx,
  157. router,
  158. logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
  159. tag,
  160. outboundOptions.Type,
  161. outboundOptions.Options,
  162. )
  163. if err != nil {
  164. return nil, E.Cause(err, "initialize outbound[", i, "]")
  165. }
  166. }
  167. outboundManager.Initialize(common.Must1(
  168. direct.NewOutbound(
  169. ctx,
  170. router,
  171. logFactory.NewLogger("outbound/direct"),
  172. "direct",
  173. option.DirectOutboundOptions{},
  174. ),
  175. ))
  176. if platformInterface != nil {
  177. err = platformInterface.Initialize(networkManager)
  178. if err != nil {
  179. return nil, E.Cause(err, "initialize platform interface")
  180. }
  181. }
  182. var services []adapter.LifecycleService
  183. if needCacheFile {
  184. cacheFile := cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
  185. service.MustRegister[adapter.CacheFile](ctx, cacheFile)
  186. services = append(services, cacheFile)
  187. }
  188. if needClashAPI {
  189. clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI)
  190. clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
  191. clashServer, err := experimental.NewClashServer(ctx, logFactory.(log.ObservableFactory), clashAPIOptions)
  192. if err != nil {
  193. return nil, E.Cause(err, "create clash-server")
  194. }
  195. router.SetTracker(clashServer)
  196. service.MustRegister[adapter.ClashServer](ctx, clashServer)
  197. services = append(services, clashServer)
  198. }
  199. if needV2RayAPI {
  200. v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
  201. if err != nil {
  202. return nil, E.Cause(err, "create v2ray-server")
  203. }
  204. if v2rayServer.StatsService() != nil {
  205. router.SetTracker(v2rayServer.StatsService())
  206. services = append(services, v2rayServer)
  207. service.MustRegister[adapter.V2RayServer](ctx, v2rayServer)
  208. }
  209. }
  210. ntpOptions := common.PtrValueOrDefault(options.NTP)
  211. if ntpOptions.Enabled {
  212. ntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions)
  213. if err != nil {
  214. return nil, E.Cause(err, "create NTP service")
  215. }
  216. timeService := ntp.NewService(ntp.Options{
  217. Context: ctx,
  218. Dialer: ntpDialer,
  219. Logger: logFactory.NewLogger("ntp"),
  220. Server: ntpOptions.ServerOptions.Build(),
  221. Interval: time.Duration(ntpOptions.Interval),
  222. WriteToSystem: ntpOptions.WriteToSystem,
  223. })
  224. service.MustRegister[ntp.TimeService](ctx, timeService)
  225. services = append(services, adapter.NewLifecycleService(timeService, "ntp service"))
  226. }
  227. return &Box{
  228. network: networkManager,
  229. router: router,
  230. inbound: inboundManager,
  231. outbound: outboundManager,
  232. createdAt: createdAt,
  233. logFactory: logFactory,
  234. logger: logFactory.Logger(),
  235. services: services,
  236. done: make(chan struct{}),
  237. }, nil
  238. }
  239. func (s *Box) PreStart() error {
  240. err := s.preStart()
  241. if err != nil {
  242. // TODO: remove catch error
  243. defer func() {
  244. v := recover()
  245. if v != nil {
  246. println(err.Error())
  247. debug.PrintStack()
  248. panic("panic on early close: " + fmt.Sprint(v))
  249. }
  250. }()
  251. s.Close()
  252. return err
  253. }
  254. s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  255. return nil
  256. }
  257. func (s *Box) Start() error {
  258. err := s.start()
  259. if err != nil {
  260. // TODO: remove catch error
  261. defer func() {
  262. v := recover()
  263. if v != nil {
  264. println(err.Error())
  265. debug.PrintStack()
  266. println("panic on early start: " + fmt.Sprint(v))
  267. }
  268. }()
  269. s.Close()
  270. return err
  271. }
  272. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  273. return nil
  274. }
  275. func (s *Box) preStart() error {
  276. monitor := taskmonitor.New(s.logger, C.StartTimeout)
  277. monitor.Start("start logger")
  278. err := s.logFactory.Start()
  279. monitor.Finish()
  280. if err != nil {
  281. return E.Cause(err, "start logger")
  282. }
  283. err = adapter.StartNamed(adapter.StartStateInitialize, s.services) // cache-file clash-api v2ray-api
  284. if err != nil {
  285. return err
  286. }
  287. err = adapter.Start(adapter.StartStateInitialize, s.network, s.router, s.outbound, s.inbound)
  288. if err != nil {
  289. return err
  290. }
  291. err = adapter.Start(adapter.StartStateStart, s.outbound, s.network, s.router)
  292. if err != nil {
  293. return err
  294. }
  295. return nil
  296. }
  297. func (s *Box) start() error {
  298. err := s.preStart()
  299. if err != nil {
  300. return err
  301. }
  302. err = adapter.StartNamed(adapter.StartStateStart, s.services)
  303. if err != nil {
  304. return err
  305. }
  306. err = s.inbound.Start(adapter.StartStateStart)
  307. if err != nil {
  308. return err
  309. }
  310. err = adapter.Start(adapter.StartStatePostStart, s.outbound, s.network, s.router, s.inbound)
  311. if err != nil {
  312. return err
  313. }
  314. err = adapter.StartNamed(adapter.StartStatePostStart, s.services)
  315. if err != nil {
  316. return err
  317. }
  318. err = adapter.Start(adapter.StartStateStarted, s.network, s.router, s.outbound, s.inbound)
  319. if err != nil {
  320. return err
  321. }
  322. err = adapter.StartNamed(adapter.StartStateStarted, s.services)
  323. if err != nil {
  324. return err
  325. }
  326. return nil
  327. }
  328. func (s *Box) Close() error {
  329. select {
  330. case <-s.done:
  331. return os.ErrClosed
  332. default:
  333. close(s.done)
  334. }
  335. err := common.Close(
  336. s.inbound, s.outbound, s.router, s.network,
  337. )
  338. for _, lifecycleService := range s.services {
  339. err = E.Append(err, lifecycleService.Close(), func(err error) error {
  340. return E.Cause(err, "close ", lifecycleService.Name())
  341. })
  342. }
  343. err = E.Append(err, s.logFactory.Close(), func(err error) error {
  344. return E.Cause(err, "close logger")
  345. })
  346. return err
  347. }
  348. func (s *Box) Network() adapter.NetworkManager {
  349. return s.network
  350. }
  351. func (s *Box) Router() adapter.Router {
  352. return s.router
  353. }
  354. func (s *Box) Inbound() adapter.InboundManager {
  355. return s.inbound
  356. }
  357. func (s *Box) Outbound() adapter.OutboundManager {
  358. return s.outbound
  359. }