simulcrypt 0.1.0

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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! Continuous ECMG client loop for one CAS channel: handshake, reconnect after a fixed delay, any
//! number of streams (including adding a stream on a live connection) and CW provisioning. One
//! `DriverHandle` = one TCP connection per CAS.

use std::{
    collections::HashMap,
    net::SocketAddr,
    time::Duration,
};

use bytes::Bytes;
use tokio::{
    net::TcpStream,
    sync::{
        mpsc,
        oneshot,
    },
    time::Instant,
};

use crate::ecmg::{
    ChannelParams,
    SectionTsPktFlag,
    session::{
        EcmgEvent,
        EcmgSession,
        SessionError,
    },
};

/// Settings of one driver: ECMG address, channel identifiers, reconnect timings.
#[derive(Clone, Debug)]
pub struct DriverConfig {
    /// Channel name for logs.
    pub name: String,
    /// `channel_id` as defined by ETSI TS 103.197.
    pub channel_id: u16,
    /// `CA_system_id << 16 | subsystem_id`.
    pub super_cas_id: u32,
    /// ECMG server address.
    pub addr: SocketAddr,
    /// Delay before the next connection attempt after a disconnect.
    pub reconnect_delay: Duration,
    /// Timeout for the TCP connect and for a reply to a request.
    pub response_timeout: Duration,
    /// How long to wait without a single message from the ECMG before sending our own
    /// `CHANNEL_TEST` - catches a half-open connection (TCP looks established, but no data flows
    /// in either direction) during idle time between ECMs, when reads deliberately have no
    /// timeout.
    pub idle_probe_interval: Duration,
}

impl DriverConfig {
    async fn connect(&self, known_streams: &[(u16, u16)]) -> Result<EcmgSession, SessionError> {
        tracing::info!(
            name = %self.name,
            addr = %self.addr,
            "connecting to ECMG"
        );

        let tcp_stream =
            tokio::time::timeout(self.response_timeout, TcpStream::connect(self.addr)).await??;

        EcmgSession::open(
            tcp_stream,
            self.channel_id,
            self.super_cas_id,
            known_streams,
            &self.name,
            self.response_timeout,
        )
        .await
    }

    async fn run(
        self,
        mut cmd_rx: mpsc::UnboundedReceiver<DriverCommand>,
        events_tx: mpsc::UnboundedSender<DriverEvent>,
    ) {
        let mut known_streams: Vec<(u16, u16)> = Vec::new();
        let mut last_provision: HashMap<u16, ProvisionRecord> = HashMap::new();

        loop {
            if cmd_rx.is_closed() {
                return;
            }

            let _ = events_tx.send(DriverEvent::State(DriverState::Connecting));

            match self.connect(&known_streams).await {
                Ok(mut session) => {
                    for (stream_id, record) in &last_provision {
                        if let Err(error) = session
                            .send_cw_provision_to(
                                *stream_id,
                                record.cp_number,
                                &record.current,
                                &record.next,
                                record.access_criteria.as_deref(),
                            )
                            .await
                        {
                            tracing::warn!(
                                name = %self.name,
                                stream_id,
                                error = %error,
                                "failed to replay CW_PROVISION after reconnect"
                            );
                        }
                    }

                    let _ = events_tx.send(DriverEvent::State(DriverState::Ready {
                        section_ts_pkt_flag: session.section_ts_pkt_flag(),
                        params: session.channel_params(),
                        ready_stream_ids: session.stream_ids().collect(),
                    }));

                    run_session(
                        &self,
                        &mut session,
                        &mut cmd_rx,
                        &events_tx,
                        &mut known_streams,
                        &mut last_provision,
                    )
                    .await;
                }
                Err(error) => {
                    tracing::warn!(
                        name = %self.name,
                        error = %error,
                        "ECMG connection failed"
                    );
                    let _ = events_tx.send(DriverEvent::State(DriverState::Error {
                        code: None,
                        info: Some(error.to_string()),
                    }));
                }
            }

            let _ = events_tx.send(DriverEvent::State(DriverState::Disconnected));
            tokio::time::sleep(self.reconnect_delay).await;
        }
    }
}

