box.go 18 KB

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