urltest.go 13 KB

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