/// Event emitted by the driver (to `CasEntry`).
#[derive(Debug)]
pub enum DriverEvent {
    /// ECM received for a specific stream.
    Ecm {
        /// Stream the ECM belongs to.
        stream_id: u16,
        /// Crypto period number, if the ECMG sent one.
        cp_number: Option<u16>,
        /// Datagram format.
        format: SectionTsPktFlag,
        /// Raw ECM bytes.
        data: Bytes,
    },
    /// ECM for a past crypto period, dropped.
    StaleEcm {
        /// Stream the ECM belongs to.
        stream_id: u16,
    },
    /// Connection state changed (see [`DriverState`]).
    State(DriverState),
}

/// State of the driver's ECMG connection.
#[derive(Clone, Debug)]
pub enum DriverState {
    /// Connecting or reconnecting.
    Connecting,
    /// Handshake of the channel and all currently known streams is complete.
    Ready {
        /// Datagram format negotiated in `CHANNEL_STATUS`.
        section_ts_pkt_flag: SectionTsPktFlag,
        /// Other parameters negotiated in `CHANNEL_STATUS`.
        params: ChannelParams,
        /// Streams the ECMG accepted in this session.
        ready_stream_ids: Vec<u16>,
    },
    /// The ECMG returned an error or the connection failed with an error.
    Error {
        /// Error code, if known.
        code: Option<u16>,
        /// Error description, if known.
        info: Option<String>,
    },
    /// Connection closed, reconnect pending.
    Disconnected,
}

/// [`DriverHandle`] call error.
#[derive(Debug, thiserror::Error)]
pub enum DriverError {
    /// The driver task is no longer running (usually means the CAS has been destroyed).
    #[error("ECMG driver task is no longer running")]
    Closed,

    /// The ECMG rejected or failed to process `STREAM_SETUP`.
    #[error("ECMG stream setup failed: {0}")]
    Session(#[source] SessionError),
}

enum DriverCommand {
    AddStream {
        stream_id: u16,
        nominal_cp_duration: u16,
        reply: oneshot::Sender<Result<(), DriverError>>,
    },
    ProvisionCw {
        stream_id: u16,
        cp_number: u16,
        current: [u8; 8],
        next: [u8; 8],
        access_criteria: Option<Vec<u8>>,
    },
    RemoveStream {
        stream_id: u16,
    },
}

/// Cheap copyable reference to a running driver. Survives reconnects, since the task itself (and
/// the TCP connection) lives independently of the `DriverHandle` holders.
#[derive(Clone)]
pub struct DriverHandle {
    tx: mpsc::UnboundedSender<DriverCommand>,
}

impl DriverHandle {
    /// Registers a stream in the driver. If the connection is established, runs `STREAM_SETUP`
    /// right away; if the channel is reconnecting, the stream is set up on the next successful
    /// handshake.
    ///
    /// # Errors
    ///
    /// Returns `Err(DriverError::Closed)` if the driver task is no longer running, and
    /// `Err(DriverError::Session(_))` if the ECMG rejected `STREAM_SETUP` or the connection
    /// dropped before the reply arrived.
    pub async fn add_stream(
        &self,
        stream_id: u16,
        nominal_cp_duration: u16,
    ) -> Result<(), DriverError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.tx
            .send(DriverCommand::AddStream {
                stream_id,
                nominal_cp_duration,
                reply: reply_tx,
            })
            .map_err(|_| DriverError::Closed)?;

        reply_rx.await.map_err(|_| DriverError::Closed)?
    }

