forked from pion/transport
/
bridge.go
450 lines (385 loc) · 10.1 KB
/
bridge.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
package test
import (
"errors"
"fmt"
"io"
"math/rand"
"net"
"sync"
"time"
"github.com/pion/transport/deadline"
)
const (
tickWait = 10 * time.Microsecond
udpString = "udp"
)
var (
errIOTimeout = errors.New("i/o timeout")
errBridgeConnClosed = errors.New("bridgeConn closed")
errBridgeAlreadyClosed = errors.New("bridge has already been closed")
errInverseArrayWithOne = errors.New("inverse requires more than one item in the array")
errBadLossChanceRange = errors.New("loss must be < 100 && > 0")
)
type bridgeConnAddr int
func (a bridgeConnAddr) Network() string {
return udpString
}
func (a bridgeConnAddr) String() string {
return fmt.Sprintf("a%d", a)
}
// bridgeConn is a net.Conn that represents an endpoint of the bridge.
type bridgeConn struct {
br *Bridge
id int
closeReq bool
closing bool
closed bool
mutex sync.RWMutex
readCh chan []byte
lossChance int
readDeadline *deadline.Deadline
writeDeadline *deadline.Deadline
}
type netError struct {
error
timeout, temporary bool
}
func (e *netError) Timeout() bool {
return e.timeout
}
func (e *netError) Temporary() bool {
return e.timeout
}
// Read reads data, block until the data becomes available.
func (conn *bridgeConn) Read(b []byte) (int, error) {
select {
case <-conn.readDeadline.Done():
return 0, &netError{errIOTimeout, true, true}
default:
}
select {
case data, ok := <-conn.readCh:
if !ok {
return 0, io.EOF
}
n := copy(b, data)
return n, nil
case <-conn.readDeadline.Done():
return 0, &netError{errIOTimeout, true, true}
}
}
// Write writes data to the bridge.
func (conn *bridgeConn) Write(b []byte) (int, error) {
select {
case <-conn.writeDeadline.Done():
return 0, &netError{errIOTimeout, true, true}
default:
}
if rand.Intn(100) < conn.lossChance { //nolint:gosec
return len(b), nil
}
if !conn.br.Push(b, conn.id) {
return 0, &netError{errBridgeConnClosed, false, false}
}
return len(b), nil
}
// Close closes the bridge (releases resources used).
func (conn *bridgeConn) Close() error {
conn.mutex.Lock()
defer conn.mutex.Unlock()
if conn.closeReq {
return &netError{errBridgeAlreadyClosed, false, false}
}
conn.closeReq = true
conn.closing = true
return nil
}
// LocalAddr is not used
func (conn *bridgeConn) LocalAddr() net.Addr {
return bridgeConnAddr(conn.id)
}
// RemoteAddr is not used
func (conn *bridgeConn) RemoteAddr() net.Addr { return nil }
// SetDeadline sets deadline of Read/Write operation.
// Setting zero means no deadline.
func (conn *bridgeConn) SetDeadline(t time.Time) error {
conn.writeDeadline.Set(t)
conn.readDeadline.Set(t)
return nil
}
// SetReadDeadline sets deadline of Read operation.
// Setting zero means no deadline.
func (conn *bridgeConn) SetReadDeadline(t time.Time) error {
conn.readDeadline.Set(t)
return nil
}
// SetWriteDeadline sets deadline of Write operation.
// Setting zero means no deadline.
func (conn *bridgeConn) SetWriteDeadline(t time.Time) error {
conn.writeDeadline.Set(t)
return nil
}
func (conn *bridgeConn) isClosed() bool {
conn.mutex.RLock()
defer conn.mutex.RUnlock()
return conn.closed
}
// Bridge represents a network between the two endpoints.
type Bridge struct {
mutex sync.RWMutex
conn0 *bridgeConn
conn1 *bridgeConn
queue0to1 [][]byte
queue1to0 [][]byte
dropNWrites0 int
dropNWrites1 int
reorderNWrites0 int
reorderNWrites1 int
stack0 [][]byte
stack1 [][]byte
filterCB0 func([]byte) bool
filterCB1 func([]byte) bool
err error // last error
}
func inverse(s [][]byte) error {
if len(s) < 2 {
return errInverseArrayWithOne
}
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return nil
}
// drop n packets from the slice starting from offset
func drop(s [][]byte, offset, n int) [][]byte {
if offset+n > len(s) {
n = len(s) - offset
}
return append(s[:offset], s[offset+n:]...)
}
// NewBridge creates a new bridge with two endpoints.
func NewBridge() *Bridge {
br := &Bridge{
queue0to1: make([][]byte, 0),
queue1to0: make([][]byte, 0),
}
br.conn0 = &bridgeConn{
br: br,
id: 0,
readCh: make(chan []byte),
readDeadline: deadline.New(),
writeDeadline: deadline.New(),
}
br.conn1 = &bridgeConn{
br: br,
id: 1,
readCh: make(chan []byte),
readDeadline: deadline.New(),
writeDeadline: deadline.New(),
}
return br
}
// GetConn0 returns an endpoint of the bridge, conn0.
func (br *Bridge) GetConn0() net.Conn {
return br.conn0
}
// GetConn1 returns an endpoint of the bridge, conn1.
func (br *Bridge) GetConn1() net.Conn {
return br.conn1
}
// Len returns number of queued packets.
func (br *Bridge) Len(fromID int) int {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
return len(br.queue0to1)
}
return len(br.queue1to0)
}
// Push pushes a packet into the specified queue.
func (br *Bridge) Push(packet []byte, fromID int) bool { //nolint:gocognit
d := make([]byte, len(packet))
copy(d, packet)
// Push rate should be limited as same as Tick rate.
// Otherwise, queue grows too fast on free running Write.
time.Sleep(tickWait)
br.mutex.Lock()
defer br.mutex.Unlock()
br.conn0.mutex.Lock()
br.conn1.mutex.Lock()
closing0 := br.conn0.closing
closing1 := br.conn1.closing
br.conn1.mutex.Unlock()
br.conn0.mutex.Unlock()
if closing0 || closing1 {
if fromID == 0 && closing0 {
return false
}
if fromID == 1 && closing1 {
return false
}
return true
}
if fromID == 0 {
switch {
case br.dropNWrites0 > 0:
br.dropNWrites0--
// fmt.Printf("br: dropped a packet of size %d (rem: %d for q0)\n", len(d), br.dropNWrites0) // nolint
case br.reorderNWrites0 > 0:
br.reorderNWrites0--
br.stack0 = append(br.stack0, d)
// fmt.Printf("stack0 size: %d\n", len(br.stack0)) // nolint
if br.reorderNWrites0 == 0 {
if err := inverse(br.stack0); err == nil {
// fmt.Printf("stack0 reordered!\n") // nolint
br.queue0to1 = append(br.queue0to1, br.stack0...)
} else {
br.err = err
}
}
case br.filterCB0 != nil && !br.filterCB0(d):
// fmt.Printf("br: filtered out a packet of size %d (q0)\n", len(d)) // nolint
default:
// fmt.Printf("br: routed a packet of size %d (q0)\n", len(d)) // nolint
br.queue0to1 = append(br.queue0to1, d)
}
} else {
switch {
case br.dropNWrites1 > 0:
br.dropNWrites1--
// fmt.Printf("br: dropped a packet of size %d (rem: %d for q1)\n", len(d), br.dropNWrites0) // nolint
case br.reorderNWrites1 > 0:
br.reorderNWrites1--
br.stack1 = append(br.stack1, d)
if br.reorderNWrites1 == 0 {
if err := inverse(br.stack1); err != nil {
br.err = err
}
br.queue1to0 = append(br.queue1to0, br.stack1...)
}
case br.filterCB1 != nil && !br.filterCB1(d):
// fmt.Printf("br: filtered out a packet of size %d (q1)\n", len(d)) // nolint
default:
// fmt.Printf("br: routed a packet of size %d (q1)\n", len(d)) // nolint
br.queue1to0 = append(br.queue1to0, d)
}
}
return true
}
// Reorder inverses the order of packets currently in the specified queue.
func (br *Bridge) Reorder(fromID int) error {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
return inverse(br.queue0to1)
}
return inverse(br.queue1to0)
}
// Drop drops the specified number of packets from the given offset index
// of the specified queue.
func (br *Bridge) Drop(fromID, offset, n int) {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
br.queue0to1 = drop(br.queue0to1, offset, n)
} else {
br.queue1to0 = drop(br.queue1to0, offset, n)
}
}
// DropNextNWrites drops the next n packets that will be written
// to the specified queue.
func (br *Bridge) DropNextNWrites(fromID, n int) {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
br.dropNWrites0 = n
} else {
br.dropNWrites1 = n
}
}
// ReorderNextNWrites drops the next n packets that will be written
// to the specified queue.
func (br *Bridge) ReorderNextNWrites(fromID, n int) {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
br.reorderNWrites0 = n
} else {
br.reorderNWrites1 = n
}
}
func (br *Bridge) clear() {
br.mutex.Lock()
defer br.mutex.Unlock()
br.queue1to0 = nil
br.queue0to1 = nil
}
// Tick attempts to hand a packet from the queue for each directions, to readers,
// if there are waiting on the queue. If there's no reader, it will return
// immediately.
func (br *Bridge) Tick() int {
br.mutex.Lock()
defer br.mutex.Unlock()
br.conn0.mutex.Lock()
if br.conn0.closing && !br.conn0.closed && len(br.queue1to0) == 0 {
br.conn0.closed = true
close(br.conn0.readCh)
}
br.conn0.mutex.Unlock()
br.conn1.mutex.Lock()
if br.conn1.closing && !br.conn1.closed && len(br.queue0to1) == 0 {
br.conn1.closed = true
close(br.conn1.readCh)
}
br.conn1.mutex.Unlock()
var n int
if len(br.queue0to1) > 0 && !br.conn1.isClosed() {
select {
case br.conn1.readCh <- br.queue0to1[0]:
n++
// fmt.Printf("conn1 received data (%d bytes)\n", len(br.queue0to1[0])) // nolint
br.queue0to1 = br.queue0to1[1:]
default:
}
}
if len(br.queue1to0) > 0 && !br.conn0.isClosed() {
select {
case br.conn0.readCh <- br.queue1to0[0]:
n++
// fmt.Printf("conn0 received data (%d bytes)\n", len(br.queue1to0[0])) // nolint
br.queue1to0 = br.queue1to0[1:]
default:
}
}
return n
}
// Process repeats tick() calls until no more outstanding packet in the queues.
func (br *Bridge) Process() {
for {
time.Sleep(tickWait)
br.Tick()
if br.Len(0) == 0 && br.Len(1) == 0 {
break
}
}
}
// SetLossChance sets the probability of writes being discard (to introduce artificial loss)
func (br *Bridge) SetLossChance(chance int) error {
if chance > 100 || chance < 0 {
return errBadLossChanceRange
}
rand.Seed(time.Now().UTC().UnixNano())
br.conn0.lossChance = chance
br.conn1.lossChance = chance
return nil
}
// Filter filters (drops) packets based on return value of the given callback.
func (br *Bridge) Filter(fromID int, cb func([]byte) bool) {
br.mutex.Lock()
defer br.mutex.Unlock()
if fromID == 0 {
br.filterCB0 = cb
} else {
br.filterCB1 = cb
}
}