rtci-sctp 0.5.0

Sans-I/O SCTP (RFC 9260) with partial reliability and stream reconfiguration, for WebRTC data channels
Documentation
//! ETSI TS 102 369 test purposes the clause audit found without a test (the nplab
//! ETSI-SCTP-Conformance-Testsuite, BSD-2, lists them; the purposes are re-expressed here,
//! nothing of its scripts is copied), and a forged HEARTBEAT ACK (dcSCTP, BSD-3, idea).

use super::robustness_test::*;
use super::*;
use crate::chunk::chunk_type::*;
use crate::endpoint::Endpoint;
use crate::{ClientConfig, EndpointConfig, TimerConfig};

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

fn connecting() -> (Association, Instant) {
    let mut endpoint = Endpoint::new(
        remote(),
        TransportProtocol::UDP,
        Arc::new(EndpointConfig::default()),
        None,
    );
    let now = Instant::now();
    let (_, mut a) = endpoint
        .connect(
            now,
            ClientConfig::new(TransportConfig::default()),
            "10.0.0.2:5000".parse().unwrap(),
        )
        .unwrap();
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(&mut a, now), CT_INIT.0).len()
    );
    (a, now)
}

/// imh-i-3-2: an INIT ACK too small for its mandatory fields (Chunk Length 8) in COOKIE-WAIT.
/// The chunk does not parse and its packet is discarded (FreeBSD's behaviour; RFC 9260
/// prescribes no answer to a malformed INIT ACK): the endpoint stays in COOKIE-WAIT, T1-init
/// sends the INIT again, and a proper INIT ACK still completes the step.
#[test]
fn an_init_ack_too_small_for_its_fields_is_discarded_in_cookie_wait() {
    let (mut a, now) = connecting();
    let raw = packet_to(&a, &[raw_chunk(CT_INIT_ACK.0, 0, &[1, 2, 3, 4])]);
    inject(&mut a, now, raw);
    assert_eq!(AssociationState::CookieWait, a.state());
    assert!(!a.is_ended());
    assert!(sent_datagrams(&mut a, now).is_empty(), "nothing answers it");

    let due = a.timers.get(Timer::T1Init).expect("T1-init still runs");
    a.handle_timeout(due);
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(&mut a, due), CT_INIT.0).len(),
        "the INIT is sent again"
    );
    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, due, raw);
    assert_eq!(AssociationState::CookieEchoed, a.state());
}

/// dm-o-4-7-2: a SHUTDOWN ACK in ESTABLISHED. RFC 9260 acts on one in SHUTDOWN-SENT and
/// SHUTDOWN-ACK-SENT (9.2) and in COOKIE-WAIT / COOKIE-ECHOED (8.5.1 E); in ESTABLISHED it is
/// silently discarded: nothing is answered, and the association carries on. Nothing of it is
/// kept either: when this side shuts down later (as the purpose's script does), it sends its
/// SHUTDOWN and waits for the SHUTDOWN ACK that answers it, instead of completing at once on
/// the stray one.
#[test]
fn a_shutdown_ack_in_established_is_discarded() {
    let mut link = connected_link(361);
    let now = link.now;
    let a = link.server.conn();
    let raw = packet_to(a, &[raw_chunk(CT_SHUTDOWN_ACK.0, 0, &[])]);
    inject(a, now, raw);
    assert_eq!(AssociationState::Established, a.state());
    let sent = sent_after(a, now, Duration::from_secs(1));
    assert!(
        sent.iter().all(|d| !types(d).contains(&CT_SHUTDOWN_COMPLETE.0)
            && !types(d).contains(&CT_ABORT.0)),
        "nothing answers it: {sent:?}"
    );
    let tsn = a.peer_last_tsn.wrapping_add(1);
    let raw = packet_to(a, &[data_chunk(tsn, 1, 0, b"after")]);
    inject(a, now + Duration::from_secs(1), raw);
    assert_eq!(vec![Bytes::from_static(b"after")], read_all(a, 1));

    let later = now + Duration::from_secs(1);
    a.shutdown().unwrap();
    let sent = sent_datagrams(a, later);
    assert_eq!(
        1,
        chunks_of_type(&sent, CT_SHUTDOWN.0).len(),
        "the SHUTDOWN"
    );
    assert!(
        chunks_of_type(&sent, CT_SHUTDOWN_COMPLETE.0).is_empty(),
        "no SHUTDOWN COMPLETE before the peer's SHUTDOWN ACK: {sent:?}"
    );
    assert_eq!(AssociationState::ShutdownSent, a.state());
    assert!(
        !a.is_ended(),
        "the stray SHUTDOWN ACK ended the shutdown early"
    );

    let raw = packet_to(a, &[raw_chunk(CT_SHUTDOWN_ACK.0, 0, &[])]);
    inject(a, later, raw);
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, later), CT_SHUTDOWN_COMPLETE.0).len(),
        "the genuine SHUTDOWN ACK completes it"
    );
    assert!(a.is_ended());
}

