box.go 15 KB

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