simulcrypt 0.2.2

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! End-to-end tests against fake ECMG and EMM generator peers on loopback. Shared peers and
//! helpers live here, the tests in one module per area.

use std::{
    net::SocketAddr,
    time::Duration,
};

use simulcrypt::{
    CasConfig,
    CasLease,
    CasRef,
    CasState,
    DatagramFormat,
    EcmgConfig,
    EmmgConfig,
    Error,
    Event,
    ServiceCas,
    ServiceConfig,
    Simulcrypt,
    messages::{
        RawSimulcryptMessage,
        ecmg::{
            ECMG_MSG_CHANNEL_CLOSE,
            ECMG_MSG_CHANNEL_SETUP,
            ECMG_MSG_CHANNEL_STATUS,
            ECMG_MSG_CW_PROVISION,
            ECMG_MSG_ECM_RESPONSE,
            ECMG_MSG_STREAM_CLOSE_REQUEST,
            ECMG_MSG_STREAM_ERROR,
            ECMG_MSG_STREAM_SETUP,
            ECMG_MSG_STREAM_STATUS,
            ECMG_VAR_CHANNEL_ID,
            ECMG_VAR_CP_NUMBER,
            ECMG_VAR_ECM_DATAGRAM,
            ECMG_VAR_ECM_REP_PERIOD,
            ECMG_VAR_ERROR_STATUS,
            ECMG_VAR_MIN_CP_DURATION,
            ECMG_VAR_SECTION_TS_PKT_FLAG,
            ECMG_VAR_STREAM_ID,
        },
        emmg::{
            EMMG_MSG_CHANNEL_SETUP,
            EMMG_MSG_CHANNEL_STATUS,
            EMMG_MSG_DATA_PROVISION,
            EMMG_MSG_STREAM_SETUP,
            EMMG_MSG_STREAM_STATUS,
            EMMG_VAR_CHANNEL_ID,
            EMMG_VAR_DATA_ID,
            EMMG_VAR_DATA_TYPE,
            EMMG_VAR_DATAGRAM,
            EMMG_VAR_SECTION_TS_PKT_FLAG,
            EMMG_VAR_STREAM_ID,
            EMMG_VAR_SUPER_CAS_ID,
        },
    },
};

mod carousel;
mod cas;
mod ecmg;
mod emmg;
mod service;

const ECM_DATA: [u8; 3] = [0xAA, 0xBB, 0xCC];

const EMM_DATA: [u8; 4] = [0xDE, 0xAD, 0xBE, 0xEF];

async fn fake_ecmg(listener: tokio::net::TcpListener, channel_id: u16) {
    ecmg_peer(listener, channel_id, 0x00, None, |_| ECM_DATA.to_vec()).await;
}

/// ECMG on one connection: `section_ts_pkt_flag` and `rep_period` go into `CHANNEL_STATUS`, every
/// `CW_PROVISION` is answered with `ecm(cp_number)`.
async fn ecmg_peer(
    listener: tokio::net::TcpListener,
    channel_id: u16,
    section_ts_pkt_flag: u8,
    rep_period: Option<u16>,
    ecm: fn(u16) -> Vec<u8>,
) {
    let (mut socket, _) = listener.accept().await.expect("ecmg accept");

    let setup = RawSimulcryptMessage::read_from(&mut socket)
        .await
        .expect("read CHANNEL_SETUP");
    assert_eq!(setup.message_type, ECMG_MSG_CHANNEL_SETUP);

    let mut status = RawSimulcryptMessage::new(ECMG_MSG_CHANNEL_STATUS);
    status.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
    status.set_u8(ECMG_VAR_SECTION_TS_PKT_FLAG, section_ts_pkt_flag);
    if let Some(rep_period) = rep_period {
        status.set_u16(ECMG_VAR_ECM_REP_PERIOD, rep_period);
    }
    status
        .write_to(&mut socket)
        .await
        .expect("write CHANNEL_STATUS");

    loop {
        let Ok(request) = RawSimulcryptMessage::read_from(&mut socket).await else {
            return;
        };

        match request.message_type {
            ECMG_MSG_STREAM_SETUP => {
                let stream_id = request.get_u16(ECMG_VAR_STREAM_ID).expect("stream_id");
                let mut status = RawSimulcryptMessage::new(ECMG_MSG_STREAM_STATUS);
                status.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
                status.set_u16(ECMG_VAR_STREAM_ID, stream_id);
                status
                    .write_to(&mut socket)
                    .await
                    .expect("write STREAM_STATUS");
            }
            ECMG_MSG_CW_PROVISION => {
                let stream_id = request.get_u16(ECMG_VAR_STREAM_ID).expect("stream_id");
                let cp_number = request.get_u16(ECMG_VAR_CP_NUMBER).expect("cp_number");

                let mut response = RawSimulcryptMessage::new(ECMG_MSG_ECM_RESPONSE);
                response.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
                response.set_u16(ECMG_VAR_STREAM_ID, stream_id);
                response.set_u16(ECMG_VAR_CP_NUMBER, cp_number);
                response.add_var(ECMG_VAR_ECM_DATAGRAM, ecm(cp_number));
                response
                    .write_to(&mut socket)
                    .await
                    .expect("write ECM_RESPONSE");
            }
            _ => {}
        }
    }
}

