box.go 15 KB

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