sing-box/protocol/group/urltest.go

414 lines
12 KiB
Go
Raw Normal View History

2024-11-02 00:39:02 +08:00
package group
2022-09-15 15:22:08 +08:00
import (
"context"
"net"
2023-04-11 16:43:45 +08:00
"sync"
2022-09-15 15:22:08 +08:00
"time"
"github.com/sagernet/sing-box/adapter"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing-box/adapter/outbound"
"github.com/sagernet/sing-box/common/interrupt"
2022-09-15 15:22:08 +08:00
"github.com/sagernet/sing-box/common/urltest"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
2023-04-13 16:11:46 +08:00
"github.com/sagernet/sing/common/atomic"
2022-09-15 15:22:08 +08:00
"github.com/sagernet/sing/common/batch"
E "github.com/sagernet/sing/common/exceptions"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
2023-07-02 16:45:30 +08:00
"github.com/sagernet/sing/service"
2023-08-07 17:46:51 +08:00
"github.com/sagernet/sing/service/pause"
2022-09-15 15:22:08 +08:00
)
2024-11-02 00:39:02 +08:00
func RegisterURLTest(registry *outbound.Registry) {
outbound.Register[option.URLTestOutboundOptions](registry, C.TypeURLTest, NewURLTest)
}
2022-09-15 15:22:08 +08:00
var (
2023-04-13 16:11:46 +08:00
_ adapter.OutboundGroup = (*URLTest)(nil)
_ adapter.InterfaceUpdateListener = (*URLTest)(nil)
2022-09-15 15:22:08 +08:00
)
type URLTest struct {
2024-11-02 00:39:02 +08:00
outbound.Adapter
ctx context.Context
2024-11-02 00:39:02 +08:00
router adapter.Router
outboundManager adapter.OutboundManager
2024-11-02 00:39:02 +08:00
logger log.ContextLogger
tags []string
link string
interval time.Duration
tolerance uint16
idleTimeout time.Duration
group *URLTestGroup
interruptExternalConnections bool
2022-09-15 15:22:08 +08:00
}
2024-11-02 00:39:02 +08:00
func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.URLTestOutboundOptions) (adapter.Outbound, error) {
2022-09-15 15:22:08 +08:00
outbound := &URLTest{
2024-11-02 00:39:02 +08:00
Adapter: outbound.NewAdapter(C.TypeURLTest, []string{N.NetworkTCP, N.NetworkUDP}, tag, options.Outbounds),
ctx: ctx,
2024-11-02 00:39:02 +08:00
router: router,
outboundManager: service.FromContext[adapter.OutboundManager](ctx),
2024-11-02 00:39:02 +08:00
logger: logger,
tags: options.Outbounds,
link: options.URL,
interval: time.Duration(options.Interval),
tolerance: options.Tolerance,
idleTimeout: time.Duration(options.IdleTimeout),
interruptExternalConnections: options.InterruptExistConnections,
2022-09-15 15:22:08 +08:00
}
if len(outbound.tags) == 0 {
return nil, E.New("missing tags")
}
return outbound, nil
}
func (s *URLTest) Start() error {
outbounds := make([]adapter.Outbound, 0, len(s.tags))
for i, tag := range s.tags {
detour, loaded := s.outboundManager.Outbound(tag)
2022-09-15 15:22:08 +08:00
if !loaded {
return E.New("outbound ", i, " not found: ", tag)
}
outbounds = append(outbounds, detour)
}
group, err := NewURLTestGroup(s.ctx, s.outboundManager, s.logger, outbounds, s.link, s.interval, s.tolerance, s.idleTimeout, s.interruptExternalConnections)
if err != nil {
return err
}
s.group = group
2023-07-02 16:45:30 +08:00
return nil
}
func (s *URLTest) PostStart() error {
2023-12-02 17:47:57 +08:00
s.group.PostStart()
2023-04-13 16:11:46 +08:00
return nil
2022-09-15 15:22:08 +08:00
}
2023-04-11 16:43:45 +08:00
func (s *URLTest) Close() error {
2022-09-15 15:22:08 +08:00
return common.Close(
common.PtrOrNil(s.group),
)
}
func (s *URLTest) Now() string {
2023-12-23 16:26:16 +08:00
if s.group.selectedOutboundTCP != nil {
return s.group.selectedOutboundTCP.Tag()
} else if s.group.selectedOutboundUDP != nil {
return s.group.selectedOutboundUDP.Tag()
}
return ""
2022-09-15 15:22:08 +08:00
}
func (s *URLTest) All() []string {
return s.tags
}
2023-12-02 17:47:57 +08:00
func (s *URLTest) URLTest(ctx context.Context) (map[string]uint16, error) {
return s.group.URLTest(ctx)
2023-04-11 16:43:45 +08:00
}
2023-07-02 16:45:30 +08:00
func (s *URLTest) CheckOutbounds() {
s.group.CheckOutbounds(true)
}
2022-09-15 15:22:08 +08:00
func (s *URLTest) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
2023-12-02 17:47:57 +08:00
s.group.Touch()
var outbound adapter.Outbound
switch N.NetworkName(network) {
case N.NetworkTCP:
outbound = s.group.selectedOutboundTCP
case N.NetworkUDP:
outbound = s.group.selectedOutboundUDP
default:
return nil, E.Extend(N.ErrUnknownNetwork, network)
}
if outbound == nil {
outbound, _ = s.group.Select(network)
}
2023-12-23 16:26:16 +08:00
if outbound == nil {
return nil, E.New("missing supported outbound")
}
2022-09-15 15:22:08 +08:00
conn, err := outbound.DialContext(ctx, network, destination)
if err == nil {
return s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
2022-09-15 15:22:08 +08:00
}
s.logger.ErrorContext(ctx, err)
2023-04-13 09:03:08 +08:00
s.group.history.DeleteURLTestHistory(outbound.Tag())
2022-09-15 15:22:08 +08:00
return nil, err
}
func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
2023-12-02 17:47:57 +08:00
s.group.Touch()
outbound := s.group.selectedOutboundUDP
if outbound == nil {
outbound, _ = s.group.Select(N.NetworkUDP)
}
2023-12-23 16:26:16 +08:00
if outbound == nil {
return nil, E.New("missing supported outbound")
}
2022-09-15 15:22:08 +08:00
conn, err := outbound.ListenPacket(ctx, destination)
if err == nil {
return s.group.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx)), nil
2022-09-15 15:22:08 +08:00
}
s.logger.ErrorContext(ctx, err)
2023-04-13 09:03:08 +08:00
s.group.history.DeleteURLTestHistory(outbound.Tag())
2022-09-15 15:22:08 +08:00
return nil, err
}
2024-10-21 23:38:34 +08:00
// TODO
// Deprecated
2022-09-15 15:22:08 +08:00
func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
2024-11-02 00:39:02 +08:00
return outbound.NewConnection(ctx, s, conn, metadata)
2022-09-15 15:22:08 +08:00
}
2024-10-21 23:38:34 +08:00
// TODO
// Deprecated
2022-09-15 15:22:08 +08:00
func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
2024-11-02 00:39:02 +08:00
return outbound.NewPacketConnection(ctx, s, conn, metadata)
2022-09-15 15:22:08 +08:00
}
2023-07-23 14:42:19 +08:00
func (s *URLTest) InterfaceUpdated() {
2023-04-13 16:11:46 +08:00
go s.group.CheckOutbounds(true)
2023-07-23 14:42:19 +08:00
return
2023-04-13 16:11:46 +08:00
}
2022-09-15 15:22:08 +08:00
type URLTestGroup struct {
ctx context.Context
router adapter.Router
outboundManager adapter.OutboundManager
logger log.Logger
outbounds []adapter.Outbound
link string
interval time.Duration
tolerance uint16
idleTimeout time.Duration
history *urltest.HistoryStorage
checking atomic.Bool
pauseManager pause.Manager
selectedOutboundTCP adapter.Outbound
selectedOutboundUDP adapter.Outbound
interruptGroup *interrupt.Group
interruptExternalConnections bool
2022-09-15 15:22:08 +08:00
2023-12-02 17:47:57 +08:00
access sync.Mutex
ticker *time.Ticker
close chan struct{}
started bool
lastActive atomic.TypedValue[time.Time]
2022-09-15 15:22:08 +08:00
}
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) {
2022-09-15 15:22:08 +08:00
if interval == 0 {
2022-09-17 20:52:16 +08:00
interval = C.DefaultURLTestInterval
2022-09-15 15:22:08 +08:00
}
if tolerance == 0 {
tolerance = 50
}
if idleTimeout == 0 {
idleTimeout = C.DefaultURLTestIdleTimeout
}
if interval > idleTimeout {
return nil, E.New("interval must be less or equal than idle_timeout")
}
2022-09-15 15:22:08 +08:00
var history *urltest.HistoryStorage
2023-07-02 16:45:30 +08:00
if history = service.PtrFromContext[urltest.HistoryStorage](ctx); history != nil {
} else if clashServer := service.FromContext[adapter.ClashServer](ctx); clashServer != nil {
2022-09-15 15:22:08 +08:00
history = clashServer.HistoryStorage()
} else {
history = urltest.NewHistoryStorage()
}
return &URLTestGroup{
ctx: ctx,
outboundManager: outboundManager,
logger: logger,
outbounds: outbounds,
link: link,
interval: interval,
tolerance: tolerance,
idleTimeout: idleTimeout,
history: history,
close: make(chan struct{}),
2023-12-16 15:40:14 +08:00
pauseManager: service.FromContext[pause.Manager](ctx),
interruptGroup: interrupt.NewGroup(),
interruptExternalConnections: interruptExternalConnections,
}, nil
2022-09-15 15:22:08 +08:00
}
2023-12-02 17:47:57 +08:00
func (g *URLTestGroup) PostStart() {
g.started = true
g.lastActive.Store(time.Now())
go g.CheckOutbounds(false)
}
func (g *URLTestGroup) Touch() {
if !g.started {
return
}
2023-04-13 16:11:46 +08:00
if g.ticker != nil {
2023-12-02 17:47:57 +08:00
g.lastActive.Store(time.Now())
2023-04-13 16:11:46 +08:00
return
}
g.access.Lock()
defer g.access.Unlock()
if g.ticker != nil {
return
}
2022-09-15 15:22:08 +08:00
g.ticker = time.NewTicker(g.interval)
go g.loopCheck()
}
func (g *URLTestGroup) Close() error {
2023-04-13 16:11:46 +08:00
if g.ticker == nil {
return nil
}
2022-09-15 15:22:08 +08:00
g.ticker.Stop()
close(g.close)
return nil
}
func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
2022-09-15 15:22:08 +08:00
var minDelay uint16
var minOutbound adapter.Outbound
2024-05-10 17:40:54 +08:00
switch network {
case N.NetworkTCP:
if g.selectedOutboundTCP != nil {
if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundTCP)); history != nil {
minOutbound = g.selectedOutboundTCP
minDelay = history.Delay
}
}
case N.NetworkUDP:
if g.selectedOutboundUDP != nil {
if history := g.history.LoadURLTestHistory(RealTag(g.selectedOutboundUDP)); history != nil {
minOutbound = g.selectedOutboundUDP
minDelay = history.Delay
}
}
}
2022-09-15 15:22:08 +08:00
for _, detour := range g.outbounds {
if !common.Contains(detour.Network(), network) {
continue
}
history := g.history.LoadURLTestHistory(RealTag(detour))
if history == nil {
continue
}
2024-05-10 17:40:54 +08:00
if minDelay == 0 || minDelay > history.Delay+g.tolerance {
2022-09-15 15:22:08 +08:00
minDelay = history.Delay
minOutbound = detour
}
}
if minOutbound == nil {
for _, detour := range g.outbounds {
if !common.Contains(detour.Network(), network) {
continue
}
return detour, false
2022-09-15 15:22:08 +08:00
}
return nil, false
2022-09-15 15:22:08 +08:00
}
return minOutbound, true
2022-09-15 15:22:08 +08:00
}
func (g *URLTestGroup) loopCheck() {
2023-12-02 17:47:57 +08:00
if time.Now().Sub(g.lastActive.Load()) > g.interval {
g.lastActive.Store(time.Now())
2023-12-02 17:47:57 +08:00
g.CheckOutbounds(false)
}
2022-09-15 15:22:08 +08:00
for {
select {
case <-g.close:
return
case <-g.ticker.C:
}
if time.Now().Sub(g.lastActive.Load()) > g.idleTimeout {
g.access.Lock()
g.ticker.Stop()
g.ticker = nil
g.access.Unlock()
return
}
2023-12-02 17:47:57 +08:00
g.pauseManager.WaitActive()
g.CheckOutbounds(false)
2022-09-15 15:22:08 +08:00
}
}
2023-04-13 16:11:46 +08:00
func (g *URLTestGroup) CheckOutbounds(force bool) {
2023-12-02 17:47:57 +08:00
_, _ = g.urlTest(g.ctx, force)
2023-04-11 16:43:45 +08:00
}
2023-12-02 17:47:57 +08:00
func (g *URLTestGroup) URLTest(ctx context.Context) (map[string]uint16, error) {
return g.urlTest(ctx, false)
2023-04-13 16:11:46 +08:00
}
2023-12-02 17:47:57 +08:00
func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint16, error) {
2023-04-13 16:11:46 +08:00
result := make(map[string]uint16)
if g.checking.Swap(true) {
return result, nil
}
defer g.checking.Store(false)
2023-04-11 16:43:45 +08:00
b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
2022-09-15 15:22:08 +08:00
checked := make(map[string]bool)
2023-04-11 16:43:45 +08:00
var resultAccess sync.Mutex
2022-09-15 15:22:08 +08:00
for _, detour := range g.outbounds {
tag := detour.Tag()
realTag := RealTag(detour)
if checked[realTag] {
continue
}
history := g.history.LoadURLTestHistory(realTag)
2023-04-13 16:11:46 +08:00
if !force && history != nil && time.Now().Sub(history.Time) < g.interval {
2022-09-15 15:22:08 +08:00
continue
}
checked[realTag] = true
p, loaded := g.outboundManager.Outbound(realTag)
2022-09-15 15:22:08 +08:00
if !loaded {
continue
}
b.Go(realTag, func() (any, error) {
2024-06-25 13:10:25 +08:00
testCtx, cancel := context.WithTimeout(g.ctx, C.TCPTimeout)
2022-09-15 15:22:08 +08:00
defer cancel()
2024-06-25 13:10:25 +08:00
t, err := urltest.URLTest(testCtx, g.link, p)
2022-09-15 15:22:08 +08:00
if err != nil {
g.logger.Debug("outbound ", tag, " unavailable: ", err)
g.history.DeleteURLTestHistory(realTag)
} else {
g.logger.Debug("outbound ", tag, " available: ", t, "ms")
g.history.StoreURLTestHistory(realTag, &urltest.History{
Time: time.Now(),
Delay: t,
})
2023-04-11 16:43:45 +08:00
resultAccess.Lock()
result[tag] = t
resultAccess.Unlock()
2022-09-15 15:22:08 +08:00
}
return nil, nil
})
}
b.Wait()
g.performUpdateCheck()
2023-04-11 16:43:45 +08:00
return result, nil
2022-09-15 15:22:08 +08:00
}
func (g *URLTestGroup) performUpdateCheck() {
var updated bool
if outbound, exists := g.Select(N.NetworkTCP); outbound != nil && (g.selectedOutboundTCP == nil || (exists && outbound != g.selectedOutboundTCP)) {
g.selectedOutboundTCP = outbound
updated = true
}
if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
g.selectedOutboundUDP = outbound
updated = true
}
if updated {
g.interruptGroup.Interrupt(g.interruptExternalConnections)
}
}