urltest.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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{C.NetworkTCP, C.NetworkUDP}
  51. }
  52. return s.group.Select().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().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. return s.group.Select().DialContext(ctx, network, destination)
  79. }
  80. func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  81. return s.group.Select().ListenPacket(ctx, destination)
  82. }
  83. func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  84. return s.group.Select().NewConnection(ctx, conn, metadata)
  85. }
  86. func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  87. return s.group.Select().NewPacketConnection(ctx, conn, metadata)
  88. }
  89. type URLTestGroup struct {
  90. router adapter.Router
  91. logger log.Logger
  92. outbounds []adapter.Outbound
  93. link string
  94. interval time.Duration
  95. tolerance uint16
  96. ticker *time.Ticker
  97. close chan struct{}
  98. }
  99. func NewURLTestGroup(router adapter.Router, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, tolerance uint16) *URLTestGroup {
  100. if link == "" {
  101. //goland:noinspection HttpUrlsUsage
  102. link = "http://www.gstatic.com/generate_204"
  103. }
  104. if interval == 0 {
  105. interval = C.DefaultURLTestInterval
  106. }
  107. if tolerance == 0 {
  108. tolerance = 50
  109. }
  110. return &URLTestGroup{
  111. router: router,
  112. logger: logger,
  113. outbounds: outbounds,
  114. link: link,
  115. interval: interval,
  116. tolerance: tolerance,
  117. close: make(chan struct{}),
  118. }
  119. }
  120. func (g *URLTestGroup) Start() error {
  121. g.ticker = time.NewTicker(g.interval)
  122. go g.loopCheck()
  123. return nil
  124. }
  125. func (g *URLTestGroup) Close() error {
  126. g.ticker.Stop()
  127. close(g.close)
  128. return nil
  129. }
  130. func (g *URLTestGroup) Select() adapter.Outbound {
  131. var minDelay uint16
  132. var minTime time.Time
  133. var minOutbound adapter.Outbound
  134. for _, detour := range g.outbounds {
  135. history := g.router.URLTestHistoryStorage(false).LoadURLTestHistory(RealTag(detour))
  136. if history == nil {
  137. continue
  138. }
  139. if minDelay == 0 || minDelay > history.Delay+g.tolerance || minDelay > history.Delay-g.tolerance && minTime.Before(history.Time) {
  140. minDelay = history.Delay
  141. minTime = history.Time
  142. minOutbound = detour
  143. }
  144. }
  145. if minOutbound == nil {
  146. minOutbound = g.outbounds[0]
  147. }
  148. return minOutbound
  149. }
  150. func (g *URLTestGroup) Fallback(used adapter.Outbound) []adapter.Outbound {
  151. outbounds := make([]adapter.Outbound, 0, len(g.outbounds)-1)
  152. for _, detour := range g.outbounds {
  153. if detour != used {
  154. outbounds = append(outbounds, detour)
  155. }
  156. }
  157. sort.Slice(outbounds, func(i, j int) bool {
  158. oi := outbounds[i]
  159. oj := outbounds[j]
  160. hi := g.router.URLTestHistoryStorage(false).LoadURLTestHistory(RealTag(oi))
  161. if hi == nil {
  162. return false
  163. }
  164. hj := g.router.URLTestHistoryStorage(false).LoadURLTestHistory(RealTag(oj))
  165. if hj == nil {
  166. return false
  167. }
  168. return hi.Delay < hj.Delay
  169. })
  170. return outbounds
  171. }
  172. func (g *URLTestGroup) loopCheck() {
  173. go g.checkOutbounds()
  174. for {
  175. select {
  176. case <-g.close:
  177. return
  178. case <-g.ticker.C:
  179. g.checkOutbounds()
  180. }
  181. }
  182. }
  183. func (g *URLTestGroup) checkOutbounds() {
  184. b, _ := batch.New(context.Background(), batch.WithConcurrencyNum[any](10))
  185. checked := make(map[string]bool)
  186. for _, detour := range g.outbounds {
  187. tag := detour.Tag()
  188. realTag := RealTag(detour)
  189. if checked[realTag] {
  190. continue
  191. }
  192. history := g.router.URLTestHistoryStorage(false).LoadURLTestHistory(realTag)
  193. if history != nil && time.Now().Sub(history.Time) < g.interval {
  194. continue
  195. }
  196. checked[realTag] = true
  197. p, loaded := g.router.Outbound(realTag)
  198. if !loaded {
  199. continue
  200. }
  201. b.Go(realTag, func() (any, error) {
  202. ctx, cancel := context.WithTimeout(context.Background(), C.URLTestTimeout)
  203. defer cancel()
  204. t, err := urltest.URLTest(ctx, g.link, p)
  205. if err != nil {
  206. g.logger.Debug("outbound ", tag, " unavailable: ", err)
  207. g.router.URLTestHistoryStorage(true).DeleteURLTestHistory(realTag)
  208. } else {
  209. g.logger.Debug("outbound ", tag, " available: ", t, "ms")
  210. g.router.URLTestHistoryStorage(true).StoreURLTestHistory(realTag, &urltest.History{
  211. Time: time.Now(),
  212. Delay: t,
  213. })
  214. }
  215. return nil, nil
  216. })
  217. }
  218. b.Wait()
  219. }
  220. func RealTag(detour adapter.Outbound) string {
  221. if group, isGroup := detour.(adapter.OutboundGroup); isGroup {
  222. return group.Now()
  223. }
  224. return detour.Tag()
  225. }