-
Notifications
You must be signed in to change notification settings - Fork 0
/
natpmp_mock.go
305 lines (266 loc) · 6.89 KB
/
natpmp_mock.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package mocknat
import (
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
)
const (
extenralAddressOpcode = 0 + iota
udpMappingOpcode
tcpMappingOpcode
unsupportedVersion = 1
unsupportedOpcode = 5
)
type mockNAT struct {
conn *net.UDPConn
listenAddr *net.UDPAddr
externalIP net.IP
epoch uint32
// flag; 0: negative, 1: positive
supportedPMP uint32
isRun uint32
mu sync.Mutex
mapping map[string]map[uint16]*Internal // Mapping protocol to external port
}
// Internal stores the internal port number and the expiration timer
// according to the lifetime.
type Internal struct {
Port uint16
timer *time.Timer
}
func New(listenIP net.IP, externalIP net.IP, supportPMP bool) *mockNAT {
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", listenIP.String(), 5351))
if err != nil {
panic(err)
}
nat := &mockNAT{
conn: nil,
listenAddr: addr,
externalIP: externalIP,
mapping: makeProtocolMap(),
}
if supportPMP {
nat.supportedPMP = 1
}
return nat
}
// Clear goroutines about lifetime, and also reset 'Seconds Since Start of Epoch'
func (p *mockNAT) Restart() {
p.mu.Lock()
for k := range p.mapping {
for _, v := range p.mapping[k] {
v.timer.Stop()
}
}
p.mapping = makeProtocolMap()
p.mu.Unlock()
atomic.StoreUint32(&p.epoch, 0)
}
// Since calling this, the corresponding NAT-MOCK server supports PMP
func (p *mockNAT) SupportPMP() {
atomic.StoreUint32(&p.supportedPMP, 1)
}
// Since calling this, the corresponding NAT-MOCK server does not support PMP.
func (p *mockNAT) UnsupportPMP() {
atomic.StoreUint32(&p.supportedPMP, 0)
}
func (p *mockNAT) LocalAddr() net.Addr {
return p.conn.LocalAddr()
}
func (p *mockNAT) ExternalIP() net.IP {
return p.externalIP
}
func (p *mockNAT) Close() error {
if atomic.LoadUint32(&p.isRun) == 0 {
return errors.New("already closed")
}
atomic.StoreUint32(&p.isRun, 0)
return p.conn.Close()
}
func (p *mockNAT) Map(protocol string, extport uint16) *Internal {
p.mu.Lock()
defer p.mu.Unlock()
return p.mapping[protocol][extport]
}
func (p *mockNAT) Epoch() uint32 {
return atomic.LoadUint32(&p.epoch)
}
func (p *mockNAT) Run() {
if atomic.LoadUint32(&p.isRun) == 1 {
return
}
var err error
p.conn, err = net.ListenUDP("udp", p.listenAddr)
if err != nil {
panic(err)
}
atomic.StoreUint32(&p.isRun, 1)
go p.run()
}
func (p *mockNAT) run() {
// Count Seconds Since Start of Epoch.
go func() {
for {
time.Sleep(time.Millisecond)
// Check state is running
if atomic.LoadUint32(&p.isRun) == 0 {
return
}
atomic.AddUint32(&p.epoch, 1)
}
}()
for {
// Check state is running
if atomic.LoadUint32(&p.isRun) == 0 {
return
}
// Read process
b := make([]byte, 12)
len, sender, err := p.conn.ReadFromUDP(b)
if err != nil {
continue
}
// Just ignore if NAT doesn't support PMP.
if atomic.LoadUint32(&p.supportedPMP) == 0 {
// OR reply 'ICMP Port unreachable'
continue
}
if len < 2 {
continue
}
// Allowing loopback IPs is not a specification. But user usually
// use the loopback IP for testing. So this mock NAT allows loopback.
if !sender.IP.IsPrivate() && !sender.IP.IsLoopback() {
continue
}
// Invalid request format.
if b[1] > 128 {
continue
}
p.handle(b, sender)
}
}
func (p *mockNAT) handle(b []byte, sender *net.UDPAddr) {
response := make([]byte, 16)
response[0] = 0
defer func() {
// Set Seconds Since Start of Epoch if the message is successed.
if binary.BigEndian.Uint16(response[2:4]) == 0 {
epoch := atomic.LoadUint32(&p.epoch)
binary.BigEndian.PutUint32(response[4:8], epoch)
}
p.conn.WriteToUDP(response, sender)
}()
// Only accept version 0.
if b[0] != 0 {
binary.BigEndian.PutUint16(response[2:4], unsupportedVersion)
return
}
switch b[1] {
case extenralAddressOpcode:
response[1] = 128 + extenralAddressOpcode
copy(response[8:12], p.externalIP.To4())
response = response[0:12]
case udpMappingOpcode:
rop, rcode, body := p.handleMappingOpcode(b, "udp", udpMappingOpcode)
response[1] = rop
copy(response[2:4], rcode[:])
copy(response[8:16], body[:])
case tcpMappingOpcode:
rop, rcode, body := p.handleMappingOpcode(b, "tcp", tcpMappingOpcode)
response[1] = rop
copy(response[2:4], rcode[:])
copy(response[8:16], body[:])
default:
binary.BigEndian.PutUint16(response[2:4], unsupportedOpcode)
}
}
func (p *mockNAT) handleMappingOpcode(b []byte, protocol string, opcode byte) (ropcode byte, rcode [2]byte, body [8]byte) {
ropcode = 128 + opcode
intport, extport, lifeTime := parseMappingRequest(b)
p.mu.Lock()
defer p.mu.Unlock()
v, exist := p.mapping[protocol][extport]
// Destroying a mapping
if lifeTime == 0 && extport == 0 {
if exist {
v.timer.Stop()
delete(p.mapping[protocol], extport)
}
} else {
if exist {
// This is renewal request. Reset the timer to lifetime.
if v.Port == intport {
if !v.timer.Stop() {
<-v.timer.C
}
v.timer.Reset(time.Duration(lifeTime) * time.Second)
} else {
// This is the case that already used request's port.
//
// Maps alternative port.
extport = p.suggestExternalPort(protocol)
p.addExternal(protocol, extport, intport, time.Duration(lifeTime)*time.Second)
}
}
// Add new mapping.
if !exist {
// Client would prefer to have a high-numbered "anonymous" external port assigned
if extport == 0 {
extport = p.suggestExternalPort(protocol)
}
p.addExternal(protocol, extport, intport, time.Duration(lifeTime)*time.Second)
}
}
binary.BigEndian.PutUint16(body[0:2], intport)
binary.BigEndian.PutUint16(body[2:4], extport)
binary.BigEndian.PutUint32(body[4:8], lifeTime)
return
}
// addExternal stores the new internal port number and runs the
// lifetime expiration goroutine.
//
// The caller must hold p.mu.
func (p *mockNAT) addExternal(protocol string, extport, intport uint16, duration time.Duration) {
e := &Internal{
Port: intport,
timer: time.NewTimer(duration),
}
p.mapping[protocol][extport] = e
go func(t *time.Timer) {
defer t.Stop()
for range t.C {
p.mu.Lock()
delete(p.mapping[protocol], extport)
p.mu.Unlock()
return
}
}(e.timer)
}
// suggestExternalPort returns a available port number. Originally
// it should respond with an 'Out of resources' error if it
// expected all port numbers to be in use, but currently it simply
// causes a panic.
//
// The caller must hold p.mu.
func (p *mockNAT) suggestExternalPort(protocol string) uint16 {
for i := uint16(1024); i < 65535; i++ {
if _, ok := p.mapping[protocol][i]; !ok {
return i
}
}
panic("Out of resources")
}
func parseMappingRequest(b []byte) (uint16, uint16, uint32) {
return binary.BigEndian.Uint16(b[4:6]), binary.BigEndian.Uint16(b[6:8]), binary.BigEndian.Uint32(b[8:12])
}
func makeProtocolMap() map[string]map[uint16]*Internal {
m := make(map[string]map[uint16]*Internal)
m["tcp"] = make(map[uint16]*Internal)
m["udp"] = make(map[uint16]*Internal)
return m
}