Skip to content

Commit

Permalink
udpnat2: Add purge expire ticker
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 26, 2024
1 parent 717d9c3 commit 3796d32
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions common/udpnat2/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package udpnat
import (
"context"
"net/netip"
"sync"
"time"

"github.com/sagernet/sing/common"
Expand All @@ -18,6 +19,10 @@ 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 @@ -50,12 +55,38 @@ func New(handler N.UDPConnectionHandlerEx, prepare PrepareFunc, timeout time.Dur
conn.Close()
})
return &Service{
cache: cache,
handler: handler,
prepare: prepare,
cache: cache,
handler: handler,
prepare: prepare,
timeout: timeout,
doneChan: make(chan struct{}),
}
}

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() error {
s.closeOnce.Do(func() {
close(s.doneChan)
})
return nil
}

func (s *Service) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destination M.Socksaddr, userData any) {
conn, loaded := s.cache.Get(source.AddrPort())
if !loaded {
Expand Down

0 comments on commit 3796d32

Please sign in to comment.