box.go 10 KB

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