rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! SACKs a misbehaving or broken peer may send (RFC 9260 3.3.4, 6.2.1, 7.2, 12.4): Gap Ack
//! Blocks out of order, overlapping, reversed, starting at offset 0 or reaching past the last
//! TSN sent; a Cumulative TSN Ack behind the ack point or past the last TSN sent; floods of
//! duplicate TSNs. Each leaves the sender as the equivalent well-formed SACK would, or aborts
//! the association where RFC 9260 12.4 says to: "An SCTP implementation MUST abort the
//! association if it receives a SACK chunk acknowledging a TSN that has not been sent."
//!
//! The SACKs reach the server of a connected link as datagrams; ideas from usrsctp's
//! `sctp_handle_segments` (BSD-3: a reversed block is skipped), dcSCTP's
//! `HandleInvalidGapAckBlocks` (BSD-3), pion's `TestHandleSack_ReversedGapDoesNotPartially
//! Process` (MIT) and aiortc's `test_receive_sack_invalid_gap` (BSD-3). Nothing is copied.

use super::robustness_test::*;
use super::*;
use crate::chunk::chunk_selective_ack::GapAckBlock;
use crate::chunk::chunk_type::*;
use crate::endpoint::link_test::Link;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;
const CAUSE_PROTOCOL_VIOLATION: u16 = 13;
/// What each message is on the wire: 300 bytes of user data and the 16-byte DATA header.
const WIRE: u32 = 316;
const A_RWND: u32 = 1 << 20;

/// The server of a connected link with eight 300-byte messages on the wire (the window takes
/// them all), and their TSNs.
fn sending(seed: u64) -> (Link, Vec<u32>) {
    let mut link = connected_link(seed);
    let now = link.now;
    let a = link.server.conn();
    {
        let mut s = a.open_stream(1, PPI).unwrap();
        for _ in 0..8 {
            s.write_sctp(now, &Bytes::from(vec![7u8; 300]), PPI)
                .unwrap();
        }
    }
    let sent = sent_datagrams(a, now);
    let tsns: Vec<u32> = chunks_of_type(&sent, CT_PAYLOAD_DATA.0)
        .iter()
        .map(|c| u32::from_be_bytes([c[4], c[5], c[6], c[7]]))
        .collect();
    assert_eq!(8, tsns.len(), "precondition: every message on the wire");
    assert_eq!(a.my_next_tsn, tsns[7].wrapping_add(1));
    (link, tsns)
}

fn sack(cumulative: u32, gaps: &[(u16, u16)], duplicates: &[u32]) -> Vec<u8> {
    chunk_bytes(&ChunkSelectiveAck {
        cumulative_tsn_ack: cumulative,
        advertised_receiver_window_credit: A_RWND,
        gap_ack_blocks: gaps
            .iter()
            .map(|&(start, end)| GapAckBlock { start, end })
            .collect(),
        duplicate_tsn: duplicates.to_vec(),
    })
}

fn deliver_sack(link: &mut Link, cumulative: u32, gaps: &[(u16, u16)], duplicates: &[u32]) {
    let now = link.now;
    let a = link.server.conn();
    let raw = packet_to(a, &[sack(cumulative, gaps, duplicates)]);
    inject(a, now, raw);
}

/// What a SACK changes at the sender, TSNs as offsets from the first one sent.
#[derive(Debug, PartialEq)]
struct SenderState {
    ended: bool,
    cumulative: u32,
    rwnd: u32,
    cwnd: u32,
    partial_bytes_acked: u32,
    in_fast_recovery: bool,
    gap_acknowledged: Vec<u32>,
    outstanding: usize,
    miss_indicators: Vec<(u32, u32)>,
}

fn sender_state(a: &Association, first: u32) -> SenderState {
    SenderState {
        ended: a.is_ended(),
        cumulative: a.cumulative_tsn_ack_point.wrapping_sub(first),
        rwnd: a.rwnd,
        cwnd: a.cwnd,
        partial_bytes_acked: a.partial_bytes_acked,
        in_fast_recovery: a.in_fast_recovery,
        gap_acknowledged: a
            .inflight_queue
            .gap_acknowledged()
            .iter()
            .map(|tsn| tsn.wrapping_sub(first))
            .collect(),
        outstanding: a.inflight_queue.len(),
        miss_indicators: a
            .inflight_queue
            .sorted
            .iter()
            .filter_map(|tsn| a.inflight_queue.get(*tsn))
            .map(|c| (c.tsn.wrapping_sub(first), c.miss_indicator))
            .collect(),
    }
}

/// Congestion avoidance with a window nothing fills: `partial_bytes_acked` then counts every
/// byte a SACK newly acknowledges (RFC 9260 7.2.2), so bytes counted twice would show.
fn counting_bytes(link: &mut Link) {
    let a = link.server.conn();
    a.cwnd = 1 << 24;
    a.ssthresh = 1;
}

