box.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. )
  86. if err != nil {
  87. return nil, E.Cause(err, "parse route options")
  88. }
  89. inbounds := make([]adapter.Inbound, 0, len(options.Inbounds))
  90. outbounds := make([]adapter.Outbound, 0, len(options.Outbounds))
  91. for i, inboundOptions := range options.Inbounds {
  92. var in adapter.Inbound
  93. var tag string
  94. if inboundOptions.Tag != "" {
  95. tag = inboundOptions.Tag
  96. } else {
  97. tag = F.ToString(i)
  98. }
  99. in, err = inbound.New(
  100. ctx,
  101. router,
  102. logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
  103. inboundOptions,
  104. )
  105. if err != nil {
  106. return nil, E.Cause(err, "parse inbound[", i, "]")
  107. }
  108. inbounds = append(inbounds, in)
  109. }
  110. for i, outboundOptions := range options.Outbounds {
  111. var out adapter.Outbound
  112. var tag string
  113. if outboundOptions.Tag != "" {
  114. tag = outboundOptions.Tag
  115. } else {
  116. tag = F.ToString(i)
  117. }
  118. out, err = outbound.New(
  119. router,
  120. logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
  121. outboundOptions)
  122. if err != nil {
  123. return nil, E.Cause(err, "parse outbound[", i, "]")
  124. }
  125. outbounds = append(outbounds, out)
  126. }
  127. err = router.Initialize(outbounds, func() adapter.Outbound {
  128. out, oErr := outbound.New(router, logFactory.NewLogger("outbound/direct"), option.Outbound{Type: "direct", Tag: "default"})
  129. common.Must(oErr)
  130. outbounds = append(outbounds, out)
  131. return out
  132. })
  133. if err != nil {
  134. return nil, err
  135. }
  136. var clashServer adapter.ClashServer
  137. if needClashAPI {
  138. clashServer, err = experimental.NewClashServer(router, observableLogFactory, common.PtrValueOrDefault(options.Experimental.ClashAPI))
  139. if err != nil {
  140. return nil, E.Cause(err, "create clash api server")
  141. }
  142. router.SetTrafficController(clashServer)
  143. }
  144. return &Box{
  145. router: router,
  146. inbounds: inbounds,
  147. outbounds: outbounds,
  148. createdAt: createdAt,
  149. logFactory: logFactory,
  150. logger: logFactory.NewLogger(""),
  151. logFile: logFile,
  152. clashServer: clashServer,
  153. }, nil
  154. }
  155. func (s *Box) Start() error {
  156. err := s.router.Start()
  157. if err != nil {
  158. return err
  159. }
  160. for i, in := range s.inbounds {
  161. err = in.Start()
  162. if err != nil {
  163. for g := 0; g < i; g++ {
  164. s.inbounds[g].Close()
  165. }
  166. return err
  167. }
  168. }
  169. if s.clashServer != nil {
  170. err = s.clashServer.Start()
  171. if err != nil {
  172. return E.Cause(err, "start clash api server")
  173. }
  174. }
  175. s.logger.Info("sing-box started (", F.Seconds(time.Since(s.createdAt).Seconds()), "s)")
  176. return nil
  177. }
  178. func (s *Box) Close() error {
  179. for _, in := range s.inbounds {
  180. in.Close()
  181. }
  182. for _, out := range s.outbounds {
  183. common.Close(out)
  184. }
  185. return common.Close(
  186. s.router,
  187. s.clashServer,
  188. common.PtrOrNil(s.logFile),
  189. )
  190. }