From 0a2e2a3eaf749cb202e80ac2b9c8505014f5ee50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Wed, 27 Nov 2024 18:02:22 +0800 Subject: [PATCH] udpnat2: Fix timeout --- common/udpnat2/service.go | 37 ++++--------------------------------- 1 file changed, 4 insertions(+), 33 deletions(-) diff --git a/common/udpnat2/service.go b/common/udpnat2/service.go index b04d2334..5e529301 100644 --- a/common/udpnat2/service.go +++ b/common/udpnat2/service.go @@ -3,7 +3,6 @@ package udpnat import ( "context" "net/netip" - "sync" "time" "github.com/sagernet/sing/common" @@ -19,10 +18,6 @@ type Service struct { handler N.UDPConnectionHandlerEx prepare PrepareFunc metrics Metrics - - timeout time.Duration - closeOnce sync.Once - doneChan chan struct{} } type PrepareFunc func(source M.Socksaddr, destination M.Socksaddr, userData any) (bool, context.Context, N.PacketWriter, N.CloseHandlerFunc) @@ -58,37 +53,12 @@ func New(handler N.UDPConnectionHandlerEx, prepare PrepareFunc, timeout time.Dur conn.Close() }) return &Service{ - cache: cache, - handler: handler, - prepare: prepare, - timeout: timeout, - doneChan: make(chan struct{}), + cache: cache, + handler: handler, + prepare: prepare, } } -func (s *Service) Start() error { - ticker := time.NewTicker(s.timeout) - go func() { - defer ticker.Stop() - for { - select { - case <-ticker.C: - s.PurgeExpired() - case <-s.doneChan: - s.Purge() - return - } - } - }() - return nil -} - -func (s *Service) Close() { - s.closeOnce.Do(func() { - close(s.doneChan) - }) -} - func (s *Service) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destination M.Socksaddr, userData any) { conn, loaded := s.cache.Get(source.AddrPort()) if !loaded { @@ -105,6 +75,7 @@ func (s *Service) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destinati doneChan: make(chan struct{}), readDeadline: pipe.MakeDeadline(), } + s.PurgeExpired() s.cache.Add(source.AddrPort(), conn) go s.handler.NewPacketConnectionEx(ctx, conn, source, destination, onClose) s.metrics.Creates++