rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! Partial reliability against a peer that shuts down or sends malformed FORWARD TSN /
//! I-FORWARD-TSN chunks (RFC 3758 3.5, 3.6; RFC 8260 2.3.1), at association level. Test
//! purposes from the nplab PR_SCTP_Testsuite (BSD-3: the shutdown-received and error-case
//! families, re-expressed; nothing copied).

use super::robustness_test::*;
use super::*;
use crate::chunk::chunk_i_forward_tsn::ChunkIForwardTsnStream;
use crate::chunk::chunk_type::*;
use crate::endpoint::link_test::Link;
use std::cell::RefCell;
use std::rc::Rc;
use stream::ReliabilityType;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;

/// The chunk types of each datagram on the link, with whether it came from the client.
type Seen = Rc<RefCell<Vec<(bool, Vec<u8>)>>>;

fn types(datagram: &Bytes) -> Vec<u8> {
    chunks_of(datagram).iter().map(|c| c[0]).collect()
}

/// The peer shuts down while partially reliable DATA of this side is outstanding and lost
/// (the shutdown-received purposes). RFC 9260 9.2: in SHUTDOWN-RECEIVED this side goes on
/// with what it has outstanding; RFC 3758 3.5: what its policy gives up is abandoned and
/// skipped with FORWARD TSN, which the peer, in SHUTDOWN-SENT, takes (3.6). The shutdown
/// then completes: SHUTDOWN ACK, SHUTDOWN COMPLETE, both associations closed without an
/// ABORT and the lost messages never delivered.
#[test]
fn a_peer_shutdown_with_lost_unreliable_data_completes_after_a_forward_tsn() {
    for (n, (unordered, policy, value)) in [
        (false, ReliabilityType::Rexmit, 0),
        (true, ReliabilityType::Rexmit, 0),
        (false, ReliabilityType::Timed, 100),
    ]
    .into_iter()
    .enumerate()
    {
        let case = format!("unordered {unordered}, {policy:?} {value}");
        let mut link = connected_link(370 + n as u64);
        let seen: Seen = Rc::default();
        let record = seen.clone();
        link.filter = Some(Box::new(move |from_client: bool, datagram: &Bytes| {
            let t = types(datagram);
            record.borrow_mut().push((from_client, t.clone()));
            // Every packet of the server's that carries DATA is lost.
            !from_client && t.contains(&CT_PAYLOAD_DATA.0)
        }));
        let now = link.now;
        {
            let a = link.server.conn();
            let mut s = a.open_stream(2, PPI).unwrap();
            s.set_reliability_params(unordered, policy, value).unwrap();
            for _ in 0..3 {
                s.write_sctp(now, &Bytes::from_static(b"lost"), PPI)
                    .unwrap();
            }
        }
        link.run_for(Duration::from_millis(1));
        assert!(link.dropped > 0, "{case}: precondition: the DATA was lost");
        link.client.conn().shutdown().unwrap();

        let deadline = link.now + Duration::from_secs(120);
        assert!(
            link.run_until(deadline, |l| l.client.conn().is_ended()
                && l.server.conn().is_ended()),
            "{case}: the shutdown did not complete"
        );
        let seen = seen.borrow();
        let sent = |from_client: bool, typ: ChunkType| {
            seen.iter()
                .filter(|(c, t)| *c == from_client && t.contains(&typ.0))
                .count()
        };
        assert!(sent(false, CT_FORWARD_TSN) > 0, "{case}: a FORWARD TSN");
        assert!(sent(false, CT_SHUTDOWN_ACK) > 0, "{case}: a SHUTDOWN ACK");
        assert!(sent(true, CT_SHUTDOWN_COMPLETE) > 0, "{case}");
        assert_eq!(0, sent(true, CT_ABORT) + sent(false, CT_ABORT), "{case}");
        assert!(link.client.received.is_empty(), "{case}");
    }
}

/// The error-case purposes for FORWARD TSN: a chunk too short for its New Cumulative TSN, or
/// whose stream entries are cut. It does not parse and its packet is discarded (FreeBSD's
/// behaviour; RFC 3758 prescribes no answer), DATA bundled with it too: the cumulative TSN
/// does not move, nothing is answered, and the next well-formed FORWARD TSN is taken.
#[test]
fn a_malformed_forward_tsn_is_discarded_with_its_packet() {
    for value_length in [0usize, 2, 6, 10] {
        let mut link = connected_link(374);
        let now = link.now;
        let a = link.server.conn();
        assert!(a.use_forward_tsn, "precondition: PR-SCTP negotiated");
        let last = a.peer_last_tsn;
        let mut value = last.wrapping_add(1).to_be_bytes().to_vec();
        value.extend_from_slice(&[0, 1, 0, 0, 0, 2]);
        value.truncate(value_length);
        let raw = packet_to(
            a,
            &[
                raw_chunk(CT_FORWARD_TSN.0, 0, &value),
                data_chunk(last.wrapping_add(2), 1, 0, b"with it"),
            ],
        );
        inject(a, now, raw);
        assert!(!a.is_ended(), "value of {value_length} bytes");
        assert_eq!(last, a.peer_last_tsn, "value of {value_length} bytes");
        assert!(sent_after(a, now, Duration::from_secs(1)).is_empty());

        let valid = chunk_bytes(&ChunkForwardTsn {
            new_cumulative_tsn: last.wrapping_add(1),
            streams: vec![],
        });
        let raw = packet_to(a, &[valid]);
        inject(a, now + Duration::from_secs(1), raw);
        assert_eq!(last.wrapping_add(1), a.peer_last_tsn);
    }
}

