simulcrypt 0.2.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
//! Typed parsing of incoming EMMG requests.

use crate::messages::{
    RawSimulcryptMessage,
    emmg::{
        EMMG_MSG_CHANNEL_CLOSE,
        EMMG_MSG_CHANNEL_SETUP,
        EMMG_MSG_CHANNEL_TEST,
        EMMG_MSG_DATA_PROVISION,
        EMMG_MSG_STREAM_BW_REQUEST,
        EMMG_MSG_STREAM_CLOSE_REQUEST,
        EMMG_MSG_STREAM_SETUP,
        EMMG_MSG_STREAM_TEST,
        EMMG_VAR_BANDWIDTH,
        EMMG_VAR_CHANNEL_ID,
        EMMG_VAR_DATA_ID,
        EMMG_VAR_DATA_TYPE,
        EMMG_VAR_DATAGRAM,
        EMMG_VAR_SECTION_TS_PKT_FLAG,
        EMMG_VAR_STREAM_ID,
        EMMG_VAR_SUPER_CAS_ID,
    },
    tlv::Tlv,
};

/// Typed EMMG message received from an external EMM generator.
#[derive(Debug)]
pub enum EmmgMessage {
    /// Channel open request.
    ChannelSetup(ChannelSetupMessage),
    /// Channel liveness check.
    ChannelTest(ChannelTestMessage),
    /// Channel close request.
    ChannelClose(ChannelCloseMessage),

    /// Request to open a stream inside a channel.
    StreamSetup(StreamSetupMessage),
    /// Stream liveness check.
    StreamTest(StreamTestMessage),
    /// Stream close request.
    StreamCloseRequest(StreamCloseRequestMessage),
    /// Bandwidth request for a stream.
    StreamBwRequest(StreamBwRequestMessage),

    /// EMM datagram to insert into the transport stream.
    DataProvision(DataProvisionMessage),
}

impl TryFrom<RawSimulcryptMessage> for EmmgMessage {
    type Error = EmmgMessageError;

    fn try_from(raw: RawSimulcryptMessage) -> Result<Self, Self::Error> {
        ParsedFields::parse(raw.vars)?.into_message(raw.message_type)
    }
}

fn parse_u8(value: &[u8], field: &'static str) -> Result<u8, EmmgMessageError> {
    if value.len() != 1 {
        return Err(EmmgMessageError::InvalidFieldLength {
            field,
            expected: 1,
            actual: value.len(),
        });
    }
    Ok(value[0])
}

fn parse_u16(value: &[u8], field: &'static str) -> Result<u16, EmmgMessageError> {
    if value.len() != 2 {
        return Err(EmmgMessageError::InvalidFieldLength {
            field,
            expected: 2,
            actual: value.len(),
        });
    }
    Ok(u16::from_be_bytes([value[0], value[1]]))
}

fn parse_u32(value: &[u8], field: &'static str) -> Result<u32, EmmgMessageError> {
    if value.len() != 4 {
        return Err(EmmgMessageError::InvalidFieldLength {
            field,
            expected: 4,
            actual: value.len(),
        });
    }
    Ok(u32::from_be_bytes([value[0], value[1], value[2], value[3]]))
}

fn parse_bool(value: &[u8], field: &'static str) -> Result<bool, EmmgMessageError> {
    match parse_u8(value, field)? {
        0 => Ok(false),
        1 => Ok(true),
        other => Err(EmmgMessageError::InvalidFieldValue {
            field,
            value: other.to_string(),
        }),
    }
}

/// Intermediate result of parsing the request TLV variables - before it is known which message type
/// this is (and therefore which fields are mandatory).
#[derive(Default)]
pub(super) struct ParsedFields {
    pub(super) super_cas_id: Option<u32>,
    pub(super) channel_id: Option<u16>,
    section_ts_pkt_flag: Option<bool>,
    pub(super) stream_id: Option<u16>,
    pub(super) data_id: Option<u16>,
    data_type: Option<u8>,
    bandwidth: Option<u16>,
    pub(super) datagram: Option<Vec<u8>>,
}

