urltest.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. outbound := s.group.Select(network)
  116. if outbound == nil {
  117. return nil, E.New("missing supported outbound")
  118. }
  119. conn, err := outbound.DialContext(ctx, network, destination)
  120. if err == nil {
  121. return s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  122. }
  123. s.logger.ErrorContext(ctx, err)
  124. s.group.history.DeleteURLTestHistory(outbound.Tag())
  125. return nil, err
  126. }
  127. func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  128. s.group.Touch()
  129. outbound := s.group.Select(N.NetworkUDP)
  130. if outbound == nil {
  131. return nil, E.New("missing supported outbound")
  132. }
  133. conn, err := outbound.ListenPacket(ctx, destination)
  134. if err == nil {
  135. return s.group.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
  136. }
  137. s.logger.ErrorContext(ctx, err)
  138. s.group.history.DeleteURLTestHistory(outbound.Tag())
  139. return nil, err
  140. }
  141. func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  142. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  143. return NewConnection(ctx, s, conn, metadata)
  144. }
  145. func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  146. ctx = interrupt.ContextWithIsExternalConnection(ctx)
  147. return NewPacketConnection(ctx, s, conn, metadata)
  148. }
  149. func (s *URLTest) InterfaceUpdated() {
  150. go s.group.CheckOutbounds(true)
  151. return
  152. }
  153. type URLTestGroup struct {
  154. ctx context.Context
  155. router adapter.Router
  156. logger log.Logger
  157. outbounds []adapter.Outbound
  158. link string
  159. interval time.Duration
  160. tolerance uint16
  161. idleTimeout time.Duration
  162. history *urltest.HistoryStorage
  163. checking atomic.Bool
  164. pauseManager pause.Manager
  165. selectedOutboundTCP adapter.Outbound
  166. selectedOutboundUDP adapter.Outbound
  167. interruptGroup *interrupt.Group
  168. interruptExternalConnections bool
  169. access sync.Mutex
  170. ticker *time.Ticker
  171. close chan struct{}
  172. started bool
  173. lastActive atomic.TypedValue[time.Time]
  174. }
  175. func NewURLTestGroup(
  176. ctx context.Context,
  177. router adapter.Router,
  178. logger log.Logger,
  179. outbounds []adapter.Outbound,
  180. link string,
  181. interval time.Duration,
  182. tolerance uint16,
  183. idleTimeout time.Duration,
  184. interruptExternalConnections bool,
  185. ) (*URLTestGroup, error) {
  186. if interval == 0 {
  187. interval = C.DefaultURLTestInterval
  188. }
  189. if tolerance == 0 {
  190. tolerance = 50
  191. }
  192. if idleTimeout == 0 {
  193. idleTimeout = C.DefaultURLTestIdleTimeout
  194. }
  195. if interval > idleTimeout {
  196. return nil, E.New("interval must be less or equal than idle_timeout")
  197. }
  198. var history *urltest.HistoryStorage
  199. if history = service.PtrFromContext[urltest.HistoryStorage](ctx); history != nil {
  200. } else if clashServer := router.ClashServer(); clashServer != nil {
  201. history = clashServer.HistoryStorage()
  202. } else {
  203. history = urltest.NewHistoryStorage()
  204. }
  205. return &URLTestGroup{
  206. ctx: ctx,
  207. router: router,
  208. logger: logger,
  209. outbounds: outbounds,
  210. link: link,
  211. interval: interval,
  212. tolerance: tolerance,
  213. idleTimeout: idleTimeout,
  214. history: history,
  215. close: make(chan struct{}),
  216. pauseManager: service.FromContext[pause.Manager](ctx),
  217. interruptGroup: interrupt.NewGroup(),
  218. interruptExternalConnections: interruptExternalConnections,
  219. }, nil
  220. }
  221. func (g *URLTestGroup) PostStart() {
  222. g.started = true
  223. g.lastActive.Store(time.Now())
  224. go g.CheckOutbounds(false)
  225. }
  226. func (g *URLTestGroup) Touch() {
  227. if !g.started {
  228. return
  229. }
  230. if g.ticker != nil {
  231. g.lastActive.Store(time.Now())
  232. return
  233. }
  234. g.access.Lock()
  235. defer g.access.Unlock()
  236. if g.ticker != nil {
  237. return
  238. }
  239. g.ticker = time.NewTicker(g.interval)
  240. go g.loopCheck()
  241. }
  242. func (g *URLTestGroup) Close() error {
  243. if g.ticker == nil {
  244. return nil
  245. }
  246. g.ticker.Stop()
  247. close(g.close)
  248. return nil
  249. }
  250. func (g *URLTestGroup) Select(network string) adapter.Outbound {
  251. var minDelay uint16
  252. var minTime time.Time
  253. var minOutbound adapter.Outbound
  254. for _, detour := range g.outbounds {
  255. if !common.Contains(detour.Network(), network) {
  256. continue
  257. }
  258. history := g.history.LoadURLTestHistory(RealTag(detour))
  259. if history == nil {
  260. continue
  261. }
  262. if minDelay == 0 || minDelay > history.Delay+g.tolerance || minDelay > history.Delay-g.tolerance && minTime.Before(history.Time) {
  263. minDelay = history.Delay
  264. minTime = history.Time
  265. minOutbound = detour
  266. }
  267. }
  268. if minOutbound == nil {
  269. for _, detour := range g.outbounds {
  270. if !common.Contains(detour.Network(), network) {
  271. continue
  272. }
  273. minOutbound = detour
  274. break
  275. }
  276. }
  277. return minOutbound
  278. }
  279. func (g *URLTestGroup) loopCheck() {
  280. if time.Now().Sub(g.lastActive.Load()) > g.interval {
  281. g.lastActive.Store(time.Now())
  282. g.CheckOutbounds(false)
  283. }
  284. for {
  285. select {
  286. case <-g.close:
  287. return
  288. case <-g.ticker.C:
  289. }
  290. if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
  291. g.access.Lock()
  292. g.ticker.Stop()
  293. g.ticker = nil
  294. g.access.Unlock()
  295. return
  296. }
  297. g.pauseManager.WaitActive()
  298. g.CheckOutbounds(false)
  299. }
  300. }
  301. func (g *URLTestGroup) CheckOutbounds(force bool) {
  302. _, _ = g.urlTest(g.ctx, force)
  303. }
  304. func (g *URLTestGroup) URLTest(ctx context.Context) (map[string]uint16, error) {
  305. return g.urlTest(ctx, false)
  306. }
  307. func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint16, error) {
  308. result := make(map[string]uint16)
  309. if g.checking.Swap(true) {
  310. return result, nil
  311. }
  312. defer g.checking.Store(false)
  313. b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
  314. checked := make(map[string]bool)
  315. var resultAccess sync.Mutex
  316. for _, detour := range g.outbounds {
  317. tag := detour.Tag()
  318. realTag := RealTag(detour)
  319. if checked[realTag] {
  320. continue
  321. }
  322. history := g.history.LoadURLTestHistory(realTag)
  323. if !force && history != nil && time.Now().Sub(history.Time) < g.interval {
  324. continue
  325. }
  326. checked[realTag] = true
  327. p, loaded := g.router.Outbound(realTag)
  328. if !loaded {
  329. continue
  330. }
  331. b.Go(realTag, func() (any, error) {
  332. ctx, cancel := context.WithTimeout(context.Background(), C.TCPTimeout)
  333. defer cancel()
  334. t, err := urltest.URLTest(ctx, g.link, p)
  335. if err != nil {
  336. g.logger.Debug("outbound ", tag, " unavailable: ", err)
  337. g.history.DeleteURLTestHistory(realTag)
  338. } else {
  339. g.logger.Debug("outbound ", tag, " available: ", t, "ms")
  340. g.history.StoreURLTestHistory(realTag, &urltest.History{
  341. Time: time.Now(),
  342. Delay: t,
  343. })
  344. resultAccess.Lock()
  345. result[tag] = t
  346. resultAccess.Unlock()
  347. }
  348. return nil, nil
  349. })
  350. }
  351. b.Wait()
  352. g.performUpdateCheck()
  353. return result, nil
  354. }
  355. func (g *URLTestGroup) performUpdateCheck() {
  356. outbound := g.Select(N.NetworkTCP)
  357. var updated bool
  358. if outbound != nil && outbound != g.selectedOutboundTCP {
  359. g.selectedOutboundTCP = outbound
  360. updated = true
  361. }
  362. outbound = g.Select(N.NetworkUDP)
  363. if outbound != nil && outbound != g.selectedOutboundUDP {
  364. g.selectedOutboundUDP = outbound
  365. updated = true
  366. }
  367. if updated {
  368. g.interruptGroup.Interrupt(g.interruptExternalConnections)
  369. }
  370. }