rtci-sctp 0.4.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! RFC 9260 6.2, the zero window renege: "When the receiver's advertised window is 0, ... if
//! the new incoming DATA chunk holds a TSN value less than the largest TSN received so far,
//! then the receiver SHOULD drop the largest TSN held for reordering and accept the new
//! incoming DATA chunk." The RFC form is `TransportConfig::with_zero_window_renege(true)`; the
//! default takes the gap filler with nothing dropped (up to one message beyond the buffer).

use super::*;
use crate::TransportConfig;
use crate::endpoint::link_test::Link;

const BUFFER: u32 = 4096;
const CHUNK: usize = 1024;

/// A whole message in one DATA chunk of `CHUNK` bytes on ordered stream 0, number `ssn`.
fn whole_message(tsn: u32, ssn: u16) -> ChunkPayloadData {
    ChunkPayloadData {
        beginning_fragment: true,
        ending_fragment: true,
        tsn,
        stream_identifier: 0,
        stream_sequence_number: ssn,
        payload_type: PayloadProtocolIdentifier::Binary,
        user_data: Bytes::from(vec![ssn as u8; CHUNK]),
        ..Default::default()
    }
}

/// The TSNs a SACK reports in its Gap Ack Blocks.
fn gap_acked(sack: &ChunkSelectiveAck) -> Vec<u32> {
    sack.gap_ack_blocks
        .iter()
        .flat_map(|b| {
            (b.start..=b.end).map(|offset| sack.cumulative_tsn_ack.wrapping_add(u32::from(offset)))
        })
        .collect()
}

/// The receiver alone. Message 0 of an ordered stream is lost; the messages after it are held
/// for reordering until the window is advertised closed (a_rwnd 0) with them in a Gap Ack
/// Block. Then message 0 arrives: it fills the gap.
///
/// With the setting it takes the place of the largest TSN held: that TSN is dropped from the
/// stream and from the next SACK (6.2: no longer reported), which acknowledges message 0 and
/// the rest cumulatively; the bytes held stay within the buffer; the dropped chunk, sent
/// again, is taken and its message read in order. Without the setting (the default) message
/// 0 is taken with nothing dropped: the cumulative TSN covers the last one too.
///
/// Both ways the window comes to be advertised closed: the buffer full (no space left), and
/// silly window avoidance (RFC 9260 6.2: a_rwnd 0 with less than a full chunk free, the space
/// a sender stopped by it leaves unused, as two associations of this crate do). The renege
/// keys on the advertised window, so it happens in both.
#[test]
fn with_zero_window_renege_a_gap_filler_through_a_closed_window_takes_the_place_of_the_largest_held_tsn()
-> Result<()> {
    for (renege, full) in [(true, true), (true, false), (false, true), (false, false)] {
        let mut a = create_association(
            TransportConfig::default()
                .with_max_receive_buffer_size(BUFFER)
                .with_max_message_size(16 * 1024)
                .with_zero_window_renege(renege),
        );
        a.set_state(AssociationState::Established);
        assert!(
            a.create_stream(0, true, PayloadProtocolIdentifier::Binary)
                .is_some()
        );
        let first = a.peer_last_tsn.wrapping_add(1);
        let mut ssn = 1u16;
        while if full {
            a.get_my_receiver_window_credit() > 0
        } else {
            a.advertised_window() > 0
        } {
            a.handle_data(&whole_message(first.wrapping_add(u32::from(ssn)), ssn))?;
            ssn += 1;
        }
        let largest = first.wrapping_add(u32::from(ssn - 1));
        let held = usize::from(ssn - 1) * CHUNK;
        assert_eq!(a.bytes_in_reassembly_queues(), held);
        assert_eq!(
            a.get_my_receiver_window_credit() > 0,
            !full,
            "precondition: space left only when closed by silly window avoidance ({held} held)"
        );
        let closed = a.create_selective_ack_chunk();
        // Preconditions: the window is advertised closed, nothing is readable (message 0 is
        // missing), and every held TSN, the largest among them, is in a Gap Ack Block.
        assert_eq!(closed.advertised_receiver_window_credit, 0);
        assert_eq!(closed.cumulative_tsn_ack, first.wrapping_sub(1));
        assert!(!a.has_readable_data());
        assert_eq!(
            gap_acked(&closed),
            (1..ssn)
                .map(|i| first.wrapping_add(u32::from(i)))
                .collect::<Vec<_>>()
        );
        assert!(ssn >= 3, "at least two messages held: {ssn}");

        a.immediate_ack_triggered = false;
        a.handle_data(&whole_message(first, 0))?;
        assert!(
            a.immediate_ack_triggered,
            "taken through a closed window: SACK at once"
        );
        let sack = a.create_selective_ack_chunk();
        let reneged = a.stats().get_num_reneged();
        if !renege {
            assert_eq!(sack.cumulative_tsn_ack, largest, "default: nothing dropped");
            assert_eq!(reneged, 0);
            assert_eq!(
                a.bytes_in_reassembly_queues(),
                held + CHUNK,
                "default: taken in addition"
            );
            continue;
        }
        assert_eq!(
            sack.cumulative_tsn_ack,
            largest.wrapping_sub(1),
            "message 0 and the ones after it up to the dropped TSN acknowledged"
        );
        assert!(
            sack.gap_ack_blocks.is_empty(),
            "the dropped TSN is no longer reported: {:?}",
            sack.gap_ack_blocks
        );
        assert_eq!(reneged, 1);
        assert!(a.payload_queue.get(largest).is_none());
        assert_eq!(
            a.bytes_in_reassembly_queues(),
            held,
            "one chunk for another"
        );

        // The application reads messages 0 to ssn - 2 in order; the dropped one is not there.
        let mut read = vec![];
        while let Some(chunks) = a.stream(0)?.read_sctp()? {
            read.push(chunks.ssn);
        }
        assert_eq!(read, (0..ssn - 1).collect::<Vec<_>>());

        // The peer sends the dropped chunk again: it is taken and read.
        a.handle_data(&whole_message(largest, ssn - 1))?;
        assert_eq!(a.peer_last_tsn, largest);
        let again = a.stream(0)?.read_sctp()?.map(|c| c.ssn);
        assert_eq!(again, Some(ssn - 1));
    }
    Ok(())
}

