merge: Merge upstream v1.14.6

This commit is contained in:
Shtorm
2026-11-30 19:46:00 +03:00
292 changed files with 6311 additions and 5159 deletions
+7 -2
View File
@@ -2,6 +2,7 @@ package group
import (
"context"
"io"
"net"
"sync"
"time"
@@ -73,10 +74,14 @@ func (s *Fallback) Start(stage adapter.StartStage, scope *adapter.Scope) error {
return nil
}
func (s *Fallback) Now() string {
func (s *Fallback) Selected(network string) adapter.Outbound {
s.mtx.Lock()
defer s.mtx.Unlock()
return s.lastUsedOutbound
return s.outbounds[s.lastUsedOutbound]
}
func (s *Fallback) AttachConnection(closer io.Closer) func() {
return func() {}
}
func (s *Fallback) All() []string {
+28 -46
View File
@@ -2,8 +2,10 @@ package group
import (
"context"
"io"
"net"
"regexp"
"slices"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/adapter/outbound"
@@ -25,17 +27,14 @@ func RegisterSelector(registry *outbound.Registry) {
}
var (
_ adapter.OutboundGroup = (*Selector)(nil)
_ adapter.Referrer = (*Selector)(nil)
_ adapter.ConnectionHandler = (*Selector)(nil)
_ adapter.PacketConnectionHandler = (*Selector)(nil)
_ adapter.OutboundGroup = (*Selector)(nil)
_ adapter.Referrer = (*Selector)(nil)
)
type Selector struct {
outbound.Adapter
ctx context.Context
outbound adapter.OutboundManager
connection adapter.ConnectionManager
logger logger.ContextLogger
tags []string
defaultTag string
@@ -60,7 +59,6 @@ func NewSelector(ctx context.Context, router adapter.Router, logger log.ContextL
Adapter: outbound.NewAdapter(C.TypeSelector, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
ctx: ctx,
outbound: service.FromContext[adapter.OutboundManager](ctx),
connection: service.FromContext[adapter.ConnectionManager](ctx),
logger: logger,
tags: options.Outbounds,
defaultTag: options.Default,
@@ -78,6 +76,11 @@ func NewSelector(ctx context.Context, router adapter.Router, logger log.ContextL
include: (*regexp.Regexp)(options.Include),
useAllProviders: options.UseAllProviders,
}
for i, tag := range outbound.tags {
if slices.Contains(outbound.tags[:i], tag) {
return nil, E.New("duplicate tag: ", tag)
}
}
return outbound, nil
}
@@ -134,20 +137,24 @@ func (s *Selector) Start(stage adapter.StartStage, scope *adapter.Scope) error {
return nil
}
func (s *Selector) Now() string {
selected := s.selected.Load()
if selected == nil {
return s.tags[0]
}
return selected.Tag()
}
func (s *Selector) All() []string {
return s.tags
}
func (s *Selector) References() []string {
return []string{s.Now()}
func (s *Selector) Selected(network string) adapter.Outbound {
return s.selected.Load()
}
func (s *Selector) AttachConnection(closer io.Closer) func() {
return s.interruptGroup.Add(closer, true)
}
func (s *Selector) References() ([]string, []string) {
selected := s.selected.Load()
if selected == nil {
return s.tags[:1], nil
}
return []string{selected.Tag()}, nil
}
func (s *Selector) SelectOutbound(tag string) bool {
@@ -190,40 +197,15 @@ func (s *Selector) ListenPacket(ctx context.Context, destination M.Socksaddr) (n
return s.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
}
func (s *Selector) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
selected := s.selected.Load()
conn = s.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
if outboundHandler, isHandler := selected.(adapter.ConnectionHandler); isHandler {
outboundHandler.NewConnection(ctx, conn, metadata, onClose)
} else {
s.connection.NewConnection(ctx, s, conn, metadata, onClose)
}
}
func (s *Selector) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
selected := s.selected.Load()
conn = s.interruptGroup.NewSingPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
if outboundHandler, isHandler := selected.(adapter.PacketConnectionHandler); isHandler {
outboundHandler.NewPacketConnection(ctx, conn, metadata, onClose)
} else {
s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
}
}
func RealTag(outboundManager adapter.OutboundManager, detour adapter.Outbound) string {
tag := detour.Tag()
func RealTag(detour adapter.Outbound, network string) string {
for {
group, isGroup := detour.(adapter.OutboundGroup)
if !isGroup {
return tag
return detour.Tag()
}
tag = group.Now()
var loaded bool
detour, loaded = outboundManager.Outbound(tag)
if !loaded {
return tag
detour = group.Selected(network)
if detour == nil {
return ""
}
}
}
+103 -77
View File
@@ -2,9 +2,11 @@ package group
import (
"context"
"io"
"maps"
"net"
"regexp"
"slices"
"sync"
"sync/atomic"
"time"
@@ -40,7 +42,6 @@ type URLTest struct {
outbound.Adapter
ctx context.Context
outbound adapter.OutboundManager
connection adapter.ConnectionManager
logger log.ContextLogger
tags []string
link string
@@ -67,7 +68,6 @@ func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLo
Adapter: outbound.NewAdapter(C.TypeURLTest, tag, []string{N.NetworkTCP, N.NetworkUDP}, options.Outbounds),
ctx: ctx,
outbound: service.FromContext[adapter.OutboundManager](ctx),
connection: service.FromContext[adapter.ConnectionManager](ctx),
logger: logger,
tags: options.Outbounds,
link: options.URL,
@@ -85,6 +85,11 @@ func NewURLTest(ctx context.Context, router adapter.Router, logger log.ContextLo
include: (*regexp.Regexp)(options.Include),
useAllProviders: options.UseAllProviders,
}
for i, tag := range outbound.tags {
if slices.Contains(outbound.tags[:i], tag) {
return nil, E.New("duplicate tag: ", tag)
}
}
return outbound, nil
}
@@ -137,32 +142,43 @@ func (s *URLTest) Start(stage adapter.StartStage, scope *adapter.Scope) error {
return nil
}
func (s *URLTest) Now() string {
if s.group.selectedOutboundTCP != nil {
return s.group.selectedOutboundTCP.Tag()
} else if s.group.selectedOutboundUDP != nil {
return s.group.selectedOutboundUDP.Tag()
}
return ""
}
func (s *URLTest) All() []string {
return s.tags
}
func (s *URLTest) References() []string {
func (s *URLTest) Selected(network string) adapter.Outbound {
var outbound adapter.Outbound
if network == N.NetworkUDP {
outbound = s.group.selectedOutboundUDP.Load()
} else {
outbound = s.group.selectedOutboundTCP.Load()
}
if outbound == nil {
outbound, _ = s.group.Select(network)
}
return outbound
}
func (s *URLTest) AttachConnection(closer io.Closer) func() {
s.group.Touch()
return s.group.interruptGroup.Add(closer, true)
}
func (s *URLTest) References() ([]string, []string) {
group := s.group
if group == nil {
return nil
return nil, nil
}
var references []string
if group.selectedOutboundTCP != nil {
references = append(references, group.selectedOutboundTCP.Tag())
selectedOutboundTCP := group.selectedOutboundTCP.Load()
selectedOutboundUDP := group.selectedOutboundUDP.Load()
if selectedOutboundTCP != nil {
references = append(references, selectedOutboundTCP.Tag())
}
if group.selectedOutboundUDP != nil && group.selectedOutboundUDP != group.selectedOutboundTCP {
references = append(references, group.selectedOutboundUDP.Tag())
if selectedOutboundUDP != nil && selectedOutboundUDP != selectedOutboundTCP {
references = append(references, selectedOutboundUDP.Tag())
}
return references
return references, nil
}
func (s *URLTest) URLTest(ctx context.Context) (map[string]uint16, error) {
@@ -174,7 +190,9 @@ func (s *URLTest) CheckOutbounds() {
}
func (s *URLTest) PerformUpdateCheck() {
s.group.performUpdateCheck()
if s.group.performUpdateCheck() {
s.group.history.NotifyUpdated()
}
}
func (s *URLTest) InterfaceUpdated(ctx context.Context) {
@@ -200,9 +218,9 @@ func (s *URLTest) DialContext(ctx context.Context, network string, destination M
var outbound adapter.Outbound
switch N.NetworkName(network) {
case N.NetworkTCP:
outbound = s.group.selectedOutboundTCP
outbound = s.group.selectedOutboundTCP.Load()
case N.NetworkUDP:
outbound = s.group.selectedOutboundUDP
outbound = s.group.selectedOutboundUDP.Load()
default:
return nil, E.Extend(N.ErrUnknownNetwork, network)
}
@@ -217,13 +235,16 @@ func (s *URLTest) DialContext(ctx context.Context, network string, destination M
return s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
}
s.logger.ErrorContext(ctx, err)
s.group.history.DeleteURLTestHistory(outbound.Tag())
if !E.IsClosedOrCanceled(err) {
s.group.history.DeleteURLTestHistory(RealTag(outbound, N.NetworkName(network)))
s.PerformUpdateCheck()
}
return nil, err
}
func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
s.group.Touch()
outbound := s.group.selectedOutboundUDP
outbound := s.group.selectedOutboundUDP.Load()
if outbound == nil {
outbound, _ = s.group.Select(N.NetworkUDP)
}
@@ -235,22 +256,13 @@ func (s *URLTest) ListenPacket(ctx context.Context, destination M.Socksaddr) (ne
return s.group.interruptGroup.NewPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx)), nil
}
s.logger.ErrorContext(ctx, err)
s.group.history.DeleteURLTestHistory(outbound.Tag())
if !E.IsClosedOrCanceled(err) {
s.group.history.DeleteURLTestHistory(RealTag(outbound, N.NetworkUDP))
s.PerformUpdateCheck()
}
return nil, err
}
func (s *URLTest) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
conn = s.group.interruptGroup.NewConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
s.connection.NewConnection(ctx, s, conn, metadata, onClose)
}
func (s *URLTest) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, onClose N.CloseHandlerFunc) {
ctx = interrupt.ContextWithIsExternalConnection(ctx)
conn = s.group.interruptGroup.NewSingPacketConn(conn, interrupt.IsExternalConnectionFromContext(ctx), interrupt.IsProviderConnectionFromContext(ctx))
s.connection.NewPacketConnection(ctx, s, conn, metadata, onClose)
}
func (s *URLTest) onProviderUpdated(tag string) error {
_, loaded := s.providers[tag]
if !loaded {
@@ -321,15 +333,16 @@ type URLTestGroup struct {
idleTimeout time.Duration
history *urltest.HistoryStorage
checking atomic.Bool
selectedOutboundTCP adapter.Outbound
selectedOutboundUDP adapter.Outbound
selectedOutboundTCP common.TypedValue[adapter.Outbound]
selectedOutboundUDP common.TypedValue[adapter.Outbound]
interruptGroup *interrupt.Group
interruptExternalConnections bool
access sync.Mutex
updateAccess sync.Mutex
ticker *time.Ticker
close chan struct{}
started bool
started atomic.Bool
closed atomic.Bool
lastActive common.TypedValue[time.Time]
}
@@ -370,17 +383,20 @@ func NewURLTestGroup(ctx context.Context, outboundManager adapter.OutboundManage
func (g *URLTestGroup) PostStart() {
g.access.Lock()
defer g.access.Unlock()
g.started = true
g.started.Store(true)
g.lastActive.Store(time.Now())
go g.CheckOutbounds(g.ctx, false)
}
func (g *URLTestGroup) Touch() {
if !g.started {
if !g.started.Load() {
return
}
g.access.Lock()
defer g.access.Unlock()
if g.closed.Load() {
return
}
if g.ticker != nil {
g.lastActive.Store(time.Now())
return
@@ -394,13 +410,15 @@ func (g *URLTestGroup) Touch() {
func (g *URLTestGroup) Close() error {
g.access.Lock()
defer g.access.Unlock()
if g.ticker == nil {
if g.closed.Swap(true) {
return nil
}
g.ticker.Stop()
g.ticker = nil
g.pause.UnregisterCallback(g.pauseCallback)
g.pauseCallback = nil
if g.ticker != nil {
g.ticker.Stop()
g.ticker = nil
g.pause.UnregisterCallback(g.pauseCallback)
g.pauseCallback = nil
}
close(g.close)
return nil
}
@@ -408,27 +426,24 @@ func (g *URLTestGroup) Close() error {
func (g *URLTestGroup) Select(network string) (adapter.Outbound, bool) {
var minDelay uint16
var minOutbound adapter.Outbound
var selectedOutbound adapter.Outbound
switch network {
case N.NetworkTCP:
if g.selectedOutboundTCP != nil {
if history := g.history.LoadURLTestHistory(RealTag(g.outbound, g.selectedOutboundTCP)); history != nil {
minOutbound = g.selectedOutboundTCP
minDelay = history.Delay
}
}
selectedOutbound = g.selectedOutboundTCP.Load()
case N.NetworkUDP:
if g.selectedOutboundUDP != nil {
if history := g.history.LoadURLTestHistory(RealTag(g.outbound, g.selectedOutboundUDP)); history != nil {
minOutbound = g.selectedOutboundUDP
minDelay = history.Delay
}
selectedOutbound = g.selectedOutboundUDP.Load()
}
if selectedOutbound != nil {
if history := g.history.LoadURLTestHistory(RealTag(selectedOutbound, network)); history != nil {
minOutbound = selectedOutbound
minDelay = history.Delay
}
}
for _, detour := range g.outbounds {
if !common.Contains(detour.Network(), network) {
continue
}
history := g.history.LoadURLTestHistory(RealTag(g.outbound, detour))
history := g.history.LoadURLTestHistory(RealTag(detour, network))
if history == nil {
continue
}
@@ -488,12 +503,11 @@ func (g *URLTestGroup) urlTest(ctx context.Context, force bool) (map[string]uint
return make(map[string]uint16), nil
}
defer g.checking.Store(false)
result := URLTestOutbounds(ctx, g.outbound, g.history, g.logger, g.outbounds, g.link, g.interval, force)
select {
case <-ctx.Done():
default:
result := urlTestOutbounds(ctx, g.outbound, g.history, g.logger, g.outbounds, g.link, g.interval, force)
if ctx.Err() == nil {
g.performUpdateCheck()
}
g.history.NotifyUpdated()
return result, nil
}
@@ -512,9 +526,17 @@ type urlTestBatch struct {
groups []adapter.OutboundGroup
access sync.Mutex
result map[string]uint16
stored map[string]*adapter.URLTestHistory
deleted []string
}
func URLTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManager, history *urltest.HistoryStorage, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, force bool) map[string]uint16 {
result := urlTestOutbounds(ctx, outboundManager, history, logger, outbounds, link, interval, force)
history.NotifyUpdated()
return result
}
func urlTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManager, history *urltest.HistoryStorage, logger log.Logger, outbounds []adapter.Outbound, link string, interval time.Duration, force bool) map[string]uint16 {
b, _ := batch.New(ctx, batch.WithConcurrencyNum[any](10))
testBatch := &urlTestBatch{
ctx: ctx,
@@ -524,11 +546,13 @@ func URLTestOutbounds(ctx context.Context, outboundManager adapter.OutboundManag
batch: b,
checked: make(map[string]bool),
result: make(map[string]uint16),
stored: make(map[string]*adapter.URLTestHistory),
}
testBatch.test(outbounds, link, interval, force)
b.Wait()
history.UpdateURLTestHistory(testBatch.stored, testBatch.deleted)
for _, outboundGroup := range testBatch.groups {
groupHistory := history.LoadURLTestHistory(RealTag(outboundManager, outboundGroup))
groupHistory := history.LoadURLTestHistory(RealTag(outboundGroup, N.NetworkTCP))
if groupHistory != nil {
testBatch.result[outboundGroup.Tag()] = groupHistory.Delay
}
@@ -585,14 +609,16 @@ func (b *urlTestBatch) test(outbounds []adapter.Outbound, link string, interval
return nil, nil
}
b.logger.Debug("outbound ", tag, " unavailable: ", testResult.err)
b.history.DeleteURLTestHistory(tag)
b.access.Lock()
b.deleted = append(b.deleted, tag)
b.access.Unlock()
} else {
b.logger.Debug("outbound ", tag, " available: ", testResult.delay, "ms")
b.history.StoreURLTestHistory(tag, &adapter.URLTestHistory{
b.access.Lock()
b.stored[tag] = &adapter.URLTestHistory{
Time: time.Now(),
Delay: testResult.delay,
})
b.access.Lock()
}
b.result[tag] = testResult.delay
b.access.Unlock()
}
@@ -602,31 +628,31 @@ func (b *urlTestBatch) test(outbounds []adapter.Outbound, link string, interval
}
}
func (g *URLTestGroup) performUpdateCheck() {
func (g *URLTestGroup) performUpdateCheck() bool {
g.updateAccess.Lock()
defer g.updateAccess.Unlock()
var (
updated bool
selected bool
)
if outbound, exists := g.Select(N.NetworkTCP); outbound != nil && (g.selectedOutboundTCP == nil || (exists && outbound != g.selectedOutboundTCP)) {
if g.selectedOutboundTCP != nil {
selectedOutboundTCP := g.selectedOutboundTCP.Load()
if outbound, _ := g.Select(N.NetworkTCP); outbound != nil && outbound != selectedOutboundTCP {
if selectedOutboundTCP != nil {
updated = true
}
g.selectedOutboundTCP = outbound
g.selectedOutboundTCP.Store(outbound)
selected = true
}
if outbound, exists := g.Select(N.NetworkUDP); outbound != nil && (g.selectedOutboundUDP == nil || (exists && outbound != g.selectedOutboundUDP)) {
if g.selectedOutboundUDP != nil {
selectedOutboundUDP := g.selectedOutboundUDP.Load()
if outbound, _ := g.Select(N.NetworkUDP); outbound != nil && outbound != selectedOutboundUDP {
if selectedOutboundUDP != nil {
updated = true
}
g.selectedOutboundUDP = outbound
g.selectedOutboundUDP.Store(outbound)
selected = true
}
if updated {
g.interruptGroup.Interrupt(g.interruptExternalConnections)
}
if selected {
g.history.NotifyUpdated()
}
return selected
}