/// The server of a connected link after the client's SHUTDOWN: in SHUTDOWN-ACK-SENT, its
/// SHUTDOWN ACK sent.
fn in_shutdown_ack_sent(seed: u64) -> (crate::endpoint::link_test::Link, Instant) {
    let mut link = connected_link(seed);
    let now = link.now;
    let a = link.server.conn();
    let acknowledged = a.my_next_tsn.wrapping_sub(1);
    let raw = packet_to(
        a,
        &[raw_chunk(CT_SHUTDOWN.0, 0, &acknowledged.to_be_bytes())],
    );
    inject(a, now, raw);
    assert_eq!(AssociationState::ShutdownAckSent, a.state(), "precondition");
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, now), CT_SHUTDOWN_ACK.0).len(),
        "precondition: the SHUTDOWN ACK"
    );
    (link, now)
}

/// bdc-i-7-3: a SHUTDOWN COMPLETE bundled with DATA, in SHUTDOWN-ACK-SENT. RFC 9260 3.1 and
/// 6.10: "INIT, INIT ACK, and SHUTDOWN COMPLETE chunks MUST NOT be bundled with any other
/// chunk into an SCTP packet". Such a packet is discarded, as one that bundles an INIT is
/// (5.1; FreeBSD ignores it, Linux aborts): the association stays in SHUTDOWN-ACK-SENT, sends
/// the SHUTDOWN ACK again at T2-shutdown, and a lone SHUTDOWN COMPLETE ends it.
#[test]
fn a_shutdown_complete_bundled_with_data_is_discarded() {
    let (mut link, now) = in_shutdown_ack_sent(362);
    let a = link.server.conn();
    let tsn = a.peer_last_tsn.wrapping_add(1);
    let raw = packet_to(
        a,
        &[
            raw_chunk(CT_SHUTDOWN_COMPLETE.0, 0, &[]),
            data_chunk(tsn, 1, 0, b"late"),
        ],
    );
    inject(a, now, raw);
    assert!(
        !a.is_ended(),
        "the bundled SHUTDOWN COMPLETE ended the association"
    );
    assert_eq!(AssociationState::ShutdownAckSent, a.state());
    assert_eq!(
        tsn.wrapping_sub(1),
        a.peer_last_tsn,
        "the DATA was not taken"
    );
    assert!(sent_datagrams(a, now).is_empty());

    let due = a.timers.get(Timer::T2Shutdown).expect("T2-shutdown runs");
    a.handle_timeout(due);
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, due), CT_SHUTDOWN_ACK.0).len(),
        "the SHUTDOWN ACK again"
    );
    let raw = packet_to(a, &[raw_chunk(CT_SHUTDOWN_COMPLETE.0, 0, &[])]);
    inject(a, due, raw);
    assert!(a.is_ended(), "a lone SHUTDOWN COMPLETE ends it");
}