impl ParsedFields {
    /// Parses TLV variables regardless of the message type: unknown tags are silently ignored,
    /// duplicates and bad lengths/values of known fields are an error.
    pub(super) fn parse(vars: Vec<Tlv>) -> Result<Self, EmmgMessageError> {
        let mut fields = Self::default();

        for var in vars {
            let value = &var.value;

            match var.tag {
                EMMG_VAR_SUPER_CAS_ID => {
                    if fields.super_cas_id.is_some() {
                        return Err(EmmgMessageError::DuplicateField("super_cas_id"));
                    }
                    fields.super_cas_id = Some(parse_u32(value, "super_cas_id")?);
                }
                EMMG_VAR_SECTION_TS_PKT_FLAG => {
                    if fields.section_ts_pkt_flag.is_some() {
                        return Err(EmmgMessageError::DuplicateField("section_ts_pkt_flag"));
                    }
                    fields.section_ts_pkt_flag = Some(parse_bool(value, "section_ts_pkt_flag")?);
                }
                EMMG_VAR_CHANNEL_ID => {
                    if fields.channel_id.is_some() {
                        return Err(EmmgMessageError::DuplicateField("channel_id"));
                    }
                    fields.channel_id = Some(parse_u16(value, "channel_id")?);
                }
                EMMG_VAR_STREAM_ID => {
                    if fields.stream_id.is_some() {
                        return Err(EmmgMessageError::DuplicateField("stream_id"));
                    }
                    fields.stream_id = Some(parse_u16(value, "stream_id")?);
                }
                EMMG_VAR_DATAGRAM => {
                    if fields.datagram.is_some() {
                        return Err(EmmgMessageError::DuplicateField("datagram"));
                    }
                    fields.datagram = Some(var.value);
                }
                EMMG_VAR_BANDWIDTH => {
                    if fields.bandwidth.is_some() {
                        return Err(EmmgMessageError::DuplicateField("bandwidth"));
                    }
                    fields.bandwidth = Some(parse_u16(value, "bandwidth")?);
                }
                EMMG_VAR_DATA_TYPE => {
                    if fields.data_type.is_some() {
                        return Err(EmmgMessageError::DuplicateField("data_type"));
                    }
                    fields.data_type = Some(parse_u8(value, "data_type")?);
                }
                EMMG_VAR_DATA_ID => {
                    if fields.data_id.is_some() {
                        return Err(EmmgMessageError::DuplicateField("data_id"));
                    }
                    fields.data_id = Some(parse_u16(value, "data_id")?);
                }
                _ => {}
            }
        }

        Ok(fields)
    }

    /// Builds the `EmmgMessage` variant for `message_type`, checking that all its mandatory fields
    /// are present.
    fn into_message(self, message_type: u16) -> Result<EmmgMessage, EmmgMessageError> {
        match message_type {
            EMMG_MSG_CHANNEL_SETUP => Ok(EmmgMessage::ChannelSetup(ChannelSetupMessage {
                super_cas_id: self
                    .super_cas_id
                    .ok_or(EmmgMessageError::MissingField("super_cas_id"))?,
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                section_ts_pkt_flag: self
                    .section_ts_pkt_flag
                    .ok_or(EmmgMessageError::MissingField("section_ts_pkt_flag"))?,
            })),
            EMMG_MSG_CHANNEL_TEST => Ok(EmmgMessage::ChannelTest(ChannelTestMessage {
                super_cas_id: self
                    .super_cas_id
                    .ok_or(EmmgMessageError::MissingField("super_cas_id"))?,
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
            })),
            EMMG_MSG_CHANNEL_CLOSE => Ok(EmmgMessage::ChannelClose(ChannelCloseMessage {
                super_cas_id: self
                    .super_cas_id
                    .ok_or(EmmgMessageError::MissingField("super_cas_id"))?,
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
            })),
            EMMG_MSG_STREAM_SETUP => Ok(EmmgMessage::StreamSetup(StreamSetupMessage {
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                stream_id: self
                    .stream_id
                    .ok_or(EmmgMessageError::MissingField("stream_id"))?,
                data_id: self
                    .data_id
                    .ok_or(EmmgMessageError::MissingField("data_id"))?,
                data_type: self
                    .data_type
                    .ok_or(EmmgMessageError::MissingField("data_type"))?,
            })),
            EMMG_MSG_STREAM_TEST => Ok(EmmgMessage::StreamTest(StreamTestMessage {
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                stream_id: self
                    .stream_id
                    .ok_or(EmmgMessageError::MissingField("stream_id"))?,
            })),
            EMMG_MSG_STREAM_CLOSE_REQUEST => {
                Ok(EmmgMessage::StreamCloseRequest(StreamCloseRequestMessage {
                    channel_id: self
                        .channel_id
                        .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                    stream_id: self
                        .stream_id
                        .ok_or(EmmgMessageError::MissingField("stream_id"))?,
                }))
            }
            EMMG_MSG_STREAM_BW_REQUEST => {
                Ok(EmmgMessage::StreamBwRequest(StreamBwRequestMessage {
                    channel_id: self
                        .channel_id
                        .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                    stream_id: self
                        .stream_id
                        .ok_or(EmmgMessageError::MissingField("stream_id"))?,
                    bandwidth: self
                        .bandwidth
                        .ok_or(EmmgMessageError::MissingField("bandwidth"))?,
                }))
            }
            EMMG_MSG_DATA_PROVISION => Ok(EmmgMessage::DataProvision(DataProvisionMessage {
                channel_id: self
                    .channel_id
                    .ok_or(EmmgMessageError::MissingField("channel_id"))?,
                stream_id: self
                    .stream_id
                    .ok_or(EmmgMessageError::MissingField("stream_id"))?,
                data: self
                    .datagram
                    .ok_or(EmmgMessageError::MissingField("datagram"))?,
            })),
            _ => Err(EmmgMessageError::UnknownMessageType(message_type)),
        }
    }
}

