-
Notifications
You must be signed in to change notification settings - Fork 79
/
association.go
2064 lines (1738 loc) · 58.1 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
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sctp
import (
"bytes"
"fmt"
"io"
"math"
"math/rand"
"net"
"sync"
"sync/atomic"
"time"
"github.com/pion/logging"
"github.com/pkg/errors"
)
const (
receiveMTU uint32 = 8192 // MTU for inbound packet (from DTLS)
initialMTU uint32 = 1228 // initial MTU for outgoing packets (to DTLS)
maxReceiveBufferSize uint32 = 64 * 1024
commonHeaderSize uint32 = 12
dataChunkHeaderSize uint32 = 16
)
// association state enums
const (
closed uint32 = iota
cookieWait
cookieEchoed
established
shutdownAckSent
shutdownPending
shutdownReceived
shutdownSent
)
// retransmission timer IDs
const (
timerT1Init int = iota
timerT1Cookie
timerT3RTX
)
// ack mode (for testing)
const (
ackModeNormal int = iota
ackModeNoDelay
ackModeAlwaysDelay
)
// ack transmission state
const (
ackStateIdle int = iota
ackStateImmediate
ackStateDelay
)
// other constants
const (
acceptChSize = 16
)
func getAssociationStateString(a uint32) string {
switch a {
case closed:
return "Closed"
case cookieWait:
return "CookieWait"
case cookieEchoed:
return "CookieEchoed"
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 association state %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 {
bytesReceived uint64
bytesSent uint64
lock sync.RWMutex
netConn net.Conn
peerVerificationTag uint32
myVerificationTag uint32
state uint32
myNextTSN uint32 // nextTSN
peerLastTSN uint32 // lastRcvdTSN
minTSN2MeasureRTT uint32 // for RTT measurement
willRetransmitDataChunks bool
willSendForwardTSN bool
willRetransmitFast bool
// Reconfig
myNextRSN uint32
reconfigs map[uint32]*chunkReconfig
reconfigRequests map[uint32]*paramOutgoingResetRequest
// Non-RFC internal data
sourcePort uint16
destinationPort uint16
myMaxNumInboundStreams uint16
myMaxNumOutboundStreams uint16
myCookie *paramStateCookie
payloadQueue *payloadQueue
inflightQueue *payloadQueue
pendingQueue *pendingQueue
controlQueue *controlQueue
mtu uint32
maxPayloadSize uint32 // max DATA chunk payload size
cumulativeTSNAckPoint uint32
advancedPeerTSNAckPoint uint32
useForwardTSN bool
// Congestion control parameters
cwnd uint32 // my congestion window size
rwnd uint32 // calculated peer's receiver windows size
ssthresh uint32 // slow start threshold
partialBytesAcked uint32
inFastRecovery bool
fastRecoverExitPoint uint32
// RTX & Ack timer
rtoMgr *rtoManager
t1Init *rtxTimer
t1Cookie *rtxTimer
t3RTX *rtxTimer
ackTimer *ackTimer
// Chunks stored for retransmission
storedInit *chunkInit
storedCookieEcho *chunkCookieEcho
streams map[uint16]*Stream
acceptCh chan *Stream
readLoopCloseCh chan struct{}
awakeWriteLoopCh chan struct{}
closeWriteLoopCh chan struct{}
handshakeCompletedCh chan error
closeWriteLoopOnce sync.Once
// local error
silentError error
ackState int
ackMode int // for testing
// stats
stats *associationStats
name string
log logging.LeveledLogger
}
// Config collects the arguments to createAssociation construction into
// a single structure
type Config struct {
NetConn net.Conn
LoggerFactory logging.LoggerFactory
}
// Server accepts a SCTP stream over a conn
func Server(config Config) (*Association, error) {
a := createAssociation(config)
a.init(false)
select {
case err := <-a.handshakeCompletedCh:
if err != nil {
return nil, err
}
return a, nil
case <-a.readLoopCloseCh:
return nil, errors.Errorf("association closed before connecting")
}
}
// Client opens a SCTP stream over a conn
func Client(config Config) (*Association, error) {
a := createAssociation(config)
a.init(true)
select {
case err := <-a.handshakeCompletedCh:
if err != nil {
return nil, err
}
return a, nil
case <-a.readLoopCloseCh:
return nil, errors.Errorf("association closed before connecting")
}
}
func createAssociation(config Config) *Association {
rs := rand.NewSource(time.Now().UnixNano())
r := rand.New(rs)
tsn := r.Uint32()
a := &Association{
netConn: config.NetConn,
myMaxNumOutboundStreams: math.MaxUint16,
myMaxNumInboundStreams: math.MaxUint16,
payloadQueue: newPayloadQueue(),
inflightQueue: newPayloadQueue(),
pendingQueue: newPendingQueue(),
controlQueue: newControlQueue(),
mtu: initialMTU,
maxPayloadSize: initialMTU - (commonHeaderSize + dataChunkHeaderSize),
myVerificationTag: r.Uint32(),
myNextTSN: tsn,
myNextRSN: tsn,
minTSN2MeasureRTT: tsn,
state: closed,
rtoMgr: newRTOManager(),
streams: map[uint16]*Stream{},
reconfigs: map[uint32]*chunkReconfig{},
reconfigRequests: map[uint32]*paramOutgoingResetRequest{},
acceptCh: make(chan *Stream, acceptChSize),
readLoopCloseCh: make(chan struct{}),
awakeWriteLoopCh: make(chan struct{}, 1),
closeWriteLoopCh: make(chan struct{}),
handshakeCompletedCh: make(chan error),
cumulativeTSNAckPoint: tsn - 1,
advancedPeerTSNAckPoint: tsn - 1,
silentError: errors.Errorf("silently discard"),
stats: &associationStats{},
log: config.LoggerFactory.NewLogger("sctp"),
}
a.name = fmt.Sprintf("%p", a)
// RFC 4690 Sec 7.2.1
// o The initial cwnd before DATA transmission or after a sufficiently
// long idle period MUST be set to min(4*MTU, max (2*MTU, 4380
// bytes)).
a.cwnd = min32(4*a.mtu, max32(2*a.mtu, 4380))
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
a.t1Init = newRTXTimer(timerT1Init, a, maxInitRetrans)
a.t1Cookie = newRTXTimer(timerT1Cookie, a, maxInitRetrans)
a.t3RTX = newRTXTimer(timerT3RTX, a, noMaxRetrans) // retransmit forever
a.ackTimer = newAckTimer(a)
return a
}
func (a *Association) init(isClient bool) {
a.lock.Lock()
defer a.lock.Unlock()
go a.readLoop()
go a.writeLoop()
if isClient {
a.setState(cookieWait)
init := &chunkInit{}
init.initialTSN = a.myNextTSN
init.numOutboundStreams = a.myMaxNumOutboundStreams
init.numInboundStreams = a.myMaxNumInboundStreams
init.initiateTag = a.myVerificationTag
init.advertisedReceiverWindowCredit = maxReceiveBufferSize
setSupportedExtensions(&init.chunkInitCommon)
a.storedInit = init
err := a.sendInit()
if err != nil {
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
}
a.t1Init.start(a.rtoMgr.getRTO())
}
}
// caller must hold a.lock
func (a *Association) sendInit() error {
a.log.Debugf("[%s] sending INIT", a.name)
if a.storedInit == nil {
return errors.Errorf("the init not stored to send")
}
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
a.sourcePort = 5000 // TODO: Spec??
a.destinationPort = 5000 // TODO: Spec??
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
outbound.chunks = []chunk{a.storedInit}
a.controlQueue.push(outbound)
a.awakeWriteLoop()
return nil
}
// caller must hold a.lock
func (a *Association) sendCookieEcho() error {
if a.storedCookieEcho == nil {
return errors.Errorf("cookieEcho not stored to send")
}
a.log.Debugf("[%s] sending COOKIE-ECHO", a.name)
outbound := &packet{}
outbound.verificationTag = a.peerVerificationTag
outbound.sourcePort = a.sourcePort
outbound.destinationPort = a.destinationPort
outbound.chunks = []chunk{a.storedCookieEcho}
a.controlQueue.push(outbound)
a.awakeWriteLoop()
return nil
}
// Close ends the SCTP Association and cleans up any state
func (a *Association) Close() error {
a.log.Debugf("[%s] closing association..", a.name)
// TODO: shutdown sequence
a.setState(closed)
err := a.netConn.Close()
a.closeAllTimers()
// awake writeLoop to exit
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
// Wait for readLoop to end
<-a.readLoopCloseCh
a.log.Debugf("[%s] association closed", a.name)
a.log.Debugf("[%s] stats nDATAs (in) : %d", a.name, a.stats.getNumDATAs())
a.log.Debugf("[%s] stats nSACKs (in) : %d", a.name, a.stats.getNumSACKs())
a.log.Debugf("[%s] stats nT3Timeouts : %d", a.name, a.stats.getNumT3Timeouts())
a.log.Debugf("[%s] stats nAckTimeouts: %d", a.name, a.stats.getNumAckTimeouts())
a.log.Debugf("[%s] stats nFastRetrans: %d", a.name, a.stats.getNumFastRetrans())
return err
}
func (a *Association) closeAllTimers() {
// Close all retransmission & ack timers
a.t1Init.close()
a.t1Cookie.close()
a.t3RTX.close()
a.ackTimer.close()
}
func (a *Association) readLoop() {
var closeErr error
defer func() {
// also stop writeLoop, otherwise writeLoop can be leaked
// if connection is lost when there is no writing packet.
a.closeWriteLoopOnce.Do(func() { close(a.closeWriteLoopCh) })
a.lock.Lock()
for _, s := range a.streams {
a.unregisterStream(s, closeErr)
}
a.lock.Unlock()
close(a.acceptCh)
close(a.readLoopCloseCh)
}()
a.log.Debugf("[%s] readLoop entered", a.name)
for {
// buffer is recreated because the user data is
// passed to the reassembly queue without copying
buffer := make([]byte, receiveMTU)
n, err := a.netConn.Read(buffer)
if err != nil {
closeErr = err
break
}
atomic.AddUint64(&a.bytesReceived, uint64(n))
if err = a.handleInbound(buffer[:n]); err != nil {
a.log.Warnf("[%s] %s]", a.name, errors.Wrap(err, "failed to push SCTP packet").Error())
}
}
a.log.Debugf("[%s] readLoop exited", a.name)
}
func (a *Association) writeLoop() {
a.log.Debugf("[%s] writeLoop entered", a.name)
loop:
for {
rawPackets := a.gatherOutbound()
for _, raw := range rawPackets {
_, err := a.netConn.Write(raw)
if err != nil {
if err != io.EOF {
a.log.Warnf("[%s] failed to write packets on netConn: %v", a.name, err)
}
a.log.Debugf("[%s] writeLoop ended", a.name)
break loop
}
atomic.AddUint64(&a.bytesSent, uint64(len(raw)))
}
select {
case <-a.awakeWriteLoopCh:
case <-a.closeWriteLoopCh:
break loop
}
}
a.setState(closed)
a.closeAllTimers()
a.log.Debugf("[%s] writeLoop exited", a.name)
}
func (a *Association) awakeWriteLoop() {
select {
case a.awakeWriteLoopCh <- struct{}{}:
default:
}
}
// unregisterStream un-registers a stream from the association
// The caller should hold the association write lock.
func (a *Association) unregisterStream(s *Stream, err error) {
s.lock.Lock()
defer s.lock.Unlock()
delete(a.streams, s.streamIdentifier)
s.readErr = err
s.readNotifier.Broadcast()
}
// 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 {
err := a.handleChunk(p, c)
if err != nil {
return errors.Wrap(err, "failed handling chunk")
}
}
return nil
}
// handleOutbound handles outgoing processes
func (a *Association) gatherOutbound() [][]byte {
a.lock.Lock()
defer a.lock.Unlock()
rawPackets := [][]byte{}
if a.controlQueue.size() > 0 {
for _, p := range a.controlQueue.popAll() {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a control packet", a.name)
continue
}
rawPackets = append(rawPackets, raw)
}
}
state := a.getState()
if state == established {
if a.willRetransmitDataChunks {
a.willRetransmitDataChunks = false
for _, p := range a.getDataPacketsToRetransmit() {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet to be retransmitted", a.name)
continue
}
a.log.Debugf("[%s] retransmitting %d bytes", a.name, len(raw))
rawPackets = append(rawPackets, raw)
}
}
// Pop unsent data chunks from the pending queue to send as much as
// cwnd and rwnd allow.
chunks, sisToReset := a.popPendingDataChunksToSend()
if len(chunks) > 0 {
// Start timer. (noop if already started)
a.log.Tracef("[%s] T3-rtx timer start (pt1)", a.name)
a.t3RTX.start(a.rtoMgr.getRTO())
for _, p := range a.bundleDataChunksIntoPackets(chunks) {
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet", a.name)
continue
}
rawPackets = append(rawPackets, raw)
}
}
if len(sisToReset) > 0 {
rsn := a.generateNextRSN()
tsn := a.myNextTSN - 1
c := &chunkReconfig{
paramA: ¶mOutgoingResetRequest{
reconfigRequestSequenceNumber: rsn,
senderLastTSN: tsn,
streamIdentifiers: sisToReset,
},
}
a.reconfigs[rsn] = c // store in the map for retransmission
a.log.Debugf("[%s] sending RECONFIG: rsn=%d tsn=%d streams=%v",
a.name, rsn, a.myNextTSN-1, sisToReset)
p := a.createPacket([]chunk{c})
raw, err := p.marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a RECONFIG packet to be retransmitted", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
if a.willRetransmitFast {
a.willRetransmitFast = false
toFastRetrans := []chunk{}
fastRetransSize := commonHeaderSize
for i := 0; ; i++ {
c, ok := a.inflightQueue.get(a.cumulativeTSNAckPoint + uint32(i) + 1)
if !ok {
break // end of pending data
}
if c.acked || c.abandoned {
continue
}
if c.nSent > 1 || c.missIndicator < 3 {
continue
}
// RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports
// 3) Determine how many of the earliest (i.e., lowest TSN) DATA chunks
// marked for retransmission will fit into a single packet, subject
// to constraint of the path MTU of the destination transport
// address to which the packet is being sent. Call this value K.
// Retransmit those K DATA chunks in a single packet. When a Fast
// Retransmit is being performed, the sender SHOULD ignore the value
// of cwnd and SHOULD NOT delay retransmission for this single
// packet.
dataChunkSize := dataChunkHeaderSize + uint32(len(c.userData))
if a.mtu < fastRetransSize+dataChunkSize {
break
}
fastRetransSize += dataChunkSize
a.stats.incFastRetrans()
c.nSent++
a.checkPartialReliabilityStatus(c)
toFastRetrans = append(toFastRetrans, c)
a.log.Tracef("[%s] fast-retransmit: tsn=%d sent=%d htna=%d",
a.name, c.tsn, c.nSent, a.fastRecoverExitPoint)
}
if len(toFastRetrans) > 0 {
raw, err := a.createPacket(toFastRetrans).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a DATA packet to be fast-retransmitted", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
}
if a.ackState == ackStateImmediate {
a.ackState = ackStateIdle
sack := a.createSelectiveAckChunk()
raw, err := a.createPacket([]chunk{sack}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a SACK packet", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
if a.willSendForwardTSN {
a.willSendForwardTSN = false
if sna32GT(a.advancedPeerTSNAckPoint, a.cumulativeTSNAckPoint) {
fwdtsn := a.createForwardTSN()
raw, err := a.createPacket([]chunk{fwdtsn}).marshal()
if err != nil {
a.log.Warnf("[%s] failed to serialize a Forward TSN packet", a.name)
} else {
rawPackets = append(rawPackets, raw)
}
}
}
}
return rawPackets
}
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.Errorf("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.Errorf("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.Errorf("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 min16(a, b uint16) uint16 {
if a < b {
return a
}
return b
}
func max32(a, b uint32) uint32 {
if a > b {
return a
}
return b
}
func min32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
// setState atomically sets the state of the Association.
// The caller should hold the lock.
func (a *Association) setState(newState uint32) {
oldState := atomic.SwapUint32(&a.state, newState)
if newState != oldState {
a.log.Debugf("[%s] state change: '%s' => '%s'",
a.name,
getAssociationStateString(oldState),
getAssociationStateString(newState))
}
}
// getState atomically returns the state of the Association.
func (a *Association) getState() uint32 {
return atomic.LoadUint32(&a.state)
}
// BytesSent returns the number of bytes sent
func (a *Association) BytesSent() uint64 {
return atomic.LoadUint64(&a.bytesSent)
}
// BytesReceived returns the number of bytes received
func (a *Association) BytesReceived() uint64 {
return atomic.LoadUint64(&a.bytesReceived)
}
func setSupportedExtensions(init *chunkInitCommon) {
// TODO RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2
// An implementation supporting this (Supported Extensions Parameter)
// extension MUST list the ASCONF, the ASCONF-ACK, and the AUTH chunks
// in its INIT and INIT-ACK parameters.
init.params = append(init.params, ¶mSupportedExtensions{
ChunkTypes: []chunkType{ctReconfig, ctForwardTSN},
})
}
// The caller should hold the lock.
func (a *Association) handleInit(p *packet, i *chunkInit) ([]*packet, error) {
state := a.getState()
a.log.Debugf("[%s] chunkInit received in state '%s'", a.name, getAssociationStateString(state))
// https://tools.ietf.org/html/rfc4960#section-5.2.1
// Upon receipt of an INIT in the COOKIE-WAIT 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). When
// responding, the endpoint MUST send the INIT ACK back to the same
// address that the original INIT (sent by this endpoint) was sent.
// 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)
if state != closed && state != cookieWait && state != cookieEchoed {
// 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED,
// COOKIE-WAIT, and SHUTDOWN-ACK-SENT
return nil, errors.Errorf("todo: handle Init when in state %s", getAssociationStateString(state))
}
// Should we be setting any of these permanently until we've ACKed further?
a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min16(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 = maxReceiveBufferSize
if a.myCookie == nil {
a.myCookie = newRandomStateCookie()
}
initAck.params = []param{a.myCookie}
setSupportedExtensions(&initAck.chunkInitCommon)
outbound.chunks = []chunk{initAck}
return pack(outbound), nil
}
// The caller should hold the lock.
func (a *Association) handleInitAck(p *packet, i *chunkInitAck) error {
state := a.getState()
a.log.Debugf("[%s] chunkInitAck received in state '%s'", a.name, getAssociationStateString(state))
if state != cookieWait {
// RFC 4960
// 5.2.3. Unexpected INIT ACK
// If an INIT ACK is received by an endpoint in any state other than the
// COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk.
// An unexpected INIT ACK usually indicates the processing of an old or
// duplicated INIT chunk.
return nil
}
a.myMaxNumInboundStreams = min16(i.numInboundStreams, a.myMaxNumInboundStreams)
a.myMaxNumOutboundStreams = min16(i.numOutboundStreams, a.myMaxNumOutboundStreams)
a.peerVerificationTag = i.initiateTag
a.peerLastTSN = i.initialTSN - 1
if a.sourcePort != p.destinationPort ||
a.destinationPort != p.sourcePort {
a.log.Warnf("[%s] handleInitAck: port mismatch", a.name)
return nil
}
a.rwnd = i.advertisedReceiverWindowCredit
a.log.Debugf("[%s] initial rwnd=%d", a.name, a.rwnd)
// RFC 4690 Sec 7.2.1
// o The initial value of ssthresh MAY be arbitrarily high (for
// example, implementations MAY use the size of the receiver
// advertised window).
a.ssthresh = a.rwnd
a.log.Tracef("[%s] updated cwnd=%d ssthresh=%d inflight=%d (INI)",
a.name, a.cwnd, a.ssthresh, a.inflightQueue.getNumBytes())
a.t1Init.stop()
a.storedInit = nil
var cookieParam *paramStateCookie
for _, param := range i.params {
switch v := param.(type) {
case *paramStateCookie:
cookieParam = v
case *paramSupportedExtensions:
for _, t := range v.ChunkTypes {
if t == ctForwardTSN {
a.useForwardTSN = true
}
}
}
}
if cookieParam == nil {
return errors.Errorf("no cookie in InitAck")
}
a.storedCookieEcho = &chunkCookieEcho{}
a.storedCookieEcho.cookie = cookieParam.cookie
err := a.sendCookieEcho()
if err != nil {
a.log.Errorf("[%s] failed to send init: %s", a.name, err.Error())
}
a.t1Cookie.start(a.rtoMgr.getRTO())
a.setState(cookieEchoed)
return nil
}
// The caller should hold the lock.
func (a *Association) handleHeartbeat(c *chunkHeartbeat) []*packet {
a.log.Tracef("[%s] chunkHeartbeat", a.name)
hbi, ok := c.params[0].(*paramHeartbeatInfo)
if !ok {
a.log.Warnf("[%s] failed to handle Heartbeat, no ParamHeartbeatInfo", a.name)
}
return pack(&packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkHeartbeatAck{
params: []param{
¶mHeartbeatInfo{
heartbeatInformation: hbi.heartbeatInformation,
},
},
}},
})
}
// The caller should hold the lock.
func (a *Association) handleCookieEcho(c *chunkCookieEcho) []*packet {
state := a.getState()
a.log.Debugf("[%s] COOKIE-ECHO received in state '%s'", a.name, getAssociationStateString(state))
if state != closed && state != cookieWait && state != cookieEchoed {
return nil
}
if !bytes.Equal(a.myCookie.cookie, c.cookie) {
return nil
}
a.t1Init.stop()
a.storedInit = nil
a.t1Cookie.stop()
a.storedCookieEcho = nil
p := &packet{
verificationTag: a.peerVerificationTag,
sourcePort: a.sourcePort,
destinationPort: a.destinationPort,
chunks: []chunk{&chunkCookieAck{}},
}
a.setState(established)
a.handshakeCompletedCh <- nil
return pack(p)
}
// The caller should hold the lock.
func (a *Association) handleCookieAck() []*packet {
state := a.getState()
a.log.Debugf("[%s] COOKIE-ACK received in state '%s'", a.name, getAssociationStateString(state))
if state != cookieEchoed {
// RFC 4960
// 5.2.5. Handle Duplicate COOKIE-ACK.
// At any state other than COOKIE-ECHOED, an endpoint should silently
// discard a received COOKIE ACK chunk.
return nil
}
a.t1Cookie.stop()
a.storedCookieEcho = nil
a.setState(established)
a.handshakeCompletedCh <- nil
return nil
}
// The caller should hold the lock.
func (a *Association) handleData(d *chunkPayloadData) []*packet {
a.log.Tracef("[%s] DATA: tsn=%d immediateSack=%v len=%d",
a.name, d.tsn, d.immediateSack, len(d.userData))
a.stats.incDATAs()
canPush := a.payloadQueue.canPush(d, a.peerLastTSN)
if canPush {
if a.getMyReceiverWindowCredit() > 0 {
s := a.getOrCreateStream(d.streamIdentifier)
if s == nil {
// silentely discard the data. (sender will retry on T3-rtx timeout)
// see pion/sctp#30
return nil
}
// Pass the new chunk to stream level as soon as it arrives
a.payloadQueue.push(d, a.peerLastTSN)
s.handleData(d)
} else {
a.log.Debugf("[%s] receive buffer full. dropping DATA with tsn=%d", a.name, d.tsn)
}
}
reply := []*packet{}
// Try to advance peerLastTSN
for {
if _, popOk := a.payloadQueue.pop(a.peerLastTSN + 1); !popOk {
break
}
a.peerLastTSN++
for _, rstReq := range a.reconfigRequests {
resp := a.resetStreams(rstReq)
if resp != nil {
a.log.Debugf("[%s] RESET RESPONSE: %+v", a.name, resp)
reply = append(reply, resp)
}
}
}
hasPacketLoss := (a.payloadQueue.size() > 0)
if hasPacketLoss {
a.log.Tracef("[%s] packetloss: %s", a.name, a.payloadQueue.getGapAckBlocksString(a.peerLastTSN))
}
if (a.ackState != ackStateImmediate && !d.immediateSack && !hasPacketLoss && a.ackMode == ackModeNormal) || a.ackMode == ackModeAlwaysDelay {
// Will send delayed ack in the next ack timeout
a.ackState = ackStateDelay
a.ackTimer.start()
} else {
// Send SACK now!
a.ackState = ackStateImmediate