simulcrypt 0.2.2

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! ECMG messages the SCS side builds and parses.

use derive_more::Display;

use crate::messages::{
    RawSimulcryptMessage,
    ecmg::{
        ECMG_MSG_CHANNEL_SETUP,
        ECMG_MSG_CHANNEL_STATUS,
        ECMG_MSG_CW_PROVISION,
        ECMG_MSG_STREAM_SETUP,
        ECMG_VAR_ACCESS_CRITERIA,
        ECMG_VAR_CHANNEL_ID,
        ECMG_VAR_CP_CW_COMBINATION,
        ECMG_VAR_CP_DURATION,
        ECMG_VAR_CP_NUMBER,
        ECMG_VAR_CW_PER_MSG,
        ECMG_VAR_ECM_DATAGRAM,
        ECMG_VAR_ECM_ID,
        ECMG_VAR_ECM_REP_PERIOD,
        ECMG_VAR_LEAD_CW,
        ECMG_VAR_MAX_COMP_TIME,
        ECMG_VAR_MAX_STREAMS,
        ECMG_VAR_MIN_CP_DURATION,
        ECMG_VAR_NOMINAL_CP_DURATION,
        ECMG_VAR_SECTION_TS_PKT_FLAG,
        ECMG_VAR_STREAM_ID,
        ECMG_VAR_SUPER_CAS_ID,
    },
};

/// `CHANNEL_SETUP`: opens an ECMG channel.
pub fn channel_setup(channel_id: u16, super_cas_id: u32) -> RawSimulcryptMessage {
    let mut raw = RawSimulcryptMessage::new(ECMG_MSG_CHANNEL_SETUP);
    raw.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
    raw.set_u32(ECMG_VAR_SUPER_CAS_ID, super_cas_id);
    raw
}

/// `STREAM_SETUP`: opens a stream inside an open channel; `ECM_id` equals `stream_id`.
pub fn stream_setup(
    channel_id: u16,
    stream_id: u16,
    nominal_cp_duration: u16,
) -> RawSimulcryptMessage {
    let mut raw = RawSimulcryptMessage::new(ECMG_MSG_STREAM_SETUP);
    raw.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
    raw.set_u16(ECMG_VAR_STREAM_ID, stream_id);
    raw.set_u16(ECMG_VAR_ECM_ID, stream_id);
    raw.set_u16(ECMG_VAR_NOMINAL_CP_DURATION, nominal_cp_duration);
    raw
}

/// `CW_PROVISION`: the CW of `cp_number` and of the next crypto period. A value over the 16-bit
/// TLV length limit fails when the message is written (see `RawSimulcryptMessage::marshal`).
pub fn cw_provision(
    channel_id: u16,
    stream_id: u16,
    cp_number: u16,
    cp_duration: u16,
    cw_current: &[u8; 8],
    cw_next: &[u8; 8],
    access_criteria: Option<&[u8]>,
) -> RawSimulcryptMessage {
    let mut raw = RawSimulcryptMessage::new(ECMG_MSG_CW_PROVISION);
    raw.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
    raw.set_u16(ECMG_VAR_STREAM_ID, stream_id);
    raw.set_u16(ECMG_VAR_CP_NUMBER, cp_number);
    raw.set_u16(ECMG_VAR_CP_DURATION, cp_duration);
    for (cp_number, cw) in [
        (cp_number, cw_current),
        (cp_number.wrapping_add(1), cw_next),
    ] {
        let mut value = Vec::with_capacity(10);
        value.extend_from_slice(&cp_number.to_be_bytes());
        value.extend_from_slice(cw);
        raw.add_var(ECMG_VAR_CP_CW_COMBINATION, value);
    }
    if let Some(value) = access_criteria.filter(|value| !value.is_empty()) {
        raw.add_var(ECMG_VAR_ACCESS_CRITERIA, value.to_vec());
    }
    raw
}

/// `CHANNEL_STATUS`: the reply to a `CHANNEL_TEST` from the ECMG.
pub fn channel_status(
    channel_id: u16,
    section_ts_pkt_flag: SectionTsPktFlag,
) -> RawSimulcryptMessage {
    let mut raw = RawSimulcryptMessage::new(ECMG_MSG_CHANNEL_STATUS);
    raw.set_u16(ECMG_VAR_CHANNEL_ID, channel_id);
    raw.set_u8(ECMG_VAR_SECTION_TS_PKT_FLAG, section_ts_pkt_flag.as_u8());
    raw
}

/// Negotiated ECMG parameters from `CHANNEL_STATUS`. Units are kept as the ECMG sent them in
/// the TLV, not converted: `min_cp_duration` is in hundreds of milliseconds, the other time
/// fields are in milliseconds. `CasParams` converts them to `Duration`.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ChannelParams {
    /// ECM repetition period recommended by the ECMG, in milliseconds.
    pub rep_period: Option<u16>,
    /// Maximum number of streams the ECMG allows on this channel.
    pub max_streams: Option<u16>,
    /// Minimum allowed crypto period duration, in hundreds of milliseconds.
    pub min_cp_duration: Option<u16>,
    /// How many crypto periods ahead the ECMG wants to receive CWs.
    pub lead_cw: Option<u8>,
    /// How many CWs the ECMG expects in one `CW_PROVISION`.
    pub cw_per_msg: Option<u8>,
    /// Maximum time the ECMG spends building an ECM, in milliseconds.
    pub max_comp_time: Option<u16>,
}

