urltest.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 *urltest.HistoryStorage
  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 *urltest.HistoryStorage
  198. if history = service.PtrFromContext[urltest.HistoryStorage](ctx); history != nil {
  199. } else if clashServer := service.FromContext[adapter.ClashServer](ctx); clashServer != nil {
  200. history = clashServer.HistoryStorage()
  201. } else {
  202. history = urltest.NewHistoryStorage()
  203. }
  204. return &URLTestGroup{
  205. ctx: ctx,
  206. outboundManager: outboundManager,
  207. logger: logger,
  208. outbounds: outbounds,
  209. link: link,
  210. interval: interval,
  211. tolerance: tolerance,
  212. idleTimeout: idleTimeout,
  213. history: history,
  214. close: make(chan struct{}),
  215. pauseManager: service.FromContext[pause.Manager](ctx),
  216. interruptGroup: interrupt.NewGroup(),
  217. interruptExternalConnections: interruptExternalConnections,
  218. }, nil
  219. }
  220. func (g *URLTestGroup) PostStart() {
  221. g.started = true
  222. g.lastActive.Store(time.Now())
  223. go g.CheckOutbounds(false)
  224. }
  225. func (g *URLTestGroup) Touch() {
  226. if !g.started {
  227. return
  228. }
  229. if g.ticker != nil {
  230. g.lastActive.Store(time.Now())
  231. return
  232. }
  233. g.access.Lock()
  234. defer g.access.Unlock()
  235. if g.ticker != nil {
  236. return
  237. }
  238. g.ticker = time.NewTicker(g.interval)
  239. go g.loopCheck()
  240. }
  241. func (g *URLTestGroup) Close() error {
  242. if g.ticker == nil {
  243. return nil
  244. }
  245. g.ticker.Stop()
  246. close(g.close)
  247. return nil
  248. }
  249. func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
  250. var minDelay uint16
  251. var minOutbound adapter.Outbound
  252. switch network {
  253. case N.NetworkTCP:
  254. if g.selectedOutboundTCP != nil {
  255. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundTCP)); history != nil {
  256. minOutbound = g.selectedOutboundTCP
  257. minDelay = history.Delay
  258. }
  259. }
  260. case N.NetworkUDP:
  261. if g.selectedOutboundUDP != nil {
  262. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundUDP)); history != nil {
  263. minOutbound = g.selectedOutboundUDP
  264. minDelay = history.Delay
  265. }
  266. }
  267. }
  268. for _, detour := range g.outbounds {
  269. if !common.Contains(detour.Network(), network) {
  270. continue
  271. }
  272. history := g.history.LoadURLTestHistory(RealTag(detour))
  273. if history == nil {
  274. continue
  275. }
  276. if minDelay == 0 || minDelay > history.Delay+g.tolerance {
  277. minDelay = history.Delay
  278. minOutbound = detour
  279. }
  280. }
  281. if minOutbound == nil {
  282. for _, detour := range g.outbounds {
  283. if !common.Contains(detour.Network(), network) {
  284. continue
  285. }
  286. return detour, false
  287. }
  288. return nil, false
  289. }
  290. return minOutbound, true
  291. }
  292. func (g *URLTestGroup) loopCheck() {
  293. if time.Now().Sub(g.lastActive.Load()) > g.interval {
  294. g.lastActive.Store(time.Now())
  295. g.CheckOutbounds(false)
  296. }
  297. for {
  298. select {
  299. case <-g.close:
  300. return
  301. case <-g.ticker.C:
  302. }
  303. if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
  304. g.access.Lock()
  305. g.ticker.Stop()
  306. g.ticker = nil
  307. g.access.Unlock()
  308. return
  309. }
  310. g.pauseManager.WaitActive()
  311. g.CheckOutbounds(false)
  312. }
  313. }
  314. func (g *URLTestGroup) CheckOutbounds(force bool) {
  315. _, _ = g.urlTest(g.ctx, force)
  316. }
  317. func (g *URLTestGroup) URLTest(ctx context.Context) (map[string]uint16, error) {
  318. return g.urlTest(ctx, false)
  319. }
  320. func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint16, error) {
  321. result := make(map[string]uint16)
  322. if g.checking.Swap(true) {
  323. return result, nil
  324. }
  325. defer g.checking.Store(false)
  326. b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
  327. checked := make(map[string]bool)
  328. var resultAccess sync.Mutex
  329. for _, detour := range g.outbounds {
  330. tag := detour.Tag()
  331. realTag := RealTag(detour)
  332. if checked[realTag] {
  333. continue
  334. }
  335. history := g.history.LoadURLTestHistory(realTag)
  336. if !force && history != nil && time.Now().Sub(history.Time) < g.interval {
  337. continue
  338. }
  339. checked[realTag] = true
  340. p, loaded := g.outboundManager.Outbound(realTag)
  341. if !loaded {
  342. continue
  343. }
  344. b.Go(realTag, func() (any, error) {
  345. testCtx, cancel := context.WithTimeout(g.ctx, C.TCPTimeout)
  346. defer cancel()
  347. t, err := urltest.URLTest(testCtx, g.link, p)
  348. if err != nil {
  349. g.logger.Debug("outbound ", tag, " unavailable: ", err)
  350. g.history.DeleteURLTestHistory(realTag)
  351. } else {
  352. g.logger.Debug("outbound ", tag, " available: ", t, "ms")
  353. g.history.StoreURLTestHistory(realTag, &urltest.History{
  354. Time: time.Now(),
  355. Delay: t,
  356. })
  357. resultAccess.Lock()
  358. result[tag] = t
  359. resultAccess.Unlock()
  360. }
  361. return nil, nil
  362. })
  363. }
  364. b.Wait()
  365. g.performUpdateCheck()
  366. return result, nil
  367. }
  368. func (g *URLTestGroup) performUpdateCheck() {
  369. var updated bool
  370. if outbound, exists := g.Select(N.NetworkTCP); outbound != nil && (g.selectedOutboundTCP == nil || (exists && outbound != g.selectedOutboundTCP)) {
  371. g.selectedOutboundTCP = outbound
  372. updated = true
  373. }
  374. if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
  375. g.selectedOutboundUDP = outbound
  376. updated = true
  377. }
  378. if updated {
  379. g.interruptGroup.Interrupt(g.interruptExternalConnections)
  380. }
  381. }