box.go 5.0 KB

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