Debian Codegraph @

reassembly_queue.go

raw
1 // SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
2 // SPDX-License-Identifier: MIT
3
4 package sctp
5
6 import (
7 "errors"
8 "io"
9 "sort"
10 "sync/atomic"
11 )
12
13 func sortChunksByTSN(a []*chunkPayloadData) {
14 sort.Slice(a, func(i, j int) bool {
15 return sna32LT(a[i].tsn, a[j].tsn)
16 })
17 }
18
19 func sortChunksBySSN(a []*chunkSet) {
20 sort.Slice(a, func(i, j int) bool {
21 return sna16LT(a[i].ssn, a[j].ssn)
22 })
23 }
24
25 func sortChunksByFSN(a []*chunkPayloadData) {
26 sort.Slice(a, func(i, j int) bool {
27 return sna32LT(a[i].fragmentSequenceNumber, a[j].fragmentSequenceNumber)
28 })
29 }
30
31 func insertChunkSetByMID(a []*chunkSetMID, cset *chunkSetMID) []*chunkSetMID {
32 insertAt := sort.Search(len(a), func(i int) bool {
33 return !sna32LT(a[i].mid, cset.mid)
34 })
35
36 a = append(a, nil)
37 copy(a[insertAt+1:], a[insertAt:])
38 a[insertAt] = cset
39
40 return a
41 }
42
43 // chunkSet is a set of chunks that share the same SSN.
44 type chunkSet struct {
45 ssn uint16 // used only with the ordered chunks
46 ppi PayloadProtocolIdentifier
47 chunks []*chunkPayloadData
48 }
49
50 func newChunkSet(ssn uint16, ppi PayloadProtocolIdentifier) *chunkSet {
51 return &chunkSet{
52 ssn: ssn,
53 ppi: ppi,
54 chunks: []*chunkPayloadData{},
55 }
56 }
57
58 func (set *chunkSet) push(chunk *chunkPayloadData) bool {
59 // check if dup
60 if set.hasTSN(chunk.tsn) {
61 return false
62 }
63
64 return set.pushNoDuplicate(chunk)
65 }
66
67 func (set *chunkSet) pushNoDuplicate(chunk *chunkPayloadData) bool {
68 // append and sort
69 set.chunks = append(set.chunks, chunk)
70 sortChunksByTSN(set.chunks)
71
72 // Check if we now have a complete set
73 complete := set.isComplete()
74
75 return complete
76 }
77
78 func (set *chunkSet) hasTSN(tsn uint32) bool {
79 for _, c := range set.chunks {
80 if c.tsn == tsn {
81 return true
82 }
83 }
84
85 return false
86 }
87
88 func (set *chunkSet) isComplete() bool {
89 // Condition for complete set
90 // 0. Has at least one chunk.
91 // 1. Begins with beginningFragment set to true
92 // 2. Ends with endingFragment set to true
93 // 3. TSN monotinically increase by 1 from beginning to end
94
95 // 0.
96 nChunks := len(set.chunks)
97 if nChunks == 0 {
98 return false
99 }
100
101 // 1.
102 if !set.chunks[0].beginningFragment {
103 return false
104 }
105
106 // 2.
107 if !set.chunks[nChunks-1].endingFragment {
108 return false
109 }
110
111 // 3.
112 var lastTSN uint32
113 for i, chunk := range set.chunks {
114 if i > 0 {
115 // Fragments must have contiguous TSN
116 // From RFC 4960 Section 3.3.1:
117 // When a user message is fragmented into multiple chunks, the TSNs are
118 // used by the receiver to reassemble the message. This means that the
119 // TSNs for each fragment of a fragmented user message MUST be strictly
120 // sequential.
121 if chunk.tsn != lastTSN+1 {
122 // mid or end fragment is missing
123 return false
124 }
125 }
126
127 lastTSN = chunk.tsn
128 }
129
130 return true
131 }
132
133 // chunkSetMID is a set of chunks that share the same MID.
134 type chunkSetMID struct {
135 mid uint32
136 ppi PayloadProtocolIdentifier
137 chunks []*chunkPayloadData
138 }
139
140 func newChunkSetMID(mid uint32, ppi PayloadProtocolIdentifier) *chunkSetMID {
141 return &chunkSetMID{
142 mid: mid,
143 ppi: ppi,
144 chunks: []*chunkPayloadData{},
145 }
146 }
147
148 func (set *chunkSetMID) pushAndCheck(chunk *chunkPayloadData) (complete bool, accepted bool) {
149 if set.isComplete() {
150 return false, false
151 }
152
153 for _, c := range set.chunks {
154 if c.fragmentSequenceNumber == chunk.fragmentSequenceNumber {
155 return false, false
156 }
157 }
158
159 set.chunks = append(set.chunks, chunk)
160 if chunk.beginningFragment {
161 set.ppi = chunk.payloadType
162 }
163 sortChunksByFSN(set.chunks)
164
165 return set.isComplete(), true
166 }
167
168 func (set *chunkSetMID) isComplete() bool {
169 nChunks := len(set.chunks)
170 if nChunks == 0 {
171 return false
172 }
173
174 if !set.chunks[0].beginningFragment {
175 return false
176 }
177
178 if !set.chunks[nChunks-1].endingFragment {
179 return false
180 }
181
182 if set.chunks[0].fragmentSequenceNumber != 0 {
183 return false
184 }
185
186 lastFSN := set.chunks[0].fragmentSequenceNumber
187 for i, chunk := range set.chunks {
188 if i > 0 {
189 if chunk.fragmentSequenceNumber != lastFSN+1 {
190 return false
191 }
192 }
193 lastFSN = chunk.fragmentSequenceNumber
194 }
195
196 return true
197 }
198
199 type reassemblyQueue struct {
200 si uint16
201 nextSSN uint16 // expected SSN for next ordered chunk
202 nextMID uint32 // expected MID for next ordered I-DATA
203 ordered []*chunkSet
204 unordered []*chunkSet
205 unorderedChunks []*chunkPayloadData
206 orderedMID []*chunkSetMID
207 unorderedMID []*chunkSetMID
208 orderedMIDMap map[uint32]*chunkSetMID
209 unorderedMIDMap map[uint32]*chunkSetMID
210 useInterleaving bool
211 nBytes uint64
212 maxEntries uint32
213 }
214
215 var (
216 errTryAgain = errors.New("try again")
217
218 errReassemblyQueueLimitExceeded = errors.New("reassembly queue data limit exceeded")
219
220 errReassemblyQueueMIDLimitExceeded = errors.New("reassembly queue i-data message identifier limit exceeded")
221 )
222
223 func newReassemblyQueue(si uint16, maxEntries uint32) *reassemblyQueue {
224 // From RFC 4960 Sec 6.5:
225 // The Stream Sequence Number in all the streams MUST start from 0 when
226 // the association is established. Also, when the Stream Sequence
227 // Number reaches the value 65535 the next Stream Sequence Number MUST
228 // be set to 0.
229 return &reassemblyQueue{
230 si: si,
231 nextSSN: 0, // From RFC 4960 Sec 6.5:
232 nextMID: 0,
233 ordered: make([]*chunkSet, 0),
234 unordered: make([]*chunkSet, 0),
235 orderedMID: make([]*chunkSetMID, 0),
236 unorderedMID: make([]*chunkSetMID, 0),
237 orderedMIDMap: map[uint32]*chunkSetMID{},
238 unorderedMIDMap: map[uint32]*chunkSetMID{},
239 maxEntries: maxEntries,
240 }
241 }
242
243 func isReassemblyQueueLimitReached(maxEntries uint32, nEntries int) bool {
244 return maxEntries > 0 && int64(nEntries) >= int64(maxEntries)
245 }
246
247 func (r *reassemblyQueue) isDataLimitReached(nEntries int) bool {
248 return isReassemblyQueueLimitReached(r.maxEntries, nEntries)
249 }
250
251 func (r *reassemblyQueue) hasDataLimit() bool {
252 return r.maxEntries > 0
253 }
254
255 func (r *reassemblyQueue) isMIDLimitReached(nEntries int) bool {
256 return isReassemblyQueueLimitReached(r.maxEntries, nEntries)
257 }
258
259 func (r *reassemblyQueue) orderedDataEntryCount() int {
260 nEntries := 0
261 for _, set := range r.ordered {
262 nEntries += len(set.chunks)
263 }
264
265 return nEntries
266 }
267
268 func (r *reassemblyQueue) unorderedDataEntryCount() int {
269 nEntries := len(r.unorderedChunks)
270 for _, set := range r.unordered {
271 nEntries += len(set.chunks)
272 }
273
274 return nEntries
275 }
276
277 func (r *reassemblyQueue) push(chunk *chunkPayloadData) bool {
278 complete, _ := r.pushWithError(chunk)
279
280 return complete
281 }
282
283 func (r *reassemblyQueue) pushWithError(chunk *chunkPayloadData) (bool, error) { //nolint:cyclop
284 var cset *chunkSet
285
286 if chunk.isIData() {
287 r.useInterleaving = true
288
289 return r.pushIData(chunk)
290 }
291
292 if chunk.streamIdentifier != r.si {
293 return false, nil
294 }
295
296 if chunk.unordered {
297 if r.hasDataLimit() && r.isDataLimitReached(r.unorderedDataEntryCount()) {
298 return false, errReassemblyQueueLimitExceeded
299 }
300
301 // First, insert into unorderedChunks array
302 r.unorderedChunks = append(r.unorderedChunks, chunk)
303 atomic.AddUint64(&r.nBytes, uint64(len(chunk.userData)))
304 sortChunksByTSN(r.unorderedChunks)
305
306 // Scan unorderedChunks that are contiguous (in TSN)
307 cset = r.findCompleteUnorderedChunkSet()
308
309 // If found, append the complete set to the unordered array
310 if cset != nil {
311 r.unordered = append(r.unordered, cset)
312
313 return true, nil
314 }
315
316 return false, nil
317 }
318
319 // This is an ordered chunk
320
321 if sna16LT(chunk.streamSequenceNumber, r.nextSSN) {
322 return false, nil
323 }
324
325 // Check if a fragmented chunkSet with the fragmented SSN already exists
326 if chunk.isFragmented() {
327 for _, set := range r.ordered {
328 // nolint:godox
329 // TODO: add caution around SSN wrapping here... this helps only a little bit
330 // by ensuring we don't add to an unfragmented cset (1 chunk). There's
331 // a case where if the SSN does wrap around, we may see the same SSN
332 // for a different chunk.
333
334 // nolint:godox
335 // TODO: this slice can get pretty big; it may be worth maintaining a map
336 // for O(1) lookups at the cost of 2x memory.
337 if set.ssn == chunk.streamSequenceNumber && set.chunks[0].isFragmented() {
338 cset = set
339
340 break
341 }
342 }
343 }
344
345 // Reject a new queued DATA entry once the descriptor cap is reached.
346 if cset != nil && cset.hasTSN(chunk.tsn) {
347 return false, nil
348 }
349 if r.hasDataLimit() && r.isDataLimitReached(r.orderedDataEntryCount()) {
350 return false, errReassemblyQueueLimitExceeded
351 }
352 if cset == nil {
353 cset = newChunkSet(chunk.streamSequenceNumber, chunk.payloadType)
354 r.ordered = append(r.ordered, cset)
355 if !chunk.unordered {
356 sortChunksBySSN(r.ordered)
357 }
358 }
359
360 atomic.AddUint64(&r.nBytes, uint64(len(chunk.userData)))
361
362 return cset.pushNoDuplicate(chunk), nil
363 }
364
365 func (r *reassemblyQueue) pushIData(chunk *chunkPayloadData) (bool, error) {
366 if chunk.streamIdentifier != r.si {
367 return false, nil
368 }
369
370 if chunk.unordered {
371 return r.pushUnorderedIData(chunk)
372 }
373
374 return r.pushOrderedIData(chunk)
375 }
376
377 func (r *reassemblyQueue) pushUnorderedIData(chunk *chunkPayloadData) (bool, error) {
378 if r.hasQueuedUnorderedMID(chunk.messageIdentifier) {
379 return false, nil
380 }
381
382 if r.unorderedMIDMap == nil {
383 r.unorderedMIDMap = map[uint32]*chunkSetMID{}
384 }
385 cset := r.unorderedMIDMap[chunk.messageIdentifier]
386 if cset == nil {
387 if r.isMIDLimitReached(r.unorderedMIDEntryCount()) {
388 return false, errReassemblyQueueMIDLimitExceeded
389 }
390 cset = newChunkSetMID(chunk.messageIdentifier, chunk.payloadType)
391 r.unorderedMIDMap[chunk.messageIdentifier] = cset
392 }
393
394 complete, accepted := cset.pushAndCheck(chunk)
395 if !accepted {
396 return false, nil
397 }
398
399 atomic.AddUint64(&r.nBytes, uint64(len(chunk.userData)))
400 if complete {
401 delete(r.unorderedMIDMap, chunk.messageIdentifier)
402 r.unorderedMID = append(r.unorderedMID, cset)
403
404 return true, nil
405 }
406
407 return false, nil
408 }
409
410 func (r *reassemblyQueue) pushOrderedIData(chunk *chunkPayloadData) (bool, error) {
411 if sna32LT(chunk.messageIdentifier, r.nextMID) {
412 return false, nil
413 }
414
415 if r.orderedMIDMap == nil {
416 r.orderedMIDMap = map[uint32]*chunkSetMID{}
417 }
418 cset := r.orderedMIDMap[chunk.messageIdentifier]
419 if cset == nil {
420 if r.isMIDLimitReached(len(r.orderedMIDMap)) {
421 return false, errReassemblyQueueMIDLimitExceeded
422 }
423 cset = newChunkSetMID(chunk.messageIdentifier, chunk.payloadType)
424 r.orderedMIDMap[chunk.messageIdentifier] = cset
425 r.orderedMID = insertChunkSetByMID(r.orderedMID, cset)
426 }
427
428 complete, accepted := cset.pushAndCheck(chunk)
429 if !accepted {
430 return false, nil
431 }
432
433 atomic.AddUint64(&r.nBytes, uint64(len(chunk.userData)))
434
435 return complete, nil
436 }
437
438 func (r *reassemblyQueue) unorderedMIDEntryCount() int {
439 return len(r.unorderedMIDMap) + len(r.unorderedMID)
440 }
441
442 func (r *reassemblyQueue) hasQueuedUnorderedMID(mid uint32) bool {
443 for _, set := range r.unorderedMID {
444 if set.mid == mid {
445 return true
446 }
447 }
448
449 return false
450 }
451
452 func (r *reassemblyQueue) findCompleteUnorderedChunkSet() *chunkSet {
453 startIdx := -1
454 nChunks := 0
455 var lastTSN uint32
456 var found bool
457
458 for i, chunk := range r.unorderedChunks {
459 // seek beigining
460 if chunk.beginningFragment {
461 startIdx = i
462 nChunks = 1
463 lastTSN = chunk.tsn
464
465 if chunk.endingFragment {
466 found = true
467
468 break
469 }
470
471 continue
472 }
473
474 if startIdx < 0 {
475 continue
476 }
477
478 // Check if contiguous in TSN
479 if chunk.tsn != lastTSN+1 {
480 startIdx = -1
481
482 continue
483 }
484
485 lastTSN = chunk.tsn
486 nChunks++
487
488 if chunk.endingFragment {
489 found = true
490
491 break
492 }
493 }
494
495 if !found {
496 return nil
497 }
498
499 // Extract the range of chunks
500 var chunks []*chunkPayloadData
501 chunks = append(chunks, r.unorderedChunks[startIdx:startIdx+nChunks]...)
502
503 r.unorderedChunks = append(
504 r.unorderedChunks[:startIdx],
505 r.unorderedChunks[startIdx+nChunks:]...)
506
507 chunkSet := newChunkSet(0, chunks[0].payloadType)
508 chunkSet.chunks = chunks
509
510 return chunkSet
511 }
512
513 func (r *reassemblyQueue) isReadable() bool {
514 if r.useInterleaving {
515 if len(r.unorderedMID) > 0 {
516 return true
517 }
518 if len(r.orderedMID) > 0 {
519 cset := r.orderedMID[0]
520 if cset.isComplete() && sna32LTE(cset.mid, r.nextMID) {
521 return true
522 }
523 }
524
525 return false
526 }
527
528 // Check unordered first
529 if len(r.unordered) > 0 {
530 // The chunk sets in r.unordered should all be complete.
531 return true
532 }
533
534 // Check ordered sets
535 if len(r.ordered) > 0 {
536 cset := r.ordered[0]
537 if cset.isComplete() {
538 if sna16LTE(cset.ssn, r.nextSSN) {
539 return true
540 }
541 }
542 }
543
544 return false
545 }
546
547 func (r *reassemblyQueue) read(buf []byte) (int, PayloadProtocolIdentifier, error) { // nolint: cyclop,gocognit
548 var (
549 cset *chunkSet
550 isUnordered bool
551 nTotal int
552 err error
553 )
554
555 if r.useInterleaving { //nolint:nestif
556 var iSet *chunkSetMID
557 switch {
558 case len(r.unorderedMID) > 0:
559 iSet = r.unorderedMID[0]
560 isUnordered = true
561 case len(r.orderedMID) > 0:
562 iSet = r.orderedMID[0]
563 if !iSet.isComplete() {
564 return 0, 0, errTryAgain
565 }
566 if sna32GT(iSet.mid, r.nextMID) {
567 return 0, 0, errTryAgain
568 }
569 default:
570 return 0, 0, errTryAgain
571 }
572
573 for _, c := range iSet.chunks {
574 if len(buf)-nTotal < len(c.userData) {
575 err = io.ErrShortBuffer
576 } else {
577 copy(buf[nTotal:], c.userData)
578 }
579 nTotal += len(c.userData)
580 }
581
582 switch {
583 case err != nil:
584 return nTotal, 0, err
585 case isUnordered:
586 r.unorderedMID = r.unorderedMID[1:]
587 default:
588 r.orderedMID = r.orderedMID[1:]
589 delete(r.orderedMIDMap, iSet.mid)
590 if iSet.mid == r.nextMID {
591 r.nextMID++
592 }
593 }
594
595 r.subtractNumBytes(nTotal)
596
597 return nTotal, iSet.ppi, err
598 }
599
600 switch {
601 case len(r.unordered) > 0:
602 cset = r.unordered[0]
603 isUnordered = true
604 case len(r.ordered) > 0:
605 cset = r.ordered[0]
606 if !cset.isComplete() {
607 return 0, 0, errTryAgain
608 }
609 if sna16GT(cset.ssn, r.nextSSN) {
610 return 0, 0, errTryAgain
611 }
612 default:
613 return 0, 0, errTryAgain
614 }
615
616 for _, c := range cset.chunks {
617 if len(buf)-nTotal < len(c.userData) {
618 err = io.ErrShortBuffer
619 } else {
620 copy(buf[nTotal:], c.userData)
621 }
622
623 nTotal += len(c.userData)
624 }
625
626 switch {
627 case err != nil:
628 return nTotal, 0, err
629 case isUnordered:
630 r.unordered = r.unordered[1:]
631 default:
632 r.ordered = r.ordered[1:]
633 if cset.ssn == r.nextSSN {
634 r.nextSSN++
635 }
636 }
637
638 r.subtractNumBytes(nTotal)
639
640 return nTotal, cset.ppi, err
641 }
642
643 func (r *reassemblyQueue) forwardTSNForOrdered(lastSSN uint16) {
644 // Use lastSSN to locate a chunkSet then remove it if the set has
645 // not been complete
646 keep := []*chunkSet{}
647 for _, set := range r.ordered {
648 if sna16LTE(set.ssn, lastSSN) {
649 if !set.isComplete() {
650 // drop the set
651 for _, c := range set.chunks {
652 r.subtractNumBytes(len(c.userData))
653 }
654
655 continue
656 }
657 }
658 keep = append(keep, set)
659 }
660 r.ordered = keep
661
662 // Finally, forward nextSSN
663 if sna16LTE(r.nextSSN, lastSSN) {
664 r.nextSSN = lastSSN + 1
665 }
666 }
667
668 func (r *reassemblyQueue) forwardTSNForUnordered(newCumulativeTSN uint32) {
669 // Remove all fragments in the unordered sets that contains chunks
670 // equal to or older than `newCumulativeTSN`.
671 // We know all sets in the r.unordered are complete ones.
672 // Just remove chunks that are equal to or older than newCumulativeTSN
673 // from the unorderedChunks
674 lastIdx := -1
675 for i, c := range r.unorderedChunks {
676 if sna32GT(c.tsn, newCumulativeTSN) {
677 break
678 }
679 lastIdx = i
680 }
681 if lastIdx >= 0 {
682 for _, c := range r.unorderedChunks[0 : lastIdx+1] {
683 r.subtractNumBytes(len(c.userData))
684 }
685 r.unorderedChunks = r.unorderedChunks[lastIdx+1:]
686 }
687 }
688
689 func (r *reassemblyQueue) forwardTSNForOrderedMID(lastMID uint32) {
690 keep := []*chunkSetMID{}
691 for _, set := range r.orderedMID {
692 if sna32LTE(set.mid, lastMID) {
693 if !set.isComplete() {
694 for _, c := range set.chunks {
695 r.subtractNumBytes(len(c.userData))
696 }
697 delete(r.orderedMIDMap, set.mid)
698
699 continue
700 }
701 }
702 keep = append(keep, set)
703 }
704 r.orderedMID = keep
705
706 if sna32LTE(r.nextMID, lastMID) {
707 r.nextMID = lastMID + 1
708 }
709 }
710
711 func (r *reassemblyQueue) forwardTSNForUnorderedMID(lastMID uint32) {
712 for mid, set := range r.unorderedMIDMap {
713 if sna32LTE(mid, lastMID) {
714 for _, c := range set.chunks {
715 r.subtractNumBytes(len(c.userData))
716 }
717 delete(r.unorderedMIDMap, mid)
718 }
719 }
720 }
721
722 func (r *reassemblyQueue) subtractNumBytes(nBytes int) {
723 cur := atomic.LoadUint64(&r.nBytes)
724 if int(cur) >= nBytes { //nolint:gosec // G115
725 atomic.AddUint64(&r.nBytes, -uint64(nBytes)) //nolint:gosec // G115
726 } else {
727 atomic.StoreUint64(&r.nBytes, 0)
728 }
729 }
730
731 func (r *reassemblyQueue) getNumBytes() int {
732 return int(atomic.LoadUint64(&r.nBytes)) //nolint:gosec // G115
733 }