box.go 10 KB

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