forked from pion/ice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connectivity_vnet_test.go
641 lines (540 loc) · 15.3 KB
/
connectivity_vnet_test.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
// +build !js
package ice
import (
"context"
"fmt"
"net"
"sync/atomic"
"testing"
"time"
"github.com/pion/logging"
"github.com/pion/stun"
"github.com/pion/transport/test"
"github.com/pion/transport/vnet"
"github.com/pion/turn/v2"
"github.com/stretchr/testify/assert"
)
const (
vnetGlobalIPA = "27.1.1.1"
vnetLocalIPA = "192.168.0.1"
vnetLocalSubnetMaskA = "24"
vnetGlobalIPB = "28.1.1.1"
vnetLocalIPB = "10.2.0.1"
vnetLocalSubnetMaskB = "24"
vnetSTUNServerIP = "1.2.3.4"
vnetSTUNServerPort = 3478
)
type virtualNet struct {
wan *vnet.Router
net0 *vnet.Net
net1 *vnet.Net
server *turn.Server
}
func (v *virtualNet) close() {
v.server.Close() // nolint:errcheck,gosec
v.wan.Stop() // nolint:errcheck,gosec
}
func buildVNet(natType0, natType1 *vnet.NATType) (*virtualNet, error) {
loggerFactory := logging.NewDefaultLoggerFactory()
// WAN
wan, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: loggerFactory,
})
if err != nil {
return nil, err
}
wanNet := vnet.NewNet(&vnet.NetConfig{
StaticIP: vnetSTUNServerIP, // will be assigned to eth0
})
err = wan.AddNet(wanNet)
if err != nil {
return nil, err
}
// LAN 0
lan0, err := vnet.NewRouter(&vnet.RouterConfig{
StaticIPs: func() []string {
if natType0.Mode == vnet.NATModeNAT1To1 {
return []string{
vnetGlobalIPA + "/" + vnetLocalIPA,
}
}
return []string{
vnetGlobalIPA,
}
}(),
CIDR: vnetLocalIPA + "/" + vnetLocalSubnetMaskA,
NATType: natType0,
LoggerFactory: loggerFactory,
})
if err != nil {
return nil, err
}
net0 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{vnetLocalIPA},
})
err = lan0.AddNet(net0)
if err != nil {
return nil, err
}
err = wan.AddRouter(lan0)
if err != nil {
return nil, err
}
// LAN 1
lan1, err := vnet.NewRouter(&vnet.RouterConfig{
StaticIPs: func() []string {
if natType1.Mode == vnet.NATModeNAT1To1 {
return []string{
vnetGlobalIPB + "/" + vnetLocalIPB,
}
}
return []string{
vnetGlobalIPB,
}
}(),
CIDR: vnetLocalIPB + "/" + vnetLocalSubnetMaskB,
NATType: natType1,
LoggerFactory: loggerFactory,
})
if err != nil {
return nil, err
}
net1 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{vnetLocalIPB},
})
err = lan1.AddNet(net1)
if err != nil {
return nil, err
}
err = wan.AddRouter(lan1)
if err != nil {
return nil, err
}
// Start routers
err = wan.Start()
if err != nil {
return nil, err
}
server, err := addVNetSTUN(wanNet, loggerFactory)
if err != nil {
return nil, err
}
return &virtualNet{
wan: wan,
net0: net0,
net1: net1,
server: server,
}, nil
}
func addVNetSTUN(wanNet *vnet.Net, loggerFactory logging.LoggerFactory) (*turn.Server, error) {
// Run TURN(STUN) server
credMap := map[string]string{}
credMap["user"] = "pass"
wanNetPacketConn, err := wanNet.ListenPacket("udp", fmt.Sprintf("%s:%d", vnetSTUNServerIP, vnetSTUNServerPort))
if err != nil {
return nil, err
}
server, err := turn.NewServer(turn.ServerConfig{
AuthHandler: func(username, realm string, srcAddr net.Addr) (key []byte, ok bool) {
if pw, ok := credMap[username]; ok {
return turn.GenerateAuthKey(username, realm, pw), true
}
return nil, false
},
PacketConnConfigs: []turn.PacketConnConfig{
{
PacketConn: wanNetPacketConn,
RelayAddressGenerator: &turn.RelayAddressGeneratorStatic{
RelayAddress: net.ParseIP(vnetSTUNServerIP),
Address: "0.0.0.0",
Net: wanNet,
},
},
},
Realm: "pion.ly",
LoggerFactory: loggerFactory,
})
if err != nil {
return nil, err
}
return server, err
}
func connectWithVNet(aAgent, bAgent *Agent) (*Conn, *Conn) {
// Manual signaling
aUfrag, aPwd, err := aAgent.GetLocalUserCredentials()
check(err)
bUfrag, bPwd, err := bAgent.GetLocalUserCredentials()
check(err)
gatherAndExchangeCandidates(aAgent, bAgent)
accepted := make(chan struct{})
var aConn *Conn
go func() {
var acceptErr error
aConn, acceptErr = aAgent.Accept(context.TODO(), bUfrag, bPwd)
check(acceptErr)
close(accepted)
}()
bConn, err := bAgent.Dial(context.TODO(), aUfrag, aPwd)
check(err)
// Ensure accepted
<-accepted
return aConn, bConn
}
type agentTestConfig struct {
urls []*URL
nat1To1IPCandidateType CandidateType
}
func pipeWithVNet(v *virtualNet, a0TestConfig, a1TestConfig *agentTestConfig) (*Conn, *Conn) {
aNotifier, aConnected := onConnected()
bNotifier, bConnected := onConnected()
var nat1To1IPs []string
if a0TestConfig.nat1To1IPCandidateType != CandidateTypeUnspecified {
nat1To1IPs = []string{
vnetGlobalIPA,
}
}
cfg0 := &AgentConfig{
Urls: a0TestConfig.urls,
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
NAT1To1IPs: nat1To1IPs,
NAT1To1IPCandidateType: a0TestConfig.nat1To1IPCandidateType,
Net: v.net0,
}
aAgent, err := NewAgent(cfg0)
if err != nil {
panic(err)
}
err = aAgent.OnConnectionStateChange(aNotifier)
if err != nil {
panic(err)
}
if a1TestConfig.nat1To1IPCandidateType != CandidateTypeUnspecified {
nat1To1IPs = []string{
vnetGlobalIPB,
}
}
cfg1 := &AgentConfig{
Urls: a1TestConfig.urls,
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
NAT1To1IPs: nat1To1IPs,
NAT1To1IPCandidateType: a1TestConfig.nat1To1IPCandidateType,
Net: v.net1,
}
bAgent, err := NewAgent(cfg1)
if err != nil {
panic(err)
}
err = bAgent.OnConnectionStateChange(bNotifier)
if err != nil {
panic(err)
}
aConn, bConn := connectWithVNet(aAgent, bAgent)
// Ensure pair selected
// Note: this assumes ConnectionStateConnected is thrown after selecting the final pair
<-aConnected
<-bConnected
return aConn, bConn
}
func closePipe(t *testing.T, ca *Conn, cb *Conn) bool {
err := ca.Close()
if !assert.NoError(t, err, "should succeed") {
return false
}
err = cb.Close()
return assert.NoError(t, err, "should succeed")
}
func TestConnectivityVNet(t *testing.T) {
report := test.CheckRoutines(t)
defer report()
stunServerURL := &URL{
Scheme: SchemeTypeSTUN,
Host: vnetSTUNServerIP,
Port: vnetSTUNServerPort,
Proto: ProtoTypeUDP,
}
turnServerURL := &URL{
Scheme: SchemeTypeTURN,
Host: vnetSTUNServerIP,
Port: vnetSTUNServerPort,
Username: "user",
Password: "pass",
Proto: ProtoTypeUDP,
}
t.Run("Full-cone NATs on both ends", func(t *testing.T) {
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
// buildVNet with a Full-cone NATs both LANs
natType := &vnet.NATType{
MappingBehavior: vnet.EndpointIndependent,
FilteringBehavior: vnet.EndpointIndependent,
}
v, err := buildVNet(natType, natType)
if !assert.NoError(t, err, "should succeed") {
return
}
defer v.close()
log.Debug("Connecting...")
a0TestConfig := &agentTestConfig{
urls: []*URL{
stunServerURL,
},
}
a1TestConfig := &agentTestConfig{
urls: []*URL{
stunServerURL,
},
}
ca, cb := pipeWithVNet(v, a0TestConfig, a1TestConfig)
time.Sleep(1 * time.Second)
log.Debug("Closing...")
if !closePipe(t, ca, cb) {
return
}
})
t.Run("Symmetric NATs on both ends", func(t *testing.T) {
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
// buildVNet with a Symmetric NATs for both LANs
natType := &vnet.NATType{
MappingBehavior: vnet.EndpointAddrPortDependent,
FilteringBehavior: vnet.EndpointAddrPortDependent,
}
v, err := buildVNet(natType, natType)
if !assert.NoError(t, err, "should succeed") {
return
}
defer v.close()
log.Debug("Connecting...")
a0TestConfig := &agentTestConfig{
urls: []*URL{
stunServerURL,
turnServerURL,
},
}
a1TestConfig := &agentTestConfig{
urls: []*URL{
stunServerURL,
},
}
ca, cb := pipeWithVNet(v, a0TestConfig, a1TestConfig)
log.Debug("Closing...")
if !closePipe(t, ca, cb) {
return
}
})
t.Run("1:1 NAT with host candidate vs Symmetric NATs", func(t *testing.T) {
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
// Agent0 is behind 1:1 NAT
natType0 := &vnet.NATType{
Mode: vnet.NATModeNAT1To1,
}
// Agent1 is behind a symmetric NAT
natType1 := &vnet.NATType{
MappingBehavior: vnet.EndpointAddrPortDependent,
FilteringBehavior: vnet.EndpointAddrPortDependent,
}
v, err := buildVNet(natType0, natType1)
if !assert.NoError(t, err, "should succeed") {
return
}
defer v.close()
log.Debug("Connecting...")
a0TestConfig := &agentTestConfig{
urls: []*URL{},
nat1To1IPCandidateType: CandidateTypeHost, // Use 1:1 NAT IP as a host candidate
}
a1TestConfig := &agentTestConfig{
urls: []*URL{},
}
ca, cb := pipeWithVNet(v, a0TestConfig, a1TestConfig)
log.Debug("Closing...")
if !closePipe(t, ca, cb) {
return
}
})
t.Run("1:1 NAT with srflx candidate vs Symmetric NATs", func(t *testing.T) {
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
// Agent0 is behind 1:1 NAT
natType0 := &vnet.NATType{
Mode: vnet.NATModeNAT1To1,
}
// Agent1 is behind a symmetric NAT
natType1 := &vnet.NATType{
MappingBehavior: vnet.EndpointAddrPortDependent,
FilteringBehavior: vnet.EndpointAddrPortDependent,
}
v, err := buildVNet(natType0, natType1)
if !assert.NoError(t, err, "should succeed") {
return
}
defer v.close()
log.Debug("Connecting...")
a0TestConfig := &agentTestConfig{
urls: []*URL{},
nat1To1IPCandidateType: CandidateTypeServerReflexive, // Use 1:1 NAT IP as a srflx candidate
}
a1TestConfig := &agentTestConfig{
urls: []*URL{},
}
ca, cb := pipeWithVNet(v, a0TestConfig, a1TestConfig)
log.Debug("Closing...")
if !closePipe(t, ca, cb) {
return
}
})
}
// TestDisconnectedToConnected asserts that an agent can go to disconnected, and then return to connected successfully
func TestDisconnectedToConnected(t *testing.T) {
report := test.CheckRoutines(t)
defer report()
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
loggerFactory := logging.NewDefaultLoggerFactory()
// Create a network with two interfaces
wan, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: loggerFactory,
})
assert.NoError(t, err)
var dropAllData uint64
wan.AddChunkFilter(func(vnet.Chunk) bool {
return atomic.LoadUint64(&dropAllData) != 1
})
net0 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{"192.168.0.1"},
})
assert.NoError(t, wan.AddNet(net0))
net1 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{"192.168.0.2"},
})
assert.NoError(t, wan.AddNet(net1))
assert.NoError(t, wan.Start())
disconnectTimeout := time.Second
keepaliveInterval := time.Millisecond * 20
// Create two agents and connect them
controllingAgent, err := NewAgent(&AgentConfig{
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
Net: net0,
DisconnectedTimeout: &disconnectTimeout,
KeepaliveInterval: &keepaliveInterval,
checkInterval: keepaliveInterval,
})
assert.NoError(t, err)
controlledAgent, err := NewAgent(&AgentConfig{
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
Net: net1,
DisconnectedTimeout: &disconnectTimeout,
KeepaliveInterval: &keepaliveInterval,
checkInterval: keepaliveInterval,
})
assert.NoError(t, err)
controllingStateChanges := make(chan ConnectionState, 100)
assert.NoError(t, controllingAgent.OnConnectionStateChange(func(c ConnectionState) {
controllingStateChanges <- c
}))
controlledStateChanges := make(chan ConnectionState, 100)
assert.NoError(t, controlledAgent.OnConnectionStateChange(func(c ConnectionState) {
controlledStateChanges <- c
}))
connectWithVNet(controllingAgent, controlledAgent)
blockUntilStateSeen := func(expectedState ConnectionState, stateQueue chan ConnectionState) {
for s := range stateQueue {
if s == expectedState {
return
}
}
}
// Assert we have gone to connected
blockUntilStateSeen(ConnectionStateConnected, controllingStateChanges)
blockUntilStateSeen(ConnectionStateConnected, controlledStateChanges)
// Drop all packets, and block until we have gone to disconnected
atomic.StoreUint64(&dropAllData, 1)
blockUntilStateSeen(ConnectionStateDisconnected, controllingStateChanges)
blockUntilStateSeen(ConnectionStateDisconnected, controlledStateChanges)
// Allow all packets through again, block until we have gone to connected
atomic.StoreUint64(&dropAllData, 0)
blockUntilStateSeen(ConnectionStateConnected, controllingStateChanges)
blockUntilStateSeen(ConnectionStateConnected, controlledStateChanges)
assert.NoError(t, wan.Stop())
assert.NoError(t, controllingAgent.Close())
assert.NoError(t, controlledAgent.Close())
}
// Agent.Write should use the best valid pair if a selected pair is not yet available
func TestWriteUseValidPair(t *testing.T) {
report := test.CheckRoutines(t)
defer report()
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
loggerFactory := logging.NewDefaultLoggerFactory()
// Create a network with two interfaces
wan, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
LoggerFactory: loggerFactory,
})
assert.NoError(t, err)
wan.AddChunkFilter(func(c vnet.Chunk) bool {
if stun.IsMessage(c.UserData()) {
m := &stun.Message{
Raw: c.UserData(),
}
if decErr := m.Decode(); decErr != nil {
return false
} else if m.Contains(stun.AttrUseCandidate) {
return false
}
}
return true
})
net0 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{"192.168.0.1"},
})
assert.NoError(t, wan.AddNet(net0))
net1 := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{"192.168.0.2"},
})
assert.NoError(t, wan.AddNet(net1))
assert.NoError(t, wan.Start())
// Create two agents and connect them
controllingAgent, err := NewAgent(&AgentConfig{
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
Net: net0,
})
assert.NoError(t, err)
controlledAgent, err := NewAgent(&AgentConfig{
NetworkTypes: supportedNetworkTypes(),
MulticastDNSMode: MulticastDNSModeDisabled,
Net: net1,
})
assert.NoError(t, err)
gatherAndExchangeCandidates(controllingAgent, controlledAgent)
controllingUfrag, controllingPwd, err := controllingAgent.GetLocalUserCredentials()
assert.NoError(t, err)
controlledUfrag, controlledPwd, err := controlledAgent.GetLocalUserCredentials()
assert.NoError(t, err)
assert.NoError(t, controllingAgent.startConnectivityChecks(true, controlledUfrag, controlledPwd))
assert.NoError(t, controlledAgent.startConnectivityChecks(false, controllingUfrag, controllingPwd))
testMessage := []byte("Test Message")
go func() {
for {
if _, writeErr := (&Conn{agent: controllingAgent}).Write(testMessage); writeErr != nil {
return
}
time.Sleep(20 * time.Millisecond)
}
}()
readBuf := make([]byte, len(testMessage))
_, err = (&Conn{agent: controlledAgent}).Read(readBuf)
assert.NoError(t, err)
assert.Equal(t, readBuf, testMessage)
assert.NoError(t, wan.Stop())
assert.NoError(t, controllingAgent.Close())
assert.NoError(t, controlledAgent.Close())
}