selector.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package group
  2. import (
  3. "context"
  4. "net"
  5. "time"
  6. "github.com/sagernet/sing-box/adapter"
  7. "github.com/sagernet/sing-box/adapter/outbound"
  8. "github.com/sagernet/sing-box/common/interrupt"
  9. C "github.com/sagernet/sing-box/constant"
  10. "github.com/sagernet/sing-box/log"
  11. "github.com/sagernet/sing-box/option"
  12. tun "github.com/sagernet/sing-tun"
  13. "github.com/sagernet/sing/common"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. "github.com/sagernet/sing/common/logger"
  16. M "github.com/sagernet/sing/common/metadata"
  17. N "github.com/sagernet/sing/common/network"
  18. "github.com/sagernet/sing/service"
  19. )
  20. func RegisterSelector(registry *outbound.Registry) {
  21. outbound.Register[option.SelectorOutboundOptions](registry, C.TypeSelector, NewSelector)
  22. }
  23. var (
  24. _ adapter.OutboundGroup = (*Selector)(nil)
  25. _ adapter.ConnectionHandlerEx = (*Selector)(nil)
  26. _ adapter.PacketConnectionHandlerEx = (*Selector)(nil)
  27. )
  28. type Selector struct {
  29. outbound.Adapter
  30. ctx context.Context
  31. outbound adapter.OutboundManager
  32. connection adapter.ConnectionManager
  33. logger logger.ContextLogger
  34. tags []string
  35. defaultTag string
  36. outbounds map[string]adapter.Outbound
  37. selected common.TypedValue[adapter.Outbound]
  38. interruptGroup *interrupt.Group
  39. interruptExternalConnections bool
  40. }
  41. func NewSelector(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SelectorOutboundOptions) (adapter.Outbound, error) {
  42. outbound := &Selector{
  43. Adapter: outbound.NewAdapter(C.TypeSelector, tag, nil, options.Outbounds),
  44. ctx: ctx,
  45. outbound: service.FromContext[adapter.OutboundManager](ctx),
  46. connection: service.FromContext[adapter.ConnectionManager](ctx),
  47. logger: logger,
  48. tags: options.Outbounds,
  49. defaultTag: options.Default,
  50. outbounds: make(map[string]adapter.Outbound),
  51. interruptGroup: interrupt.NewGroup(),
  52. interruptExternalConnections: options.InterruptExistConnections,
  53. }
  54. if len(outbound.tags) == 0 {
  55. return nil, E.New("missing tags")
  56. }
  57. return outbound, nil
  58. }
  59. func (s *Selector) Network() []string {
  60. selected := s.selected.Load()
  61. if selected == nil {
  62. return []string{N.NetworkTCP, N.NetworkUDP}
  63. }
  64. return selected.Network()
  65. }
  66. func (s *Selector) Start() error {
  67. for i, tag := range s.tags {
  68. detour, loaded := s.outbound.Outbound(tag)
  69. if !loaded {
  70. return E.New("outbound ", i, " not found: ", tag)
  71. }
  72. s.outbounds[tag] = detour
  73. }
  74. if s.Tag() != "" {
  75. cacheFile := service.FromContext[adapter.CacheFile](s.ctx)
  76. if cacheFile != nil {
  77. selected := cacheFile.LoadSelected(s.Tag())
  78. if selected != "" {
  79. detour, loaded := s.outbounds[selected]
  80. if loaded {
  81. s.selected.Store(detour)
  82. return nil
  83. }
  84. }
  85. }
  86. }
  87. if s.defaultTag != "" {
  88. detour, loaded := s.outbounds[s.defaultTag]
  89. if !loaded {
  90. return E.New("default outbound not found: ", s.defaultTag)
  91. }
  92. s.selected.Store(detour)
  93. return nil
  94. }
  95. s.selected.Store(s.outbounds[s.tags[0]])
  96. return nil
  97. }
  98. func (s *Selector) Now() string {
  99. selected := s.selected.Load()
  100. if selected == nil {
  101. return s.tags[0]
  102. }
  103. return selected.Tag()
  104. }
  105. func (s *Selector) All() []string {
  106. return s.tags
  107. }
  108. func (s *Selector) SelectOutbound(tag string) bool {
  109. detour, loaded := s.outbounds[tag]
  110. if !loaded {
  111. return false
  112. }
  113. if s.selected.Swap(detour) == detour {
  114. return true
  115. }
  116. if s.Tag() != "" {
  117. cacheFile := service.FromContext[adapter.CacheFile](s.ctx)
  118. if cacheFile != nil {
  119. err := cacheFile.StoreSelected(s.Tag(), tag)
  120. if err != nil {
  121. s.logger.Error("store selected: ", err)
  122. }
  123. }
  124. }
  125. s.interruptGroup.Interrupt(s.interruptExternalConnections)
  126. return true
  127. }
  128. func (s *Selector) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  129. conn, err := s.selected.Load().DialContext(ctx, network, destination)
  130. if err != nil {
  131. return nil, err
  132. }
  133. return s.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  134. }
  135. func (s *Selector) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  136. conn, err := s.selected.Load().ListenPacket(ctx, destination)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return s.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  141. }
  142. func (s *Selector) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  143. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  144. selected := s.selected.Load()
  145. if outboundHandler, isHandler := selected.(adapter.ConnectionHandlerEx); isHandler {
  146. outboundHandler.NewConnectionEx(ctx, conn, metadata, onClose)
  147. } else {
  148. s.connection.NewConnection(ctx, selected, conn, metadata, onClose)
  149. }
  150. }
  151. func (s *Selector) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  152. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  153. selected := s.selected.Load()
  154. if outboundHandler, isHandler := selected.(adapter.PacketConnectionHandlerEx); isHandler {
  155. outboundHandler.NewPacketConnectionEx(ctx, conn, metadata, onClose)
  156. } else {
  157. s.connection.NewPacketConnection(ctx, selected, conn, metadata, onClose)
  158. }
  159. }
  160. func (s *Selector) NewDirectRouteConnection(metadata adapter.InboundContext, routeContext tun.DirectRouteContext, timeout time.Duration) (tun.DirectRouteDestination, error) {
  161. selected := s.selected.Load()
  162. if !common.Contains(selected.Network(), metadata.Network) {
  163. return nil, E.New(metadata.Network, " is not supported by outbound: ", selected.Tag())
  164. }
  165. return selected.(adapter.DirectRouteOutbound).NewDirectRouteConnection(metadata, routeContext, timeout)
  166. }
  167. func RealTag(detour adapter.Outbound) string {
  168. if group, isGroup := detour.(adapter.OutboundGroup); isGroup {
  169. return group.Now()
  170. }
  171. return detour.Tag()
  172. }