simulcrypt 0.1.1

DVB SimulCrypt (ETSI TS 103 197) head-end protocol: ECMG client, EMMG server, control words
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! `Service` and its CW group: shared CW, rotation, stream membership.

use std::{
    collections::{
        HashMap,
        VecDeque,
    },
    sync::{
        Arc,
        Mutex,
        Weak,
    },
    time::Duration,
};

use rand::{
    SeedableRng,
    rngs::StdRng,
};
use tokio::{
    sync::{
        broadcast,
        watch,
    },
    task::AbortHandle,
};

use crate::{
    cas::{
        CasEntry,
        register_new_member_io,
    },
    config::ServiceConfig,
    cw::{
        CwGenerator,
        Parity,
    },
    error::Error,
    event::{
        Event,
        StreamInfo,
    },
    lock_ext::MutexExt,
    simulcrypt::{
        CasRef,
        Inner,
    },
    spawn::spawn_supervised,
};

/// ECM/EMM/state channel capacity of one CW group. A slow receiver that falls behind by more than
/// this many events skips part of them (`Service::recv` logs and continues). The CW does not go
/// through this channel and is never skipped.
const EVENT_CHANNEL_CAPACITY: usize = 1024;

/// CW rotation tick. The rotation timer always runs with this fixed period; `crypto_period` does
/// not set the timer duration directly but the number of ticks until rotation
/// (`nominal_cp_duration`, the protocol unit of hundreds of milliseconds). This is the single
/// source of truth for CWs: the same value goes into `STREAM_SETUP` as `nominal_cp_duration`, so
/// the actual rotation and the duration announced to the ECMG never diverge, and `crypto_period =
/// 0` simply rotates on every tick instead of dividing the timer by zero.
const CW_ROTATION_TICK: Duration = Duration::from_millis(100);

/// One CW group member: a specific `(CasRef, stream_id)` that at least one `Service` currently
/// tracks.
#[derive(Clone)]
pub struct Member {
    cas: CasRef,
    pub stream_id: u16,
    pub access_criteria: Vec<u8>,
    /// How many live `Service`s currently include this stream in their `ServiceConfig.cas`. When
    /// it reaches zero, the member is removed from the group and its resources
    /// (`stream_sinks`/`ready_streams`/`used_ecm_pids`/EMMG registration) are released - whether
    /// or not the group as a whole is still alive (it may have members from other `Service`s).
    refcount: usize,
}

#[derive(Clone, Copy)]
struct Cw {
    cp_number: u16,
    parity: Parity,
    cw: [u8; 8],
}

impl From<Cw> for Event {
    fn from(cw: Cw) -> Self {
        Event::Cw {
            cp_number: cw.cp_number,
            parity: cw.parity,
            cw: cw.cw,
        }
    }
}

/// Shared state of one CW group: one CW pair for the whole group, shared by all `Service`s whose
/// `(CasRef, ecm_pid)` overlap in at least one pair - two services with the same CAS and the same
/// `ecm_pid` must share one stream and therefore one CW group. `members` can grow when another
/// `Service` joins and brings new, previously unused pairs.
pub struct ServiceGroup {
    crypto_period: Duration,
    nominal_cp_duration: u16,
    /// Latest CW of the group. Kept apart from `events_tx` so that no amount of ECM/EMM can evict
    /// it.
    cw_tx: watch::Sender<Option<Cw>>,
    events_tx: broadcast::Sender<Event>,
    rotation: Mutex<Option<AbortHandle>>,
    members: Mutex<HashMap<(CasRef, u16), Member>>,
}

impl ServiceGroup {
    pub fn nominal_cp_duration(&self) -> u16 {
        self.nominal_cp_duration
    }

    pub fn cp_number(&self) -> Option<u16> {
        self.cw_tx.borrow().map(|cw| cw.cp_number)
    }

    pub fn remove_member(&self, cas: CasRef, stream_id: u16) {
        self.members.lock_or_recover().remove(&(cas, stream_id));
    }
}