async fn fake_emm_generator(
    port: u16,
    super_cas_id: u32,
    channel_id: u16,
    stream_id: u16,
    count: usize,
) {
    let mut socket = emm_generator_setup(port, super_cas_id, channel_id, stream_id).await;

    // DATA_PROVISION deliberately carries no data_id/data_type - neither the protocol nor any real
    // EMM generator puts them there, they are STREAM_SETUP fields.
    let mut data_provision = RawSimulcryptMessage::new(EMMG_MSG_DATA_PROVISION);
    data_provision.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
    data_provision.set_u16(EMMG_VAR_STREAM_ID, stream_id);
    data_provision.add_var(EMMG_VAR_DATAGRAM, EMM_DATA.to_vec());
    for _ in 0 .. count {
        data_provision
            .write_to(&mut socket)
            .await
            .expect("write DATA_PROVISION");
    }
}

/// Sets up the channel and `stream_id` with `data_id = 1`. The setup lives while the returned
/// connection stays open.
async fn emm_generator_setup(
    port: u16,
    super_cas_id: u32,
    channel_id: u16,
    stream_id: u16,
) -> tokio::net::TcpStream {
    let mut socket = tokio::net::TcpStream::connect(("127.0.0.1", port))
        .await
        .expect("connect to EMMG");

    let mut channel_setup = RawSimulcryptMessage::new(EMMG_MSG_CHANNEL_SETUP);
    channel_setup.set_u32(EMMG_VAR_SUPER_CAS_ID, super_cas_id);
    channel_setup.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
    channel_setup.set_u8(EMMG_VAR_SECTION_TS_PKT_FLAG, 0x00);
    channel_setup
        .write_to(&mut socket)
        .await
        .expect("write CHANNEL_SETUP");

    let response = RawSimulcryptMessage::read_from(&mut socket)
        .await
        .expect("read CHANNEL_STATUS");
    assert_eq!(response.message_type, EMMG_MSG_CHANNEL_STATUS);

    let mut stream_setup = RawSimulcryptMessage::new(EMMG_MSG_STREAM_SETUP);
    stream_setup.set_u16(EMMG_VAR_CHANNEL_ID, channel_id);
    stream_setup.set_u16(EMMG_VAR_STREAM_ID, stream_id);
    stream_setup.set_u16(EMMG_VAR_DATA_ID, 1);
    stream_setup.set_u8(EMMG_VAR_DATA_TYPE, 0x00);
    stream_setup
        .write_to(&mut socket)
        .await
        .expect("write STREAM_SETUP");

    let response = RawSimulcryptMessage::read_from(&mut socket)
        .await
        .expect("read STREAM_STATUS");
    assert_eq!(response.message_type, EMMG_MSG_STREAM_STATUS);
    socket
}

/// Reserves a port free for both TCP and UDP: binds and closes right away to learn the port number
/// before `Simulcrypt::acquire_cas` takes it.
async fn reserve_port() -> u16 {
    loop {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        if std::net::UdpSocket::bind(("0.0.0.0", port)).is_ok() {
            return port;
        }
    }
}

/// `(stream_id, data_id, data)` of the next EMM.
async fn next_emm(service: &mut simulcrypt::Service) -> (u16, u16, Vec<u8>) {
    loop {
        if let Event::Emm {
            stream_id,
            data_id,
            data,
            ..
        } = service.recv().await.expect("service closed unexpectedly")
        {
            return (stream_id, data_id, data.to_vec());
        }
    }
}