simulcrypt 0.1.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);

/// 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>>>,
    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<()>,
}

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)
    }

    /// See [`Simulcrypt::remove_cas`]. The caller holds `topology`.
    fn remove_cas(&self, cas: CasRef) -> Result<(), Error> {
        let entry = self
            .cas
            .lock_or_recover()
            .remove(&cas)
            .ok_or(Error::UnknownCas)?;
        self.cas_by_config_id
            .lock_or_recover()
            .retain(|_, cas_ref| *cas_ref != cas);

        entry.detach(&self.emmg, cas);
        Ok(())
    }
}

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()),
                emmg: EmmgListeners::default(),
                topology: Mutex::new(()),
            }),
        }
    }

    /// Registers a CAS and connects to its ECMG. A repeated call with the same `id` applies the new
    /// settings to that CAS and returns its `CasRef`: 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.
    ///
    /// # 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 `cfg.ecmg.channel_id` is
    /// already taken by another CAS channel on the same EMMG port. A failed update leaves the
    /// CAS unchanged.
    pub fn add_cas(&self, cfg: CasConfig) -> Result<CasRef, Error> {
        let _topology = self.inner.topology.lock_or_recover();

        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)
    }

    /// Removes a CAS: closes its ECMG channel and its EMMG channel, and detaches its streams from
    /// open services, which keep running on their other CAS. The EMMG listener closes with the
    /// last CAS on its port.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `cas` is not registered in this `Simulcrypt`.
    pub fn remove_cas(&self, cas: CasRef) -> Result<(), Error> {
        let _topology = self.inner.topology.lock_or_recover();
        self.inner.remove_cas(cas)
    }

    /// Removes every CAS (see [`Self::remove_cas`]): all ECMG connections and EMMG listeners are
    /// closed.
    pub fn close(&self) {
        let _topology = self.inner.topology.lock_or_recover();
        let all: Vec<CasRef> = self.inner.cas.lock_or_recover().keys().copied().collect();
        for cas in all {
            let _ = self.inner.remove_cas(cas);
        }
    }

    /// 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()
    }
}