/// Datagram format and channel parameters from the ECMG `CHANNEL_STATUS`.
///
/// # Errors
///
/// Returns `Err` if the message has no `channel_id`.
pub fn parse_channel_status(
    raw: &RawSimulcryptMessage,
) -> Result<(SectionTsPktFlag, ChannelParams), ParseError> {
    raw.get_u16(ECMG_VAR_CHANNEL_ID)
        .ok_or(ParseError::MissingChannelId)?;
    let section_ts_pkt_flag = raw
        .get_u8(ECMG_VAR_SECTION_TS_PKT_FLAG)
        .map_or(SectionTsPktFlag::DEFAULT, SectionTsPktFlag::from);
    let params = ChannelParams {
        rep_period: raw.get_u16(ECMG_VAR_ECM_REP_PERIOD),
        max_streams: raw.get_u16(ECMG_VAR_MAX_STREAMS),
        min_cp_duration: raw.get_u16(ECMG_VAR_MIN_CP_DURATION),
        lead_cw: raw.get_u8(ECMG_VAR_LEAD_CW),
        cw_per_msg: raw.get_u8(ECMG_VAR_CW_PER_MSG),
        max_comp_time: raw.get_u16(ECMG_VAR_MAX_COMP_TIME),
    };
    Ok((section_ts_pkt_flag, params))
}

/// Decoded `ECM_RESPONSE`.
#[derive(Debug)]
pub struct Ecm {
    stream_id: Option<u16>,
    datagram: Vec<u8>,
    cp_number: Option<u16>,
}

impl TryFrom<RawSimulcryptMessage> for Ecm {
    type Error = ParseError;

    /// Takes the message by value: the ECM datagram is moved into `Ecm` instead of copied.
    fn try_from(mut message: RawSimulcryptMessage) -> Result<Self, Self::Error> {
        let index = message
            .vars
            .iter()
            .position(|var| var.tag == ECMG_VAR_ECM_DATAGRAM)
            .ok_or(ParseError::MissingEcmDatagram)?;
        let datagram = message.vars.remove(index).value;

        Ok(Self {
            stream_id: message.get_u16(ECMG_VAR_STREAM_ID),
            datagram,
            cp_number: message.get_u16(ECMG_VAR_CP_NUMBER),
        })
    }
}

impl Ecm {
    /// Stream the ECM belongs to, if the ECMG specified it.
    #[must_use]
    pub fn stream_id(&self) -> Option<u16> {
        self.stream_id
    }

    /// Takes the ECM datagram, consuming `Ecm`.
    #[must_use]
    pub fn into_datagram(self) -> Vec<u8> {
        self.datagram
    }

    /// Crypto period number, if the ECMG sent one.
    #[must_use]
    pub fn cp_number(&self) -> Option<u16> {
        self.cp_number
    }
}

/// Error decoding an ECMG message.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    /// `ECM_RESPONSE` has no ECM datagram.
    #[error("missing ECM datagram in ECM_RESPONSE")]
    MissingEcmDatagram,

    /// `CHANNEL_STATUS` has no `channel_id`.
    #[error("missing channel_id in CHANNEL_STATUS")]
    MissingChannelId,
}

/// ECM datagram format negotiated in `CHANNEL_STATUS`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Display)]
pub enum SectionTsPktFlag {
    /// The datagram is a PSI/SI section.
    #[display("section")]
    Section,
    /// The datagram is already split into TS packets.
    #[display("ts-packet")]
    TsPacket,
    /// The flag value is outside the known set (0x00/0x01).
    #[display("unknown(0x{:02x})", _0)]
    Unknown(u8),
}

impl SectionTsPktFlag {
    /// Default value until the ECMG sends `CHANNEL_STATUS`.
    pub const DEFAULT: Self = SectionTsPktFlag::Section;

    /// Wire byte representation of the flag.
    #[must_use]
    pub const fn as_u8(self) -> u8 {
        match self {
            SectionTsPktFlag::Section => 0x00,
            SectionTsPktFlag::TsPacket => 0x01,
            SectionTsPktFlag::Unknown(value) => value,
        }
    }
}

impl From<u8> for SectionTsPktFlag {
    fn from(value: u8) -> Self {
        match value {
            0x00 => SectionTsPktFlag::Section,
            0x01 => SectionTsPktFlag::TsPacket,
            other => SectionTsPktFlag::Unknown(other),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cw_provision_with_ac(access_criteria: &[u8]) -> RawSimulcryptMessage {
        cw_provision(1, 1, 0, 100, &[0u8; 8], &[0u8; 8], Some(access_criteria))
    }

    #[test]
    fn display_of_flags_and_parity() {
        assert_eq!(SectionTsPktFlag::Section.to_string(), "section");
        assert_eq!(SectionTsPktFlag::TsPacket.to_string(), "ts-packet");
        assert_eq!(SectionTsPktFlag::Unknown(7).to_string(), "unknown(0x07)");
        assert_eq!(crate::Parity::Even.to_string(), "even");
        assert_eq!(crate::Parity::Odd.to_string(), "odd");
    }

    /// `access_criteria` goes on the wire under tag 0x000D, not 0x0011
    /// (`access_criteria_transfer_mode`, a different field).
    #[test]
    fn access_criteria_goes_out_under_the_correct_tlv_tag() {
        let ac = [0xAA, 0xBB, 0xCC];
        let raw = cw_provision_with_ac(&ac);

        let var = raw
            .find_var(ECMG_VAR_ACCESS_CRITERIA)
            .expect("access_criteria must be present under tag 0x000D");
        assert_eq!(var.value, ac, "access_criteria bytes must round-trip as-is");
        assert!(raw.find_var(0x0011).is_none());
    }

    /// The only ceiling for `access_criteria` is the 16-bit TLV length on the wire.
    #[test]
    fn access_criteria_is_limited_only_by_the_tlv_length() {
        assert!(cw_provision_with_ac(&[0xAB; 300]).marshal().is_ok());
        assert!(cw_provision_with_ac(&vec![0xEF; 65536]).marshal().is_err());
    }
}