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/common/x/list"
  21. "github.com/sagernet/sing/service"
  22. "github.com/sagernet/sing/service/pause"
  23. )
  24. func RegisterURLTest(registry *outbound.Registry) {
  25. outbound.Register[option.URLTestOutboundOptions](registry, C.TypeURLTest, NewURLTest)
  26. }
  27. var _ adapter.OutboundGroup = (*URLTest)(nil)
  28. type URLTest struct {
  29. outbound.Adapter
  30. ctx context.Context
  31. router adapter.Router
  32. outbound adapter.OutboundManager
  33. connection adapter.ConnectionManager
  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, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
  46. ctx: ctx,
  47. router: router,
  48. outbound: service.FromContext[adapter.OutboundManager](ctx),
  49. connection: service.FromContext[adapter.ConnectionManager](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.outbound.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.outbound, 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. func (s *URLTest) NewConnectionEx(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  148. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  149. s.connection.NewConnection(ctx, s, conn, metadata, onClose)
  150. }
  151. func (s *URLTest) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
  152. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  153. s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
  154. }
  155. type URLTestGroup struct {
  156. ctx context.Context
  157. router adapter.Router
  158. outbound adapter.OutboundManager
  159. pause pause.Manager
  160. pauseCallback *list.Element[pause.Callback]
  161. logger log.Logger
  162. outbounds []adapter.Outbound
  163. link string
  164. interval time.Duration
  165. tolerance uint16
  166. idleTimeout time.Duration
  167. history adapter.URLTestHistoryStorage
  168. checking atomic.Bool
  169. selectedOutboundTCP adapter.Outbound
  170. selectedOutboundUDP adapter.Outbound
  171. interruptGroup *interrupt.Group
  172. interruptExternalConnections bool
  173. access sync.Mutex
  174. ticker *time.Ticker
  175. close chan struct{}
  176. started bool
  177. lastActive atomic.TypedValue[time.Time]
  178. }
  179. 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) {
  180. if interval == 0 {
  181. interval = C.DefaultURLTestInterval
  182. }
  183. if tolerance == 0 {
  184. tolerance = 50
  185. }
  186. if idleTimeout == 0 {
  187. idleTimeout = C.DefaultURLTestIdleTimeout
  188. }
  189. if interval > idleTimeout {
  190. return nil, E.New("interval must be less or equal than idle_timeout")
  191. }
  192. var history adapter.URLTestHistoryStorage
  193. if historyFromCtx := service.PtrFromContext[urltest.HistoryStorage](ctx); historyFromCtx != nil {
  194. history = historyFromCtx
  195. } else if clashServer := service.FromContext[adapter.ClashServer](ctx); clashServer != nil {
  196. history = clashServer.HistoryStorage()
  197. } else {
  198. history = urltest.NewHistoryStorage()
  199. }
  200. return &URLTestGroup{
  201. ctx: ctx,
  202. outbound: outboundManager,
  203. logger: logger,
  204. outbounds: outbounds,
  205. link: link,
  206. interval: interval,
  207. tolerance: tolerance,
  208. idleTimeout: idleTimeout,
  209. history: history,
  210. close: make(chan struct{}),
  211. pause: service.FromContext[pause.Manager](ctx),
  212. interruptGroup: interrupt.NewGroup(),
  213. interruptExternalConnections: interruptExternalConnections,
  214. }, nil
  215. }
  216. func (g *URLTestGroup) PostStart() {
  217. g.access.Lock()
  218. defer g.access.Unlock()
  219. g.started = true
  220. g.lastActive.Store(time.Now())
  221. go g.CheckOutbounds(false)
  222. }
  223. func (g *URLTestGroup) Touch() {
  224. if !g.started {
  225. return
  226. }
  227. g.access.Lock()
  228. defer g.access.Unlock()
  229. if g.ticker != nil {
  230. g.lastActive.Store(time.Now())
  231. return
  232. }
  233. g.ticker = time.NewTicker(g.interval)
  234. go g.loopCheck()
  235. g.pauseCallback = pause.RegisterTicker(g.pause, g.ticker, g.interval, nil)
  236. }
  237. func (g *URLTestGroup) Close() error {
  238. g.access.Lock()
  239. defer g.access.Unlock()
  240. if g.ticker == nil {
  241. return nil
  242. }
  243. g.ticker.Stop()
  244. g.pause.UnregisterCallback(g.pauseCallback)
  245. close(g.close)
  246. return nil
  247. }
  248. func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
  249. var minDelay uint16
  250. var minOutbound adapter.Outbound
  251. switch network {
  252. case N.NetworkTCP:
  253. if g.selectedOutboundTCP != nil {
  254. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundTCP)); history != nil {
  255. minOutbound = g.selectedOutboundTCP
  256. minDelay = history.Delay
  257. }
  258. }
  259. case N.NetworkUDP:
  260. if g.selectedOutboundUDP != nil {
  261. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundUDP)); history != nil {
  262. minOutbound = g.selectedOutboundUDP
  263. minDelay = history.Delay
  264. }
  265. }
  266. }
  267. for _, detour := range g.outbounds {
  268. if !common.Contains(detour.Network(), network) {
  269. continue
  270. }
  271. history := g.history.LoadURLTestHistory(RealTag(detour))
  272. if history == nil {
  273. continue
  274. }
  275. if minDelay == 0 || minDelay > history.Delay+g.tolerance {
  276. minDelay = history.Delay
  277. minOutbound = detour
  278. }
  279. }
  280. if minOutbound == nil {
  281. for _, detour := range g.outbounds {
  282. if !common.Contains(detour.Network(), network) {
  283. continue
  284. }
  285. return detour, false
  286. }
  287. return nil, false
  288. }
  289. return minOutbound, true
  290. }
  291. func (g *URLTestGroup) loopCheck() {
  292. if time.Now().Sub(g.lastActive.Load()) > g.interval {
  293. g.lastActive.Store(time.Now())
  294. g.CheckOutbounds(false)
  295. }
  296. for {
  297. select {
  298. case <-g.close:
  299. return
  300. case <-g.ticker.C:
  301. }
  302. if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
  303. g.access.Lock()
  304. g.ticker.Stop()
  305. g.ticker = nil
  306. g.pause.UnregisterCallback(g.pauseCallback)
  307. g.pauseCallback = nil
  308. g.access.Unlock()
  309. return
  310. }
  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.outbound.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, &adapter.URLTestHistory{
  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. if g.selectedOutboundTCP != nil {
  372. updated = true
  373. }
  374. g.selectedOutboundTCP = outbound
  375. }
  376. if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
  377. if g.selectedOutboundUDP != nil {
  378. updated = true
  379. }
  380. g.selectedOutboundUDP = outbound
  381. }
  382. if updated {
  383. g.interruptGroup.Interrupt(g.interruptExternalConnections)
  384. }
  385. }