/// A chunk of a message the application can read now is not held for reordering: with the
/// setting, a gap filler through a closed window drops none of an unordered message that is
/// complete (readable), and is taken as without the setting.
#[test]
fn with_zero_window_renege_a_readable_message_is_not_dropped() -> Result<()> {
    let mut a = create_association(
        TransportConfig::default()
            .with_max_receive_buffer_size(BUFFER)
            .with_max_message_size(16 * 1024)
            .with_zero_window_renege(true),
    );
    a.set_state(AssociationState::Established);
    assert!(
        a.create_stream(0, true, PayloadProtocolIdentifier::Binary)
            .is_some()
    );
    let first = a.peer_last_tsn.wrapping_add(1);
    let mut i = 1u32;
    while a.get_my_receiver_window_credit() > 0 {
        let mut c = whole_message(first.wrapping_add(i), 0);
        c.unordered = true;
        a.handle_data(&c)?;
        i += 1;
    }
    assert_eq!(
        a.create_selective_ack_chunk()
            .advertised_receiver_window_credit,
        0
    );
    assert!(
        a.has_readable_data(),
        "precondition: complete unordered messages"
    );
    a.handle_data(&whole_message(first, 0))?;
    assert_eq!(a.stats().get_num_reneged(), 0);
    assert_eq!(
        a.peer_last_tsn,
        first.wrapping_add(i - 1),
        "taken, nothing dropped"
    );
    Ok(())
}

/// The TSNs of the DATA chunks in an SCTP packet (RFC 9260 3.2: chunks follow the 12-byte
/// common header, each padded to 4 bytes; a DATA chunk's TSN follows its 4-byte header).
fn data_tsns(datagram: &Bytes) -> Vec<u32> {
    let mut tsns = vec![];
    let mut at = 12;
    while at + 4 <= datagram.len() {
        let kind = datagram[at];
        let len = usize::from(u16::from_be_bytes([datagram[at + 2], datagram[at + 3]]));
        if len < 4 {
            break;
        }
        if kind == 0 && at + 8 <= datagram.len() {
            tsns.push(u32::from_be_bytes([
                datagram[at + 4],
                datagram[at + 5],
                datagram[at + 6],
                datagram[at + 7],
            ]));
        }
        at += len.div_ceil(4) * 4;
    }
    tsns
}

/// The SACK chunks in an SCTP packet: their Cumulative TSN Ack and the TSNs their Gap Ack
/// Blocks report (RFC 9260 3.3.4: after the chunk header, the Cumulative TSN Ack, a_rwnd, the
/// numbers of Gap Ack Blocks and of Duplicate TSNs, then the blocks as 16-bit offsets).
fn sacks(datagram: &Bytes) -> Vec<(u32, Vec<u32>)> {
    let u16_at = |i: usize| u16::from_be_bytes([datagram[i], datagram[i + 1]]);
    let mut out = vec![];
    let mut at = 12;
    while at + 4 <= datagram.len() {
        let len = usize::from(u16_at(at + 2));
        if len < 4 || at + len > datagram.len() {
            break;
        }
        if datagram[at] == 3 && len >= 16 {
            let cum = u32::from_be_bytes([
                datagram[at + 4],
                datagram[at + 5],
                datagram[at + 6],
                datagram[at + 7],
            ]);
            let blocks = usize::from(u16_at(at + 12));
            let mut tsns = vec![];
            for b in 0..blocks {
                let i = at + 16 + 4 * b;
                if i + 4 > at + len {
                    break;
                }
                for offset in u16_at(i)..=u16_at(i + 2) {
                    tsns.push(cum.wrapping_add(u32::from(offset)));
                }
            }
            out.push((cum, tsns));
        }
        at += len.div_ceil(4) * 4;
    }
    out
}

