box.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. for i, inboundOptions := range options.Inbounds {
  114. var currentInbound adapter.Inbound
  115. var tag string
  116. if inboundOptions.Tag != "" {
  117. tag = inboundOptions.Tag
  118. } else {
  119. tag = F.ToString(i)
  120. }
  121. currentInbound, err = inboundRegistry.CreateInbound(
  122. ctx,
  123. router,
  124. logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
  125. tag,
  126. inboundOptions.Type,
  127. inboundOptions.Options,
  128. )
  129. if err != nil {
  130. return nil, E.Cause(err, "parse inbound[", i, "]")
  131. }
  132. inbounds = append(inbounds, currentInbound)
  133. }
  134. for i, outboundOptions := range options.Outbounds {
  135. var currentOutbound adapter.Outbound
  136. var tag string
  137. if outboundOptions.Tag != "" {
  138. tag = outboundOptions.Tag
  139. } else {
  140. tag = F.ToString(i)
  141. }
  142. outboundCtx := ctx
  143. if tag != "" {
  144. // TODO: remove this
  145. outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
  146. Outbound: tag,
  147. })
  148. }
  149. currentOutbound, err = outboundRegistry.CreateOutbound(
  150. outboundCtx,
  151. router,
  152. logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
  153. tag,
  154. outboundOptions.Type,
  155. outboundOptions.Options,
  156. )
  157. if err != nil {
  158. return nil, E.Cause(err, "parse outbound[", i, "]")
  159. }
  160. outbounds = append(outbounds, currentOutbound)
  161. }
  162. err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
  163. defaultOutbound, cErr := direct.NewOutbound(ctx, router, logFactory.NewLogger("outbound/direct"), "direct", option.DirectOutboundOptions{})
  164. common.Must(cErr)
  165. outbounds = append(outbounds, defaultOutbound)
  166. return defaultOutbound
  167. })
  168. if err != nil {
  169. return nil, err
  170. }
  171. if platformInterface != nil {
  172. err = platformInterface.Initialize(ctx, router)
  173. if err != nil {
  174. return nil, E.Cause(err, "initialize platform interface")
  175. }
  176. }
  177. preServices1 := make(map[string]adapter.Service)
  178. preServices2 := make(map[string]adapter.Service)
  179. postServices := make(map[string]adapter.Service)
  180. if needCacheFile {
  181. cacheFile := service.FromContext[adapter.CacheFile](ctx)
  182. if cacheFile == nil {
  183. cacheFile = cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
  184. service.MustRegister[adapter.CacheFile](ctx, cacheFile)
  185. }
  186. preServices1["cache file"] = cacheFile
  187. }
  188. if needClashAPI {
  189. clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI)
  190. clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
  191. clashServer, err := experimental.NewClashServer(ctx, router, logFactory.(log.ObservableFactory), clashAPIOptions)
  192. if err != nil {
  193. return nil, E.Cause(err, "create clash api server")
  194. }
  195. router.SetClashServer(clashServer)
  196. preServices2["clash api"] = clashServer
  197. }
  198. if needV2RayAPI {
  199. v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
  200. if err != nil {
  201. return nil, E.Cause(err, "create v2ray api server")
  202. }
  203. router.SetV2RayServer(v2rayServer)
  204. preServices2["v2ray api"] = v2rayServer
  205. }
  206. return &Box{
  207. router: router,
  208. inbounds: inbounds,
  209. outbounds: outbounds,
  210. createdAt: createdAt,
  211. logFactory: logFactory,
  212. logger: logFactory.Logger(),
  213. preServices1: preServices1,
  214. preServices2: preServices2,
  215. postServices: postServices,
  216. done: make(chan struct{}),
  217. }, nil
  218. }
  219. func (s *Box) PreStart() error {
  220. err := s.preStart()
  221. if err != nil {
  222. // TODO: remove catch error
  223. defer func() {
  224. v := recover()
  225. if v != nil {
  226. println(err.Error())
  227. debug.PrintStack()
  228. panic("panic on early close: " + fmt.Sprint(v))
  229. }
  230. }()
  231. s.Close()
  232. return err
  233. }
  234. s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  235. return nil
  236. }
  237. func (s *Box) Start() error {
  238. err := s.start()
  239. if err != nil {
  240. // TODO: remove catch error
  241. defer func() {
  242. v := recover()
  243. if v != nil {
  244. println(err.Error())
  245. debug.PrintStack()
  246. println("panic on early start: " + fmt.Sprint(v))
  247. }
  248. }()
  249. s.Close()
  250. return err
  251. }
  252. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  253. return nil
  254. }
  255. func (s *Box) preStart() error {
  256. monitor := taskmonitor.New(s.logger, C.StartTimeout)
  257. monitor.Start("start logger")
  258. err := s.logFactory.Start()
  259. monitor.Finish()
  260. if err != nil {
  261. return E.Cause(err, "start logger")
  262. }
  263. for serviceName, service := range s.preServices1 {
  264. if preService, isPreService := service.(adapter.PreStarter); isPreService {
  265. monitor.Start("pre-start ", serviceName)
  266. err := preService.PreStart()
  267. monitor.Finish()
  268. if err != nil {
  269. return E.Cause(err, "pre-start ", serviceName)
  270. }
  271. }
  272. }
  273. for serviceName, service := range s.preServices2 {
  274. if preService, isPreService := service.(adapter.PreStarter); isPreService {
  275. monitor.Start("pre-start ", serviceName)
  276. err := preService.PreStart()
  277. monitor.Finish()
  278. if err != nil {
  279. return E.Cause(err, "pre-start ", serviceName)
  280. }
  281. }
  282. }
  283. err = s.router.PreStart()
  284. if err != nil {
  285. return E.Cause(err, "pre-start router")
  286. }
  287. err = s.startOutbounds()
  288. if err != nil {
  289. return err
  290. }
  291. return s.router.Start()
  292. }
  293. func (s *Box) start() error {
  294. err := s.preStart()
  295. if err != nil {
  296. return err
  297. }
  298. for serviceName, service := range s.preServices1 {
  299. err = service.Start()
  300. if err != nil {
  301. return E.Cause(err, "start ", serviceName)
  302. }
  303. }
  304. for serviceName, service := range s.preServices2 {
  305. err = service.Start()
  306. if err != nil {
  307. return E.Cause(err, "start ", serviceName)
  308. }
  309. }
  310. for i, in := range s.inbounds {
  311. var tag string
  312. if in.Tag() == "" {
  313. tag = F.ToString(i)
  314. } else {
  315. tag = in.Tag()
  316. }
  317. err = in.Start()
  318. if err != nil {
  319. return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
  320. }
  321. }
  322. err = s.postStart()
  323. if err != nil {
  324. return err
  325. }
  326. return s.router.Cleanup()
  327. }
  328. func (s *Box) postStart() error {
  329. for serviceName, service := range s.postServices {
  330. err := service.Start()
  331. if err != nil {
  332. return E.Cause(err, "start ", serviceName)
  333. }
  334. }
  335. // TODO: reorganize ALL start order
  336. for _, out := range s.outbounds {
  337. if lateOutbound, isLateOutbound := out.(adapter.PostStarter); isLateOutbound {
  338. err := lateOutbound.PostStart()
  339. if err != nil {
  340. return E.Cause(err, "post-start outbound/", out.Tag())
  341. }
  342. }
  343. }
  344. err := s.router.PostStart()
  345. if err != nil {
  346. return err
  347. }
  348. for _, in := range s.inbounds {
  349. if lateInbound, isLateInbound := in.(adapter.PostStarter); isLateInbound {
  350. err = lateInbound.PostStart()
  351. if err != nil {
  352. return E.Cause(err, "post-start inbound/", in.Tag())
  353. }
  354. }
  355. }
  356. return nil
  357. }
  358. func (s *Box) Close() error {
  359. select {
  360. case <-s.done:
  361. return os.ErrClosed
  362. default:
  363. close(s.done)
  364. }
  365. monitor := taskmonitor.New(s.logger, C.StopTimeout)
  366. var errors error
  367. for serviceName, service := range s.postServices {
  368. monitor.Start("close ", serviceName)
  369. errors = E.Append(errors, service.Close(), func(err error) error {
  370. return E.Cause(err, "close ", serviceName)
  371. })
  372. monitor.Finish()
  373. }
  374. for i, in := range s.inbounds {
  375. monitor.Start("close inbound/", in.Type(), "[", i, "]")
  376. errors = E.Append(errors, in.Close(), func(err error) error {
  377. return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
  378. })
  379. monitor.Finish()
  380. }
  381. for i, out := range s.outbounds {
  382. monitor.Start("close outbound/", out.Type(), "[", i, "]")
  383. errors = E.Append(errors, common.Close(out), func(err error) error {
  384. return E.Cause(err, "close outbound/", out.Type(), "[", i, "]")
  385. })
  386. monitor.Finish()
  387. }
  388. monitor.Start("close router")
  389. if err := common.Close(s.router); err != nil {
  390. errors = E.Append(errors, err, func(err error) error {
  391. return E.Cause(err, "close router")
  392. })
  393. }
  394. monitor.Finish()
  395. for serviceName, service := range s.preServices1 {
  396. monitor.Start("close ", serviceName)
  397. errors = E.Append(errors, service.Close(), func(err error) error {
  398. return E.Cause(err, "close ", serviceName)
  399. })
  400. monitor.Finish()
  401. }
  402. for serviceName, service := range s.preServices2 {
  403. monitor.Start("close ", serviceName)
  404. errors = E.Append(errors, service.Close(), func(err error) error {
  405. return E.Cause(err, "close ", serviceName)
  406. })
  407. monitor.Finish()
  408. }
  409. if err := common.Close(s.logFactory); err != nil {
  410. errors = E.Append(errors, err, func(err error) error {
  411. return E.Cause(err, "close logger")
  412. })
  413. }
  414. return errors
  415. }
  416. func (s *Box) Router() adapter.Router {
  417. return s.router
  418. }