-
Notifications
You must be signed in to change notification settings - Fork 10
/
association.js
1945 lines (1786 loc) · 64.2 KB
/
association.js
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
const crypto = require('crypto')
const EventEmitter = require('events').EventEmitter
const debug = require('debug')
const ip = require('ip')
const Chunk = require('./chunk')
const defs = require('./defs')
const SN = require('./serial')
const Reassembly = require('./reassembly')
class Association extends EventEmitter {
constructor (endpoint, options) {
super()
this.state = 'CLOSED'
this.endpoint = endpoint
this.localPort = endpoint.localPort
this.remoteAddress = options.remoteAddress || undefined
this.remotePort = options.remotePort
this.my_tag = options.my_tag || crypto.randomBytes(4).readUInt32BE(0)
this.a_rwnd = options.a_rwnd || endpoint.a_rwnd || defs.NET_SCTP.RWND
this.OS = options.OS
this.MIS = options.MIS
this.debugger = {}
const label = `[${this.localPort}/${this.remoteAddress}:${this.remotePort}]`
this.debugger.warn = debug(`sctp:assoc:### ${label}`)
this.debugger.info = debug(`sctp:assoc:## ${label}`)
this.debugger.debug = debug(`sctp:assoc:# ${label}`)
this.debugger.trace = debug(`sctp:assoc: ${label}`)
this.debugger.debug('create association')
// TODO provide also good way to iterate
const key = this.remoteAddress + ':' + this.remotePort
endpoint.associations_lookup[key] = this
endpoint.associations.push(this)
this.reassembly = new Reassembly({
rwnd: this.a_rwnd
})
this.reassembly.on('data', (buffer, stream, ppid) => {
this._deliver(buffer, stream, ppid)
})
this.rto_initial = defs.NET_SCTP.rto_initial
this.rto_min = defs.NET_SCTP.rto_min
this.rto_max = defs.NET_SCTP.rto_max
const PMTU = defs.NET_SCTP.PMTU || 1500 // TODO
this.peer_rwnd = 0
// TODO: for each remote address if multi-homing
this.sack_timeout = defs.NET_SCTP.sack_timeout
this.sack_freq = defs.NET_SCTP.sack_freq
this.hb_interval = defs.NET_SCTP.hb_interval
this.flightsize = 0
// 13.3. Per Transport Address Data
this.default_address_data = {
active: false,
errors: 0,
error_threshold: 10,
cwnd: Math.min(4 * PMTU, Math.max(2 * PMTU, 4380)), // 7.2.1. Slow-Start
RTO: this.rto_initial,
SRTT: 0,
RTTVAR: 0,
PMTU,
rtoPending: false // RTO-Pending
}
Object.assign(this, this.default_address_data) // TODO
this.destinations = {}
if (this.remoteAddress) {
this.destinations[this.remoteAddress] = this.default_address_data
}
this.my_next_tsn = new SN(this.my_tag)
this.HTNA = this.my_next_tsn.copy()
this.bundling = 0
this.sacks = 0
this.ssn = []
this.fastRecovery = false
this.readBuffer = []
this.everSentSack = false
this.packetsSinceLastSack = 0
this.queue = []
this.sent = {}
this.countRcv = 0
this.nonces = {}
this.mute = false // If received ABORT chunk
this.drainCallback = null
this.on('data', this.onData.bind(this))
this.on('sack', this.onSack.bind(this))
this.on('init', this.onInit.bind(this))
this.on('init_ack', this.onInitAck.bind(this))
this.on('heartbeat', this.onHeartbeat.bind(this))
this.on('heartbeat_ack', this.onHeartbeatAck.bind(this))
this.on('cookie_echo', this.onCookieEcho.bind(this))
this.on('cookie_ack', this.onCookieAck.bind(this))
this.on('shutdown', this.onShutdown.bind(this))
this.on('shutdown_ack', this.onShutdownAck.bind(this))
this.on('shutdown_complete', this.onShutdownComplete.bind(this))
this.on('error', this.onError.bind(this))
this.on('abort', this.onAbort.bind(this))
this.on('icmp', this.onICMP.bind(this))
}
acceptRemote (chunk) {
if (!chunk) {
throw new Error('peer init chunk not provided')
}
this.debugger.debug('accept remote association with chunk %O', chunk)
this._updatePeer(chunk)
/*
TODO
A COOKIE ACK MAY be sent to an UNCONFIRMED address,
but it MUST be bundled with a HEARTBEAT including a nonce.
An implementation that does NOT support bundling
MUST NOT send a COOKIE ACK to an UNCONFIRMED address.
2) For the receiver of the COOKIE ECHO,
the only CONFIRMED address is the one to which the INIT-ACK was sent.
*/
this._up()
this._sendChunk('cookie_ack', {})
}
onInit (chunk, src, header) {
this.debugger.warn('rfc4960 "5.2.2. Unexpected INIT ...', this.state, chunk, src, header)
// TODO restart association
/*
Before responding, the endpoint MUST check to see if the
unexpected INIT adds new addresses to the association. If new
addresses are added to the association, the endpoint MUST respond
with an ABORT, copying the 'Initiate Tag' of the unexpected INIT into
the 'Verification Tag' of the outbound packet carrying the ABORT. In
the ABORT response, the cause of error MAY be set to 'restart of an
association with new addresses'. The error SHOULD list the addresses
that were added to the restarting association.
*/
if (chunk.ipv4_address) {
// TODO check if addresses are really new. now is a placeholder
let abort = new Chunk('abort', {})
// we MUST copy initiate_tag, so use low-level endpoint function to send packet
this.endpoint._sendPacket(
src,
this.remotePort,
chunk.initiate_tag,
[abort.toBuffer()],
() => {
this.debugger.info('responded with an ABORT')
}
)
}
}
onCookieEcho (chunk, src, header) {
this.debugger.warn(
'Handle a COOKIE ECHO when a TCB Exists',
this.state,
chunk
)
const cookieData = this.endpoint.validateCookie(chunk.cookie, header)
let initChunk
if (cookieData) {
this.debugger.trace('cookie is valid %O', cookieData)
initChunk = Chunk.fromBuffer(cookieData.initChunk)
}
this.debugger.debug('association my_tag %d peer_tag %d, cookie my_tag %d peer_tag %d',
this.my_tag, this.peer_tag, cookieData.my_tag, initChunk.initiate_tag)
let action = ''
if (this.my_tag === cookieData.my_tag) {
// B or D
if (this.peer_tag === initChunk.initiate_tag) {
action = 'D'
} else {
action = 'B'
}
} else if (this.peer_tag === initChunk.initiate_tag) {
// TODO tmp, implement tie-tags
const tieTagsUnknown = true
if (tieTagsUnknown) {
action = 'C'
}
} else {
// TODO tmp, implement tie-tags
const tieTagsMatch = true
if (tieTagsMatch) {
action = 'A'
}
}
this.debugger.warn('COOKIE ECHO action', action)
switch (action) {
case 'A':
/*
TODO tie-tags
TODO SHUTDOWN-ACK-SENT state
A) In this case, the peer may have restarted. When the endpoint
recognizes this potential 'restart', the existing session is
treated the same as if it received an ABORT followed by a new
COOKIE ECHO with the following exceptions:
- Any SCTP DATA chunks MAY be retained (this is an
implementation-specific option).
- A notification of RESTART SHOULD be sent to the ULP instead of
a "COMMUNICATION LOST" notification.
All the congestion control parameters (e.g., cwnd, ssthresh)
related to this peer MUST be reset to their initial values (see
Section 6.2.1).
After this, the endpoint shall enter the ESTABLISHED state.
If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes
that the peer has restarted (Action A), it MUST NOT set up a new
association but instead resend the SHUTDOWN ACK and send an ERROR
chunk with a "Cookie Received While Shutting Down" error cause to
its peer.
*/
if (this.state === 'SHUTDOWN-ACK-SENT') {
this._sendChunk('shutdown_ack', {}, src, () => {
this.debugger.info('sent shutdown_ack')
})
return
}
// TODO
this.debugger.warn('association restart is not implemented and was not tested!')
this.emit('RESTART')
break
case 'B':
/*
TODO init collision
B) In this case, both sides may be attempting to start an association
at about the same time, but the peer endpoint started its INIT
after responding to the local endpoint's INIT. Thus, it may have
picked a new Verification Tag, not being aware of the previous tag
it had sent this endpoint. The endpoint should stay in or enter
the ESTABLISHED state, but it MUST update its peer's Verification
Tag from the State Cookie, stop any init or cookie timers that may
be running, and send a COOKIE ACK.
*/
this.peer_tag = initChunk.initiate_tag
// TODO stop init & cookie timers
this._sendChunk('cookie_ack')
break
case 'C':
/*
C) In this case, the local endpoint's cookie has arrived late.
Before it arrived, the local endpoint sent an INIT and received an
INIT ACK and finally sent a COOKIE ECHO with the peer's same tag
but a new tag of its own. The cookie should be silently
discarded. The endpoint SHOULD NOT change states and should leave
any timers running.
*/
break
case 'D':
/*
D) When both local and remote tags match, the endpoint should enter
the ESTABLISHED state, if it is in the COOKIE-ECHOED state. It
should stop any cookie timer that may be running and send a COOKIE ACK.
*/
if (this.state === 'COOKIE-ECHOED') {
this.state = 'ESTABLISHED'
}
// TODO should be already running, state also be ESTABLISHED
// this._enableHeartbeat()
// TODO stop cookie timer
this.debugger.warn('COOKIE ECHO send cookie_ack')
this._sendChunk('cookie_ack')
break
default:
/*
Note: For any case not shown in Table 2,
the cookie should be silently discarded
*/
}
}
onICMP (packet, code) {
/*
An implementation MAY ignore any ICMPv4 messages where the code
does not indicate "Protocol Unreachable" or "Fragmentation Needed".
*/
this.debugger.warn('< received ICMP code %d', code)
if (packet.v_tag && packet.v_tag !== this.peer_tag) {
return
}
if (code === 4) {
if (packet.v_tag === 0 && packet.chunks.length === 1) {
const chunk = packet.chunks[0]
if (chunk.chunkType === 'init' && chunk.initiate_tag === this.my_tag) {
this.debugger.warn('< ICMP fragmentation needed')
// TODO process this information as defined for PATH MTU discovery
}
}
} else {
this.debugger.warn('< ICMP signals that peer unreachable')
this.emit('COMMUNICATION LOST')
this._destroy()
}
}
onData (chunk, source) {
this.countRcv++
this.debugger.debug('< DATA %d, total: %d', chunk.tsn, this.countRcv)
if (!(this.state === 'ESTABLISHED' ||
this.state === 'SHUTDOWN-PENDING' ||
this.state === 'SHUTDOWN-SENT'
)) {
return
}
if (!chunk.user_data || !chunk.user_data.length > 0) {
this.debugger.warn('< received empty DATA chunk %o', chunk)
this._abort({ error_causes: [{ cause: 'NO_USER_DATA', tsn: chunk.tsn }] }, source)
return
}
const dataAccepted = this.reassembly.process(chunk)
if (this.state === 'SHUTDOWN-SENT') {
/*
While in the SHUTDOWN-SENT state, the SHUTDOWN sender MUST
immediately respond to each received packet containing one or more
DATA chunks with a SHUTDOWN chunk and restart the T2-shutdown timer.
If a SHUTDOWN chunk by itself cannot acknowledge all of the received
DATA chunks (i.e., there are TSNs that can be acknowledged that are
larger than the cumulative TSN, and thus gaps exist in the TSN
sequence), or if duplicate TSNs have been received, then a SACK chunk
MUST also be sent.
*/
this.debugger.trace('we are in the SHUTDOWN-SENT state - repeat SHUTDOWN')
this._sendChunk('shutdown', { c_tsn_ack: this.reassembly.peer_c_tsn.number })
if (!this.reassembly.have_gaps && this.duplicates.length === 0) {
return
}
}
/*
The guidelines on delayed acknowledgement algorithm specified in
Section 4.2 of [RFC2581] SHOULD be followed. Specifically, an
acknowledgement SHOULD be generated for at least every second packet
(not every second DATA chunk) received, and SHOULD be generated
within 200 ms of the arrival of any unacknowledged DATA chunk. In
some situations, it may be beneficial for an SCTP transmitter to be
more conservative than the algorithms detailed in this document
allow. However, an SCTP transmitter MUST NOT be more aggressive than
the following algorithms allow.
*/
if (!chunk.last_in_packet) {
/*
An SCTP receiver MUST NOT generate more than one SACK for every
incoming packet, other than to update the offered window as the
receiving application consumes new data.
*/
// TODO sacks on data consumption?
return
}
let immediately = false
if (dataAccepted) {
if (++this.packetsSinceLastSack >= this.sack_freq) {
immediately = true
}
}
if (!this.everSentSack) {
/*
After the reception of the first DATA chunk in an association the
endpoint MUST immediately respond with a SACK to acknowledge the DATA
chunk. Subsequent acknowledgements should be done as described in
Section 6.2.
*/
immediately = true
}
if (this.reassembly.have_gaps) {
/*
If the endpoint detects a gap in the received DATA chunk sequence,
it SHOULD send a SACK with Gap Ack Blocks immediately.
*/
immediately = true
}
if (this.reassembly.duplicates.length > 0) {
/*
When a packet arrives with duplicate DATA chunk(s) and with no new
DATA chunk(s), the endpoint MUST immediately send a SACK with no delay.
*/
immediately = true
}
if (!dataAccepted) {
/*
In either case, if such a DATA chunk is dropped, the
receiver MUST immediately send back a SACK with the current receive
window showing only DATA chunks received and accepted so far.
*/
immediately = true
}
if (immediately) {
// For all such we do sack immediately
this.debugger.trace('SACK immediately')
// Serves to group sack sending for chunks in packet
this.sacks++
this._sack()
} else {
this.scheduleSack()
}
}
scheduleSack () {
if (this._sack_timer) {
this.debugger.trace('SACK timer already set')
} else {
this.debugger.trace('SACK timer set', this.sack_timeout)
this._sack_timer = setTimeout(() => {
this.debugger.trace('SACK timer expired', this.sack_timeout)
this._sack()
}, this.sack_timeout)
}
}
onSack (chunk) {
this.debugger.trace('< sack c_tsn %d, peer_rwnd %d', chunk.c_tsn_ack, chunk.a_rwnd)
/*
A SACK MUST be processed in ESTABLISHED, SHUTDOWN-PENDING, and
SHUTDOWN-RECEIVED. An incoming SACK MAY be processed in COOKIE-
ECHOED. A SACK in the CLOSED state is out of the blue and SHOULD be
processed according to the rules in Section 8.4. A SACK chunk
received in any other state SHOULD be discarded.
*/
if (
!(
this.state === 'ESTABLISHED' ||
this.state === 'SHUTDOWN-PENDING' ||
this.state === 'SHUTDOWN-RECEIVED' ||
this.state === 'COOKIE-ECHOED'
)
) {
return
}
// TODO 'PROTOCOL_VIOLATION' The cumulative tsn ack beyond the max tsn currently sent
// This.debugger.warn('< sack %O', chunk)
this.peer_rwnd = chunk.a_rwnd
const cTSN = new SN(chunk.c_tsn_ack)
const ackAdvanced = this.c_tsn_ack ? cTSN.gt(this.c_tsn_ack) : true
this.c_tsn_ack = cTSN.copy()
if (this.fastRecovery && cTSN.ge(this.fastRecoveryExitPoint)) {
this.fastRecovery = false
this.fastRecoveryExitPoint = null
}
const flightsize = this.flightsize
for (const tsn in this.sent) {
const TSN = new SN(tsn)
if (TSN.le(this.c_tsn_ack)) {
// this.debugger.trace('acknowledge tsn %d, flightsize %d', tsn, flightsize)
this._acknowledge(TSN)
}
}
if (this.drainCallback && this.drain()) {
this.debugger.debug('drain callback c_tsn %d, peer_rwnd %d', chunk.c_tsn_ack, chunk.peer_rwnd)
this.drainCallback()
delete this.drainCallback
}
if (
chunk.sack_info &&
chunk.sack_info.gap_blocks &&
chunk.sack_info.gap_blocks.length > 0
) {
const gapBlocks = chunk.sack_info.gap_blocks
this.debugger.trace('< gap blocks ', chunk.c_tsn_ack, gapBlocks)
/*
Whenever an endpoint receives a SACK that indicates that some TSNs
are missing, it SHOULD wait for two further miss indications (via
subsequent SACKs for a total of three missing reports) on the same
TSNs before taking action with regard to Fast Retransmit.
*/
const absent = []
gapBlocks.forEach((block, idx) => {
// TODO rewrite with SN api
absent.push({
start: new SN(idx ? chunk.c_tsn_ack + gapBlocks[idx - 1].finish + 1 : chunk.c_tsn_ack + 1),
finish: new SN(chunk.c_tsn_ack + block.start - 1)
})
for (
let t = this.c_tsn_ack.copy().inc(block.start);
t.le(this.c_tsn_ack.copy().inc(block.finish));
t.inc(1)
) {
if (this.sent[t.getNumber()]) {
this._acknowledge(t)
}
}
})
// 7.2.4. Fast Retransmit on Gap Reports
/*
Whenever an endpoint receives a SACK that indicates that some TSNs
are missing, it SHOULD wait for two further miss indications (via
subsequent SACKs for a total of three missing reports) on the same
TSNs before taking action with regard to Fast Retransmit.
*/
let doFastRetransmit = false
absent.forEach(block => {
for (let TSN = block.start.copy(); TSN.le(block.finish); TSN.inc(1)) {
const tsn = TSN.getNumber()
if (this.sent[tsn]) {
/*
Miss indications SHOULD follow the HTNA (Highest TSN Newly
Acknowledged) algorithm. For each incoming SACK, miss indications
are incremented only for missing TSNs prior to the highest TSN newly
acknowledged in the SACK. A newly acknowledged DATA chunk is one not
previously acknowledged in a SACK. If an endpoint is in Fast
Recovery and a SACK arrives that advances the Cumulative TSN Ack
Point, the miss indications are incremented for all TSNs reported
missing in the SACK.
*/
this.debugger.trace(
'fast retransmit %d ? HTNA %d, fast recovery %s, ack advanced %s',
tsn,
this.HTNA.number,
this.fastRecovery,
ackAdvanced
)
if (TSN.lt(this.HTNA) || (this.fastRecovery && ackAdvanced)) {
this.sent[tsn].losses++
this.debugger.trace(
'increase miss indications for %d to %d',
tsn,
this.sent[tsn].losses
)
if (this.sent[tsn].losses >= 3) {
/*
Mark the DATA chunk(s) with three miss indications for
retransmission.
A straightforward implementation of the above keeps a counter for
each TSN hole reported by a SACK. The counter increments for each
consecutive SACK reporting the TSN hole. After reaching 3 and
starting the Fast-Retransmit procedure, the counter resets to 0.
*/
this.sent[tsn].losses = 0
this.sent[tsn].fastRetransmit = true
doFastRetransmit = true
}
}
}
}
})
if (doFastRetransmit) {
this._fastRetransmit()
}
/*
Whenever a SACK is received missing a TSN that was previously
acknowledged via a Gap Ack Block, start the T3-rtx for the
destination address to which the DATA chunk was originally
transmitted if it is not already running.
*/
} else if (this.my_next_tsn.eq(this.c_tsn_ack.copy().inc(1))) {
/*
Whenever all outstanding data sent to an address have been
acknowledged, turn off the T3-rtx timer of that address.
*/
this.flightsize = 0
this.debugger.trace('all outstanding data has been acknowledged')
this._stopT3()
if (this.state === 'SHUTDOWN-PENDING') {
this._shutdown()
return
}
}
if (chunk.sack_info && chunk.sack_info.duplicate_tsn &&
chunk.sack_info.duplicate_tsn.length > 0) {
this.debugger.trace('peer indicates duplicates %o', chunk.sack_info.duplicate_tsn)
}
if (ackAdvanced && this.flightsize) {
/*
When cwnd is less than or equal to ssthresh, an SCTP endpoint MUST
use the slow-start algorithm to increase cwnd only if the current
congestion window is being fully utilized, an incoming SACK
advances the Cumulative TSN Ack Point, and the data sender is not
in Fast Recovery. Only when these three conditions are met can
the cwnd be increased; otherwise, the cwnd MUST not be increased.
If these conditions are met, then cwnd MUST be increased by, at
most, the lesser of 1) the total size of the previously
outstanding DATA chunk(s) acknowledged, and 2) the destination's
path MTU. This upper bound protects against the ACK-Splitting
attack outlined in [SAVAGE99].
*/
// TODO: rule to increase cwnd is unclear to me
if (this.cwnd <= this.ssthresh && this.cwnd <= this.flightsize && !this.fastRecovery) {
const totalAcknowledgedSize = flightsize - this.flightsize
const cwndIncrease = Math.min(totalAcknowledgedSize, this.PMTU)
const previousCwnd = this.cwnd
this.cwnd += cwndIncrease
this.debugger.debug('increase cwnd +%d from %d to %d, ssthresh %d',
cwndIncrease, previousCwnd, this.cwnd, this.ssthresh)
}
/*
Whenever a SACK is received that acknowledges the DATA chunk
with the earliest outstanding TSN for that address, restart the
T3-rtx timer for that address with its current RTO (if there is
still outstanding data on that address).
*/
this.debugger.trace('c_tsn_ack advanced to %d', this.c_tsn_ack.number)
this._restartT3()
}
if (this.flightsize > 0 && this.flightsize < this.cwnd) {
this.debugger.trace('flightsize %d < cwnd %d', this.flightsize, this.cwnd)
this._retransmit()
}
}
onInitAck (chunk, source) {
if (this.state === 'COOKIE-WAIT') {
this.debugger.debug('< init_ack cookie', chunk.state_cookie)
clearTimeout(this.T1)
if (chunk.inbound_streams === 0) {
// Receiver of an INIT ACK with the MIS value set to 0
// SHOULD destroy the association discarding its TCB
this._abort({ error_causes: [{ cause: 'INVALID_MANDATORY_PARAMETER' }] }, source)
return
}
this._updatePeer(chunk)
this._sendChunk('cookie_echo', { cookie: chunk.state_cookie }, source, () => {
this.debugger.debug('sent cookie_echo', chunk.state_cookie)
})
/*
If the receiver of an INIT ACK chunk detects unrecognized parameters
and has to report them according to Section 3.2.1, it SHOULD bundle
the ERROR chunk containing the 'Unrecognized Parameters' error cause
with the COOKIE ECHO chunk sent in response to the INIT ACK chunk.
If the receiver of the INIT ACK cannot bundle the COOKIE ECHO chunk
with the ERROR chunk, the ERROR chunk MAY be sent separately but not
before the COOKIE ACK has been received.
Note: Any time a COOKIE ECHO is sent in a packet, it MUST be the
first chunk.
*/
if (chunk.errors) {
this.ERROR([{
cause: 'UNRECONGNIZED_PARAMETERS',
unrecognized_parameters: Buffer.concat(chunk.errors)
}], source)
}
this.state = 'COOKIE-ECHOED'
} else {
/*
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.
*/
this.debugger.warn('Unexpected INIT ACK')
}
}
ERROR (errors, dst) {
this._sendChunk('error', {
error_causes: errors
}, dst)
}
onHeartbeat (chunk, source) {
/*
A receiver of a HEARTBEAT MUST respond to a
HEARTBEAT with a HEARTBEAT-ACK after entering the COOKIE-ECHOED state
(INIT sender) or the ESTABLISHED state (INIT receiver), up until
reaching the SHUTDOWN-SENT state (SHUTDOWN sender) or the SHUTDOWN-
ACK-SENT state (SHUTDOWN receiver). TODO
*/
this.debugger.trace(
'< HEARTBEAT',
chunk.heartbeat_info.length,
chunk.heartbeat_info
)
this._sendChunk(
'heartbeat_ack',
{ heartbeat_info: chunk.heartbeat_info },
source
)
}
onHeartbeatAck (chunk) {
this.debugger.trace(
'< HEARTBEAT ACK',
chunk.heartbeat_info.length,
chunk.heartbeat_info
)
/*
Upon receipt of the HEARTBEAT ACK, a verification is made that the
nonce included in the HEARTBEAT parameter is the one sent to the
address indicated inside the HEARTBEAT parameter. When this match
occurs, the address that the original HEARTBEAT was sent to is now
considered CONFIRMED and available for normal data transfer.
*/
const nonce = chunk.heartbeat_info.readUInt32BE(0)
if (this.nonces[nonce]) {
const address = ip.toString(chunk.heartbeat_info, 8, 4)
this.debugger.trace('address confirmed alive', address)
}
delete this.nonces[nonce]
}
onCookieAck () {
this.debugger.debug('< COOKIE ACK in state %s', this.state)
if (this.state === 'COOKIE-ECHOED') {
this._up()
}
}
onShutdown (chunk, source) {
// TODO: 9.2. Shutdown of an Association
if (this.state === 'SHUTDOWN-RECEIVED') {
/*
Once an endpoint has reached the SHUTDOWN-RECEIVED state, it MUST NOT
send a SHUTDOWN in response to a ULP request, and should discard
subsequent SHUTDOWN chunks.
*/
return
}
this.debugger.info('< SHUTDOWN')
// TODO check c_tsn_ack
/*
cause: 'PROTOCOL_VIOLATION',
additional_information:
'The cumulative tsn ack beyond the max tsn currently sent:...'
verify, by checking the Cumulative TSN Ack field of the chunk,
that all its outstanding DATA chunks have been received by the
SHUTDOWN sender.
If there are still outstanding DATA chunks left, the SHUTDOWN
receiver MUST continue to follow normal data transmission procedures
defined in Section 6, until all outstanding DATA chunks are
acknowledged; however, the SHUTDOWN receiver MUST NOT accept new data
from its SCTP user.
*/
if (this.state === 'SHUTDOWN-SENT') {
/*
If an endpoint is in the SHUTDOWN-SENT state and receives a SHUTDOWN
chunk from its peer, the endpoint shall respond immediately with a
SHUTDOWN ACK to its peer, and move into the SHUTDOWN-ACK-SENT state
restarting its T2-shutdown timer.
*/
this._sendChunk('shutdown_ack', {}, source, () => {
this.debugger.info('sent shutdown_ack')
})
this._restartT2()
return
}
this.state = 'SHUTDOWN-RECEIVED'
if (this.flightsize === 0) {
this._sendChunk('shutdown_ack', {}, source, () => {
this.state = 'SHUTDOWN-ACK-SENT'
this.debugger.info('sent shutdown_ack')
})
this._startT2()
}
}
onShutdownAck (chunk, source) {
/*
Upon the receipt of the SHUTDOWN ACK, the SHUTDOWN sender shall stop
the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its peer,
and remove all record of the association.
*/
this.debugger.info('< SHUTDOWN ACK in state %s', this.state)
if (this.state === 'SHUTDOWN-SENT' || this.state === 'SHUTDOWN-ACK-SENT') {
this._down()
this.state = 'CLOSED'
this.debugger.info('> sending SHUTDOWN COMPLETE')
this._sendChunk('shutdown_complete', {}, source, () => {
this.debugger.trace('sent SHUTDOWN COMPLETE')
this.emit('SHUTDOWN COMPLETE')
this._destroy()
})
}
}
onShutdownComplete () {
/*
- The receiver of a SHUTDOWN COMPLETE shall accept the packet if
the Verification Tag field of the packet matches its own tag and
the T bit is not set OR if it is set to its peer's tag and the T
bit is set in the Chunk Flags. Otherwise, the receiver MUST
silently discard the packet and take no further action. An
endpoint MUST ignore the SHUTDOWN COMPLETE if it is not in the
SHUTDOWN-ACK-SENT state.
Upon reception of the SHUTDOWN COMPLETE chunk, the endpoint will
verify that it is in the SHUTDOWN-ACK-SENT state; if it is not, the
chunk should be discarded. If the endpoint is in the SHUTDOWN-ACK-
SENT state, the endpoint should stop the T2-shutdown timer and remove
all knowledge of the association (and thus the association enters the
CLOSED state).
*/
if (this.state === 'SHUTDOWN-ACK-SENT') {
this._down()
this.debugger.info('< SHUTDOWN COMPLETE')
this.emit('SHUTDOWN COMPLETE')
this._destroy()
}
}
onError (chunk) {
this.debugger.warn('< ERROR', chunk)
if (
chunk.error_causes.some(
item => item.cause === 'STALE_COOKIE_ERROR'
)
) {
// TODO: 5.2.6. Handle Stale COOKIE Error
}
this.emit('COMMUNICATION ERROR', chunk.error_causes)
}
onAbort (chunk) {
this.debugger.info('< ABORT, connection closed')
if (chunk.error_causes) {
this.debugger.warn('< ABORT has error causes', chunk.error_causes)
}
this._down()
if (this.queue.length > 0) {
this.debugger.trace('abandon sending of chunks', this.queue.length)
}
this.queue = []
this.emit('COMMUNICATION LOST', 'abort', chunk.error_causes)
this._destroy()
}
init () {
const initParams = {
initiate_tag: this.my_tag,
a_rwnd: this.a_rwnd,
outbound_streams: this.OS,
inbound_streams: this.MIS,
initial_tsn: this.my_next_tsn.number
}
if (this.endpoint.localAddress) {
initParams.ipv4_address = this.endpoint.localAddress
}
this.debugger.info('INIT params', initParams)
let counter = 0
this.RTI = this.rto_initial
const init = () => {
if (counter >= defs.NET_SCTP.max_init_retransmits) {
// Fail
} else {
if (counter) {
// Not from RFC, but from lk-sctp
this.RTI *= 2
if (this.RTI > this.rto_max) {
this.RTI = this.rto_max
}
}
this._sendChunk('init', initParams)
counter++
this.T1 = setTimeout(init, this.RTO)
}
}
init()
this.state = 'COOKIE-WAIT'
}
_sendChunk (chunkType, options, destination, callback) {
const chunk = new Chunk(chunkType, options)
this.debugger.debug('> send chunk', chunkType)
this.debugger.trace('> %O', chunk)
/*
By default, an endpoint SHOULD always transmit to the primary path,
unless the SCTP user explicitly specifies the destination transport
address (and possibly source transport address) to use.
An endpoint SHOULD transmit reply chunks (e.g., SACK, HEARTBEAT ACK,
etc.) to the same destination transport address from which it
received the DATA or control chunk to which it is replying. This
rule should also be followed if the endpoint is bundling DATA chunks
together with the reply chunk.
However, when acknowledging multiple DATA chunks received in packets
from different source addresses in a single SACK, the SACK chunk may
be transmitted to one of the destination transport addresses from
which the DATA or control chunks being acknowledged were received.
*/
if (
chunkType === 'data' ||
chunkType === 'sack' ||
chunkType === 'heartbeat_ack'
) {
// RFC allows to bundle other control chunks,
// but this gives almost no benefits
this.debugger.trace('> bundle-send', chunkType, options)
chunk.callback = callback
if (chunkType === 'data') {
// Do not encode here because we'll add tsn later, during bundling
chunk.size = chunk.user_data.length + 16
} else {
chunk.buffer = chunk.toBuffer()
chunk.size = chunk.buffer.length
}
this.debugger.trace('chunk size', chunk.size)
this.queue.push(chunk)
this.bundling++
setTimeout(() => {
this._bundle()
})
} else {
// No bundle
// setTimeout(() => {
// use nextTick to be in order with bundled chunks
const buffer = chunk.toBuffer()
this.debugger.trace('> no-bundle send', chunkType)
this._sendPacket([buffer], destination, [callback])
// }, 0)
}
}
_sack () {
if (this._sack_timer) {
this.debugger.trace('cancel SACK timer and do it now')
clearTimeout(this._sack_timer)
delete this._sack_timer
}
this.sacks--
if (this.sacks > 0) {
// Wait for last sack request in idle cycle
this.debugger.trace('grouping SACKs, wait %d more...', this.sacks)
return
}
const sackOptions = this.reassembly.sackInfo()
this.debugger.trace('prepared SACK %O', sackOptions)
this._sendChunk('sack', sackOptions)
this.everSentSack = true
this.packetsSinceLastSack = 0
}
_acknowledge (TSN) {
// this.debugger.trace('acknowledge tsn %d, peer_rwnd %d, flightsize %d', TSN.number, this.peer_rwnd, this.flightsize)
this.flightsize -= this.sent[TSN.getNumber()].size
this.debugger.trace('acknowledge tsn %d, peer_rwnd %d, flightsize %d', TSN.number, this.peer_rwnd, this.flightsize)
if (!this.HTNA || TSN.gt(this.HTNA)) {
this.HTNA = TSN.copy()
}
delete this.sent[TSN.getNumber()]
// RTO calculation
if (this.rtoPending && this.rtoPending.tsn.eq(TSN)) {
this._updateRTO(new Date() - this.rtoPending.sent)
this.rtoPending = false
}
}
_updateRTO (R) {
if (this.SRTT) {
const alpha = 1 / defs.NET_SCTP.rto_alpha_exp_divisor
const beta = 1 / defs.NET_SCTP.rto_beta_exp_divisor
this.RTTVAR = (1 - beta) * this.RTTVAR + beta * Math.abs(this.SRTT - R)
this.RTTVAR = Math.max(this.RTTVAR, defs.NET_SCTP.G)
this.SRTT = (1 - alpha) * this.SRTT + alpha * R
this.RTO = this.SRTT + 4 * this.RTTVAR
} else {
this.SRTT = R
this.RTTVAR = R / 2
this.RTTVAR = Math.max(this.RTTVAR, defs.NET_SCTP.G)
this.RTO = this.SRTT + 4 * this.RTTVAR
}
if (this.RTO < this.rto_min) {
this.RTO = this.rto_min
}
if (this.RTO > this.rto_max) {
this.RTO = this.rto_max
}
this.debugger.trace('new RTO %d', this.RTO)
}
_startT2 () {
if (this.T2) {
this.debugger.trace('T2-shutdown timer is already running')
return
}