urltest.go 12 KB

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