-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathnat.go
257 lines (223 loc) · 6.77 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package nat
import (
"context"
"errors"
"fmt"
"net/netip"
"sync"
"time"
logging "github.com/ipfs/go-log/v2"
"github.com/libp2p/go-nat"
)
// ErrNoMapping signals no mapping exists for an address
var ErrNoMapping = errors.New("mapping not established")
var log = logging.Logger("nat")
// MappingDuration is a default port mapping duration.
// Port mappings are renewed every (MappingDuration / 3)
const MappingDuration = time.Minute
// CacheTime is the time a mapping will cache an external address for
const CacheTime = 15 * time.Second
type entry struct {
protocol string
port int
}
// so we can mock it in tests
var discoverGateway = nat.DiscoverGateway
// DiscoverNAT looks for a NAT device in the network and returns an object that can manage port mappings.
func DiscoverNAT(ctx context.Context) (*NAT, error) {
natInstance, err := discoverGateway(ctx)
if err != nil {
return nil, err
}
var extAddr netip.Addr
extIP, err := natInstance.GetExternalAddress()
if err == nil {
extAddr, _ = netip.AddrFromSlice(extIP)
}
// Log the device addr.
addr, err := natInstance.GetDeviceAddress()
if err != nil {
log.Debug("DiscoverGateway address error:", err)
} else {
log.Debug("DiscoverGateway address:", addr)
}
ctx, cancel := context.WithCancel(context.Background())
nat := &NAT{
nat: natInstance,
extAddr: extAddr,
mappings: make(map[entry]int),
ctx: ctx,
ctxCancel: cancel,
}
nat.refCount.Add(1)
go func() {
defer nat.refCount.Done()
nat.background()
}()
return nat, nil
}
// NAT is an object that manages address port mappings in
// NATs (Network Address Translators). It is a long-running
// service that will periodically renew port mappings,
// and keep an up-to-date list of all the external addresses.
type NAT struct {
natmu sync.Mutex
nat nat.NAT
// External IP of the NAT. Will be renewed periodically (every CacheTime).
extAddr netip.Addr
refCount sync.WaitGroup
ctx context.Context
ctxCancel context.CancelFunc
mappingmu sync.RWMutex // guards mappings
closed bool
mappings map[entry]int
}
// Close shuts down all port mappings. NAT can no longer be used.
func (nat *NAT) Close() error {
nat.mappingmu.Lock()
nat.closed = true
nat.mappingmu.Unlock()
nat.ctxCancel()
nat.refCount.Wait()
return nil
}
func (nat *NAT) GetMapping(protocol string, port int) (addr netip.AddrPort, found bool) {
nat.mappingmu.Lock()
defer nat.mappingmu.Unlock()
if !nat.extAddr.IsValid() {
return netip.AddrPort{}, false
}
extPort, found := nat.mappings[entry{protocol: protocol, port: port}]
if !found {
return netip.AddrPort{}, false
}
return netip.AddrPortFrom(nat.extAddr, uint16(extPort)), true
}
// AddMapping attempts to construct a mapping on protocol and internal port.
// It blocks until a mapping was established. Once added, it periodically renews the mapping.
//
// May not succeed, and mappings may change over time;
// NAT devices may not respect our port requests, and even lie.
func (nat *NAT) AddMapping(ctx context.Context, protocol string, port int) error {
switch protocol {
case "tcp", "udp":
default:
return fmt.Errorf("invalid protocol: %s", protocol)
}
nat.mappingmu.Lock()
defer nat.mappingmu.Unlock()
if nat.closed {
return errors.New("closed")
}
// do it once synchronously, so first mapping is done right away, and before exiting,
// allowing users -- in the optimistic case -- to use results right after.
extPort := nat.establishMapping(ctx, protocol, port)
nat.mappings[entry{protocol: protocol, port: port}] = extPort
return nil
}
// RemoveMapping removes a port mapping.
// It blocks until the NAT has removed the mapping.
func (nat *NAT) RemoveMapping(ctx context.Context, protocol string, port int) error {
nat.mappingmu.Lock()
defer nat.mappingmu.Unlock()
switch protocol {
case "tcp", "udp":
e := entry{protocol: protocol, port: port}
if _, ok := nat.mappings[e]; ok {
delete(nat.mappings, e)
return nat.nat.DeletePortMapping(ctx, protocol, port)
}
return errors.New("unknown mapping")
default:
return fmt.Errorf("invalid protocol: %s", protocol)
}
}
func (nat *NAT) background() {
const mappingUpdate = MappingDuration / 3
now := time.Now()
nextMappingUpdate := now.Add(mappingUpdate)
nextAddrUpdate := now.Add(CacheTime)
t := time.NewTimer(minTime(nextMappingUpdate, nextAddrUpdate).Sub(now)) // don't use a ticker here. We don't know how long establishing the mappings takes.
defer t.Stop()
var in []entry
var out []int // port numbers
for {
select {
case now := <-t.C:
if now.After(nextMappingUpdate) {
in = in[:0]
out = out[:0]
nat.mappingmu.Lock()
for e := range nat.mappings {
in = append(in, e)
}
nat.mappingmu.Unlock()
// Establishing the mapping involves network requests.
// Don't hold the mutex, just save the ports.
for _, e := range in {
out = append(out, nat.establishMapping(nat.ctx, e.protocol, e.port))
}
nat.mappingmu.Lock()
for i, p := range in {
if _, ok := nat.mappings[p]; !ok {
continue // entry might have been deleted
}
nat.mappings[p] = out[i]
}
nat.mappingmu.Unlock()
nextMappingUpdate = time.Now().Add(mappingUpdate)
}
if now.After(nextAddrUpdate) {
var extAddr netip.Addr
extIP, err := nat.nat.GetExternalAddress()
if err == nil {
extAddr, _ = netip.AddrFromSlice(extIP)
}
nat.extAddr = extAddr
nextAddrUpdate = time.Now().Add(CacheTime)
}
t.Reset(time.Until(minTime(nextAddrUpdate, nextMappingUpdate)))
case <-nat.ctx.Done():
nat.mappingmu.Lock()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
for e := range nat.mappings {
delete(nat.mappings, e)
nat.nat.DeletePortMapping(ctx, e.protocol, e.port)
}
nat.mappingmu.Unlock()
return
}
}
}
func (nat *NAT) establishMapping(ctx context.Context, protocol string, internalPort int) (externalPort int) {
log.Debugf("Attempting port map: %s/%d", protocol, internalPort)
const comment = "libp2p"
nat.natmu.Lock()
var err error
externalPort, err = nat.nat.AddPortMapping(ctx, protocol, internalPort, comment, MappingDuration)
if err != nil {
// Some hardware does not support mappings with timeout, so try that
externalPort, err = nat.nat.AddPortMapping(ctx, protocol, internalPort, comment, 0)
}
nat.natmu.Unlock()
if err != nil || externalPort == 0 {
// TODO: log.Event
if err != nil {
log.Warnf("failed to establish port mapping: %s", err)
} else {
log.Warnf("failed to establish port mapping: newport = 0")
}
// we do not close if the mapping failed,
// because it may work again next time.
return 0
}
log.Debugf("NAT Mapping: %d --> %d (%s)", externalPort, internalPort, protocol)
return externalPort
}
func minTime(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}