-
Notifications
You must be signed in to change notification settings - Fork 2
/
nat.go
81 lines (68 loc) · 1.28 KB
/
nat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package socks5
import (
"net"
"sync"
"time"
)
type natEntry struct {
src net.Addr
packet *packet
timestamp time.Time
}
type natTable struct {
mutex sync.RWMutex
table map[string]*natEntry
}
func newNatTable() *natTable {
return &natTable{table: make(map[string]*natEntry)}
}
func (n *natTable) set(src, dst net.Addr, packet *packet) {
n.mutex.Lock()
n.table[dst.String()] = &natEntry{
src: src,
packet: packet,
timestamp: time.Now(),
}
n.mutex.Unlock()
}
func (n *natTable) get(dst net.Addr) (net.Addr, *packet, bool) {
n.mutex.RLock()
defer n.mutex.RUnlock()
val, ok := n.table[dst.String()]
if !ok {
return nil, nil, ok
}
return val.src, val.packet, ok
}
func (n *natTable) delete(dst net.Addr) {
n.mutex.Lock()
delete(n.table, dst.String())
n.mutex.Unlock()
}
func (n *natTable) cleanup(period, ttl time.Duration) func() {
if period <= 0 || ttl <= 0 {
return func() {}
}
ticker := time.NewTicker(period)
done := make(chan struct{})
go func() {
for {
select {
case <-done:
ticker.Stop()
return
case <-ticker.C:
n.mutex.Lock()
for key, val := range n.table {
if time.Since(val.timestamp) >= ttl {
delete(n.table, key)
}
}
n.mutex.Unlock()
}
}
}()
return func() {
close(done)
}
}