urltest.go 7.0 KB

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