/// bdc-v-7-8: a SHUTDOWN ACK with DATA bundled after it, in SHUTDOWN-SENT. RFC 9260 9.2:
/// "Upon the reception of the SHUTDOWN ACK chunk, the sender of the SHUTDOWN chunk MUST stop
/// the T2-shutdown timer, send a SHUTDOWN COMPLETE chunk to its peer, and remove all record of
/// the association." The DATA after it is not taken (the purpose's expectation: "the DATA
/// chunk has been ignored"): the answer is one packet, a lone SHUTDOWN COMPLETE, and not a
/// SACK and a new SHUTDOWN as well (12.4: one packet of control chunks per packet received).
#[test]
fn a_shutdown_ack_bundled_with_data_completes_the_shutdown_alone() {
    let mut link = connected_link(363);
    let now = link.now;
    let a = link.client.conn();
    a.shutdown().unwrap();
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, now), CT_SHUTDOWN.0).len(),
        "precondition: the SHUTDOWN"
    );
    assert_eq!(AssociationState::ShutdownSent, a.state(), "precondition");

    let tsn = a.peer_last_tsn.wrapping_add(1);
    let raw = packet_to(
        a,
        &[
            raw_chunk(CT_SHUTDOWN_ACK.0, 0, &[]),
            data_chunk(tsn, 1, 0, b"late"),
        ],
    );
    inject(a, now, raw);
    assert_eq!(tsn.wrapping_sub(1), a.peer_last_tsn, "the DATA was taken");
    let sent = sent_datagrams(a, now);
    assert_eq!(
        vec![vec![CT_SHUTDOWN_COMPLETE.0]],
        sent.iter().map(types).collect::<Vec<_>>(),
        "a lone SHUTDOWN COMPLETE"
    );
    assert!(a.is_ended());
}

/// RFC 9260 8.3: "the sender of the HEARTBEAT chunk ... SHOULD ... compute an RTT" from the
/// HEARTBEAT ACK that answers it. One that echoes information this side did not send (a
/// forged or stale one, dcSCTP's case) is no answer: it gives no RTT sample and leaves the
/// HEARTBEAT outstanding, which the genuine answer then completes.
#[test]
fn a_heartbeat_ack_that_echoes_other_information_gives_no_rtt() {
    let mut link = connected_link(364);
    let a = link.server.conn();
    let due = a
        .timers
        .get(Timer::Heartbeat)
        .expect("the heartbeat timer runs");
    a.handle_timeout(due);
    let heartbeat = chunks_of_type(&sent_datagrams(a, due), CT_HEARTBEAT.0).remove(0);
    let srtt = a.rto_mgr.srtt;
    assert!(a.heartbeat_outstanding.is_some(), "precondition");

    let answered = due + Duration::from_millis(400);
    for forged in [raw_tlv(1, &[9; 16]), raw_tlv(1, &heartbeat[8..16])] {
        let raw = packet_to(a, &[raw_chunk(CT_HEARTBEAT_ACK.0, 0, &forged)]);
        inject(a, answered, raw);
        assert_eq!(srtt, a.rto_mgr.srtt, "no RTT from {forged:?}");
        assert!(a.heartbeat_outstanding.is_some());
    }
    let raw = packet_to(a, &[raw_chunk(CT_HEARTBEAT_ACK.0, 0, &heartbeat[4..])]);
    inject(a, answered, raw);
    assert_ne!(srtt, a.rto_mgr.srtt, "the genuine answer is a sample");
    assert!(a.heartbeat_outstanding.is_none());
}

fn sack_for(cumulative: u32) -> Vec<u8> {
    chunk_bytes(&ChunkSelectiveAck {
        cumulative_tsn_ack: cumulative,
        advertised_receiver_window_credit: 1 << 20,
        gap_ack_blocks: vec![],
        duplicate_tsn: vec![],
    })
}

fn data_tsns(datagrams: &[Bytes]) -> Vec<u32> {
    chunks_of_type(datagrams, CT_PAYLOAD_DATA.0)
        .iter()
        .map(|c| u32::from_be_bytes([c[4], c[5], c[6], c[7]]))
        .collect()
}

const PPI: PayloadProtocolIdentifier = PayloadProtocolIdentifier::Binary;

