box.go 17 KB

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