box.go 11 KB

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