box.go 13 KB

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