/// Resolves every requested `(CasRef, ecm_pid)` pair into a `stream_id` within `group`: either
/// reuses a pair already bound to this group, or allocates a new one and registers its I/O (EMMG
/// stream, ECMG `add_stream`). Deduplicates repeats within the same call.
fn resolve_service_streams(
    cfg: &ServiceConfig,
    entries: &[Arc<CasEntry>],
    group: &Arc<ServiceGroup>,
    nominal_cp_duration: u16,
) -> Vec<StreamInfo> {
    let mut processed: HashMap<(CasRef, u16), u16> = HashMap::new();
    let mut stream_infos = Vec::with_capacity(cfg.cas.len());

    for (service_cas, entry) in cfg.cas.iter().zip(entries) {
        let dedup_key = (service_cas.cas, service_cas.ecm_pid);

        let stream_id = if let Some(&stream_id) = processed.get(&dedup_key) {
            stream_id
        } else {
            let existing = entry.membership(service_cas.ecm_pid);

            let stream_id = match existing {
                Some(membership)
                    if membership
                        .group
                        .upgrade()
                        .is_some_and(|g| Arc::ptr_eq(&g, group)) =>
                {
                    membership.stream_id
                }
                _ => {
                    let stream_id =
                        entry.attach_stream(service_cas.ecm_pid, &Arc::downgrade(group));
                    register_new_member_io(
                        service_cas.cas,
                        entry,
                        stream_id,
                        &group.events_tx,
                        nominal_cp_duration,
                    );
                    stream_id
                }
            };

            processed.insert(dedup_key, stream_id);
            stream_id
        };

        {
            let mut members = group.members.lock_or_recover();
            match members.get_mut(&(service_cas.cas, stream_id)) {
                Some(member) => {
                    if member.access_criteria != service_cas.access_criteria {
                        tracing::warn!(
                            name = %cfg.name,
                            stream_id,
                            "access_criteria differ from the running group, keeping the first"
                        );
                    }
                    member.refcount += 1;
                }
                None => {
                    members.insert(
                        (service_cas.cas, stream_id),
                        Member {
                            cas: service_cas.cas,
                            stream_id,
                            access_criteria: service_cas.access_criteria.clone(),
                            refcount: 1,
                        },
                    );
                }
            }
        }

        stream_infos.push(StreamInfo {
            cas: service_cas.cas,
            ecm_pid: service_cas.ecm_pid,
            stream_id,
        });
    }

    stream_infos
}

/// Service handle. Several `Service`s may share one CW group fully or partially (see
/// `open_service`); each `(CasRef, stream_id)` is released when the last `Service` referencing it
/// lets go, and the whole group when no members are left. If afterwards a `CasRef` has no streams
/// at all, its ECMG driver is stopped - the `CasRef` stays valid and comes back on the next
/// `open_service` with it.
pub struct Service {
    name: String,
    inner: Arc<Inner>,
    group: Arc<ServiceGroup>,
    streams: Vec<StreamInfo>,
    cw_rx: watch::Receiver<Option<Cw>>,
    /// Replayed on open: the state of each CAS and, on a joined group, the last ECM per stream.
    pending: VecDeque<Event>,
    events_rx: broadcast::Receiver<Event>,
}

