Skip to content

Commit e229d70

Browse files
committed
Fix race codes
1 parent e250322 commit e229d70

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

stack_system_nat.go

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
)
1212

1313
type TCPNat struct {
14+
timeout time.Duration
1415
portIndex uint16
1516
portAccess sync.RWMutex
1617
addrAccess sync.RWMutex
@@ -19,45 +20,49 @@ type TCPNat struct {
1920
}
2021

2122
type TCPSession struct {
23+
sync.Mutex
2224
Source netip.AddrPort
2325
Destination netip.AddrPort
2426
LastActive time.Time
2527
}
2628

2729
func NewNat(ctx context.Context, timeout time.Duration) *TCPNat {
2830
natMap := &TCPNat{
31+
timeout: timeout,
2932
portIndex: 10000,
3033
addrMap: make(map[netip.AddrPort]uint16),
3134
portMap: make(map[uint16]*TCPSession),
3235
}
33-
go natMap.loopCheckTimeout(ctx, timeout)
36+
go natMap.loopCheckTimeout(ctx)
3437
return natMap
3538
}
3639

37-
func (n *TCPNat) loopCheckTimeout(ctx context.Context, timeout time.Duration) {
38-
ticker := time.NewTicker(timeout)
40+
func (n *TCPNat) loopCheckTimeout(ctx context.Context) {
41+
ticker := time.NewTicker(n.timeout)
3942
defer ticker.Stop()
4043
for {
4144
select {
4245
case <-ticker.C:
43-
n.checkTimeout(timeout)
46+
n.checkTimeout()
4447
case <-ctx.Done():
4548
return
4649
}
4750
}
4851
}
4952

50-
func (n *TCPNat) checkTimeout(timeout time.Duration) {
53+
func (n *TCPNat) checkTimeout() {
5154
now := time.Now()
5255
n.portAccess.Lock()
5356
defer n.portAccess.Unlock()
5457
n.addrAccess.Lock()
5558
defer n.addrAccess.Unlock()
5659
for natPort, session := range n.portMap {
57-
if now.Sub(session.LastActive) > timeout {
60+
session.Lock()
61+
if now.Sub(session.LastActive) > n.timeout {
5862
delete(n.addrMap, session.Source)
5963
delete(n.portMap, natPort)
6064
}
65+
session.Unlock()
6166
}
6267
}
6368

@@ -66,7 +71,11 @@ func (n *TCPNat) LookupBack(port uint16) *TCPSession {
6671
session := n.portMap[port]
6772
n.portAccess.RUnlock()
6873
if session != nil {
69-
session.LastActive = time.Now()
74+
session.Lock()
75+
if time.Since(session.LastActive) > time.Second {
76+
session.LastActive = time.Now()
77+
}
78+
session.Unlock()
7079
}
7180
return session
7281
}

0 commit comments

Comments
 (0)