/// at-i-2-7-1, at-i-2-7-3: RFC 9260 9.2, the endpoint shutting down "MUST NOT accept new data
/// from its SCTP user" in SHUTDOWN-PENDING (DATA still outstanding) nor in SHUTDOWN-SENT.
/// (SHUTDOWN-RECEIVED and SHUTDOWN-ACK-SENT: `nothing_new_is_accepted_once_the_peer_has_shut_down`.)
#[test]
fn no_new_data_is_accepted_in_shutdown_pending_or_shutdown_sent() {
    let mut link = connected_link(365);
    let now = link.now;
    let a = link.client.conn();
    a.open_stream(1, PPI)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"outstanding"), PPI)
        .unwrap();
    let tsns = data_tsns(&sent_datagrams(a, now));
    assert_eq!(1, tsns.len(), "precondition: the DATA is outstanding");
    a.shutdown().unwrap();
    assert_eq!(AssociationState::ShutdownPending, a.state());
    let write = |a: &mut Association| {
        a.stream(1)
            .unwrap()
            .write_sctp(now, &Bytes::from_static(b"new"), PPI)
    };
    assert!(write(a).is_err(), "refused in SHUTDOWN-PENDING");

    let raw = packet_to(a, &[sack_for(tsns[0])]);
    inject(a, now, raw);
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, now), CT_SHUTDOWN.0).len(),
        "precondition: the SHUTDOWN once the DATA is acknowledged"
    );
    assert_eq!(AssociationState::ShutdownSent, a.state());
    assert!(write(a).is_err(), "refused in SHUTDOWN-SENT");
}

/// imh-i-3-9: RFC 9260 8.5: a SHUTDOWN ACK with a Verification Tag that is not this side's,
/// in SHUTDOWN-SENT, is discarded: the shutdown waits for the genuine one.
#[test]
fn a_shutdown_ack_with_another_verification_tag_is_discarded_in_shutdown_sent() {
    let mut link = connected_link(366);
    let now = link.now;
    let a = link.client.conn();
    a.shutdown().unwrap();
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, now), CT_SHUTDOWN.0).len()
    );
    assert_eq!(AssociationState::ShutdownSent, a.state(), "precondition");
    let shutdown_ack = raw_chunk(CT_SHUTDOWN_ACK.0, 0, &[]);
    let raw = raw_packet(
        a.destination_port,
        a.source_port,
        a.my_verification_tag ^ 1,
        std::slice::from_ref(&shutdown_ack),
    );
    inject(a, now, raw);
    assert_eq!(AssociationState::ShutdownSent, a.state());
    assert!(!a.is_ended());
    assert!(sent_datagrams(a, now).is_empty(), "nothing answers it");

    let raw = packet_to(a, &[shutdown_ack]);
    inject(a, now, raw);
    assert_eq!(
        1,
        chunks_of_type(&sent_datagrams(a, now), CT_SHUTDOWN_COMPLETE.0).len()
    );
    assert!(a.is_ended());
}

/// fh-i-5-1-2: RFC 9260 8.1: the count of consecutive retransmission timeouts is cleared when
/// a SACK acknowledges outstanding DATA. With Association.Max.Retrans 2, two timeouts, a
/// SACK, and two more leave the association up; a third in a row ends it.
#[test]
fn a_sack_clears_the_retransmission_count() {
    let config = TransportConfig::default()
        .with_heartbeat_interval(None)
        .with_timer_config(TimerConfig {
            max_t3_rtx_retrans: 2,
            ..TimerConfig::default()
        });
    let mut link = crate::endpoint::link_test::Link::new(config.clone(), config, 367);
    link.connect();
    let mut now = link.now;
    let a = link.server.conn();
    let expire = |a: &mut Association, now: &mut Instant| {
        let due = a.timers.get(Timer::T3RTX).expect("T3-rtx runs");
        a.handle_timeout(due);
        let _ = sent_datagrams(a, due);
        *now = due;
    };

    a.open_stream(1, PPI)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"one"), PPI)
        .unwrap();
    let first = data_tsns(&sent_datagrams(a, now));
    assert_eq!(1, first.len(), "precondition");
    expire(a, &mut now);
    expire(a, &mut now);
    assert!(!a.is_ended(), "two timeouts are within the limit");
    let raw = packet_to(a, &[sack_for(first[0])]);
    inject(a, now, raw);

    a.stream(1)
        .unwrap()
        .write_sctp(now, &Bytes::from_static(b"two"), PPI)
        .unwrap();
    assert_eq!(1, data_tsns(&sent_datagrams(a, now)).len(), "precondition");
    expire(a, &mut now);
    expire(a, &mut now);
    assert!(!a.is_ended(), "the SACK cleared the count");
    expire(a, &mut now);
    assert!(a.is_ended(), "a third timeout in a row passes the limit");
}