rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! RFC 9260 5.1 C: "The COOKIE ECHO chunk MAY be bundled with any pending outbound DATA
//! chunks, but it MUST be the first chunk in the packet and, until the COOKIE ACK chunk is
//! returned, the sender MUST NOT send any other packets to the peer." 3.3.11: the COOKIE ECHO
//! "MUST precede any DATA chunk sent within the association but MAY be bundled with one or
//! more DATA chunks in the same packet." The form is
//! `TransportConfig::with_data_in_cookie_echo(true)`; off (the default) a stream refuses DATA
//! in COOKIE-ECHOED (`cookie_ack_loss_test::data_written_when_the_cookie_ack_arrives_leaves_at_once`).

use super::robustness_test::*;
use super::*;
use crate::chunk::chunk_type::*;
use crate::endpoint::link_test::{Link, first_chunk_type};
use std::cell::RefCell;
use std::rc::Rc;

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;

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

/// The TSNs of the DATA chunks of `datagram`.
fn data_tsns(datagram: &Bytes) -> Vec<u32> {
    chunks_of(datagram)
        .iter()
        .filter(|c| c[0] == CT_PAYLOAD_DATA.0)
        .map(|c| u32::from_be_bytes([c[4], c[5], c[6], c[7]]))
        .collect()
}

/// The user data bytes of the DATA chunks among `datagrams` (a DATA chunk header is 16 bytes).
fn data_bytes(datagrams: &[Bytes]) -> usize {
    chunks_of_type(datagrams, CT_PAYLOAD_DATA.0)
        .iter()
        .map(|c| c.len() - 16)
        .sum()
}

/// A client association, by hand, past its INIT ACK: in COOKIE-ECHOED with the COOKIE ECHO
/// queued and not yet gathered.
fn cookie_echoed_client(config: TransportConfig, now: Instant) -> Association {
    let mut endpoint = crate::endpoint::Endpoint::new(
        remote(),
        TransportProtocol::UDP,
        Arc::new(crate::EndpointConfig::default()),
        None,
    );
    let (_, mut a) = endpoint
        .connect(
            now,
            crate::ClientConfig::new(config),
            "10.0.0.2:5000".parse().unwrap(),
        )
        .unwrap();
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(&mut a, now), CT_INIT.0).len()
    );
    let init_ack = init_chunk(CT_INIT_ACK.0, 4242, 9000, &[raw_tlv(7, b"cookie")]);
    let raw = packet_to(&a, &[init_ack]);
    inject(&mut a, now, raw);
    assert_eq!(AssociationState::CookieEchoed, a.state());
    a
}

fn write(a: &mut Association, now: Instant, stream: u16, len: usize) {
    if a.stream(stream).is_err() {
        a.open_stream(stream, PPI).unwrap();
    }
    a.stream(stream)
        .unwrap()
        .write_sctp(now, &Bytes::from(vec![stream as u8; len]), PPI)
        .unwrap();
}

/// Four messages of 400 bytes are written in COOKIE-ECHOED before the COOKIE ECHO is sent: it
/// leaves first in one packet with the two that fit the MTU after it, and nothing else is sent
/// (5.1 C). A message written later waits. T1-cookie's retransmission carries the same two
/// DATA chunks again (the same TSNs, counted as retransmissions). T3-rtx does not run before
/// the COOKIE ACK; on it the rest goes, with T3-rtx running.
#[test]
fn the_cookie_echo_carries_the_pending_data_that_fits_and_its_retransmission_carries_it_again() {
    let now = Instant::now();
    let mut a = cookie_echoed_client(
        TransportConfig::default().with_data_in_cookie_echo(true),
        now,
    );
    for _ in 0..4 {
        write(&mut a, now, 1, 400);
    }
    let first = sent_datagrams(&mut a, now);
    assert_eq!(1, first.len(), "one packet before the COOKIE ACK");
    assert_eq!(
        vec![CT_COOKIE_ECHO.0, CT_PAYLOAD_DATA.0, CT_PAYLOAD_DATA.0],
        types(&first[0]),
        "the COOKIE ECHO first, then the DATA that fits"
    );
    assert!(first[0].len() <= a.mtu as usize, "within the MTU");
    assert!(
        first[0].len() + 400 + 16 > a.mtu as usize,
        "a third message would not have fit"
    );
    let tsns = data_tsns(&first[0]);
    assert!(a.timers.get(Timer::T3RTX).is_none(), "T1-cookie covers it");

    write(&mut a, now, 2, 100);
    assert!(
        sent_datagrams(&mut a, now).is_empty(),
        "nothing else before the COOKIE ACK"
    );

    let due = a.timers.get(Timer::T1Cookie).expect("T1-cookie runs");
    a.handle_timeout(due);
    let again = sent_datagrams(&mut a, due);
    assert_eq!(1, again.len());
    assert_eq!(Some(&CT_COOKIE_ECHO.0), types(&again[0]).first());
    assert_eq!(
        tsns,
        data_tsns(&again[0])[..tsns.len()],
        "the DATA sent with the lost COOKIE ECHO goes again, first"
    );
    assert_eq!(2, a.stats.get_num_retransmissions());

    let raw = packet_to(&a, &[raw_chunk(CT_COOKIE_ACK.0, 0, &[])]);
    inject(&mut a, due, raw);
    assert_eq!(AssociationState::Established, a.state());
    let rest = sent_datagrams(&mut a, due);
    assert_eq!(
        4 * 400 + 100,
        data_bytes(&again) + data_bytes(&rest),
        "the rest goes once ESTABLISHED"
    );
    assert!(a.timers.get(Timer::T3RTX).is_some());
}

