forked from pion/webrtc
/
association.go
602 lines (514 loc) · 16.5 KB
/
association.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
package sctp
import (
"bytes"
"fmt"
"sync"
"math"
"math/rand"
"time"
"github.com/pkg/errors"
)
// AssociationState is an enum for the states that an Association will transition
// through while connecting
// https://tools.ietf.org/html/rfc4960#section-13.2
type AssociationState uint8
// AssociationState enums
const (
Open AssociationState = iota + 1
CookieEchoed
CookieWait
Established
ShutdownAckSent
ShutdownPending
ShutdownReceived
ShutdownSent
)
func (a AssociationState) String() string {
switch a {
case Open:
return "Open"
case CookieEchoed:
return "CookieEchoed"
case CookieWait:
return "CookieWait"
case Established:
return "Established"
case ShutdownPending:
return "ShutdownPending"
case ShutdownSent:
return "ShutdownSent"
case ShutdownReceived:
return "ShutdownReceived"
case ShutdownAckSent:
return "ShutdownAckSent"
default:
return fmt.Sprintf("Invalid AssociationState %d", a)
}
}
// Association represents an SCTP association
// 13.2. Parameters Necessary per Association (i.e., the TCB)
// Peer : Tag value to be sent in every packet and is received
// Verification: in the INIT or INIT ACK chunk.
// Tag :
//
// My : Tag expected in every inbound packet and sent in the
// Verification: INIT or INIT ACK chunk.
//
// Tag :
// State : A state variable indicating what state the association
// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED,
// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED,
// : SHUTDOWN-ACK-SENT.
//
// Note: No "CLOSED" state is illustrated since if a
// association is "CLOSED" its TCB SHOULD be removed.
type Association struct {
sync.Mutex
peerVerificationTag uint32
myVerificationTag uint32
state AssociationState
//peerTransportList
//primaryPath
//overallErrorCount
//overallErrorThreshold
//peerReceiverWindow (peerRwnd)
myNextTSN uint32 // nextTSN
peerLastTSN uint32 // lastRcvdTSN
//peerMissingTSN (MappingArray)
//ackState
//inboundStreams
//outboundStreams
//reassemblyQueue
//localTransportAddressList
//associationPTMU
// Non-RFC internal data
sourcePort uint16
destinationPort uint16
myMaxNumInboundStreams uint16
myMaxNumOutboundStreams uint16
myReceiverWindowCredit uint32
myCookie *paramStateCookie
payloadQueue *payloadQueue
inflightQueue *payloadQueue
myMaxMTU uint16
peerCumulativeTSNAckPoint uint32
reassemblyQueue map[uint16]*reassemblyQueue
outboundStreams map[uint16]uint16
isInitiating bool
notifier func(AssociationState)
// TODO are these better as channels
// Put a blocking goroutine in port-receive (vs callbacks)
outboundHandler func([]byte)
dataHandler func([]byte, uint16, PayloadProtocolIdentifier)
}
// HandleInbound parses incoming raw packets
func (a *Association) HandleInbound(raw []byte) error {
p := &packet{}
if err := p.unmarshal(raw); err != nil {
return errors.Wrap(err, "Unable to parse SCTP packet")
}
if err := checkPacket(p); err != nil {
return errors.Wrap(err, "Failed validating packet")
}
for _, c := range p.chunks {
if err := a.handleChunk(p, c); err != nil {
return errors.Wrap(err, "Failed handling chunk")
}
}
return nil
}
func (a *Association) packetizeOutbound(raw []byte, streamIdentifier uint16, payloadType PayloadProtocolIdentifier) ([]*chunkPayloadData, error) {
if len(raw) > math.MaxUint16 {
return nil, errors.Errorf("Outbound packet larger than maximum message size %v", math.MaxUint16)
}
seqNum, ok := a.outboundStreams[streamIdentifier]
if !ok {
seqNum = 0
}
i := uint16(0)
remaining := uint16(len(raw))
var chunks []*chunkPayloadData
for remaining != 0 {
l := min(a.myMaxMTU, remaining)
chunks = append(chunks, &chunkPayloadData{
streamIdentifier: streamIdentifier,
userData: raw[i : i+l],
beginingFragment: i == 0,
endingFragment: remaining-l == 0,
immediateSack: false,
payloadType: payloadType,
streamSequenceNumber: seqNum,
tsn: a.myNextTSN,
})
a.myNextTSN++
remaining -= l
i += l
}
a.outboundStreams[streamIdentifier] = seqNum + 1
return chunks, nil
}
// HandleOutbound sends outbound raw packets
func (a *Association) HandleOutbound(raw []byte, streamIdentifier uint16, payloadType PayloadProtocolIdentifier) error {
chunks, err := a.packetizeOutbound(raw, streamIdentifier, payloadType)
if err != nil {
return errors.Wrap(err, "Unable to packetize outbound packet")
}
for _, c := range chunks {
// TODO: FIX THIS HACK, inflightQueue uses PayloadQueue which is really meant for inbound SACK generation
a.inflightQueue.pushNoCheck(c)
p := &packet{
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
verificationTag: a.peerVerificationTag,
chunks: []chunk{c}}
if err := a.send(p); err != nil {
return errors.Wrap(err, "Unable to send outbound packet")
}
}
return nil
}
// Close ends the SCTP Association and cleans up any state
func (a *Association) Close() error {
return nil
}
// NewAssocation creates a new Association and the state needed to manage it
func NewAssocation(outboundHandler func([]byte), dataHandler func([]byte, uint16, PayloadProtocolIdentifier), notifier func(AssociationState)) *Association {
rs := rand.NewSource(time.Now().UnixNano())
r := rand.New(rs)
tsn := r.Uint32()
return &Association{
myMaxNumOutboundStreams: math.MaxUint16,
myMaxNumInboundStreams: math.MaxUint16,
myReceiverWindowCredit: 10 * 1500, // 10 Max MTU packets buffer
payloadQueue: &payloadQueue{},
inflightQueue: &payloadQueue{},
myMaxMTU: 1200,
reassemblyQueue: make(map[uint16]*reassemblyQueue),
outboundStreams: make(map[uint16]uint16),
myVerificationTag: r.Uint32(),
myNextTSN: tsn,
outboundHandler: outboundHandler,
dataHandler: dataHandler,
state: Open,
notifier: notifier,
peerCumulativeTSNAckPoint: tsn - 1,
}
}
func checkPacket(p *packet) error {
// All packets must adhere to these rules
// This is the SCTP sender's port number. It can be used by the
// receiver in combination with the source IP address, the SCTP
// destination port, and possibly the destination IP address to
// identify the association to which this packet belongs. The port
// number 0 MUST NOT be used.
if p.sourcePort == 0 {
return errors.New("SCTP Packet must not have a source port of 0")
}
// This is the SCTP port number to which this packet is destined.
// The receiving host will use this port number to de-multiplex the
// SCTP packet to the correct receiving endpoint/application. The
// port number 0 MUST NOT be used.
if p.destinationPort == 0 {
return errors.New("SCTP Packet must not have a destination port of 0")
}
// Check values on the packet that are specific to a particular chunk type
for _, c := range p.chunks {
switch c.(type) {
case *chunkInit:
// An INIT or INIT ACK chunk MUST NOT be bundled with any other chunk.
// They MUST be the only chunks present in the SCTP packets that carry
// them.
if len(p.chunks) != 1 {
return errors.New("INIT chunk must not be bundled with any other chunk")
}
// A packet containing an INIT chunk MUST have a zero Verification
// Tag.
if p.verificationTag != 0 {
return errors.Errorf("INIT chunk expects a verification tag of 0 on the packet when out-of-the-blue")
}
}
}
return nil
}
func min(a, b uint16) uint16 {
if a < b {
return a
}
return b
}
// Start starts the Association
func (a *Association) Start(isInitiating bool) {
a.isInitiating = isInitiating
}
func (a *Association) setState(state AssociationState) {
if a.state != state {
a.state = state
if a.notifier != nil {
go a.notifier(state)
}
}
}
// Connect initiates the SCTP connection
func (a *Association) Connect() {
if a.isInitiating {
err := a.send(a.createInit())
if err != nil {
fmt.Printf("Failed to send init: %v", err)
}
a.setState(CookieWait)
}
}
func (a *Association) createInit() *packet {
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
a.sourcePort = 5000 // TODO: Spec??
a.destinationPort = 5000 // TODO: Spec??
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
init := &chunkInit{}
init.initialTSN = a.myNextTSN
init.numOutboundStreams = a.myMaxNumOutboundStreams
init.numInboundStreams = a.myMaxNumInboundStreams
init.initiateTag = a.myVerificationTag
init.advertisedReceiverWindowCredit = a.myReceiverWindowCredit
outbound.chunks = []chunk{init}
return outbound
}
func (a *Association) handleInit(p *packet, i *chunkInit) *packet {
// Should we be setting any of these permanently until we've ACKed further?
a.myMaxNumInboundStreams = min(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min(i.numOutboundStreams, a.myMaxNumOutboundStreams)
a.peerVerificationTag = i.initiateTag
a.sourcePort = p.destinationPort
a.destinationPort = p.sourcePort
// 13.2 This is the last TSN received in sequence. This value
// is set initially by taking the peer's initial TSN,
// received in the INIT or INIT ACK chunk, and
// subtracting one from it.
a.peerLastTSN = i.initialTSN - 1
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
initAck := &chunkInitAck{}
initAck.initialTSN = a.myNextTSN
initAck.numOutboundStreams = a.myMaxNumOutboundStreams
initAck.numInboundStreams = a.myMaxNumInboundStreams
initAck.initiateTag = a.myVerificationTag
initAck.advertisedReceiverWindowCredit = a.myReceiverWindowCredit
if a.myCookie == nil {
a.myCookie = newRandomStateCookie()
}
initAck.params = []param{a.myCookie}
outbound.chunks = []chunk{initAck}
return outbound
}
func (a *Association) handleInitAck(p *packet, i *chunkInitAck) (*packet, error) {
a.myMaxNumInboundStreams = min(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min(i.numOutboundStreams, a.myMaxNumOutboundStreams)
a.peerVerificationTag = i.initiateTag
a.peerLastTSN = i.initialTSN - 1
if a.sourcePort != p.destinationPort ||
a.destinationPort != p.sourcePort {
fmt.Println("handleInitAck: port mismatch")
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
var cookieParam *paramStateCookie
for _, param := range i.params {
switch v := param.(type) {
case *paramStateCookie:
cookieParam = v
}
}
if cookieParam == nil {
return nil, errors.New("no cookie in InitAck")
}
cookieEcho := &chunkCookieEcho{}
cookieEcho.cookie = cookieParam.cookie
outbound.chunks = []chunk{cookieEcho}
return outbound, nil
}
func (a *Association) handleData(d *chunkPayloadData) *packet {
a.payloadQueue.push(d, a.peerLastTSN)
pd, popOk := a.payloadQueue.pop(a.peerLastTSN + 1)
for popOk {
rq, ok := a.reassemblyQueue[pd.streamIdentifier]
if !ok {
// If this is the first time we've seen a stream identifier
// Expected SeqNum == 0
rq = &reassemblyQueue{}
a.reassemblyQueue[pd.streamIdentifier] = rq
}
rq.push(pd)
userData, ok := rq.pop()
if ok {
// We know the popped data will have the same stream
// identifier as the pushed data
a.dataHandler(userData, pd.streamIdentifier, pd.payloadType)
}
a.peerLastTSN++
pd, popOk = a.payloadQueue.pop(a.peerLastTSN)
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
sack := &chunkSelectiveAck{}
sack.cumulativeTSNAck = a.peerLastTSN
sack.advertisedReceiverWindowCredit = a.myReceiverWindowCredit
sack.duplicateTSN = a.payloadQueue.popDuplicates()
sack.gapAckBlocks = a.payloadQueue.getGapAckBlocks(a.peerLastTSN)
outbound.chunks = []chunk{sack}
return outbound
}
func (a *Association) handleSack(d *chunkSelectiveAck) ([]*packet, error) {
// i) If Cumulative TSN Ack is less than the Cumulative TSN Ack
// Point, then drop the SACK. Since Cumulative TSN Ack is
// monotonically increasing, a SACK whose Cumulative TSN Ack is
// less than the Cumulative TSN Ack Point indicates an out-of-
// order SACK.
// This is an old SACK, toss
if a.peerCumulativeTSNAckPoint >= d.cumulativeTSNAck {
return nil, errors.Errorf("SACK Cumulative ACK %v is older than ACK point %v",
d.cumulativeTSNAck, a.peerCumulativeTSNAckPoint)
}
// New ack point, so pop all ACKed packets from inflightQueue
// We add 1 because the "currentAckPoint" has already been popped from the inflight queue
// For the first SACK we take care of this by setting the ackpoint to cumAck - 1
for i := a.peerCumulativeTSNAckPoint + 1; i <= d.cumulativeTSNAck; i++ {
_, ok := a.inflightQueue.pop(i)
if !ok {
return nil, errors.Errorf("TSN %v unable to be popped from inflight queue", i)
}
}
a.peerCumulativeTSNAckPoint = d.cumulativeTSNAck
var sackDataPackets []*packet
var prevEnd uint16
for _, g := range d.gapAckBlocks {
for i := prevEnd + 1; i < g.start; i++ {
pp, ok := a.inflightQueue.get(d.cumulativeTSNAck + uint32(i))
if !ok {
return nil, errors.Errorf("Requested non-existent TSN %v", d.cumulativeTSNAck+uint32(i))
}
sackDataPackets = append(sackDataPackets, &packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{pp},
})
}
prevEnd = g.end
}
return sackDataPackets, nil
}
func (a *Association) send(p *packet) error {
raw, err := p.marshal()
if err != nil {
return errors.Wrap(err, "Failed to send packet to outbound handler")
}
a.outboundHandler(raw)
return nil
}
func (a *Association) handleChunk(p *packet, c chunk) error {
if _, err := c.check(); err != nil {
return errors.Wrap(err, "Failed validating chunk")
// TODO: Create ABORT
}
switch c := c.(type) {
case *chunkInit:
switch a.state {
case Open:
return a.send(a.handleInit(p, c))
case CookieEchoed:
// https://tools.ietf.org/html/rfc4960#section-5.2.1
// Upon receipt of an INIT in the COOKIE-ECHOED state, an endpoint MUST
// respond with an INIT ACK using the same parameters it sent in its
// original INIT chunk (including its Initiate Tag, unchanged)
return errors.Errorf("TODO respond with original cookie %s", a.state.String())
default:
// 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
// COOKIE-WAIT, and SHUTDOWN-ACK-SENT
return errors.Errorf("TODO Handle Init when in state %s", a.state.String())
}
case *chunkInitAck:
switch a.state {
case CookieWait:
r, err := a.handleInitAck(p, c)
if err != nil {
return err
}
err = a.send(r)
if err != nil {
return err
}
a.setState(CookieEchoed)
return nil
default:
return errors.Errorf("TODO Handle Init acks when in state %s", a.state.String())
}
case *chunkAbort:
fmt.Println("Abort chunk, with errors:")
for _, e := range c.errorCauses {
fmt.Printf("error cause: %s\n", e)
}
case *chunkHeartbeat:
hbi, ok := c.params[0].(*paramHeartbeatInfo)
if !ok {
fmt.Println("Failed to handle Heartbeat, no ParamHeartbeatInfo")
}
return a.send(&packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkHeartbeatAck{
params: []param{
¶mHeartbeatInfo{
heartbeatInformation: hbi.heartbeatInformation,
},
},
}},
})
case *chunkCookieEcho:
if bytes.Equal(a.myCookie.cookie, c.cookie) {
err := a.send(&packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkCookieAck{}},
})
if err != nil {
return err
}
a.setState(Established)
return nil
}
case *chunkCookieAck:
switch a.state {
case CookieEchoed:
a.setState(Established)
return nil
default:
return errors.Errorf("TODO Handle Init acks when in state %s", a.state.String())
}
// TODO Abort
case *chunkPayloadData:
return a.send(a.handleData(c))
case *chunkSelectiveAck:
p, err := a.handleSack(c)
if err != nil {
return errors.Wrap(err, "Failure handling SACK")
}
for _, pp := range p {
err := a.send(pp)
if err != nil {
return errors.Wrap(err, "Failure handling SACK")
}
}
default:
return errors.New("unhandled chunk type")
}
return nil
}