    /// Removes a stream from the driver and sends `STREAM_CLOSE_REQUEST` for it - used for a
    /// graceful close of one stream while the channel keeps serving the others (the whole channel
    /// is closed by dropping the `DriverHandle` itself). Does not block on the network - the
    /// actual send happens inside the driver task.
    ///
    /// # Errors
    ///
    /// Returns `Err(DriverError::Closed)` if the driver task is no longer running - errors of the
    /// `STREAM_CLOSE_REQUEST` send itself do not reach here, they are only logged inside the
    /// driver task.
    pub fn remove_stream(&self, stream_id: u16) -> Result<(), DriverError> {
        self.tx
            .send(DriverCommand::RemoveStream { stream_id })
            .map_err(|_| DriverError::Closed)
    }

    /// Queues `CW_PROVISION` in the driver. Does not block on the network: the actual send and
    /// the replay after a reconnect happen inside the driver task.
    ///
    /// # Errors
    ///
    /// Returns `Err(DriverError::Closed)` if the driver task is no longer running - errors of the
    /// `CW_PROVISION` send itself (network, ECMG rejection) do not reach here, they are only
    /// logged inside the driver task.
    pub fn provision_cw(
        &self,
        stream_id: u16,
        cp_number: u16,
        current: [u8; 8],
        next: [u8; 8],
        access_criteria: Option<Vec<u8>>,
    ) -> Result<(), DriverError> {
        self.tx
            .send(DriverCommand::ProvisionCw {
                stream_id,
                cp_number,
                current,
                next,
                access_criteria,
            })
            .map_err(|_| DriverError::Closed)
    }

    /// Starts the driver in a background task and returns a handle to control it.
    #[must_use]
    pub fn spawn(config: DriverConfig, events_tx: mpsc::UnboundedSender<DriverEvent>) -> Self {
        let (cmd_tx, cmd_rx) = mpsc::unbounded_channel();
        let name = config.name.clone();
        crate::spawn::spawn_supervised(name, config.run(cmd_rx, events_tx));
        Self { tx: cmd_tx }
    }
}

/// Last known CW provision per stream - replayed right after a reconnect so the ECMG keeps the
/// current/next CW and continues to produce a correct ECM.
struct ProvisionRecord {
    cp_number: u16,
    current: [u8; 8],
    next: [u8; 8],
    access_criteria: Option<Vec<u8>>,
}

/// Tracks connection idle time to catch a half-open ECMG: `read_event` deliberately waits without
/// a timeout (silence between ECMs within a crypto period is normal), so an active liveness check
/// on prolonged idle is done here.
struct Liveness {
    /// When the last message of any kind actually arrived from the ECMG.
    last_activity: Instant,
    /// `Some(when)` if a probe `CHANNEL_TEST` was sent and any reply is awaited.
    probe_sent_at: Option<Instant>,
}

impl Liveness {
    fn new() -> Self {
        Self {
            last_activity: Instant::now(),
            probe_sent_at: None,
        }
    }

    /// Any message arrived from the ECMG - the channel is alive, reset both idle time and probe.
    fn on_activity(&mut self) {
        self.last_activity = Instant::now();
        self.probe_sent_at = None;
    }

    /// The moment to either send a probe `CHANNEL_TEST` (if not sent yet) or, if it was sent and
    /// no reply came, declare the connection dead.
    fn deadline(&self, idle_probe_interval: Duration, response_timeout: Duration) -> Instant {
        match self.probe_sent_at {
            None => self.last_activity + idle_probe_interval,
            Some(sent_at) => sent_at + response_timeout,
        }
    }
}

async fn run_session(
    config: &DriverConfig,
    session: &mut EcmgSession,
    cmd_rx: &mut mpsc::UnboundedReceiver<DriverCommand>,
    events_tx: &mpsc::UnboundedSender<DriverEvent>,
    known_streams: &mut Vec<(u16, u16)>,
    last_provision: &mut HashMap<u16, ProvisionRecord>,
) {
    let mut liveness = Liveness::new();

    loop {
        let idle_deadline = liveness.deadline(config.idle_probe_interval, config.response_timeout);

        let keep_running = tokio::select! {
            command = cmd_rx.recv() => {
                handle_command(command, config, session, known_streams, last_provision, events_tx).await
            }
            event = session.read_event() => {
                handle_read_event(event, config, session, last_provision, events_tx, &mut liveness)
            }
            () = tokio::time::sleep_until(idle_deadline) => {
                handle_idle_probe(config, session, &mut liveness, events_tx).await
            }
        };

        if !keep_running {
            return;
        }
    }
}

