box.go 8.5 KB

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