Skip to content

Commit

Permalink
udpnat2: Fix timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 27, 2024
1 parent 4ba1eb1 commit 0a2e2a3
Showing 1 changed file with 4 additions and 33 deletions.
37 changes: 4 additions & 33 deletions common/udpnat2/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package udpnat
import (
"context"
"net/netip"
"sync"
"time"

"github.com/sagernet/sing/common"
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand All @@ -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++
Expand Down

0 comments on commit 0a2e2a3

Please sign in to comment.