Skip to content

Commit

Permalink
udpnat2: Fix missing shared impl
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 9, 2024
1 parent 72ff654 commit 0998999
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions common/udpnat2/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

type Service struct {
nat *freelru.LRU[netip.AddrPort, *Conn]
cache freelru.Cache[netip.AddrPort, *Conn]
handler N.UDPConnectionHandlerEx
prepare PrepareFunc
metrics Metrics
Expand All @@ -29,29 +29,34 @@ type Metrics struct {
Drops uint64
}

func New(handler N.UDPConnectionHandlerEx, prepare PrepareFunc, timeout time.Duration) *Service {
nat := common.Must1(freelru.New[netip.AddrPort, *Conn](1024, maphash.NewHasher[netip.AddrPort]().Hash32))
nat.SetLifetime(timeout)
nat.SetHealthCheck(func(port netip.AddrPort, conn *Conn) bool {
func New(handler N.UDPConnectionHandlerEx, prepare PrepareFunc, timeout time.Duration, shared bool) *Service {
var cache freelru.Cache[netip.AddrPort, *Conn]
if !shared {
cache = common.Must1(freelru.New[netip.AddrPort, *Conn](1024, maphash.NewHasher[netip.AddrPort]().Hash32))
} else {
cache = common.Must1(freelru.NewSharded[netip.AddrPort, *Conn](1024, maphash.NewHasher[netip.AddrPort]().Hash32))
}
cache.SetLifetime(timeout)
cache.SetHealthCheck(func(port netip.AddrPort, conn *Conn) bool {
select {
case <-conn.doneChan:
return false
default:
return true
}
})
nat.SetOnEvict(func(_ netip.AddrPort, conn *Conn) {
cache.SetOnEvict(func(_ netip.AddrPort, conn *Conn) {
conn.Close()
})
return &Service{
nat: nat,
cache: cache,
handler: handler,
prepare: prepare,
}
}

func (s *Service) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destination M.Socksaddr, userData any) {
conn, loaded := s.nat.Get(source.AddrPort())
conn, loaded := s.cache.Get(source.AddrPort())
if !loaded {
ok, ctx, writer, onClose := s.prepare(source, destination, userData)
if !ok {
Expand All @@ -65,7 +70,7 @@ func (s *Service) NewPacket(bufferSlices [][]byte, source M.Socksaddr, destinati
doneChan: make(chan struct{}),
readDeadline: pipe.MakeDeadline(),
}
s.nat.Add(source.AddrPort(), conn)
s.cache.Add(source.AddrPort(), conn)
go s.handler.NewPacketConnectionEx(ctx, conn, source, destination, onClose)
s.metrics.Creates++
}
Expand Down

0 comments on commit 0998999

Please sign in to comment.