/// The sender's state after `gaps`, and after `equivalent`, the same SACK well formed, on
/// twin links.
fn after_both(
    seed: u64,
    prepare: impl Fn(&mut Link, &[u32]),
    cumulative: usize,
    gaps: &[(u16, u16)],
    equivalent: &[(u16, u16)],
) -> (SenderState, SenderState) {
    let mut states = vec![];
    for blocks in [gaps, equivalent] {
        let (mut link, tsns) = sending(seed);
        counting_bytes(&mut link);
        prepare(&mut link, &tsns);
        deliver_sack(&mut link, tsns[cumulative], blocks, &[]);
        states.push(sender_state(link.server.conn(), tsns[0]));
    }
    let equivalent = states.pop().unwrap();
    let got = states.pop().unwrap();
    assert!(
        !equivalent.ended,
        "precondition: the well-formed SACK is taken"
    );
    (got, equivalent)
}

// ---- Gap Ack Blocks -----------------------------------------------------------------------

/// RFC 9260 3.3.4: "All DATA chunks with TSNs greater than or equal to (Cumulative TSN Ack +
/// Gap Ack Block Start) and less than or equal to (Cumulative TSN Ack + Gap Ack Block End) of
/// each Gap Ack Block are assumed to have been received correctly." Each block stands for
/// itself; no order is required, and blocks in any order acknowledge the same TSNs.
#[test]
fn gap_ack_blocks_in_any_order_acknowledge_what_each_covers() {
    let (got, sorted) = after_both(341, |_, _| {}, 0, &[(5, 6), (2, 3)], &[(2, 3), (5, 6)]);
    assert_eq!(vec![2, 3, 5, 6], sorted.gap_acknowledged);
    assert_eq!(sorted, got);
}

/// Overlapping blocks acknowledge the union, each TSN once: the bytes the congestion window
/// counts (RFC 9260 7.2.2) and the receive window (6.2.1 D ii) are those of the merged block.
#[test]
fn overlapping_gap_ack_blocks_count_each_tsn_once() {
    let (got, merged) = after_both(342, |_, _| {}, 0, &[(2, 4), (3, 6), (4, 4)], &[(2, 6)]);
    assert_eq!(vec![2, 3, 4, 5, 6], merged.gap_acknowledged);
    assert_eq!(6 * WIRE, merged.partial_bytes_acked, "TSNs 0 and 2 to 6");
    assert_eq!(merged, got);
}

/// A block whose Start is past its End covers no TSN (3.3.4, as above): it changes nothing,
/// as usrsctp skips it ("This gap report is malformed, skip it"). It reported TSNs missing
/// up to its End: in Fast Recovery a SACK that advances the Cumulative TSN Ack counts a miss
/// for every TSN "reported missing" (7.2.4), which went up to the reversed block's End, and
/// an End past the last TSN sent aborted the association as if it acknowledged one.
#[test]
fn a_reversed_gap_ack_block_changes_nothing() {
    // Outside Fast Recovery.
    let (got, without) = after_both(343, |_, _| {}, 0, &[(2, 2), (6, 4)], &[(2, 2)]);
    assert_eq!(without, got, "outside Fast Recovery");

    // In Fast Recovery: three SACKs report TSN 1 missing; then TSN 1 arrives and the
    // Cumulative TSN Ack jumps to TSN 4.
    let fast_recovery = |link: &mut Link, tsns: &[u32]| {
        for end in [2, 3, 4] {
            deliver_sack(link, tsns[0], &[(2, end)], &[]);
        }
        assert!(
            link.server.conn().in_fast_recovery,
            "precondition: in Fast Recovery"
        );
    };
    for reversed in [(5, 3), (40000, 30000)] {
        let (got, without) = after_both(344, fast_recovery, 4, &[reversed], &[]);
        assert!(
            without.in_fast_recovery,
            "precondition: still in Fast Recovery"
        );
        assert_eq!(without, got, "reversed block {reversed:?} in Fast Recovery");
    }
}

/// A block that starts at offset 0 names the Cumulative TSN Ack, which the SACK acknowledges
/// anyway: a TSN that was sent. RFC 9260 12.4 aborts for a TSN "that has not been sent"; this
/// one is no reason to, and the SACK is taken as the same SACK without offset 0.
#[test]
fn a_gap_ack_block_at_offset_zero_is_the_cumulative_tsn_ack() {
    for (blocks, equivalent) in [
        (vec![(0, 0), (2, 3)], vec![(2, 3)]),
        (vec![(0, 3)], vec![(1, 3)]),
    ] {
        let (got, without) = after_both(345, |_, _| {}, 1, &blocks, &equivalent);
        assert_eq!(without, got, "blocks {blocks:?}");
    }
}