/// Decoded `CHANNEL_SETUP` request.
#[derive(Debug)]
pub struct ChannelSetupMessage {
    /// `CA_system_id << 16 | subsystem_id`.
    pub super_cas_id: u32,
    /// Channel identifier within `super_cas_id`.
    pub channel_id: u16,
    /// `false` = section, `true` = TS packet.
    pub section_ts_pkt_flag: bool,
}

/// Decoded `CHANNEL_TEST` request.
#[derive(Debug)]
pub struct ChannelTestMessage {
    /// `CA_system_id << 16 | subsystem_id`.
    pub super_cas_id: u32,
    /// Channel identifier within `super_cas_id`.
    pub channel_id: u16,
}

/// Decoded `CHANNEL_CLOSE` request.
#[derive(Debug)]
pub struct ChannelCloseMessage {
    /// `CA_system_id << 16 | subsystem_id`.
    pub super_cas_id: u32,
    /// Channel identifier within `super_cas_id`.
    pub channel_id: u16,
}

/// Decoded `STREAM_SETUP` request.
#[derive(Debug)]
pub struct StreamSetupMessage {
    /// Channel the stream belongs to.
    pub channel_id: u16,
    /// Stream identifier within the channel.
    pub stream_id: u16,
    /// Identifier of the data the generator will send on this stream.
    pub data_id: u16,
    /// Data type (the `data_type` field of ETSI TS 103.197).
    pub data_type: u8,
}

/// Decoded `STREAM_TEST` request.
#[derive(Debug)]
pub struct StreamTestMessage {
    /// Channel the stream belongs to.
    pub channel_id: u16,
    /// Stream identifier within the channel.
    pub stream_id: u16,
}

/// Decoded `STREAM_CLOSE_REQUEST` request.
#[derive(Debug)]
pub struct StreamCloseRequestMessage {
    /// Channel the stream belongs to.
    pub channel_id: u16,
    /// Stream identifier within the channel.
    pub stream_id: u16,
}

/// Decoded `STREAM_BW_REQUEST` request.
#[derive(Debug)]
pub struct StreamBwRequestMessage {
    /// Channel the stream belongs to.
    pub channel_id: u16,
    /// Stream identifier within the channel.
    pub stream_id: u16,
    /// Requested bandwidth.
    pub bandwidth: u16,
}

/// Decoded `DATA_PROVISION` request - an EMM datagram to insert into the transport stream.
/// `data_id`/`data_type` are not part of `DATA_PROVISION` - they are `STREAM_SETUP` fields, already
/// known from `channel_id`/`stream_id` (see [`crate::emmg::dispatch::Dispatch`]).
#[derive(Debug)]
pub struct DataProvisionMessage {
    /// Channel the stream belongs to.
    pub channel_id: u16,
    /// Stream identifier within the channel.
    pub stream_id: u16,
    /// Raw EMM datagram.
    pub data: Vec<u8>,
}

/// Error decoding a raw message into a typed [`EmmgMessage`].
#[derive(Debug, thiserror::Error)]
pub enum EmmgMessageError {
    /// The message type is not a known EMMG request.
    #[error("unknown EMMG message type: {0:#06x}")]
    UnknownMessageType(u16),

