udpnat2: Fix timeout

This commit is contained in:
世界 2024-11-27 18:02:22 +08:00
parent 4ba1eb123c
commit 0a2e2a3eaf
No known key found for this signature in database
GPG key ID: CD109927C34A63C4

View file

@ -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++