urltest.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. package outbound
  2. import (
  3. "context"
  4. "net"
  5. "sync"
  6. "time"
  7. "github.com/sagernet/sing-box/adapter"
  8. "github.com/sagernet/sing-box/common/interrupt"
  9. "github.com/sagernet/sing-box/common/urltest"
  10. C "github.com/sagernet/sing-box/constant"
  11. "github.com/sagernet/sing-box/log"
  12. "github.com/sagernet/sing-box/option"
  13. "github.com/sagernet/sing/common"
  14. "github.com/sagernet/sing/common/atomic"
  15. "github.com/sagernet/sing/common/batch"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. M "github.com/sagernet/sing/common/metadata"
  18. N "github.com/sagernet/sing/common/network"
  19. "github.com/sagernet/sing/service"
  20. "github.com/sagernet/sing/service/pause"
  21. )
  22. var (
  23. _ adapter.Outbound = (*URLTest)(nil)
  24. _ adapter.OutboundGroup = (*URLTest)(nil)
  25. _ adapter.InterfaceUpdateListener = (*URLTest)(nil)
  26. )
  27. type URLTest struct {
  28. myOutboundAdapter
  29. ctx context.Context
  30. tags []string
  31. link string
  32. interval time.Duration
  33. tolerance uint16
  34. idleTimeout time.Duration
  35. group *URLTestGroup
  36. interruptExternalConnections bool
  37. }
  38. func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.URLTestOutboundOptions) (*URLTest, error) {
  39. outbound := &URLTest{
  40. myOutboundAdapter: myOutboundAdapter{
  41. protocol: C.TypeURLTest,
  42. network: []string{N.NetworkTCP, N.NetworkUDP},
  43. router: router,
  44. logger: logger,
  45. tag: tag,
  46. dependencies: options.Outbounds,
  47. },
  48. ctx: ctx,
  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. func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  156. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  157. return NewConnection(ctx, s, conn, metadata)
  158. }
  159. func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  160. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  161. return NewPacketConnection(ctx, s, conn, metadata)
  162. }
  163. func (s *URLTest) InterfaceUpdated() {
  164. go s.group.CheckOutbounds(true)
  165. return
  166. }
  167. type URLTestGroup struct {
  168. ctx context.Context
  169. router adapter.Router
  170. logger log.Logger
  171. outbounds []adapter.Outbound
  172. link string
  173. interval time.Duration
  174. tolerance uint16
  175. idleTimeout time.Duration
  176. history *urltest.HistoryStorage
  177. checking atomic.Bool
  178. pauseManager pause.Manager
  179. selectedOutboundTCP adapter.Outbound
  180. selectedOutboundUDP adapter.Outbound
  181. interruptGroup *interrupt.Group
  182. interruptExternalConnections bool
  183. access sync.Mutex
  184. ticker *time.Ticker
  185. close chan struct{}
  186. started bool
  187. lastActive atomic.TypedValue[time.Time]
  188. }
  189. func NewURLTestGroup(
  190. ctx context.Context,
  191. router adapter.Router,
  192. logger log.Logger,
  193. outbounds []adapter.Outbound,
  194. link string,
  195. interval time.Duration,
  196. tolerance uint16,
  197. idleTimeout time.Duration,
  198. interruptExternalConnections bool,
  199. ) (*URLTestGroup, error) {
  200. if interval == 0 {
  201. interval = C.DefaultURLTestInterval
  202. }
  203. if tolerance == 0 {
  204. tolerance = 50
  205. }
  206. if idleTimeout == 0 {
  207. idleTimeout = C.DefaultURLTestIdleTimeout
  208. }
  209. if interval > idleTimeout {
  210. return nil, E.New("interval must be less or equal than idle_timeout")
  211. }
  212. var history *urltest.HistoryStorage
  213. if history = service.PtrFromContext[urltest.HistoryStorage](ctx); history != nil {
  214. } else if clashServer := router.ClashServer(); clashServer != nil {
  215. history = clashServer.HistoryStorage()
  216. } else {
  217. history = urltest.NewHistoryStorage()
  218. }
  219. return &URLTestGroup{
  220. ctx: ctx,
  221. router: router,
  222. logger: logger,
  223. outbounds: outbounds,
  224. link: link,
  225. interval: interval,
  226. tolerance: tolerance,
  227. idleTimeout: idleTimeout,
  228. history: history,
  229. close: make(chan struct{}),
  230. pauseManager: service.FromContext[pause.Manager](ctx),
  231. interruptGroup: interrupt.NewGroup(),
  232. interruptExternalConnections: interruptExternalConnections,
  233. }, nil
  234. }
  235. func (g *URLTestGroup) PostStart() {
  236. g.started = true
  237. g.lastActive.Store(time.Now())
  238. go g.CheckOutbounds(false)
  239. }
  240. func (g *URLTestGroup) Touch() {
  241. if !g.started {
  242. return
  243. }
  244. if g.ticker != nil {
  245. g.lastActive.Store(time.Now())
  246. return
  247. }
  248. g.access.Lock()
  249. defer g.access.Unlock()
  250. if g.ticker != nil {
  251. return
  252. }
  253. g.ticker = time.NewTicker(g.interval)
  254. go g.loopCheck()
  255. }
  256. func (g *URLTestGroup) Close() error {
  257. if g.ticker == nil {
  258. return nil
  259. }
  260. g.ticker.Stop()
  261. close(g.close)
  262. return nil
  263. }
  264. func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
  265. var minDelay uint16
  266. var minOutbound adapter.Outbound
  267. switch network {
  268. case N.NetworkTCP:
  269. if g.selectedOutboundTCP != nil {
  270. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundTCP)); history != nil {
  271. minOutbound = g.selectedOutboundTCP
  272. minDelay = history.Delay
  273. }
  274. }
  275. case N.NetworkUDP:
  276. if g.selectedOutboundUDP != nil {
  277. if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundUDP)); history != nil {
  278. minOutbound = g.selectedOutboundUDP
  279. minDelay = history.Delay
  280. }
  281. }
  282. }
  283. for _, detour := range g.outbounds {
  284. if !common.Contains(detour.Network(), network) {
  285. continue
  286. }
  287. history := g.history.LoadURLTestHistory(RealTag(detour))
  288. if history == nil {
  289. continue
  290. }
  291. if minDelay == 0 || minDelay > history.Delay+g.tolerance {
  292. minDelay = history.Delay
  293. minOutbound = detour
  294. }
  295. }
  296. if minOutbound == nil {
  297. for _, detour := range g.outbounds {
  298. if !common.Contains(detour.Network(), network) {
  299. continue
  300. }
  301. return detour, false
  302. }
  303. return nil, false
  304. }
  305. return minOutbound, true
  306. }
  307. func (g *URLTestGroup) loopCheck() {
  308. if time.Now().Sub(g.lastActive.Load()) > g.interval {
  309. g.lastActive.Store(time.Now())
  310. g.CheckOutbounds(false)
  311. }
  312. for {
  313. select {
  314. case <-g.close:
  315. return
  316. case <-g.ticker.C:
  317. }
  318. if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
  319. g.access.Lock()
  320. g.ticker.Stop()
  321. g.ticker = nil
  322. g.access.Unlock()
  323. return
  324. }
  325. g.pauseManager.WaitActive()
  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.Now().Sub(history.Time) < g.interval {
  352. continue
  353. }
  354. checked[realTag] = true
  355. p, loaded := g.router.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, &urltest.History{
  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. g.selectedOutboundTCP = outbound
  387. updated = true
  388. }
  389. if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
  390. g.selectedOutboundUDP = outbound
  391. updated = true
  392. }
  393. if updated {
  394. g.interruptGroup.Interrupt(g.interruptExternalConnections)
  395. }
  396. }