From 92fe54be05f2b1967f1bda6e43b96b8ea6914f30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Tue, 20 Oct 2026 08:44:10 +0800 Subject: [PATCH] Fix flow close racing with tracker attach --- route/flow_tracker.go | 32 ++++++++++++++++++++------------ route/route.go | 2 +- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/route/flow_tracker.go b/route/flow_tracker.go index 6b07cab8..7a269870 100644 --- a/route/flow_tracker.go +++ b/route/flow_tracker.go @@ -2,6 +2,7 @@ package route import ( "context" + "sync" "sync/atomic" "time" @@ -16,7 +17,7 @@ import ( var ( _ tun.FlowTracker = (*flowLogger)(nil) _ tun.FlowTracker = (*flowInterrupter)(nil) - _ tun.FlowTracker = multiFlowTracker(nil) + _ tun.FlowTracker = (*multiFlowTracker)(nil) ) type flowLogger struct { @@ -70,34 +71,41 @@ func (l *flowLogger) CloseFlow(reason tun.FlowCloseReason) { ", upload ", byteformats.FormatBytes(uint64(l.upload.Load())), ", download ", byteformats.FormatBytes(uint64(l.download.Load()))) } -type multiFlowTracker []tun.FlowTracker +type multiFlowTracker struct { + access sync.Mutex + trackers []tun.FlowTracker +} -func (t multiFlowTracker) AttachFlow(handle tun.FlowHandle) { - for _, tracker := range t { +func (t *multiFlowTracker) AttachFlow(handle tun.FlowHandle) { + t.access.Lock() + defer t.access.Unlock() + for _, tracker := range t.trackers { tracker.AttachFlow(handle) } } -func (t multiFlowTracker) CountForward(n int) { - for _, tracker := range t { +func (t *multiFlowTracker) CountForward(n int) { + for _, tracker := range t.trackers { tracker.CountForward(n) } } -func (t multiFlowTracker) CountReverse(n int) { - for _, tracker := range t { +func (t *multiFlowTracker) CountReverse(n int) { + for _, tracker := range t.trackers { tracker.CountReverse(n) } } -func (t multiFlowTracker) FlowEstablished() { - for _, tracker := range t { +func (t *multiFlowTracker) FlowEstablished() { + for _, tracker := range t.trackers { tracker.FlowEstablished() } } -func (t multiFlowTracker) CloseFlow(reason tun.FlowCloseReason) { - for _, tracker := range t { +func (t *multiFlowTracker) CloseFlow(reason tun.FlowCloseReason) { + t.access.Lock() + defer t.access.Unlock() + for _, tracker := range t.trackers { tracker.CloseFlow(reason) } } diff --git a/route/route.go b/route/route.go index 4155a866..bf25baee 100644 --- a/route/route.go +++ b/route/route.go @@ -564,7 +564,7 @@ func (r *Router) preMatchFlow(ctx context.Context, metadata *adapter.InboundCont if len(flowTrackers) == 1 { return flowTrackers[0] } - return multiFlowTracker(flowTrackers) + return &multiFlowTracker{trackers: flowTrackers} } return result }