urltest.go 12 KB

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