/// RFC 9260 12.4, at the boundary: a block that ends at the last TSN sent is taken; one that
/// ends one past it, or at the largest offset (65535), acknowledges a TSN never sent and
/// aborts the association with "Protocol Violation".
#[test]
fn a_gap_ack_block_past_the_last_tsn_sent_aborts_at_the_boundary() {
    let last = 7u16;
    for (end, aborts) in [(last, false), (last + 1, true), (u16::MAX, true)] {
        let (mut link, tsns) = sending(346);
        let peer_tag = link.server.conn().peer_verification_tag;
        deliver_sack(&mut link, tsns[0], &[(2, end)], &[]);
        let now = link.now;
        let a = link.server.conn();
        assert_eq!(aborts, a.is_ended(), "block end {end}");
        let aborted = chunks_of_type(&sent_datagrams(a, now), CT_ABORT.0);
        if aborts {
            assert_eq!(1, aborted.len(), "block end {end}: one ABORT");
            assert_eq!(CAUSE_PROTOCOL_VIOLATION, tlvs(&aborted[0][4..])[0].0);
            assert_ne!(0, peer_tag);
        } else {
            assert!(aborted.is_empty());
            assert_eq!(
                vec![2, 3, 4, 5, 6, 7],
                sender_state(a, tsns[0]).gap_acknowledged
            );
        }
    }
}

// ---- Cumulative TSN Ack ---------------------------------------------------------------------

/// RFC 9260 6.2.1 D i: "If Cumulative TSN Ack is less than the Cumulative TSN Ack Point,
/// then drop the SACK chunk." Dropped whole: its a_rwnd, Gap Ack Blocks and duplicates
/// change nothing.
#[test]
fn a_sack_behind_the_ack_point_changes_nothing_at_all() {
    let (mut link, tsns) = sending(347);
    counting_bytes(&mut link);
    deliver_sack(&mut link, tsns[3], &[], &[]);
    let before = sender_state(link.server.conn(), tsns[0]);
    assert_eq!(3, before.cumulative, "precondition: the ack point is TSN 3");

    let now = link.now;
    let a = link.server.conn();
    let old = chunk_bytes(&ChunkSelectiveAck {
        cumulative_tsn_ack: tsns[1],
        advertised_receiver_window_credit: 0,
        gap_ack_blocks: vec![GapAckBlock { start: 3, end: 6 }],
        duplicate_tsn: vec![tsns[0], tsns[1]],
    });
    let raw = packet_to(a, &[old]);
    inject(a, now, raw);
    assert_eq!(before, sender_state(a, tsns[0]));
}

/// RFC 9260 12.4 at the boundary of the Cumulative TSN Ack: the last TSN sent acknowledges
/// everything; one past it (the next TSN this side would assign) was never sent and aborts.
#[test]
fn a_cumulative_tsn_ack_one_past_the_last_tsn_sent_aborts() {
    for (past, aborts) in [(0u32, false), (1, true)] {
        let (mut link, tsns) = sending(348);
        deliver_sack(&mut link, tsns[7].wrapping_add(past), &[], &[]);
        let now = link.now;
        let a = link.server.conn();
        assert_eq!(aborts, a.is_ended(), "{past} past the last TSN");
        let aborted = chunks_of_type(&sent_datagrams(a, now), CT_ABORT.0);
        assert_eq!(usize::from(aborts), aborted.len());
        if aborts {
            assert_eq!(CAUSE_PROTOCOL_VIOLATION, tlvs(&aborted[0][4..])[0].0);
        } else {
            assert_eq!(0, a.inflight_queue.len(), "everything acknowledged");
        }
    }
}

// ---- Duplicate TSNs -------------------------------------------------------------------------

/// RFC 9260 7.2.2: partial_bytes_acked counts "the number of bytes of duplicated chunks
/// reported in Duplicate TSNs"; 6.2: the sender "MAY use the duplicate TSN information to
/// determine if SACK chunk loss is occurring". A receiver that repeats a TSN hundreds of
/// times, or lists TSNs never sent, counts each chunk this side saw acknowledged once and
/// nothing else, finds no lost SACK (nothing was sent again on a timeout) and is no reason
/// to abort (the duplicates acknowledge nothing).
#[test]
fn a_flood_of_duplicate_tsns_counts_each_acknowledged_chunk_once() {
    let (mut link, tsns) = sending(349);
    counting_bytes(&mut link);
    deliver_sack(&mut link, tsns[3], &[], &[]);
    let before = sender_state(link.server.conn(), tsns[0]);
    assert_eq!(4 * WIRE, before.partial_bytes_acked, "precondition");

    let mut duplicates = vec![tsns[0]; 200];
    duplicates.extend(std::iter::repeat_n(tsns[1], 50));
    duplicates.extend(std::iter::repeat_n(tsns[7].wrapping_add(1000), 40));
    duplicates.extend(std::iter::repeat_n(tsns[6], 10));
    deliver_sack(&mut link, tsns[3], &[], &duplicates);

    let a = link.server.conn();
    let after = sender_state(a, tsns[0]);
    assert_eq!(
        SenderState {
            partial_bytes_acked: before.partial_bytes_acked + 2 * WIRE,
            ..before
        },
        after,
        "TSNs 0 and 1 once each; TSN 6 is outstanding, the others were never sent"
    );
    assert_eq!(0, a.stats.get_num_sack_losses());
}