box.go 11 KB

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