/
nat.go
71 lines (59 loc) · 1.43 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
package inet256ipv6
import (
"context"
"github.com/brendoncarroll/stdctx/logctx"
"github.com/inet256/inet256/pkg/inet256"
)
type IPv6Addr = [16]byte
type NATTable struct {
srv inet256.Service
outbound map[IPv6Addr]inet256.Addr
inbound map[inet256.Addr]IPv6Addr
vnodes map[inet256.Addr]inet256.Node
}
func NewNATTable(srv inet256.Service) *NATTable {
return &NATTable{
srv: srv,
outbound: make(map[IPv6Addr]inet256.Addr),
inbound: make(map[inet256.Addr]IPv6Addr),
vnodes: make(map[inet256.Addr]inet256.Node),
}
}
func (nt *NATTable) AddClient(ctx context.Context, ipv6 IPv6Addr) inet256.Addr {
inside := ipv6
_, priv, err := inet256.GenerateKey(nil)
if err != nil {
panic(err)
}
vnode, err := nt.srv.Open(ctx, priv)
if err != nil {
panic(err)
}
outside := vnode.LocalAddr()
nt.inbound[outside] = inside
nt.outbound[inside] = outside
nt.vnodes[outside] = vnode
return outside
}
func (nt *NATTable) DeleteClient(ctx context.Context, ip6 IPv6Addr) {
addr, exists := nt.outbound[ip6]
if !exists {
return
}
if err := nt.vnodes[addr].Close(); err != nil {
logctx.Errorln(ctx, err)
}
delete(nt.outbound, ip6)
delete(nt.inbound, addr)
delete(nt.vnodes, addr)
}
func (nt *NATTable) NodeByInner(ipv6 IPv6Addr) inet256.Node {
addr, exists := nt.outbound[ipv6]
if !exists {
return nil
}
return nt.vnodes[addr]
}
func (nt *NATTable) NodeByOuter(addr inet256.Addr) inet256.Node {
return nt.vnodes[addr]
}