/// A message that went whole with the COOKIE ECHO: from the COOKIE ACK on it is timed by
/// T3-rtx (6.3.2 R1), and sent again at its expiry when the peer has not acknowledged it.
#[test]
fn data_that_went_with_the_cookie_echo_is_timed_by_t3_rtx_once_established() {
    let now = Instant::now();
    let mut a = cookie_echoed_client(
        TransportConfig::default().with_data_in_cookie_echo(true),
        now,
    );
    write(&mut a, now, 1, 200);
    let first = sent_datagrams(&mut a, now);
    assert_eq!(vec![CT_COOKIE_ECHO.0, CT_PAYLOAD_DATA.0], types(&first[0]));
    let tsn = data_tsns(&first[0]);

    let ack_at = now + Duration::from_millis(50);
    let raw = packet_to(&a, &[raw_chunk(CT_COOKIE_ACK.0, 0, &[])]);
    inject(&mut a, ack_at, raw);
    assert_eq!(AssociationState::Established, a.state());
    assert!(
        chunks_of_type(&sent_datagrams(&mut a, ack_at), CT_PAYLOAD_DATA.0).is_empty(),
        "nothing new to send"
    );
    let t3 = a
        .timers
        .get(Timer::T3RTX)
        .expect("T3-rtx runs for the DATA outstanding");
    a.handle_timeout(t3);
    let resent = sent_datagrams(&mut a, t3);
    assert_eq!(
        tsn,
        resent.iter().flat_map(data_tsns).collect::<Vec<_>>(),
        "sent again at T3-rtx"
    );
}

/// Two associations of this crate. The client's first COOKIE ECHO is lost; a message written
/// in COOKIE-ECHOED goes in the packet of the second, the only client packet with DATA before
/// the COOKIE ACK, and the server, taking the COOKIE ECHO first, delivers it while the client
/// is still waiting for the COOKIE ACK: one round trip earlier than DATA sent after it.
#[test]
fn with_data_in_cookie_echo_the_peer_gets_the_first_message_with_the_cookie_echo() {
    let mut link = Link::new(
        TransportConfig::default().with_data_in_cookie_echo(true),
        TransportConfig::default(),
        5,
    );
    let seen: Rc<RefCell<Vec<(bool, Bytes)>>> = Rc::default();
    let record = seen.clone();
    let mut echoes = 0;
    link.filter = Some(Box::new(move |from_client, datagram: &Bytes| {
        record.borrow_mut().push((from_client, datagram.clone()));
        if from_client && first_chunk_type(datagram) == Some(CT_COOKIE_ECHO.0) {
            echoes += 1;
            return echoes == 1;
        }
        false
    }));
    link.begin_connect();
    let deadline = link.now + Duration::from_secs(5);
    assert!(link.run_until(deadline, |l| l.client.conn().state()
        == AssociationState::CookieEchoed));
    let now = link.now;
    link.client
        .conn()
        .open_stream(1, PPI)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"with the cookie echo"), PPI)
        .unwrap();
    let deadline = link.now + Duration::from_secs(10);
    assert!(link.run_until(deadline, |l| !l.server.received.is_empty()));
    assert_eq!(
        vec![(1, Bytes::from_static(b"with the cookie echo"))],
        link.server.received
    );
    assert_eq!(
        AssociationState::CookieEchoed,
        link.client.conn().state(),
        "delivered before the COOKIE ACK is back"
    );
    let with_data: Vec<Vec<u8>> = seen
        .borrow()
        .iter()
        .filter(|(from_client, d)| *from_client && types(d).contains(&CT_PAYLOAD_DATA.0))
        .map(|(_, d)| types(d))
        .collect();
    assert_eq!(vec![vec![CT_COOKIE_ECHO.0, CT_PAYLOAD_DATA.0]], with_data);

    let deadline = link.now + Duration::from_secs(5);
    assert!(link.run_until(deadline, |l| l.client.connected()
        && l.client.conn().inflight_queue.is_empty()));
}