box.go 13 KB

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