/// Handles one command from `DriverHandle`. `false` means the session must end - either the
/// connection is broken beyond recovery (reconnect is inevitable), or (the `None` case) the last
/// `DriverHandle` was dropped and the whole driver task shuts down gracefully.
async fn handle_command(
    command: Option<DriverCommand>,
    config: &DriverConfig,
    session: &mut EcmgSession,
    known_streams: &mut Vec<(u16, u16)>,
    last_provision: &mut HashMap<u16, ProvisionRecord>,
    events_tx: &mpsc::UnboundedSender<DriverEvent>,
) -> bool {
    match command {
        None => {
            // The last DriverHandle was dropped - the whole channel closes. Send CHANNEL_CLOSE
            // before the TCP connection goes away (session goes out of scope right after
            // run_session returns) instead of silently dropping the socket.
            if let Err(error) = session.close_channel().await {
                tracing::warn!(
                    name = %config.name,
                    error = %error,
                    "failed to send CHANNEL_CLOSE"
                );
            }
            false
        }
        Some(DriverCommand::RemoveStream { stream_id }) => {
            known_streams.retain(|(id, _)| *id != stream_id);
            last_provision.remove(&stream_id);

            if let Err(error) = session.close_stream(stream_id).await {
                tracing::warn!(
                    name = %config.name,
                    stream_id,
                    error = %error,
                    "failed to send STREAM_CLOSE_REQUEST"
                );
            }
            true
        }
        Some(DriverCommand::AddStream {
            stream_id,
            nominal_cp_duration,
            reply,
        }) => {
            let result = session.add_stream(stream_id, nominal_cp_duration).await;
            match result {
                Ok(()) => {
                    known_streams.push((stream_id, nominal_cp_duration));
                    let _ = reply.send(Ok(()));
                    true
                }
                // A rejection of a specific stream (STREAM_ERROR on STREAM_SETUP) does not break
                // the session - the channel and its other streams keep working. The rejected
                // stream is not added to known_streams, so the next reconnect does not inherit it.
                Err(error) if error.is_stream_error() => {
                    tracing::warn!(
                        name = %config.name,
                        stream_id,
                        error = %error,
                        "STREAM_SETUP rejected"
                    );
                    let _ = reply.send(Err(DriverError::Session(error)));
                    true
                }
                Err(error) => {
                    tracing::warn!(
                        name = %config.name,
                        stream_id,
                        error = %error,
                        "failed to add stream"
                    );
                    let _ = reply.send(Err(DriverError::Session(error)));
                    false
                }
            }
        }
        Some(DriverCommand::ProvisionCw {
            stream_id,
            cp_number,
            current,
            next,
            access_criteria,
        }) => {
            last_provision.insert(
                stream_id,
                ProvisionRecord {
                    cp_number,
                    current,
                    next,
                    access_criteria: access_criteria.clone(),
                },
            );

            if let Err(error) = session
                .send_cw_provision_to(
                    stream_id,
                    cp_number,
                    &current,
                    &next,
                    access_criteria.as_deref(),
                )
                .await
            {
                tracing::warn!(
                    name = %config.name,
                    stream_id,
                    error = %error,
                    "failed to send CW_PROVISION"
                );
                let _ = events_tx.send(DriverEvent::State(DriverState::Error {
                    code: None,
                    info: Some(error.to_string()),
                }));
                return false;
            }
            true
        }
    }
}

