simulcrypt 0.1.0

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
use bytes::{
    BufMut,
    Bytes,
    BytesMut,
};
use tokio::io::{
    AsyncRead,
    AsyncReadExt,
    AsyncWrite,
    AsyncWriteExt,
};

use crate::messages::tlv::Tlv;

pub mod ecmg;
pub mod emmg;
/// TLV (tag-length-value) - the basic unit of a `SimulCrypt` message payload.
pub mod tlv;

/// `SimulCrypt` protocol version used by this crate.
pub const SIMULCRYPT_VERSION: u8 = 0x02;
/// Message header size in bytes: version (1) + type (2) + payload length (2).
pub const SIMULCRYPT_MESSAGE_HEADER: usize = 5;

/// Error reading a message from a socket.
#[derive(Debug, thiserror::Error)]
pub enum ReadMessageError {
    /// I/O error while reading.
    #[error("I/O error while reading SimulCrypt message")]
    Io(#[source] std::io::Error),

    /// The bytes read do not form a valid `SimulCrypt` message.
    #[error("failed to parse SimulCrypt message")]
    Parse(#[source] RawSimulcryptMessageError),
}

/// Raw `SimulCrypt` message: the header is parsed, the TLV variables are not.
#[derive(Clone, Debug)]
pub struct RawSimulcryptMessage {
    /// Protocol version (see [`SIMULCRYPT_VERSION`]).
    pub version: u8,
    /// Message type - protocol-specific (ECMG/EMMG) and not checked at this level.
    pub message_type: u16,
    /// Payload TLV variables in the order received or added.
    pub vars: Vec<Tlv>,
}

impl RawSimulcryptMessage {
    /// Creates an empty message of the given type with the current protocol version.
    #[must_use]
    pub fn new(message_type: u16) -> Self {
        Self {
            version: SIMULCRYPT_VERSION,
            message_type,
            vars: Vec::new(),
        }
    }

    /// Serializes the whole message. TLV and payload lengths are `u16` on the wire; if a value or
    /// the total exceeds 65535 bytes, returns an error instead of silently truncating the length
    /// and sending a short, broken frame.
    ///
    /// # Errors
    ///
    /// Returns `Err` if any TLV value or the total message payload is longer than 65535 bytes.
    ///
    /// # Panics
    ///
    /// Does not panic: both values converted to `u16` below are checked against 65535 bytes earlier
    /// in this function.
    pub fn marshal(&self) -> Result<Bytes, RawSimulcryptMessageError> {
        for v in &self.vars {
            if v.value.len() > u16::MAX as usize {
                return Err(RawSimulcryptMessageError::ValueTooLong {
                    tag: v.tag,
                    len: v.value.len(),
                });
            }
        }

        let payload_len: usize = self.vars.iter().map(|v| 4 + v.value.len()).sum();
        if payload_len > u16::MAX as usize {
            return Err(RawSimulcryptMessageError::PayloadTooLong { len: payload_len });
        }

        let mut out = BytesMut::with_capacity(SIMULCRYPT_MESSAGE_HEADER + payload_len);

        out.put_u8(self.version);
        out.put_u16(self.message_type);
        out.put_u16(u16::try_from(payload_len).expect("payload_len checked above"));

        for v in &self.vars {
            out.put_u16(v.tag);
            out.put_u16(u16::try_from(v.value.len()).expect("v.value.len() checked above"));
            out.put_slice(&v.value);
        }

        Ok(out.freeze())
    }

    /// Parses a whole message (header + TLV) from an already read buffer.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `data` is shorter than the header, the payload declared in the header is
    /// longer than the available data, or a TLV inside the payload is truncated in its header or
    /// value.
    pub fn unmarshal(data: &[u8]) -> Result<Self, RawSimulcryptMessageError> {
        if data.len() < SIMULCRYPT_MESSAGE_HEADER {
            return Err(RawSimulcryptMessageError::TooShort);
        }

        let version = data[0];
        let message_type = u16::from_be_bytes([data[1], data[2]]);
        let payload_len = u16::from_be_bytes([data[3], data[4]]) as usize;

        if data.len() < SIMULCRYPT_MESSAGE_HEADER + payload_len {
            return Err(RawSimulcryptMessageError::PayloadTooShort);
        }

        let mut vars = Vec::new();
        let mut offset = SIMULCRYPT_MESSAGE_HEADER;

        while offset < SIMULCRYPT_MESSAGE_HEADER + payload_len {
            if offset + 4 > data.len() {
                return Err(RawSimulcryptMessageError::TruncatedTlvHeader);
            }
            let tag = u16::from_be_bytes([data[offset], data[offset + 1]]);
            let len = u16::from_be_bytes([data[offset + 2], data[offset + 3]]) as usize;
            offset += 4;

            if offset + len > data.len() {
                return Err(RawSimulcryptMessageError::TruncatedTlvValue);
            }
            let value = data[offset .. offset + len].to_vec();
            offset += len;

            vars.push(Tlv { tag, value });
        }

        Ok(Self {
            version,
            message_type,
            vars,
        })
    }

    /// Reads the header and the whole payload from the stream and parses them into a message.
    ///
    /// # Errors
    ///
    /// Returns `Err` if reading from the stream fails with an I/O error or the bytes read do not
    /// form a valid message (see [`Self::unmarshal`]).
    pub async fn read_from<R: AsyncRead + Unpin>(reader: &mut R) -> Result<Self, ReadMessageError> {
        let mut header = [0u8; SIMULCRYPT_MESSAGE_HEADER];
        reader
            .read_exact(&mut header)
            .await
            .map_err(ReadMessageError::Io)?;

        let payload_len = u16::from_be_bytes([header[3], header[4]]) as usize;
        let mut data = vec![0u8; SIMULCRYPT_MESSAGE_HEADER + payload_len];
        data[.. SIMULCRYPT_MESSAGE_HEADER].copy_from_slice(&header);

        reader
            .read_exact(&mut data[SIMULCRYPT_MESSAGE_HEADER ..])
            .await
            .map_err(ReadMessageError::Io)?;

        RawSimulcryptMessage::unmarshal(&data).map_err(ReadMessageError::Parse)
    }

    /// Serializes the whole message and writes it to the stream.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the message cannot be serialized (see [`Self::marshal`]) or writing to the
    /// stream fails with an I/O error.
    pub async fn write_to<W: AsyncWrite + Unpin>(
        &self,
        writer: &mut W,
    ) -> Result<(), std::io::Error> {
        let bytes = self.marshal().map_err(std::io::Error::other)?;
        writer.write_all(&bytes).await
    }

    /// Returns the value of the TLV with the given tag as `u8`, if the tag is present and the value
    /// has the right length.
    pub fn get_u8(&self, tag: u16) -> Option<u8> {
        self.vars
            .iter()
            .find(|var| var.tag == tag)
            .and_then(Tlv::as_u8)
    }

    /// Returns the value of the TLV with the given tag as `u16` (big-endian), if the tag is present
    /// and the value has the right length.
    pub fn get_u16(&self, tag: u16) -> Option<u16> {
        self.vars
            .iter()
            .find(|var| var.tag == tag)
            .and_then(Tlv::as_u16)
    }

    /// Returns the value of the TLV with the given tag as `u32` (big-endian), if the tag is present
    /// and the value has the right length.
    pub fn get_u32(&self, tag: u16) -> Option<u32> {
        self.vars
            .iter()
            .find(|var| var.tag == tag)
            .and_then(Tlv::as_u32)
    }

    /// Sets the value of the TLV with the given tag as `u8`, replacing an existing one.
    pub fn set_u8(&mut self, tag: u16, value: u8) {
        self.set_value(tag, vec![value]);
    }

    /// Sets the value of the TLV with the given tag as `u16` (big-endian), replacing an existing
    /// one.
    pub fn set_u16(&mut self, tag: u16, value: u16) {
        self.set_value(tag, value.to_be_bytes().to_vec());
    }

    /// Sets the value of the TLV with the given tag as `u32` (big-endian), replacing an existing
    /// one.
    pub fn set_u32(&mut self, tag: u16, value: u32) {
        self.set_value(tag, value.to_be_bytes().to_vec());
    }

    /// Appends a new TLV variable without checking for duplicate tags.
    pub fn add_var(&mut self, tag: u16, value: Vec<u8>) {
        self.vars.push(Tlv { tag, value });
    }

    /// Returns the first TLV variable with the given tag.
    #[must_use]
    pub fn find_var(&self, tag: u16) -> Option<&Tlv> {
        self.vars.iter().find(|var| var.tag == tag)
    }

    fn set_value(&mut self, tag: u16, value: Vec<u8>) {
        if let Some(var) = self.vars.iter_mut().find(|var| var.tag == tag) {
            var.value = value;
            return;
        }

        self.vars.push(Tlv { tag, value });
    }
}

/// Error parsing or building a raw `SimulCrypt` message.
#[derive(Debug, thiserror::Error)]
pub enum RawSimulcryptMessageError {
    /// Less data than the 5-byte message header.
    #[error("message is shorter than the SimulCrypt header")]
    TooShort,

    /// The header declares a payload longer than the available data.
    #[error("declared payload length exceeds available data")]
    PayloadTooShort,

    /// TLV truncated in its header (tag + length).
    #[error("truncated TLV header")]
    TruncatedTlvHeader,

    /// TLV truncated in its value.
    #[error("truncated TLV value")]
    TruncatedTlvValue,

    /// A TLV value is longer than the 16-bit length field on the wire allows.
    #[error("TLV value for tag=0x{tag:04x} is {len} bytes long, exceeds the 65535-byte wire limit")]
    ValueTooLong {
        /// Tag of the variable whose value is too long.
        tag: u16,
        /// Actual value length in bytes.
        len: usize,
    },

    /// The total message payload is longer than the 16-bit length field on the wire allows.
    #[error("message payload is {len} bytes long, exceeds the 65535-byte wire limit")]
    PayloadTooLong {
        /// Actual payload length in bytes.
        len: usize,
    },
}

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

    #[test]
    fn marshal_roundtrips_a_normal_message() {
        let mut msg = RawSimulcryptMessage::new(0x1234);
        msg.add_var(0x0001, vec![1, 2, 3]);

        let bytes = msg.marshal().expect("small message must marshal");
        let decoded = RawSimulcryptMessage::unmarshal(&bytes).expect("must unmarshal back");

        assert_eq!(decoded.message_type, 0x1234);
        assert_eq!(decoded.vars.len(), 1);
        assert_eq!(decoded.vars[0].value, vec![1, 2, 3]);
    }

    #[test]
    fn marshal_rejects_oversized_tlv_value_instead_of_truncating_the_length_prefix() {
        let mut msg = RawSimulcryptMessage::new(0x1234);
        msg.add_var(0x0001, vec![0u8; u16::MAX as usize + 1]);

        let error = msg
            .marshal()
            .expect_err("value over 65535 bytes must be rejected");
        assert!(matches!(
            error,
            RawSimulcryptMessageError::ValueTooLong { tag: 0x0001, .. }
        ));
    }

    #[test]
    fn marshal_rejects_oversized_total_payload() {
        let mut msg = RawSimulcryptMessage::new(0x1234);
        // Each value fits into u16 on its own, but their sum does not.
        for tag in 0 .. 3u16 {
            msg.add_var(tag, vec![0u8; 30_000]);
        }

        let error = msg
            .marshal()
            .expect_err("total payload over 65535 bytes must be rejected");
        assert!(matches!(
            error,
            RawSimulcryptMessageError::PayloadTooLong { .. }
        ));
    }
}