    /// A field mandatory for the message type is missing.
    #[error("missing required field: {0}")]
    MissingField(&'static str),

    /// A field occurs more than once in the message.
    #[error("duplicate field: {0}")]
    DuplicateField(&'static str),

    /// The TLV value length does not match the length expected for this field.
    #[error("invalid length for {field}: expected {expected}, got {actual}")]
    InvalidFieldLength {
        /// Field name.
        field: &'static str,
        /// Expected length in bytes.
        expected: usize,
        /// Actual length in bytes.
        actual: usize,
    },

    /// The field value is outside its allowed set.
    #[error("invalid value for {field}: {value}")]
    InvalidFieldValue {
        /// Field name.
        field: &'static str,
        /// Received value.
        value: String,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::messages::{
        RawSimulcryptMessage,
        RawSimulcryptMessageError,
        emmg::{
            EMMG_MSG_CHANNEL_SETUP,
            EMMG_MSG_DATA_PROVISION,
            EMMG_MSG_STREAM_TEST,
            EMMG_VAR_CHANNEL_ID,
            EMMG_VAR_DATAGRAM,
            EMMG_VAR_SECTION_TS_PKT_FLAG,
            EMMG_VAR_STREAM_ID,
            EMMG_VAR_SUPER_CAS_ID,
        },
    };

    fn raw_message(message_type: u16, vars: Vec<(u16, Vec<u8>)>) -> RawSimulcryptMessage {
        let mut raw = RawSimulcryptMessage::new(message_type);
        for (tag, value) in vars {
            raw.add_var(tag, value);
        }

        raw
    }

    #[test]
    fn decode_channel_setup_success() {
        let raw = raw_message(
            EMMG_MSG_CHANNEL_SETUP,
            vec![
                (EMMG_VAR_SUPER_CAS_ID, 0x1122_3344u32.to_be_bytes().to_vec()),
                (EMMG_VAR_CHANNEL_ID, 0x0102u16.to_be_bytes().to_vec()),
                (EMMG_VAR_SECTION_TS_PKT_FLAG, vec![1]),
            ],
        );

        let decoded = EmmgMessage::try_from(raw).expect("channel setup should decode");
        match decoded {
            EmmgMessage::ChannelSetup(msg) => {
                assert_eq!(msg.super_cas_id, 0x1122_3344);
                assert_eq!(msg.channel_id, 0x0102);
                assert!(msg.section_ts_pkt_flag);
            }
            _ => panic!("expected ChannelSetup"),
        }
    }

    /// `DATA_PROVISION` carries no `data_id`/`data_type` - those are `STREAM_SETUP` fields, not
    /// `DATA_PROVISION` ones; the decoder must not require them.
    #[test]
    fn decode_data_provision_success() {
        let datagram = vec![0x47, 0x40, 0x11, 0x10, 0x00, 0xAA];
        let raw = raw_message(
            EMMG_MSG_DATA_PROVISION,
            vec![
                (EMMG_VAR_CHANNEL_ID, 0x0010u16.to_be_bytes().to_vec()),
                (EMMG_VAR_STREAM_ID, 0x0020u16.to_be_bytes().to_vec()),
                (EMMG_VAR_DATAGRAM, datagram.clone()),
            ],
        );

        let decoded = EmmgMessage::try_from(raw).expect("data provision should decode");
        match decoded {
            EmmgMessage::DataProvision(msg) => {
                assert_eq!(msg.channel_id, 0x0010);
                assert_eq!(msg.stream_id, 0x0020);
                assert_eq!(msg.data, datagram);
            }
            _ => panic!("expected DataProvision"),
        }
    }

    #[test]
    fn decode_unknown_message_type_fails() {
        let raw = raw_message(
            0x9999,
            vec![(EMMG_VAR_CHANNEL_ID, 0x0001u16.to_be_bytes().to_vec())],
        );
        let err = EmmgMessage::try_from(raw).expect_err("unknown message must fail");

        match err {
            EmmgMessageError::UnknownMessageType(value) => assert_eq!(value, 0x9999),
            _ => panic!("expected UnknownMessageType"),
        }
    }

    #[test]
    fn decode_missing_required_field_fails() {
        let raw = raw_message(
            EMMG_MSG_STREAM_TEST,
            vec![(EMMG_VAR_CHANNEL_ID, 0x0001u16.to_be_bytes().to_vec())],
        );
        let err = EmmgMessage::try_from(raw).expect_err("missing stream_id must fail");

        match err {
            EmmgMessageError::MissingField(field) => assert_eq!(field, "stream_id"),
            _ => panic!("expected MissingField(stream_id)"),
        }
    }

    #[test]
    fn decode_duplicate_stream_id_fails() {
        let raw = raw_message(
            EMMG_MSG_STREAM_TEST,
            vec![
                (EMMG_VAR_CHANNEL_ID, 0x0001u16.to_be_bytes().to_vec()),
                (EMMG_VAR_STREAM_ID, 0x0010u16.to_be_bytes().to_vec()),
                (EMMG_VAR_STREAM_ID, 0x0011u16.to_be_bytes().to_vec()),
            ],
        );
        let err = EmmgMessage::try_from(raw).expect_err("duplicate stream_id must fail");

        match err {
            EmmgMessageError::DuplicateField(field) => assert_eq!(field, "stream_id"),
            _ => panic!("expected DuplicateField(stream_id)"),
        }
    }

    #[test]
    fn parse_truncated_tlv_value_fails() {
        let bytes = [
            0x02, 0x00, 0x12, 0x00, 0x06, // header
            0x00, 0x03, 0x00, 0x04, // tlv: channel_id len=4
            0x00, 0x01, // only 2 bytes payload, truncated
        ];

        let err = RawSimulcryptMessage::unmarshal(&bytes).expect_err("broken tlv length must fail");

        match err {
            RawSimulcryptMessageError::TruncatedTlvValue => {}
            _ => panic!("expected TruncatedTlvValue"),
        }
    }
}