simulcrypt 0.2.0

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
//! `Simulcrypt`: the registry of CAS channels and EMMG listeners.

use std::{
    collections::HashMap,
    sync::{
        Arc,
        Mutex,
        atomic::{
            AtomicU32,
            Ordering,
        },
    },
};

use crate::{
    cas::CasEntry,
    config::{
        CasConfig,
        ServiceConfig,
    },
    emmg::EmmgListeners,
    error::Error,
    event::{
        CasStatus,
        EmmgPortStatus,
    },
    lock_ext::MutexExt,
    service::Service,
};

/// Cheap copyable reference to a CAS channel; survives reconnects.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct CasRef(u32);

impl CasRef {
    /// A reference with a fixed id, for in-crate tests.
    #[cfg(test)]
    pub fn new(id: u32) -> Self {
        Self(id)
    }
}

/// Process registry: CAS channels and open services. Cheap to clone (an `Arc` inside), can be
/// passed freely to several tasks.
#[derive(Clone)]
pub struct Simulcrypt {
    inner: Arc<Inner>,
}

impl Default for Simulcrypt {
    fn default() -> Self {
        Self::new()
    }
}

pub struct Inner {
    next_cas_id: AtomicU32,
    cas_by_config_id: Mutex<HashMap<String, CasRef>>,
    cas: Mutex<HashMap<CasRef, Arc<CasEntry>>>,
    leases: Mutex<HashMap<CasRef, usize>>,
    emmg: EmmgListeners,
    /// Serializes CW group changes and CAS updates and removals. Without a single point, two
    /// concurrent `open_service` calls overlapping different `(CasRef, ecm_pid)` pairs of two
    /// different existing groups, or `open_service` racing `Drop`, could disagree on which
    /// group owns which pair.
    pub topology: Mutex<()>,
}

/// A CAS registered with [`Simulcrypt::acquire_cas`]. The CAS is removed when the last lease of
/// it drops: its ECMG and EMMG channels close and its streams are detached from open services,
/// which keep running on their other CAS. Drop the services that use the CAS first. The EMMG
/// listener closes with the last CAS on its port.
#[must_use = "the CAS is removed when the lease drops"]
pub struct CasLease {
    inner: Arc<Inner>,
    cas: CasRef,
}

impl CasLease {
    /// The leased CAS.
    #[must_use]
    pub fn cas(&self) -> CasRef {
        self.cas
    }
}

impl std::fmt::Debug for CasLease {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("CasLease").field(&self.cas).finish()
    }
}

impl Drop for CasLease {
    fn drop(&mut self) {
        let _topology = self.inner.topology.lock_or_recover();
        let mut leases = self.inner.leases.lock_or_recover();
        let Some(count) = leases.get_mut(&self.cas) else {
            return;
        };
        *count -= 1;
        if *count > 0 {
            return;
        }
        leases.remove(&self.cas);
        drop(leases);

        let Some(entry) = self.inner.cas.lock_or_recover().remove(&self.cas) else {
            return;
        };
        self.inner
            .cas_by_config_id
            .lock_or_recover()
            .retain(|_, cas_ref| *cas_ref != self.cas);
        entry.detach(&self.inner.emmg, self.cas);
    }
}

impl Inner {
    pub fn cas_entry(&self, cas_ref: CasRef) -> Result<Arc<CasEntry>, Error> {
        self.cas
            .lock_or_recover()
            .get(&cas_ref)
            .cloned()
            .ok_or(Error::UnknownCas)
    }
}

