box.go 5.9 KB

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