urltest.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. package outbound
  2. import (
  3. "context"
  4. "net"
  5. "sort"
  6. "sync"
  7. "time"
  8. "github.com/sagernet/sing-box/adapter"
  9. "github.com/sagernet/sing-box/common/urltest"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. "github.com/sagernet/sing/common"
  14. "github.com/sagernet/sing/common/batch"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. M "github.com/sagernet/sing/common/metadata"
  17. N "github.com/sagernet/sing/common/network"
  18. )
  19. var (
  20. _ adapter.Outbound = (*URLTest)(nil)
  21. _ adapter.OutboundGroup = (*URLTest)(nil)
  22. )
  23. type URLTest struct {
  24. myOutboundAdapter
  25. ctx context.Context
  26. tags []string
  27. link string
  28. interval time.Duration
  29. tolerance uint16
  30. group *URLTestGroup
  31. }
  32. func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.URLTestOutboundOptions) (*URLTest, error) {
  33. outbound := &URLTest{
  34. myOutboundAdapter: myOutboundAdapter{
  35. protocol: C.TypeURLTest,
  36. router: router,
  37. logger: logger,
  38. tag: tag,
  39. },
  40. ctx: ctx,
  41. tags: options.Outbounds,
  42. link: options.URL,
  43. interval: time.Duration(options.Interval),
  44. tolerance: options.Tolerance,
  45. }
  46. if len(outbound.tags) == 0 {
  47. return nil, E.New("missing tags")
  48. }
  49. return outbound, nil
  50. }
  51. func (s *URLTest) Network() []string {
  52. if s.group == nil {
  53. return []string{N.NetworkTCP, N.NetworkUDP}
  54. }
  55. return s.group.Select(N.NetworkTCP).Network()
  56. }
  57. func (s *URLTest) Start() error {
  58. outbounds := make([]adapter.Outbound, 0, len(s.tags))
  59. for i, tag := range s.tags {
  60. detour, loaded := s.router.Outbound(tag)
  61. if !loaded {
  62. return E.New("outbound ", i, " not found: ", tag)
  63. }
  64. outbounds = append(outbounds, detour)
  65. }
  66. s.group = NewURLTestGroup(s.ctx, s.router, s.logger, outbounds, s.link, s.interval, s.tolerance)
  67. return s.group.Start()
  68. }
  69. func (s *URLTest) Close() error {
  70. return common.Close(
  71. common.PtrOrNil(s.group),
  72. )
  73. }
  74. func (s *URLTest) Now() string {
  75. return s.group.Select(N.NetworkTCP).Tag()
  76. }
  77. func (s *URLTest) All() []string {
  78. return s.tags
  79. }
  80. func (s *URLTest) URLTest(ctx context.Context, link string) (map[string]uint16, error) {
  81. return s.group.URLTest(ctx, link)
  82. }
  83. func (s *URLTest) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  84. outbound := s.group.Select(network)
  85. conn, err := outbound.DialContext(ctx, network, destination)
  86. if err == nil {
  87. return conn, nil
  88. }
  89. s.logger.ErrorContext(ctx, err)
  90. s.group.history.DeleteURLTestHistory(outbound.Tag())
  91. return nil, err
  92. }
  93. func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  94. outbound := s.group.Select(N.NetworkUDP)
  95. conn, err := outbound.ListenPacket(ctx, destination)
  96. if err == nil {
  97. return conn, nil
  98. }
  99. s.logger.ErrorContext(ctx, err)
  100. s.group.history.DeleteURLTestHistory(outbound.Tag())
  101. return nil, err
  102. }
  103. func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  104. return NewConnection(ctx, s, conn, metadata)
  105. }
  106. func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  107. return NewPacketConnection(ctx, s, conn, metadata)
  108. }
  109. type URLTestGroup struct {
  110. ctx context.Context
  111. router adapter.Router
  112. logger log.Logger
  113. outbounds []adapter.Outbound
  114. link string
  115. interval time.Duration
  116. tolerance uint16
  117. history *urltest.HistoryStorage
  118. ticker *time.Ticker
  119. close chan struct{}
  120. }
  121. func NewURLTestGroup(ctx context.Context, router adapter.Router, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, tolerance uint16) *URLTestGroup {
  122. if interval == 0 {
  123. interval = C.DefaultURLTestInterval
  124. }
  125. if tolerance == 0 {
  126. tolerance = 50
  127. }
  128. var history *urltest.HistoryStorage
  129. if clashServer := router.ClashServer(); clashServer != nil {
  130. history = clashServer.HistoryStorage()
  131. } else {
  132. history = urltest.NewHistoryStorage()
  133. }
  134. return &URLTestGroup{
  135. ctx: ctx,
  136. router: router,
  137. logger: logger,
  138. outbounds: outbounds,
  139. link: link,
  140. interval: interval,
  141. tolerance: tolerance,
  142. history: history,
  143. close: make(chan struct{}),
  144. }
  145. }
  146. func (g *URLTestGroup) Start() error {
  147. g.ticker = time.NewTicker(g.interval)
  148. go g.loopCheck()
  149. return nil
  150. }
  151. func (g *URLTestGroup) Close() error {
  152. g.ticker.Stop()
  153. close(g.close)
  154. return nil
  155. }
  156. func (g *URLTestGroup) Select(network string) adapter.Outbound {
  157. var minDelay uint16
  158. var minTime time.Time
  159. var minOutbound adapter.Outbound
  160. for _, detour := range g.outbounds {
  161. if !common.Contains(detour.Network(), network) {
  162. continue
  163. }
  164. history := g.history.LoadURLTestHistory(RealTag(detour))
  165. if history == nil {
  166. continue
  167. }
  168. if minDelay == 0 || minDelay > history.Delay+g.tolerance || minDelay > history.Delay-g.tolerance && minTime.Before(history.Time) {
  169. minDelay = history.Delay
  170. minTime = history.Time
  171. minOutbound = detour
  172. }
  173. }
  174. if minOutbound == nil {
  175. for _, detour := range g.outbounds {
  176. if !common.Contains(detour.Network(), network) {
  177. continue
  178. }
  179. minOutbound = detour
  180. break
  181. }
  182. }
  183. return minOutbound
  184. }
  185. func (g *URLTestGroup) Fallback(used adapter.Outbound) []adapter.Outbound {
  186. outbounds := make([]adapter.Outbound, 0, len(g.outbounds)-1)
  187. for _, detour := range g.outbounds {
  188. if detour != used {
  189. outbounds = append(outbounds, detour)
  190. }
  191. }
  192. sort.SliceStable(outbounds, func(i, j int) bool {
  193. oi := outbounds[i]
  194. oj := outbounds[j]
  195. hi := g.history.LoadURLTestHistory(RealTag(oi))
  196. if hi == nil {
  197. return false
  198. }
  199. hj := g.history.LoadURLTestHistory(RealTag(oj))
  200. if hj == nil {
  201. return false
  202. }
  203. return hi.Delay < hj.Delay
  204. })
  205. return outbounds
  206. }
  207. func (g *URLTestGroup) loopCheck() {
  208. go g.checkOutbounds()
  209. for {
  210. select {
  211. case <-g.close:
  212. return
  213. case <-g.ticker.C:
  214. g.checkOutbounds()
  215. }
  216. }
  217. }
  218. func (g *URLTestGroup) checkOutbounds() {
  219. _, _ = g.URLTest(g.ctx, g.link)
  220. }
  221. func (g *URLTestGroup) URLTest(ctx context.Context, link string) (map[string]uint16, error) {
  222. b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
  223. checked := make(map[string]bool)
  224. result := make(map[string]uint16)
  225. var resultAccess sync.Mutex
  226. for _, detour := range g.outbounds {
  227. tag := detour.Tag()
  228. realTag := RealTag(detour)
  229. if checked[realTag] {
  230. continue
  231. }
  232. history := g.history.LoadURLTestHistory(realTag)
  233. if history != nil && time.Now().Sub(history.Time) < g.interval {
  234. continue
  235. }
  236. checked[realTag] = true
  237. p, loaded := g.router.Outbound(realTag)
  238. if !loaded {
  239. continue
  240. }
  241. b.Go(realTag, func() (any, error) {
  242. ctx, cancel := context.WithTimeout(context.Background(), C.TCPTimeout)
  243. defer cancel()
  244. t, err := urltest.URLTest(ctx, link, p)
  245. if err != nil {
  246. g.logger.Debug("outbound ", tag, " unavailable: ", err)
  247. g.history.DeleteURLTestHistory(realTag)
  248. } else {
  249. g.logger.Debug("outbound ", tag, " available: ", t, "ms")
  250. g.history.StoreURLTestHistory(realTag, &urltest.History{
  251. Time: time.Now(),
  252. Delay: t,
  253. })
  254. resultAccess.Lock()
  255. result[tag] = t
  256. resultAccess.Unlock()
  257. }
  258. return nil, nil
  259. })
  260. }
  261. b.Wait()
  262. return result, nil
  263. }