box.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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/inbound"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing-box/outbound"
  15. "github.com/sagernet/sing-box/route"
  16. "github.com/sagernet/sing/common"
  17. E "github.com/sagernet/sing/common/exceptions"
  18. F "github.com/sagernet/sing/common/format"
  19. )
  20. var _ adapter.Service = (*Box)(nil)
  21. type Box struct {
  22. createdAt time.Time
  23. router adapter.Router
  24. inbounds []adapter.Inbound
  25. outbounds []adapter.Outbound
  26. logFactory log.Factory
  27. logger log.ContextLogger
  28. logFile *os.File
  29. clashServer adapter.ClashServer
  30. v2rayServer adapter.V2RayServer
  31. done chan struct{}
  32. }
  33. func New(ctx context.Context, options option.Options) (*Box, error) {
  34. createdAt := time.Now()
  35. logOptions := common.PtrValueOrDefault(options.Log)
  36. var needClashAPI bool
  37. var needV2RayAPI bool
  38. if options.Experimental != nil {
  39. if options.Experimental.ClashAPI != nil && options.Experimental.ClashAPI.ExternalController != "" {
  40. needClashAPI = true
  41. }
  42. if options.Experimental.V2RayAPI != nil && options.Experimental.V2RayAPI.Listen != "" {
  43. needV2RayAPI = true
  44. }
  45. }
  46. var logFactory log.Factory
  47. var observableLogFactory log.ObservableFactory
  48. var logFile *os.File
  49. if logOptions.Disabled {
  50. observableLogFactory = log.NewNOPFactory()
  51. logFactory = observableLogFactory
  52. } else {
  53. var logWriter io.Writer
  54. switch logOptions.Output {
  55. case "", "stderr":
  56. logWriter = os.Stderr
  57. case "stdout":
  58. logWriter = os.Stdout
  59. default:
  60. var err error
  61. logFile, err = os.OpenFile(logOptions.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
  62. if err != nil {
  63. return nil, err
  64. }
  65. logWriter = logFile
  66. }
  67. logFormatter := log.Formatter{
  68. BaseTime: createdAt,
  69. DisableColors: logOptions.DisableColor || logFile != nil,
  70. DisableTimestamp: !logOptions.Timestamp && logFile != nil,
  71. FullTimestamp: logOptions.Timestamp,
  72. TimestampFormat: "-0700 2006-01-02 15:04:05",
  73. }
  74. if needClashAPI {
  75. observableLogFactory = log.NewObservableFactory(logFormatter, logWriter)
  76. logFactory = observableLogFactory
  77. } else {
  78. logFactory = log.NewFactory(logFormatter, logWriter)
  79. }
  80. if logOptions.Level != "" {
  81. logLevel, err := log.ParseLevel(logOptions.Level)
  82. if err != nil {
  83. return nil, E.Cause(err, "parse log level")
  84. }
  85. logFactory.SetLevel(logLevel)
  86. } else {
  87. logFactory.SetLevel(log.LevelTrace)
  88. }
  89. }
  90. router, err := route.NewRouter(
  91. ctx,
  92. logFactory,
  93. common.PtrValueOrDefault(options.Route),
  94. common.PtrValueOrDefault(options.DNS),
  95. options.Inbounds,
  96. )
  97. if err != nil {
  98. return nil, E.Cause(err, "parse route options")
  99. }
  100. inbounds := make([]adapter.Inbound, 0, len(options.Inbounds))
  101. outbounds := make([]adapter.Outbound, 0, len(options.Outbounds))
  102. for i, inboundOptions := range options.Inbounds {
  103. var in adapter.Inbound
  104. var tag string
  105. if inboundOptions.Tag != "" {
  106. tag = inboundOptions.Tag
  107. } else {
  108. tag = F.ToString(i)
  109. }
  110. in, err = inbound.New(
  111. ctx,
  112. router,
  113. logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
  114. inboundOptions,
  115. )
  116. if err != nil {
  117. return nil, E.Cause(err, "parse inbound[", i, "]")
  118. }
  119. inbounds = append(inbounds, in)
  120. }
  121. for i, outboundOptions := range options.Outbounds {
  122. var out adapter.Outbound
  123. var tag string
  124. if outboundOptions.Tag != "" {
  125. tag = outboundOptions.Tag
  126. } else {
  127. tag = F.ToString(i)
  128. }
  129. out, err = outbound.New(
  130. ctx,
  131. router,
  132. logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
  133. outboundOptions)
  134. if err != nil {
  135. return nil, E.Cause(err, "parse outbound[", i, "]")
  136. }
  137. outbounds = append(outbounds, out)
  138. }
  139. err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
  140. out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), option.Outbound{Type: "direct", Tag: "default"})
  141. common.Must(oErr)
  142. outbounds = append(outbounds, out)
  143. return out
  144. })
  145. if err != nil {
  146. return nil, err
  147. }
  148. var clashServer adapter.ClashServer
  149. var v2rayServer adapter.V2RayServer
  150. if needClashAPI {
  151. clashServer, err = experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI))
  152. if err != nil {
  153. return nil, E.Cause(err, "create clash api server")
  154. }
  155. router.SetClashServer(clashServer)
  156. }
  157. if needV2RayAPI {
  158. v2rayServer, err = experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(options.Experimental.V2RayAPI))
  159. if err != nil {
  160. return nil, E.Cause(err, "create v2ray api server")
  161. }
  162. router.SetV2RayServer(v2rayServer)
  163. }
  164. return &Box{
  165. router: router,
  166. inbounds: inbounds,
  167. outbounds: outbounds,
  168. createdAt: createdAt,
  169. logFactory: logFactory,
  170. logger: logFactory.Logger(),
  171. logFile: logFile,
  172. clashServer: clashServer,
  173. v2rayServer: v2rayServer,
  174. done: make(chan struct{}),
  175. }, 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. }
  191. return err
  192. }
  193. func (s *Box) start() error {
  194. for i, out := range s.outbounds {
  195. if starter, isStarter := out.(common.Starter); isStarter {
  196. err := starter.Start()
  197. if err != nil {
  198. var tag string
  199. if out.Tag() == "" {
  200. tag = F.ToString(i)
  201. } else {
  202. tag = out.Tag()
  203. }
  204. return E.Cause(err, "initialize outbound/", out.Type(), "[", tag, "]")
  205. }
  206. }
  207. }
  208. err := s.router.Start()
  209. if err != nil {
  210. return err
  211. }
  212. for i, in := range s.inbounds {
  213. err = in.Start()
  214. if err != nil {
  215. var tag string
  216. if in.Tag() == "" {
  217. tag = F.ToString(i)
  218. } else {
  219. tag = in.Tag()
  220. }
  221. return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
  222. }
  223. }
  224. if s.clashServer != nil {
  225. err = s.clashServer.Start()
  226. if err != nil {
  227. return E.Cause(err, "start clash api server")
  228. }
  229. }
  230. if s.v2rayServer != nil {
  231. err = s.v2rayServer.Start()
  232. if err != nil {
  233. return E.Cause(err, "start v2ray api server")
  234. }
  235. }
  236. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  237. return nil
  238. }
  239. func (s *Box) Close() error {
  240. select {
  241. case <-s.done:
  242. return os.ErrClosed
  243. default:
  244. close(s.done)
  245. }
  246. for _, in := range s.inbounds {
  247. in.Close()
  248. }
  249. for _, out := range s.outbounds {
  250. common.Close(out)
  251. }
  252. return common.Close(
  253. s.router,
  254. s.logFactory,
  255. s.clashServer,
  256. s.v2rayServer,
  257. common.PtrOrNil(s.logFile),
  258. )
  259. }
  260. func (s *Box) Router() adapter.Router {
  261. return s.router
  262. }