box.go 12 KB

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