impl Service {
    /// See `Simulcrypt::open_service`.
    pub fn open(inner: &Arc<Inner>, cfg: &ServiceConfig) -> Result<Self, Error> {
        if cfg.cas.is_empty() {
            return Err(Error::EmptyService);
        }

        let nominal_cp_duration = cfg.nominal_cp_duration()?;

        let mut entries = Vec::with_capacity(cfg.cas.len());
        for service_cas in &cfg.cas {
            entries.push(inner.cas_entry(service_cas.cas)?);
        }

        // Hold the lock for the whole find-or-create/join: otherwise a concurrent open_service or
        // Drop could break the "not taken by a foreign group" check between detection and
        // mutation.
        let _topology = inner.topology.lock_or_recover();

        // If any of the listed CasRefs is "sleeping" after a previous Drop closed it as an empty
        // channel (see `CasEntry::shutdown`), bring it back up - under the same lock as the rest of
        // the group selection, otherwise a concurrent Drop could see the channel in an intermediate
        // state.
        for (service_cas, entry) in cfg.cas.iter().zip(&entries) {
            entry.ensure_running(service_cas.cas);
        }

        let mut found: Option<Arc<ServiceGroup>> = None;
        for (service_cas, entry) in cfg.cas.iter().zip(&entries) {
            let Some(membership) = entry.membership(service_cas.ecm_pid) else {
                continue;
            };
            let Some(group) = membership.group.upgrade() else {
                continue; // stale Weak - as if the pair did not exist, it will be reallocated
            };

            match &found {
                None => found = Some(group),
                Some(existing) if Arc::ptr_eq(existing, &group) => {}
                Some(_) => {
                    return Err(Error::CwGroupConflict {
                        ecm_pid: service_cas.ecm_pid,
                        stream_id: membership.stream_id,
                    });
                }
            }
        }

        let (group, cw_rx, events_rx) = if let Some(group) = found {
            if group.crypto_period != cfg.crypto_period {
                return Err(Error::CryptoPeriodMismatch {
                    expected: group.crypto_period,
                    actual: cfg.crypto_period,
                });
            }
            let mut cw_rx = group.cw_tx.subscribe();
            // A joining service gets the CW that is already on air instead of waiting for the next
            // rotation.
            if cw_rx.borrow().is_some() {
                cw_rx.mark_changed();
            }
            let events_rx = group.events_tx.subscribe();
            (group, cw_rx, events_rx)
        } else {
            let (cw_tx, cw_rx) = watch::channel(None);
            let (events_tx, events_rx) = broadcast::channel(EVENT_CHANNEL_CAPACITY);
            let group = Arc::new(ServiceGroup {
                crypto_period: cfg.crypto_period,
                nominal_cp_duration,
                cw_tx,
                events_tx,
                rotation: Mutex::new(None),
                members: Mutex::new(HashMap::new()),
            });
            (group, cw_rx, events_rx)
        };

        let streams = resolve_service_streams(cfg, &entries, &group, nominal_cp_duration);

        let mut rotation = group.rotation.lock_or_recover();
        if rotation.is_none() {
            *rotation = Some(spawn_supervised(
                "cw-rotation",
                run_cw_rotation(
                    Arc::clone(inner),
                    nominal_cp_duration,
                    Arc::downgrade(&group),
                ),
            ));
        }
        drop(rotation);

        let mut pending = VecDeque::new();
        let mut seen = Vec::new();
        for (info, entry) in streams.iter().zip(&entries) {
            if !seen.contains(&info.cas) {
                seen.push(info.cas);
                pending.push_back(entry.state_event(info.cas));
            }
        }
        for (info, entry) in streams.iter().zip(&entries) {
            pending.extend(entry.last_ecm(info.stream_id));
        }

        Ok(Service {
            name: cfg.name.clone(),
            inner: Arc::clone(inner),
            group,
            streams,
            cw_rx,
            pending,
            events_rx,
        })
    }

    /// `stream_id`s assigned by the crate.
    #[must_use]
    pub fn streams(&self) -> &[StreamInfo] {
        &self.streams
    }

