box.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. outboundOptions)
  115. if err != nil {
  116. return nil, E.Cause(err, "parse outbound[", i, "]")
  117. }
  118. outbounds = append(outbounds, out)
  119. }
  120. err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
  121. out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), option.Outbound{Type: "direct", Tag: "default"})
  122. common.Must(oErr)
  123. outbounds = append(outbounds, out)
  124. return out
  125. })
  126. if err != nil {
  127. return nil, err
  128. }
  129. preServices := make(map[string]adapter.Service)
  130. postServices := make(map[string]adapter.Service)
  131. if needClashAPI {
  132. clashServer, err := experimental.NewClashServer(router, logFactory.(log.ObservableFactory), common.PtrValueOrDefault(options.Experimental.ClashAPI))
  133. if err != nil {
  134. return nil, E.Cause(err, "create clash api server")
  135. }
  136. router.SetClashServer(clashServer)
  137. preServices["clash api"] = clashServer
  138. }
  139. if needV2RayAPI {
  140. v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(options.Experimental.V2RayAPI))
  141. if err != nil {
  142. return nil, E.Cause(err, "create v2ray api server")
  143. }
  144. router.SetV2RayServer(v2rayServer)
  145. preServices["v2ray api"] = v2rayServer
  146. }
  147. return &Box{
  148. router: router,
  149. inbounds: inbounds,
  150. outbounds: outbounds,
  151. createdAt: createdAt,
  152. logFactory: logFactory,
  153. logger: logFactory.Logger(),
  154. preServices: preServices,
  155. postServices: postServices,
  156. done: make(chan struct{}),
  157. }, nil
  158. }
  159. func (s *Box) PreStart() error {
  160. err := s.preStart()
  161. if err != nil {
  162. // TODO: remove catch error
  163. defer func() {
  164. v := recover()
  165. if v != nil {
  166. log.Error(E.Cause(err, "origin error"))
  167. debug.PrintStack()
  168. panic("panic on early close: " + fmt.Sprint(v))
  169. }
  170. }()
  171. s.Close()
  172. return err
  173. }
  174. s.logger.Info("sing-box pre-started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  175. return nil
  176. }
  177. func (s *Box) Start() error {
  178. err := s.start()
  179. if err != nil {
  180. // TODO: remove catch error
  181. defer func() {
  182. v := recover()
  183. if v != nil {
  184. log.Error(E.Cause(err, "origin error"))
  185. debug.PrintStack()
  186. panic("panic on early close: " + fmt.Sprint(v))
  187. }
  188. }()
  189. s.Close()
  190. return err
  191. }
  192. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  193. return nil
  194. }
  195. func (s *Box) preStart() error {
  196. for serviceName, service := range s.preServices {
  197. err := adapter.PreStart(service)
  198. if err != nil {
  199. return E.Cause(err, "pre-start ", serviceName)
  200. }
  201. }
  202. for i, out := range s.outbounds {
  203. if starter, isStarter := out.(common.Starter); isStarter {
  204. err := starter.Start()
  205. if err != nil {
  206. var tag string
  207. if out.Tag() == "" {
  208. tag = F.ToString(i)
  209. } else {
  210. tag = out.Tag()
  211. }
  212. return E.Cause(err, "initialize outbound/", out.Type(), "[", tag, "]")
  213. }
  214. }
  215. }
  216. return s.router.Start()
  217. }
  218. func (s *Box) start() error {
  219. err := s.preStart()
  220. if err != nil {
  221. return err
  222. }
  223. for serviceName, service := range s.preServices {
  224. err = service.Start()
  225. if err != nil {
  226. return E.Cause(err, "start ", serviceName)
  227. }
  228. }
  229. for i, in := range s.inbounds {
  230. err = in.Start()
  231. if err != nil {
  232. var tag string
  233. if in.Tag() == "" {
  234. tag = F.ToString(i)
  235. } else {
  236. tag = in.Tag()
  237. }
  238. return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
  239. }
  240. }
  241. for serviceName, service := range s.postServices {
  242. err = service.Start()
  243. if err != nil {
  244. return E.Cause(err, "start ", serviceName)
  245. }
  246. }
  247. return nil
  248. }
  249. func (s *Box) Close() error {
  250. select {
  251. case <-s.done:
  252. return os.ErrClosed
  253. default:
  254. close(s.done)
  255. }
  256. var errors error
  257. for serviceName, service := range s.postServices {
  258. errors = E.Append(errors, service.Close(), func(err error) error {
  259. return E.Cause(err, "close ", serviceName)
  260. })
  261. }
  262. for i, in := range s.inbounds {
  263. errors = E.Append(errors, in.Close(), func(err error) error {
  264. return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
  265. })
  266. }
  267. for i, out := range s.outbounds {
  268. errors = E.Append(errors, common.Close(out), func(err error) error {
  269. return E.Cause(err, "close inbound/", out.Type(), "[", i, "]")
  270. })
  271. }
  272. if err := common.Close(s.router); err != nil {
  273. errors = E.Append(errors, err, func(err error) error {
  274. return E.Cause(err, "close router")
  275. })
  276. }
  277. for serviceName, service := range s.preServices {
  278. errors = E.Append(errors, service.Close(), func(err error) error {
  279. return E.Cause(err, "close ", serviceName)
  280. })
  281. }
  282. if err := common.Close(s.logFactory); err != nil {
  283. errors = E.Append(errors, err, func(err error) error {
  284. return E.Cause(err, "close log factory")
  285. })
  286. }
  287. return errors
  288. }
  289. func (s *Box) Router() adapter.Router {
  290. return s.router
  291. }