urltest.go 9.9 KB

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