urltest.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package group
  2. import (
  3. "context"
  4. "net"
  5. "sync"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/adapter/outbound"
  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. func RegisterURLTest(registry *outbound.Registry) {
  24. outbound.Register[option.URLTestOutboundOptions](registry, C.TypeURLTest, NewURLTest)
  25. }
  26. var (
  27. _ adapter.OutboundGroup = (*URLTest)(nil)
  28. _ adapter.InterfaceUpdateListener = (*URLTest)(nil)
  29. )
  30. type URLTest struct {
  31. outbound.Adapter
  32. ctx context.Context
  33. router adapter.Router
  34. outbound adapter.OutboundManager
  35. connection adapter.ConnectionManager
  36. logger log.ContextLogger
  37. tags []string
  38. link string
  39. interval time.Duration
  40. tolerance uint16
  41. idleTimeout time.Duration
  42. group *URLTestGroup
  43. interruptExternalConnections bool
  44. }
  45. func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.URLTestOutboundOptions) (adapter.Outbound, error) {
  46. outbound := &URLTest{
  47. Adapter: outbound.NewAdapter(C.TypeURLTest, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
  48. ctx: ctx,
  49. router: router,
  50. outbound: service.FromContext[adapter.OutboundManager](ctx),
  51. connection: service.FromContext[adapter.ConnectionManager](ctx),
  52. logger: logger,
  53. tags: options.Outbounds,
  54. link: options.URL,
  55. interval: time.Duration(options.Interval),
  56. tolerance: options.Tolerance,
  57. idleTimeout: time.Duration(options.IdleTimeout),
  58. interruptExternalConnections: options.InterruptExistConnections,
  59. }
  60. if len(outbound.tags) == 0 {
  61. return nil, E.New("missing tags")
  62. }
  63. return outbound, nil
  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.outbound.Outbound(tag)
  69. if !loaded {
  70. return E.New("outbound ", i, " not found: ", tag)
  71. }
  72. outbounds = append(outbounds, detour)
  73. }
  74. group, err := NewURLTestGroup(s.ctx, s.outbound, s.logger, outbounds, s.link, s.interval, s.tolerance, s.idleTimeout, s.interruptExternalConnections)
  75. if err != nil {
  76. return err
  77. }
  78. s.group = group
  79. return nil
  80. }
  81. func (s *URLTest) PostStart() error {
  82. s.group.PostStart()
  83. return nil
  84. }
  85. func (s *URLTest) Close() error {
  86. return common.Close(
  87. common.PtrOrNil(s.group),
  88. )
  89. }
  90. func (s *URLTest) Now() string {
  91. if s.group.selectedOutboundTCP != nil {
  92. return s.group.selectedOutboundTCP.Tag()
  93. } else if s.group.selectedOutboundUDP != nil {
  94. return s.group.selectedOutboundUDP.Tag()
  95. }
  96. return ""
  97. }
  98. func (s *URLTest) All() []string {
  99. return s.tags
  100. }
  101. func (s *URLTest) URLTest(ctx context.Context) (map[string]uint16, error) {
  102. return s.group.URLTest(ctx)
  103. }
  104. func (s *URLTest) CheckOutbounds() {
  105. s.group.CheckOutbounds(true)
  106. }
  107. func (s *URLTest) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  108. s.group.Touch()
  109. var outbound adapter.Outbound
  110. switch N.NetworkName(network) {
  111. case N.NetworkTCP:
  112. outbound = s.group.selectedOutboundTCP
  113. case N.NetworkUDP:
  114. outbound = s.group.selectedOutboundUDP
  115. default:
  116. return nil, E.Extend(N.ErrUnknownNetwork, network)
  117. }
  118. if outbound == nil {
  119. outbound, _ = s.group.Select(network)
  120. }
  121. if outbound == nil {
  122. return nil, E.New("missing supported outbound")
  123. }
  124. conn, err := outbound.DialContext(ctx, network, destination)
  125. if err == nil {
  126. return s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  127. }
  128. s.logger.ErrorContext(ctx, err)
  129. s.group.history.DeleteURLTestHistory(outbound.Tag())
  130. return nil, err
  131. }
  132. func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  133. s.group.Touch()
  134. outbound := s.group.selectedOutboundUDP
  135. if outbound == nil {
  136. outbound, _ = s.group.Select(N.NetworkUDP)
  137. }
  138. if outbound == nil {
  139. return nil, E.New("missing supported outbound")
  140. }
  141. conn, err := outbound.ListenPacket(ctx, destination)
  142. if err == nil {
  143. return s.group.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  144. }
  145. s.logger.ErrorContext(ctx, err)
  146. s.group.history.DeleteURLTestHistory(outbound.Tag())
  147. return nil, err
  148. }
  149. func (s *URLTest) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  150. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  151. s.connection.NewConnection(ctx, s, conn, metadata, onClose)
  152. }
  153. func (s *URLTest) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  154. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  155. s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
  156. }
  157. func (s *URLTest) InterfaceUpdated() {
  158. go s.group.CheckOutbounds(true)
  159. return
  160. }
  161. type URLTestGroup struct {
  162. ctx context.Context
  163. router adapter.Router
  164. outboundManager adapter.OutboundManager
  165. logger log.Logger
  166. outbounds []adapter.Outbound
  167. link string
  168. interval time.Duration
  169. tolerance uint16
  170. idleTimeout time.Duration
  171. history adapter.URLTestHistoryStorage
  172. checking atomic.Bool
  173. pauseManager pause.Manager
  174. selectedOutboundTCP adapter.Outbound
  175. selectedOutboundUDP adapter.Outbound
  176. interruptGroup *interrupt.Group
  177. interruptExternalConnections bool
  178. access sync.Mutex
  179. ticker *time.Ticker
  180. close chan struct{}
  181. started bool
  182. lastActive atomic.TypedValue[time.Time]
  183. }
  184. func NewURLTestGroup(ctx context.Context, outboundManager adapter.OutboundManager, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, tolerance uint16, idleTimeout time.Duration, interruptExternalConnections bool) (*URLTestGroup, error) {
  185. if interval == 0 {
  186. interval = C.DefaultURLTestInterval
  187. }
  188. if tolerance == 0 {
  189. tolerance = 50
  190. }
  191. if idleTimeout == 0 {
  192. idleTimeout = C.DefaultURLTestIdleTimeout
  193. }
  194. if interval > idleTimeout {
  195. return nil, E.New("interval must be less or equal than idle_timeout")
  196. }
  197. var history adapter.URLTestHistoryStorage
  198. if historyFromCtx := service.PtrFromContext[urltest.HistoryStorage](ctx); historyFromCtx != nil {
  199. history = historyFromCtx
  200. } else if clashServer := service.FromContext[adapter.ClashServer](ctx); clashServer != nil {
  201. history = clashServer.HistoryStorage()
  202. } else {
  203. history = urltest.NewHistoryStorage()
  204. }
  205. return &URLTestGroup{
  206. ctx: ctx,
  207. outboundManager: outboundManager,
  208. logger: logger,
  209. outbounds: outbounds,
  210. link: link,
  211. interval: interval,
  212. tolerance: tolerance,
  213. idleTimeout: idleTimeout,
  214. history: history,
  215. close: make(chan struct{}),
  216. pauseManager: service.FromContext[pause.Manager](ctx),
  217. interruptGroup: interrupt.NewGroup(),
  218. interruptExternalConnections: interruptExternalConnections,
  219. }, nil
  220. }
  221. func (g *URLTestGroup) PostStart() {
  222. g.started = true
  223. g.lastActive.Store(time.Now())
  224. go g.CheckOutbounds(false)
  225. }
  226. func (g *URLTestGroup) Touch() {
  227. if !g.started {
  228. return
  229. }
  230. if g.ticker != nil {
  231. g.lastActive.Store(time.Now())
  232. return
  233. }
  234. g.access.Lock()
  235. defer g.access.Unlock()
  236. if g.ticker != nil {
  237. return
  238. }
  239. g.ticker = time.NewTicker(g.interval)
  240. go g.loopCheck()
  241. }
  242. func (g *URLTestGroup) Close() error {
  243. if g.ticker == nil {
  244. return nil
  245. }
  246. g.ticker.Stop()
  247. close(g.close)
  248. return nil
  249. }
  250. func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
  251. var minDelay uint16
  252. var minOutbound adapter.Outbound
  253. switch network {
  254. case N.NetworkTCP:
  255. if g.selectedOutboundTCP != nil {
  256. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundTCP)); history != nil {
  257. minOutbound = g.selectedOutboundTCP
  258. minDelay = history.Delay
  259. }
  260. }
  261. case N.NetworkUDP:
  262. if g.selectedOutboundUDP != nil {
  263. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundUDP)); history != nil {
  264. minOutbound = g.selectedOutboundUDP
  265. minDelay = history.Delay
  266. }
  267. }
  268. }
  269. for _, detour := range g.outbounds {
  270. if !common.Contains(detour.Network(), network) {
  271. continue
  272. }
  273. history := g.history.LoadURLTestHistory(RealTag(detour))
  274. if history == nil {
  275. continue
  276. }
  277. if minDelay == 0 || minDelay > history.Delay+g.tolerance {
  278. minDelay = history.Delay
  279. minOutbound = detour
  280. }
  281. }
  282. if minOutbound == nil {
  283. for _, detour := range g.outbounds {
  284. if !common.Contains(detour.Network(), network) {
  285. continue
  286. }
  287. return detour, false
  288. }
  289. return nil, false
  290. }
  291. return minOutbound, true
  292. }
  293. func (g *URLTestGroup) loopCheck() {
  294. if time.Now().Sub(g.lastActive.Load()) > g.interval {
  295. g.lastActive.Store(time.Now())
  296. g.CheckOutbounds(false)
  297. }
  298. for {
  299. select {
  300. case <-g.close:
  301. return
  302. case <-g.ticker.C:
  303. }
  304. if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
  305. g.access.Lock()
  306. g.ticker.Stop()
  307. g.ticker = nil
  308. g.access.Unlock()
  309. return
  310. }
  311. g.pauseManager.WaitActive()
  312. g.CheckOutbounds(false)
  313. }
  314. }
  315. func (g *URLTestGroup) CheckOutbounds(force bool) {
  316. _, _ = g.urlTest(g.ctx, force)
  317. }
  318. func (g *URLTestGroup) URLTest(ctx context.Context) (map[string]uint16, error) {
  319. return g.urlTest(ctx, false)
  320. }
  321. func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint16, error) {
  322. result := make(map[string]uint16)
  323. if g.checking.Swap(true) {
  324. return result, nil
  325. }
  326. defer g.checking.Store(false)
  327. b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
  328. checked := make(map[string]bool)
  329. var resultAccess sync.Mutex
  330. for _, detour := range g.outbounds {
  331. tag := detour.Tag()
  332. realTag := RealTag(detour)
  333. if checked[realTag] {
  334. continue
  335. }
  336. history := g.history.LoadURLTestHistory(realTag)
  337. if !force && history != nil && time.Now().Sub(history.Time) < g.interval {
  338. continue
  339. }
  340. checked[realTag] = true
  341. p, loaded := g.outboundManager.Outbound(realTag)
  342. if !loaded {
  343. continue
  344. }
  345. b.Go(realTag, func() (any, error) {
  346. testCtx, cancel := context.WithTimeout(g.ctx, C.TCPTimeout)
  347. defer cancel()
  348. t, err := urltest.URLTest(testCtx, g.link, p)
  349. if err != nil {
  350. g.logger.Debug("outbound ", tag, " unavailable: ", err)
  351. g.history.DeleteURLTestHistory(realTag)
  352. } else {
  353. g.logger.Debug("outbound ", tag, " available: ", t, "ms")
  354. g.history.StoreURLTestHistory(realTag, &adapter.URLTestHistory{
  355. Time: time.Now(),
  356. Delay: t,
  357. })
  358. resultAccess.Lock()
  359. result[tag] = t
  360. resultAccess.Unlock()
  361. }
  362. return nil, nil
  363. })
  364. }
  365. b.Wait()
  366. g.performUpdateCheck()
  367. return result, nil
  368. }
  369. func (g *URLTestGroup) performUpdateCheck() {
  370. var updated bool
  371. if outbound, exists := g.Select(N.NetworkTCP); outbound != nil && (g.selectedOutboundTCP == nil || (exists && outbound != g.selectedOutboundTCP)) {
  372. g.selectedOutboundTCP = outbound
  373. updated = true
  374. }
  375. if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
  376. g.selectedOutboundUDP = outbound
  377. updated = true
  378. }
  379. if updated {
  380. g.interruptGroup.Interrupt(g.interruptExternalConnections)
  381. }
  382. }