/// RFC 3758 3.6: a FORWARD TSN whose New Cumulative TSN is "behind or at the current
/// cumulative TSN point" is out of date: "MUST NOT update its Cumulative TSN", and its stream
/// entries change nothing either. Stream 1 took SSN 0; a stale FORWARD TSN that names SSN 9
/// of it does not make SSN 1 look old.
#[test]
fn a_stale_forward_tsn_moves_no_stream_sequence_number() {
    let mut link = connected_link(375);
    let now = link.now;
    let a = link.server.conn();
    let last = a.peer_last_tsn;
    let raw = packet_to(a, &[data_chunk(last.wrapping_add(1), 1, 0, b"ssn 0")]);
    inject(a, now, raw);
    assert_eq!(vec![Bytes::from_static(b"ssn 0")], read_all(a, 1));
    let _ = sent_datagrams(a, now);

    let stale = chunk_bytes(&ChunkForwardTsn {
        new_cumulative_tsn: last,
        streams: vec![crate::chunk::chunk_forward_tsn::ChunkForwardTsnStream {
            identifier: 1,
            sequence: 9,
        }],
    });
    let raw = packet_to(a, &[stale]);
    inject(a, now, raw);
    assert_eq!(last.wrapping_add(1), a.peer_last_tsn);
    assert_eq!(1, chunks_of_type(&sent_datagrams(a, now), CT_SACK.0).len());

    let raw = packet_to(a, &[data_chunk(last.wrapping_add(2), 1, 1, b"ssn 1")]);
    inject(a, now, raw);
    assert_eq!(vec![Bytes::from_static(b"ssn 1")], read_all(a, 1));
}

fn interleaved_link(seed: u64) -> Link {
    let config = TransportConfig::default().with_message_interleaving(true);
    let mut link = Link::new(config.clone(), config, seed);
    link.connect();
    let a = link.server.conn();
    assert!(
        a.use_interleaving && a.use_forward_tsn,
        "precondition: I-DATA and I-FORWARD-TSN negotiated"
    );
    link
}

fn i_data(tsn: u32, stream: u16, mid: u32, payload: &'static [u8]) -> Vec<u8> {
    chunk_bytes(&ChunkPayloadData {
        i_data: true,
        tsn,
        stream_identifier: stream,
        mid,
        beginning_fragment: true,
        ending_fragment: true,
        payload_type: PPI,
        user_data: Bytes::from_static(payload),
        ..Default::default()
    })
}

/// The error-case purposes for I-FORWARD-TSN: entries cut short (RFC 8260 2.3.1: eight bytes
/// each). Discarded with the packet, as above.
#[test]
fn a_malformed_i_forward_tsn_is_discarded_with_its_packet() {
    for value_length in [0usize, 2, 8, 10] {
        let mut link = interleaved_link(376);
        let now = link.now;
        let a = link.server.conn();
        let last = a.peer_last_tsn;
        let mut value = last.wrapping_add(1).to_be_bytes().to_vec();
        value.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 2, 0, 3]);
        value.truncate(value_length);
        let raw = packet_to(a, &[raw_chunk(CT_I_FORWARD_TSN.0, 0, &value)]);
        inject(a, now, raw);
        assert!(!a.is_ended(), "value of {value_length} bytes");
        assert_eq!(last, a.peer_last_tsn, "value of {value_length} bytes");
        assert!(sent_after(a, now, Duration::from_secs(1)).is_empty());
    }
}

/// An I-FORWARD-TSN that lists one stream several times (pion/werift's duplicate entries) skips
/// up to the largest Message Identifier listed, whatever their order; one that names a stream
/// beyond the negotiated count changes nothing there and closes nothing.
#[test]
fn an_i_forward_tsn_with_repeated_or_out_of_range_entries_is_taken_whole() {
    let mut link = interleaved_link(377);
    let now = link.now;
    let a = link.server.conn();
    let last = a.peer_last_tsn;
    let raw = packet_to(a, &[i_data(last.wrapping_add(1), 3, 0, b"mid 0")]);
    inject(a, now, raw);
    assert_eq!(vec![Bytes::from_static(b"mid 0")], read_all(a, 3));

    let entry = |identifier, mid| ChunkIForwardTsnStream {
        identifier,
        unordered: false,
        mid,
    };
    let forward = chunk_bytes(&ChunkIForwardTsn {
        new_cumulative_tsn: last.wrapping_add(3),
        streams: vec![entry(3, 2), entry(3, 5), entry(3, 4), entry(u16::MAX, 7)],
    });
    let raw = packet_to(a, &[forward]);
    inject(a, now, raw);
    assert!(!a.is_ended());
    assert_eq!(last.wrapping_add(3), a.peer_last_tsn);
    assert!(
        !a.streams.contains_key(&u16::MAX),
        "no stream for the out-of-range entry"
    );

    let raw = packet_to(a, &[i_data(last.wrapping_add(4), 3, 6, b"mid 6")]);
    inject(a, now, raw);
    assert_eq!(
        vec![Bytes::from_static(b"mid 6")],
        read_all(a, 3),
        "MIDs 1 to 5 are skipped"
    );
}