/// The TSNs that a SACK reported in a Gap Ack Block and a later SACK, its Cumulative TSN Ack
/// still below them, no longer reports: reneges as the sender sees them on the wire.
fn reneged_on_the_wire(sacks: &[(u32, Vec<u32>)]) -> Vec<u32> {
    let mut reneged = vec![];
    for (i, (_, gaps)) in sacks.iter().enumerate() {
        for &tsn in gaps {
            if !reneged.contains(&tsn)
                && sacks[i + 1..]
                    .iter()
                    .any(|(cum, later)| sna32lt(*cum, tsn) && !later.contains(&tsn))
            {
                reneged.push(tsn);
            }
        }
    }
    reneged
}

/// Two associations of this crate over a link. The sender writes 40 messages of 1000 bytes on
/// an ordered stream to a receiver with a 4 KiB buffer; the link loses the third DATA chunk
/// twice (its first transmission and its first retransmission), so the messages after it fill
/// the buffer behind the gap and the window is advertised closed before the chunk arrives.
///
/// With the setting the receiver reneges on the largest TSN it holds, and this crate's sender
/// (RFC 9260 6.2.1 D iii: a chunk a Gap Ack Block covered that a later SACK leaves out is
/// outstanding again) sends it again: every message arrives, in order. The receiver's SACKs
/// as they cross the link show it: a TSN a Gap Ack Block reported is left out of a later SACK
/// whose Cumulative TSN Ack is below it (all a sender can see of a renege). Without it nothing is
/// dropped and every message arrives as well. libwebrtc's dcSCTP never sends such a chunk
/// again (see `TransportConfig::with_zero_window_renege`): the browser cell for that is in
/// scripts/test-env/interop/scenarios.spec.mjs.
#[test]
fn with_zero_window_renege_this_crates_sender_sends_the_dropped_chunk_again() -> Result<()> {
    for renege in [true, false] {
        let mut link = Link::new(
            TransportConfig::default().with_max_message_size(16 * 1024),
            TransportConfig::default()
                .with_max_receive_buffer_size(BUFFER)
                .with_max_receive_message_size(16 * 1024)
                .with_zero_window_renege(renege),
            7,
        );
        let lost = std::rc::Rc::new(std::cell::Cell::new(0usize));
        let (mut first_tsn, mut copies) = (None::<u32>, 0usize);
        let seen = lost.clone();
        let wire_sacks = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
        let recorded = wire_sacks.clone();
        link.filter = Some(Box::new(move |from_client, datagram| {
            if !from_client {
                recorded.borrow_mut().extend(sacks(datagram));
                return false;
            }
            let tsns = data_tsns(datagram);
            let Some(&tsn) = tsns.first() else {
                return false;
            };
            let target = first_tsn.get_or_insert(tsn).wrapping_add(2);
            if tsns.contains(&target) && copies < 2 {
                copies += 1;
                seen.set(copies);
                return true;
            }
            false
        }));
        link.connect();
        let start = link.now;
        let ppi = PayloadProtocolIdentifier::Binary;
        let messages: Vec<Bytes> = (0..40u8).map(|i| Bytes::from(vec![i; 1000])).collect();
        link.client.conn().open_stream(1, ppi)?;
        for m in &messages {
            link.client.conn().stream(1)?.write_sctp(start, m, ppi)?;
        }
        let done = link.run_until(start + Duration::from_secs(60), |l| {
            l.server.received.len() == messages.len()
        });
        let reneged = link.server.conn().stats().get_num_reneged();
        assert_eq!(lost.get(), 2, "precondition: the chunk was lost twice");
        assert!(
            done,
            "renege {renege}: {} of {} messages delivered, reneged {reneged}",
            link.server.received.len(),
            messages.len()
        );
        let got: Vec<Bytes> = link
            .server
            .received
            .iter()
            .map(|(_, b)| b.clone())
            .collect();
        assert_eq!(got, messages, "in order, each whole");
        let on_the_wire = reneged_on_the_wire(&wire_sacks.borrow());
        if renege {
            assert!(reneged >= 1, "the receiver reneged");
            assert!(
                !on_the_wire.is_empty(),
                "a later SACK on the wire leaves out the reneged TSN"
            );
        } else {
            assert_eq!(reneged, 0);
            assert_eq!(on_the_wire, Vec::<u32>::new(), "no renege on the wire");
        }
    }
    Ok(())
}