    /// Waits for the next service event. Returns `None` when the queue is closed (the service can
    /// no longer receive events under any circumstances).
    ///
    /// A pending CW is returned ahead of queued ECM/EMM and is never dropped; a receiver that
    /// misses several rotations gets only the latest CW. A new service starts with the current
    /// state of each of its CAS and, when it joins a running group, the last ECM of each stream.
    pub async fn recv(&mut self) -> Option<Event> {
        loop {
            if !self.cw_rx.has_changed().unwrap_or(false)
                && let Some(event) = self.pending.pop_front()
            {
                return Some(event);
            }
            tokio::select! {
                biased;
                changed = self.cw_rx.changed() => {
                    changed.ok()?;
                    if let Some(cw) = *self.cw_rx.borrow_and_update() {
                        return Some(cw.into());
                    }
                }
                event = self.events_rx.recv() => match event {
                    Ok(event) => return Some(event),
                    Err(broadcast::error::RecvError::Lagged(skipped)) => {
                        tracing::warn!(
                        name = %self.name,
                        skipped,
                        "service event receiver lagged"
                    );
                    }
                    Err(broadcast::error::RecvError::Closed) => return None,
                },
            }
        }
    }

    /// Non-blocking variant of `recv`.
    pub fn try_recv(&mut self) -> Option<Event> {
        if self.cw_rx.has_changed().unwrap_or(false)
            && let Some(cw) = *self.cw_rx.borrow_and_update()
        {
            return Some(cw.into());
        }
        if let Some(event) = self.pending.pop_front() {
            return Some(event);
        }
        loop {
            match self.events_rx.try_recv() {
                Ok(event) => return Some(event),
                Err(broadcast::error::TryRecvError::Lagged(skipped)) => {
                    tracing::warn!(
                        name = %self.name,
                        skipped,
                        "service event receiver lagged"
                    );
                }
                Err(_) => return None,
            }
        }
    }
}

impl Drop for Service {
    fn drop(&mut self) {
        let _topology = self.inner.topology.lock_or_recover();

        let mut freed = Vec::new();
        {
            let mut members = self.group.members.lock_or_recover();
            for info in &self.streams {
                let key = (info.cas, info.stream_id);
                if let Some(member) = members.get_mut(&key) {
                    member.refcount -= 1;
                    if member.refcount == 0 {
                        members.remove(&key);
                        freed.push(*info);
                    }
                }
            }

            if members.is_empty()
                && let Some(handle) = self.group.rotation.lock_or_recover().take()
            {
                handle.abort();
            }
        }

        if freed.is_empty() {
            return;
        }

        for info in &freed {
            if let Ok(entry) = self.inner.cas_entry(info.cas) {
                entry.release_stream(info);
            }
        }
    }
}

fn all_streams_ready(inner: &Inner, targets: &[Member]) -> bool {
    targets.iter().all(|member| {
        inner
            .cas_entry(member.cas)
            .is_ok_and(|entry| entry.is_stream_ready(member.stream_id))
    })
}

/// Rotates the group CW every `nominal_cp_duration` ticks, only while all streams are ready;
/// the first CW goes out on the first ready tick. Spawn after the group has members: an empty
/// or dropped group ends the task.
async fn run_cw_rotation(inner: Arc<Inner>, nominal_cp_duration: u16, group: Weak<ServiceGroup>) {
    let mut rng = StdRng::from_rng(&mut rand::rng());
    let mut generator = CwGenerator::new(&mut rng);
    let mut interval = tokio::time::interval(CW_ROTATION_TICK);
    let mut ticks_since_rotation = nominal_cp_duration;

    loop {
        interval.tick().await;

        let Some(group) = group.upgrade() else {
            return;
        };

        let targets: Vec<Member> = group.members.lock_or_recover().values().cloned().collect();
        if targets.is_empty() {
            return;
        }

        if ticks_since_rotation < nominal_cp_duration {
            ticks_since_rotation += 1;
            continue;
        }

        if !all_streams_ready(&inner, &targets) {
            continue;
        }

        ticks_since_rotation = 0;
        let advance = generator.advance(&mut rng);

        group.cw_tx.send_replace(Some(Cw {
            cp_number: advance.cp_number,
            parity: advance.parity,
            cw: advance.active,
        }));

        for member in targets {
            if let Ok(entry) = inner.cas_entry(member.cas) {
                entry.provision_cw(member, &advance);
            }
        }
    }
}