urltest.go 8.3 KB

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