box.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package box
  2. import (
  3. "context"
  4. "io"
  5. "os"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/experimental"
  9. "github.com/sagernet/sing-box/inbound"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing-box/option"
  12. "github.com/sagernet/sing-box/outbound"
  13. "github.com/sagernet/sing-box/route"
  14. "github.com/sagernet/sing/common"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. F "github.com/sagernet/sing/common/format"
  17. )
  18. var _ adapter.Service = (*Box)(nil)
  19. type Box struct {
  20. createdAt time.Time
  21. router adapter.Router
  22. inbounds []adapter.Inbound
  23. outbounds []adapter.Outbound
  24. logFactory log.Factory
  25. logger log.ContextLogger
  26. logFile *os.File
  27. clashServer adapter.ClashServer
  28. }
  29. func New(ctx context.Context, options option.Options) (*Box, error) {
  30. createdAt := time.Now()
  31. logOptions := common.PtrValueOrDefault(options.Log)
  32. var needClashAPI bool
  33. if options.Experimental != nil && options.Experimental.ClashAPI != nil && options.Experimental.ClashAPI.ExternalController != "" {
  34. needClashAPI = true
  35. }
  36. var logFactory log.Factory
  37. var observableLogFactory log.ObservableFactory
  38. var logFile *os.File
  39. if logOptions.Disabled {
  40. observableLogFactory = log.NewNOPFactory()
  41. logFactory = observableLogFactory
  42. } else {
  43. var logWriter io.Writer
  44. switch logOptions.Output {
  45. case "", "stderr":
  46. logWriter = os.Stderr
  47. case "stdout":
  48. logWriter = os.Stdout
  49. default:
  50. var err error
  51. logFile, err = os.OpenFile(logOptions.Output, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
  52. if err != nil {
  53. return nil, err
  54. }
  55. }
  56. logFormatter := log.Formatter{
  57. BaseTime: createdAt,
  58. DisableColors: logOptions.DisableColor || logFile != nil,
  59. DisableTimestamp: !logOptions.Timestamp && logFile != nil,
  60. FullTimestamp: logOptions.Timestamp,
  61. TimestampFormat: "-0700 2006-01-02 15:04:05",
  62. }
  63. if needClashAPI {
  64. observableLogFactory = log.NewObservableFactory(logFormatter, logWriter)
  65. logFactory = observableLogFactory
  66. } else {
  67. logFactory = log.NewFactory(logFormatter, logWriter)
  68. }
  69. if logOptions.Level != "" {
  70. logLevel, err := log.ParseLevel(logOptions.Level)
  71. if err != nil {
  72. return nil, E.Cause(err, "parse log level")
  73. }
  74. logFactory.SetLevel(logLevel)
  75. } else {
  76. logFactory.SetLevel(log.LevelTrace)
  77. }
  78. }
  79. router, err := route.NewRouter(
  80. ctx,
  81. logFactory.NewLogger("router"),
  82. logFactory.NewLogger("dns"),
  83. common.PtrValueOrDefault(options.Route),
  84. common.PtrValueOrDefault(options.DNS),
  85. options.Inbounds,
  86. )
  87. if err != nil {
  88. return nil, E.Cause(err, "parse route options")
  89. }
  90. inbounds := make([]adapter.Inbound, 0, len(options.Inbounds))
  91. outbounds := make([]adapter.Outbound, 0, len(options.Outbounds))
  92. for i, inboundOptions := range options.Inbounds {
  93. var in adapter.Inbound
  94. var tag string
  95. if inboundOptions.Tag != "" {
  96. tag = inboundOptions.Tag
  97. } else {
  98. tag = F.ToString(i)
  99. }
  100. in, err = inbound.New(
  101. ctx,
  102. router,
  103. logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
  104. inboundOptions,
  105. )
  106. if err != nil {
  107. return nil, E.Cause(err, "parse inbound[", i, "]")
  108. }
  109. inbounds = append(inbounds, in)
  110. }
  111. for i, outboundOptions := range options.Outbounds {
  112. var out adapter.Outbound
  113. var tag string
  114. if outboundOptions.Tag != "" {
  115. tag = outboundOptions.Tag
  116. } else {
  117. tag = F.ToString(i)
  118. }
  119. out, err = outbound.New(
  120. ctx,
  121. router,
  122. logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
  123. outboundOptions)
  124. if err != nil {
  125. return nil, E.Cause(err, "parse outbound[", i, "]")
  126. }
  127. outbounds = append(outbounds, out)
  128. }
  129. err = router.Initialize(outbounds, func() adapter.Outbound {
  130. out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), option.Outbound{Type: "direct", Tag: "default"})
  131. common.Must(oErr)
  132. outbounds = append(outbounds, out)
  133. return out
  134. })
  135. if err != nil {
  136. return nil, err
  137. }
  138. var clashServer adapter.ClashServer
  139. if needClashAPI {
  140. clashServer, err = experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI))
  141. if err != nil {
  142. return nil, E.Cause(err, "create clash api server")
  143. }
  144. router.SetTrafficController(clashServer)
  145. }
  146. return &Box{
  147. router: router,
  148. inbounds: inbounds,
  149. outbounds: outbounds,
  150. createdAt: createdAt,
  151. logFactory: logFactory,
  152. logger: logFactory.NewLogger(""),
  153. logFile: logFile,
  154. clashServer: clashServer,
  155. }, nil
  156. }
  157. func (s *Box) Start() error {
  158. err := s.router.Start()
  159. if err != nil {
  160. return err
  161. }
  162. for i, in := range s.inbounds {
  163. err = in.Start()
  164. if err != nil {
  165. for g := 0; g < i; g++ {
  166. s.inbounds[g].Close()
  167. }
  168. return err
  169. }
  170. }
  171. if s.clashServer != nil {
  172. err = s.clashServer.Start()
  173. if err != nil {
  174. return E.Cause(err, "start clash api server")
  175. }
  176. }
  177. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  178. return nil
  179. }
  180. func (s *Box) Close() error {
  181. for _, in := range s.inbounds {
  182. in.Close()
  183. }
  184. for _, out := range s.outbounds {
  185. common.Close(out)
  186. }
  187. return common.Close(
  188. s.router,
  189. s.logFactory,
  190. s.clashServer,
  191. common.PtrOrNil(s.logFile),
  192. )
  193. }