-
Notifications
You must be signed in to change notification settings - Fork 79
/
vnet_test.go
690 lines (579 loc) · 16.9 KB
/
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package sctp
import (
"bytes"
"fmt"
"math/rand"
"net"
"reflect"
"testing"
"time"
"github.com/pion/logging"
"github.com/pion/transport/v3/test"
"github.com/pion/transport/v3/vnet"
"github.com/stretchr/testify/assert"
)
type vNetEnvConfig struct {
minDelay time.Duration
loggerFactory logging.LoggerFactory
log logging.LeveledLogger
}
type vNetEnv struct {
wan *vnet.Router
net0 *vnet.Net
net1 *vnet.Net
numToDropData int
numToDropReconfig int
numToDropCookieEcho int
numToDropCookieAck int
}
var errSCTPPacketParse = fmt.Errorf("unable to parse SCTP packet")
func (venv *vNetEnv) dropNextDataChunk(numToDrop int) {
venv.numToDropData = numToDrop
}
func (venv *vNetEnv) dropNextReconfigChunk(numToDrop int) { // nolint:unused
venv.numToDropReconfig = numToDrop
}
func (venv *vNetEnv) dropNextCookieEchoChunk(numToDrop int) {
venv.numToDropCookieEcho = numToDrop
}
func (venv *vNetEnv) dropNextCookieAckChunk(numToDrop int) {
venv.numToDropCookieAck = numToDrop
}
func buildVNetEnv(cfg *vNetEnvConfig) (*vNetEnv, error) {
log := cfg.log
var venv *vNetEnv
serverIP := "1.1.1.1"
clientIP := "2.2.2.2"
wan, err := vnet.NewRouter(&vnet.RouterConfig{
CIDR: "0.0.0.0/0",
MinDelay: cfg.minDelay,
MaxJitter: 0 * time.Millisecond,
LoggerFactory: cfg.loggerFactory,
})
if err != nil {
return nil, err
}
tsnAutoLockOnFilter := func() func(vnet.Chunk) bool {
var lockedOnTSN bool
var tsn uint32
return func(c vnet.Chunk) bool {
var toDrop bool
p := &packet{}
if err2 := p.unmarshal(true, c.UserData()); err2 != nil {
panic(errSCTPPacketParse)
}
loop:
for i := 0; i < len(p.chunks); i++ {
switch chunk := p.chunks[i].(type) {
case *chunkPayloadData:
if venv.numToDropData > 0 {
if !lockedOnTSN {
tsn = chunk.tsn
lockedOnTSN = true
log.Infof("Chunk filter: lock on TSN %d", tsn)
}
if chunk.tsn == tsn {
toDrop = true
venv.numToDropData--
log.Infof("Chunk filter: drop TSN %d", tsn)
break loop
}
}
case *chunkReconfig:
if venv.numToDropReconfig > 0 {
toDrop = true
venv.numToDropReconfig--
log.Infof("Chunk filter: drop RECONFIG %s", chunk.String())
break loop
}
case *chunkCookieEcho:
if venv.numToDropCookieEcho > 0 {
toDrop = true
venv.numToDropCookieEcho--
log.Infof("Chunk filter: drop %s", chunk.String())
break loop
}
case *chunkCookieAck:
if venv.numToDropCookieAck > 0 {
toDrop = true
venv.numToDropCookieAck--
log.Infof("Chunk filter: drop %s", chunk.String())
break loop
}
}
}
return !toDrop
}
}
wan.AddChunkFilter(tsnAutoLockOnFilter())
net0, err := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{serverIP},
})
if err != nil {
return nil, err
}
err = wan.AddNet(net0)
if err != nil {
return nil, err
}
net1, err := vnet.NewNet(&vnet.NetConfig{
StaticIPs: []string{clientIP},
})
if err != nil {
return nil, err
}
err = wan.AddNet(net1)
if err != nil {
return nil, err
}
err = wan.Start()
if err != nil {
return nil, err
}
venv = &vNetEnv{
wan: wan,
net0: net0,
net1: net1,
}
return venv, nil
}
func testRwndFull(t *testing.T, unordered bool) {
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
venv, err := buildVNetEnv(&vNetEnvConfig{
minDelay: 200 * time.Millisecond,
loggerFactory: loggerFactory,
log: log,
})
if !assert.NoError(t, err, "should succeed") {
return
}
if !assert.NotNil(t, venv, "should not be nil") {
return
}
defer venv.wan.Stop() // nolint:errcheck
serverHandshakeDone := make(chan struct{})
clientHandshakeDone := make(chan struct{})
serverStreamReady := make(chan struct{})
clientStreamReady := make(chan struct{})
clientStartWrite := make(chan struct{})
serverRecvBufFull := make(chan struct{})
serverStartRead := make(chan struct{})
serverReadAll := make(chan struct{})
clientShutDown := make(chan struct{})
serverShutDown := make(chan struct{})
shutDownClient := make(chan struct{})
shutDownServer := make(chan struct{})
maxReceiveBufferSize := uint32(64 * 1024)
msgSize := int(float32(maxReceiveBufferSize)/2) + int(initialMTU)
msg := make([]byte, msgSize)
rand.Read(msg) // nolint:errcheck,gosec
go func() {
defer close(serverShutDown)
// connected UDP conn for server
conn, err := venv.net0.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, err, "should succeed") {
return
}
defer conn.Close() // nolint:errcheck
// server association
assoc, err := Server(Config{
NetConn: conn,
MaxReceiveBufferSize: maxReceiveBufferSize,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, err, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("server handshake complete")
close(serverHandshakeDone)
stream, err := assoc.AcceptStream()
if !assert.NoError(t, err, "should succeed") {
return
}
defer stream.Close() // nolint:errcheck
// Expunge the first HELLO packet
buf := make([]byte, 64*1024)
n, err := stream.Read(buf)
if !assert.NoError(t, err, "should succeed") {
return
}
assert.Equal(t, "HELLO", string(buf[:n]), "should match")
stream.SetReliabilityParams(unordered, ReliabilityTypeReliable, 0)
log.Info("server stream ready")
close(serverStreamReady)
for {
assoc.lock.RLock()
rbufSize := assoc.getMyReceiverWindowCredit()
log.Infof("rbufSize = %d", rbufSize)
assoc.lock.RUnlock()
if rbufSize == 0 {
break
}
time.Sleep(50 * time.Millisecond)
}
close(serverRecvBufFull)
<-serverStartRead
for i := 0; i < 2; i++ {
n, err = stream.Read(buf)
if !assert.NoError(t, err, "should succeed") {
return
}
if !assert.NoError(t, err, "should succeed") {
return
}
log.Infof("server read %d bytes", n)
assert.True(t, reflect.DeepEqual(msg, buf[:n]), "msg %d should match", i)
}
close(serverReadAll)
<-shutDownServer
log.Info("server closing")
}()
go func() {
defer close(clientShutDown)
// connected UDP conn for client
conn, err := venv.net1.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, err, "should succeed") {
return
}
// client association
assoc, err := Client(Config{
NetConn: conn,
MaxReceiveBufferSize: maxReceiveBufferSize,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, err, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("client handshake complete")
close(clientHandshakeDone)
stream, err := assoc.OpenStream(777, PayloadTypeWebRTCBinary)
if !assert.NoError(t, err, "should succeed") {
return
}
defer stream.Close() // nolint:errcheck
// Send a message to let server side stream to open
_, err = stream.Write([]byte("HELLO"))
if !assert.NoError(t, err, "should succeed") {
return
}
stream.SetReliabilityParams(unordered, ReliabilityTypeReliable, 0)
log.Info("client stream ready")
close(clientStreamReady)
<-clientStartWrite
// Set the cwnd and rwnd to the size large enough to send the large messages
// right away
assoc.lock.Lock()
assoc.cwnd = 2 * maxReceiveBufferSize
assoc.rwnd = 2 * maxReceiveBufferSize
assoc.lock.Unlock()
// Send two large messages so that the second one will
// cause receiver side buffer full
for i := 0; i < 2; i++ {
_, err = stream.Write(msg)
if !assert.NoError(t, err, "should succeed") {
return
}
}
<-shutDownClient
log.Info("client closing")
}()
//
// Scenario
//
// wait until both handshake complete
<-clientHandshakeDone
<-serverHandshakeDone
log.Info("handshake complete")
// wait until both establish a stream
<-clientStreamReady
<-serverStreamReady
log.Info("stream ready")
// drop next 1 DATA chunk sent to the server
venv.dropNextDataChunk(1)
// let client begin writing
log.Info("client start writing")
close(clientStartWrite)
// wait until the server's receive buffer becomes full
<-serverRecvBufFull
// let server start reading
close(serverStartRead)
// wait until the server receives all data
log.Info("let server start reading")
<-serverReadAll
log.Info("server received all data")
close(shutDownClient)
<-clientShutDown
close(shutDownServer)
<-serverShutDown
log.Info("all done")
}
func TestRwndFull(t *testing.T) {
t.Run("Ordered", func(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
testRwndFull(t, false)
})
t.Run("Unordered", func(t *testing.T) {
// Limit runtime in case of deadlocks
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
testRwndFull(t, true)
})
}
func TestStreamClose(t *testing.T) {
loopBackTest := func(t *testing.T, dropReconfigChunk bool) {
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
venv, err := buildVNetEnv(&vNetEnvConfig{
loggerFactory: loggerFactory,
log: log,
})
if !assert.NoError(t, err, "should succeed") {
return
}
if !assert.NotNil(t, venv, "should not be nil") {
return
}
defer venv.wan.Stop() // nolint:errcheck
clientShutDown := make(chan struct{})
serverShutDown := make(chan struct{})
const numMessages = 10
const messageSize = 1024
var messages [][]byte
var numServerReceived int
var numClientReceived int
for i := 0; i < numMessages; i++ {
bytes := make([]byte, messageSize)
messages = append(messages, bytes)
}
go func() {
defer close(serverShutDown)
// connected UDP conn for server
conn, innerErr := venv.net0.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, innerErr, "should succeed") {
return
}
defer conn.Close() // nolint:errcheck
// server association
assoc, innerErr := Server(Config{
NetConn: conn,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, innerErr, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("server handshake complete")
stream, innerErr := assoc.AcceptStream()
if !assert.NoError(t, innerErr, "should succeed") {
return
}
assert.Equal(t, StreamStateOpen, stream.State())
buf := make([]byte, 1500)
for {
n, errRead := stream.Read(buf)
if errRead != nil {
log.Infof("server: Read returned %v", errRead)
_ = stream.Close() // nolint:errcheck
assert.Equal(t, StreamStateClosed, stream.State())
break
}
log.Infof("server: received %d bytes (%d)", n, numServerReceived)
assert.Equal(t, 0, bytes.Compare(buf[:n], messages[numServerReceived]), "should receive HELLO")
_, err2 := stream.Write(buf[:n])
assert.NoError(t, err2, "should succeed")
numServerReceived++
}
// don't close association until the client's stream routine is complete
<-clientShutDown
}()
// connected UDP conn for client
conn, err := venv.net1.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, err, "should succeed") {
return
}
defer conn.Close() // nolint:errcheck
// client association
assoc, err := Client(Config{
NetConn: conn,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, err, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("client handshake complete")
stream, err := assoc.OpenStream(777, PayloadTypeWebRTCBinary)
if !assert.NoError(t, err, "should succeed") {
return
}
assert.Equal(t, StreamStateOpen, stream.State())
stream.SetReliabilityParams(false, ReliabilityTypeReliable, 0)
// begin client read-loop
buf := make([]byte, 1500)
go func() {
defer close(clientShutDown)
for {
n, err2 := stream.Read(buf)
if err2 != nil {
log.Infof("client: Read returned %v", err2)
assert.Equal(t, StreamStateClosed, stream.State())
break
}
log.Infof("client: received %d bytes (%d)", n, numClientReceived)
assert.Equal(t, 0, bytes.Compare(buf[:n], messages[numClientReceived]), "should receive HELLO")
numClientReceived++
}
}()
// Send messages to the server
for i := 0; i < numMessages; i++ {
_, err = stream.Write(messages[i])
assert.NoError(t, err, "should succeed")
}
if dropReconfigChunk {
venv.dropNextReconfigChunk(1)
}
// Immediately close the stream
err = stream.Close()
assert.NoError(t, err, "should succeed")
assert.Equal(t, StreamStateClosing, stream.State())
log.Info("client wait for exit reading..")
<-clientShutDown
assert.Equal(t, numMessages, numServerReceived, "all messages should be received")
assert.Equal(t, numMessages, numClientReceived, "all messages should be received")
_, err = stream.Write([]byte{1})
assert.Equal(t, err, ErrStreamClosed, "after closed should not allow write")
// Check if RECONFIG was actually dropped
assert.Equal(t, 0, venv.numToDropReconfig, "should be zero")
// Sleep enough time for reconfig response to come back
time.Sleep(100 * time.Millisecond)
// Verify there's no more pending reconfig
assoc.lock.RLock()
pendingReconfigs := len(assoc.reconfigs)
assoc.lock.RUnlock()
assert.Equal(t, 0, pendingReconfigs, "should be zero")
}
t.Run("without dropping Reconfig", func(t *testing.T) {
loopBackTest(t, false)
})
t.Run("with dropping Reconfig", func(t *testing.T) {
loopBackTest(t, true)
})
}
// this test case reproduces the issue mentioned in
// https://github.com/pion/webrtc/issues/1270#issuecomment-653953743
// and confirmes the fix.
// To reproduce the case mentioned above:
// * Use simultaneous-open (SCTP)
// * Drop both of the first COOKIE-ECHO and COOKIE-ACK
func TestCookieEchoRetransmission(t *testing.T) {
lim := test.TimeOut(time.Second * 10)
defer lim.Stop()
loggerFactory := logging.NewDefaultLoggerFactory()
log := loggerFactory.NewLogger("test")
venv, err := buildVNetEnv(&vNetEnvConfig{
minDelay: 200 * time.Millisecond,
loggerFactory: loggerFactory,
log: log,
})
if !assert.NoError(t, err, "should succeed") {
return
}
if !assert.NotNil(t, venv, "should not be nil") {
return
}
defer venv.wan.Stop() // nolint:errcheck
// To cause the cookie echo retransmission, both COOKIE-ECHO
// and COOKIE-ACK chunks need to be dropped at the same time.
venv.dropNextCookieEchoChunk(1)
venv.dropNextCookieAckChunk(1)
serverHandshakeDone := make(chan struct{})
clientHandshakeDone := make(chan struct{})
waitAllHandshakeDone := make(chan struct{})
clientShutDown := make(chan struct{})
serverShutDown := make(chan struct{})
maxReceiveBufferSize := uint32(64 * 1024)
// Go routine for Server
go func() {
defer close(serverShutDown)
// connected UDP conn for server
conn, err := venv.net0.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, err, "should succeed") {
return
}
defer conn.Close() // nolint:errcheck
// server association
// using Client for simultaneous open
assoc, err := Client(Config{
NetConn: conn,
MaxReceiveBufferSize: maxReceiveBufferSize,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, err, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("server handshake complete")
close(serverHandshakeDone)
<-waitAllHandshakeDone
}()
// Go routine for Client
go func() {
defer close(clientShutDown)
// connected UDP conn for client
conn, err := venv.net1.DialUDP("udp4",
&net.UDPAddr{IP: net.ParseIP("2.2.2.2"), Port: defaultSCTPSrcDstPort},
&net.UDPAddr{IP: net.ParseIP("1.1.1.1"), Port: defaultSCTPSrcDstPort},
)
if !assert.NoError(t, err, "should succeed") {
return
}
// client association
assoc, err := Client(Config{
NetConn: conn,
MaxReceiveBufferSize: maxReceiveBufferSize,
LoggerFactory: loggerFactory,
})
if !assert.NoError(t, err, "should succeed") {
return
}
defer assoc.Close() // nolint:errcheck
log.Info("client handshake complete")
close(clientHandshakeDone)
<-waitAllHandshakeDone
}()
//
// Scenario
//
// wait until both handshake complete
<-clientHandshakeDone
<-serverHandshakeDone
close(waitAllHandshakeDone)
log.Info("handshake complete")
<-clientShutDown
<-serverShutDown
log.Info("all done")
}