impl Simulcrypt {
    /// Tasks are spawned on the current tokio runtime.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Inner {
                next_cas_id: AtomicU32::new(0),
                cas_by_config_id: Mutex::new(HashMap::new()),
                cas: Mutex::new(HashMap::new()),
                leases: Mutex::new(HashMap::new()),
                emmg: EmmgListeners::default(),
                topology: Mutex::new(()),
            }),
        }
    }

    /// Registers a CAS, connects to its ECMG and returns a lease on it (see [`CasLease`]). A call
    /// with the `id` of a registered CAS applies the new settings to that CAS and returns one more
    /// lease on it: open services keep running, the ECMG connection restarts if its settings
    /// changed, the EMMG channel moves if its port or `channel_id` changed, and
    /// [`EmmgConfig::udp`](crate::EmmgConfig::udp) turned on binds UDP on the port. Identical
    /// settings change nothing.
    ///
    /// A port freed by the last lease is bound again at once, except on a current-thread runtime,
    /// where it frees only after the caller yields.
    ///
    /// # Errors
    ///
    /// If `cfg.emmg` is set, returns `Err` when the TCP listening socket (or the UDP one with
    /// [`EmmgConfig::udp`](crate::EmmgConfig::udp)) cannot be bound, or another CAS on the same
    /// EMMG port already uses the same `super_cas_id` and `ecmg.channel_id`. CAS with different
    /// `super_cas_id` may share a port and a `channel_id`. A failed update leaves the CAS
    /// unchanged.
    pub fn acquire_cas(&self, cfg: CasConfig) -> Result<CasLease, Error> {
        let _topology = self.inner.topology.lock_or_recover();
        let cas = self.upsert(cfg)?;
        *self.inner.leases.lock_or_recover().entry(cas).or_default() += 1;
        Ok(CasLease {
            inner: Arc::clone(&self.inner),
            cas,
        })
    }

    /// The caller holds `topology`.
    fn upsert(&self, cfg: CasConfig) -> Result<CasRef, Error> {
        let existing = self
            .inner
            .cas_by_config_id
            .lock_or_recover()
            .get(&cfg.id)
            .copied();
        if let Some(cas_ref) = existing {
            self.inner
                .cas_entry(cas_ref)?
                .update(&self.inner.emmg, cas_ref, cfg)?;
            return Ok(cas_ref);
        }

        let emmg = match &cfg.emmg {
            Some(emmg) => Some(self.inner.emmg.register(&cfg, emmg)?),
            None => None,
        };

        let cas_ref = CasRef(self.inner.next_cas_id.fetch_add(1, Ordering::Relaxed));
        let config_id = cfg.id.clone();
        let entry = CasEntry::new(cfg, emmg);

        self.inner
            .cas
            .lock_or_recover()
            .insert(cas_ref, Arc::clone(&entry));
        self.inner
            .cas_by_config_id
            .lock_or_recover()
            .insert(config_id, cas_ref);
        entry.ensure_running(cas_ref);

        Ok(cas_ref)
    }

    /// Opens a service: allocates `stream_id`s and brings up missing connections. If at least one
    /// `(CasRef, ecm_pid)` pair already belongs to a live CW group, the new handle joins it (and
    /// brings along any still unused pairs from its `cas`); if the requested pairs overlap TWO
    /// different live groups at once, the conflict cannot be resolved.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `cfg.cas` is empty, `cfg.crypto_period` does not fit into the 16-bit
    /// protocol field, any `CasRef` in `cfg.cas` is not registered in this `Simulcrypt`, a
    /// requested `(CasRef, ecm_pid)` pair overlaps two different live CW groups, the live group
    /// found uses a different `crypto_period`, or a channel that has to be brought back up
    /// after becoming empty failed to re-register its EMMG channel.
    pub fn open_service(&self, cfg: &ServiceConfig) -> Result<Service, Error> {
        Service::open(&self.inner, cfg)
    }

    /// State of every CAS channel and its streams: diagnostics and monitoring.
    #[must_use]
    pub fn status(&self) -> Vec<CasStatus> {
        let entries: Vec<_> = self
            .inner
            .cas
            .lock_or_recover()
            .iter()
            .map(|(cas, entry)| (*cas, Arc::clone(entry)))
            .collect();
        entries
            .into_iter()
            .map(|(cas, entry)| entry.status(cas))
            .collect()
    }

    /// Internal state of a CAS, for in-crate tests.
    #[cfg(test)]
    pub fn entry(&self, cas: CasRef) -> Arc<CasEntry> {
        self.inner.cas_entry(cas).expect("registered CAS")
    }

    /// State of every EMMG listener, one per port.
    #[must_use]
    pub fn emmg_status(&self) -> Vec<EmmgPortStatus> {
        self.inner.emmg.status()
    }
}