box.go 8.6 KB

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