/// Handles one event of the session runtime loop. `false` means the session must end.
fn handle_read_event(
    event: Result<EcmgEvent, SessionError>,
    config: &DriverConfig,
    session: &EcmgSession,
    last_provision: &HashMap<u16, ProvisionRecord>,
    events_tx: &mpsc::UnboundedSender<DriverEvent>,
    liveness: &mut Liveness,
) -> bool {
    if event.is_ok() {
        // Something arrived - the channel is not half-open, reset idle time and cancel a
        // pending probe, if any.
        liveness.on_activity();
    }

    match event {
        Ok(EcmgEvent::Ecm(ecm)) => {
            let Some(stream_id) = ecm.stream_id() else {
                tracing::warn!(
                    name = %config.name,
                    "ignoring ECM_RESPONSE without stream_id"
                );
                return true;
            };

            let cp_number = ecm.cp_number();
            // An ECM for anything but the last provisioned crypto period carries a CW the
            // scrambler no longer uses.
            if let Some(cp_number) = cp_number
                && last_provision
                    .get(&stream_id)
                    .map(|record| record.cp_number)
                    != Some(cp_number)
            {
                tracing::warn!(
                    name = %config.name,
                    stream_id,
                    cp_number,
                    "dropping ECM_RESPONSE for a past crypto period"
                );
                let _ = events_tx.send(DriverEvent::StaleEcm { stream_id });
                return true;
            }

            let format = session.section_ts_pkt_flag();
            let _ = events_tx.send(DriverEvent::Ecm {
                stream_id,
                cp_number,
                format,
                data: Bytes::from(ecm.into_datagram()),
            });
            true
        }
        Ok(EcmgEvent::ChannelError { status, info }) => {
            tracing::error!(
                name = %config.name,
                status = ?status,
                info = ?info,
                "ECMG CHANNEL_ERROR"
            );
            let _ = events_tx.send(DriverEvent::State(DriverState::Error {
                code: status,
                info,
            }));
            false
        }
        Ok(EcmgEvent::StreamError {
            stream_id,
            status,
            info,
        }) => {
            // A rejection of a specific stream, not of the whole channel - only log it.
            // Do NOT send DriverEvent::State: it is a channel-wide `Event`, and its State::Error
            // in `CasEntry` clears ready_streams for ALL streams of the channel - without a
            // following reconnect (there is none here) that record never recovers, and CW
            // rotation stops forever for the whole CW group because of one failed stream.
            tracing::error!(
                name = %config.name,
                stream_id = ?stream_id,
                status = ?status,
                info = ?info,
                "ECMG STREAM_ERROR"
            );
            true
        }
        Ok(EcmgEvent::Message) => true,
        Err(error) => {
            tracing::warn!(
                name = %config.name,
                error = %error,
                "ECMG session error"
            );
            let _ = events_tx.send(DriverEvent::State(DriverState::Error {
                code: None,
                info: Some(error.to_string()),
            }));
            false
        }
    }
}

/// Checks/advances connection idle time. `false` means the session must end (no reply to the
/// probe `CHANNEL_TEST` - the connection is considered dead).
async fn handle_idle_probe(
    config: &DriverConfig,
    session: &mut EcmgSession,
    liveness: &mut Liveness,
    events_tx: &mpsc::UnboundedSender<DriverEvent>,
) -> bool {
    if liveness.probe_sent_at.is_some() {
        // The probe CHANNEL_TEST was sent and nothing at all arrived within response_timeout
        // (neither CHANNEL_STATUS nor anything else) - classic half-open: TCP looks established,
        // but no data flows in either direction. Drop the session and reconnect.
        tracing::warn!(
            name = %config.name,
            timeout = ?config.response_timeout,
            "no reply to idle-probe CHANNEL_TEST, the connection is dead"
        );
        let _ = events_tx.send(DriverEvent::State(DriverState::Error {
            code: None,
            info: Some("half-open connection: no response to idle-probe CHANNEL_TEST".to_owned()),
        }));
        return false;
    }

    if let Err(error) = session.send_channel_test().await {
        tracing::warn!(
            name = %config.name,
            error = %error,
            "failed to send idle-probe CHANNEL_TEST"
        );
        let _ = events_tx.send(DriverEvent::State(DriverState::Error {
            code: None,
            info: Some(error.to_string()),
        }));
        return false;
    }
    liveness.probe_sent_at = Some(Instant::now());
    true
}