use std::time::Duration;
use broadcast_core::{Parse, Serialize};
use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationInfoEnq};
use dvb_ci::objects::ca_info::{CaInfo, CaInfoEnq};
use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
use dvb_ci::objects::date_time::{DateTime as CiDateTime, DateTimeEnq, UTC_TIME_LEN};
use dvb_ci::objects::host_control::{AskRelease, ClearReplace, Replace, Tune};
use dvb_ci::objects::mmi_display::{
DisplayControl, DisplayControlCmd, DisplayReply, DisplayReplyBody, DisplayReplyId, MmiMode,
};
use dvb_ci::objects::mmi_high::{Enq, List, Menu};
use dvb_ci::objects::resource_manager::{Profile, ProfileChange, ProfileEnq};
use dvb_ci::resource::{
APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, DATE_TIME, HOST_CONTROL, MMI,
RESOURCE_MANAGER, ResourceId,
};
use dvb_ci::tag::{self, ApduTag};
use crate::event::{HostControlEvent, MmiEvent, MmiMenu, Notification};
fn text(chars: &[u8]) -> String {
String::from_utf8_lossy(chars).into_owned()
}
fn to_menu(m: &Menu<'_>) -> MmiMenu {
MmiMenu {
title: text(m.title.text_chars),
subtitle: text(m.subtitle.text_chars),
bottom: text(m.bottom.text_chars),
choices: m.choices.iter().map(|c| text(c.text_chars)).collect(),
}
}
pub(crate) fn ser<S: Serialize<Error = dvb_ci::Error>>(s: &S) -> dvb_ci::Result<Vec<u8>> {
s.try_to_bytes()
}
pub(crate) fn peek_tag(apdu: &[u8]) -> Option<ApduTag> {
apdu.first_chunk::<APDU_TAG_LEN>()
.map(|&[a, b, c]| ApduTag::from_bytes(a, b, c))
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ResourceOut {
pub apdus: Vec<Vec<u8>>,
pub notify: Vec<Notification>,
pub open: Vec<ResourceId>,
}
pub trait Resource {
fn id(&self) -> ResourceId;
fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
Ok(ResourceOut::default())
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut>;
fn tick(&mut self, _elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
Ok(ResourceOut::default())
}
fn reset(&mut self) {}
}
#[derive(Debug)]
pub struct ResourceManager {
host_resources: Vec<ResourceId>,
module_resources: Vec<ResourceId>,
module_profiled: bool,
ready: bool,
}
impl ResourceManager {
#[must_use]
pub fn new(host_resources: Vec<ResourceId>) -> Self {
Self {
host_resources,
module_resources: Vec::new(),
module_profiled: false,
ready: false,
}
}
#[must_use]
pub fn module_resources(&self) -> &[ResourceId] {
&self.module_resources
}
}
impl Resource for ResourceManager {
fn id(&self) -> ResourceId {
RESOURCE_MANAGER
}
fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
Ok(ResourceOut {
apdus: vec![ser(&ProfileEnq::default())?],
..ResourceOut::default()
})
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
match peek_tag(apdu) {
Some(t) if t == tag::PROFILE_ENQ => {
out.apdus.push(ser(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: self.host_resources.clone(),
})?);
}
Some(t) if t == tag::PROFILE => {
let p = Profile::parse(apdu)?;
self.module_resources = p.resources;
self.module_profiled = true;
}
Some(t) if t == tag::PROFILE_CHANGE => {
out.apdus.push(ser(&ProfileEnq::default())?);
self.module_profiled = false;
self.ready = false;
}
_ => {}
}
if self.module_profiled && !self.ready {
self.ready = true;
out.apdus.push(ser(&ProfileChange::default())?);
out.notify.push(Notification::CamReady);
}
Ok(out)
}
fn reset(&mut self) {
self.module_resources.clear();
self.module_profiled = false;
self.ready = false;
}
}
#[derive(Debug, Default)]
pub struct ApplicationInformation;
impl Resource for ApplicationInformation {
fn id(&self) -> ResourceId {
APPLICATION_INFORMATION
}
fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
Ok(ResourceOut {
apdus: vec![ser(&ApplicationInfoEnq::default())?],
..ResourceOut::default()
})
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
if peek_tag(apdu) == Some(tag::APPLICATION_INFO) {
let ai = ApplicationInfo::parse(apdu)?;
out.notify.push(Notification::ApplicationInfo {
application_type: ai.application_type.to_u8(),
manufacturer: ai.application_manufacturer,
code: ai.manufacturer_code,
menu: String::from_utf8_lossy(ai.menu_string).into_owned(),
});
}
Ok(out)
}
}
#[derive(Debug, Default)]
pub struct ConditionalAccess;
impl Resource for ConditionalAccess {
fn id(&self) -> ResourceId {
CONDITIONAL_ACCESS_SUPPORT
}
fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
Ok(ResourceOut {
apdus: vec![ser(&CaInfoEnq::default())?],
..ResourceOut::default()
})
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
match peek_tag(apdu) {
Some(t) if t == tag::CA_INFO => {
let ci = CaInfo::parse(apdu)?;
out.notify.push(Notification::CaInfo {
ca_system_ids: ci.ca_system_ids,
});
}
Some(t) if t == tag::CA_PMT_REPLY => {
let r = CaPmtReply::parse(apdu)?;
let descrambling_ok = matches!(
r.ca_enable,
Some(
CaEnable::Possible
| CaEnable::PossiblePurchaseDialogue
| CaEnable::PossibleTechnicalDialogue
)
);
out.notify.push(Notification::CaPmtReply {
program_number: r.program_number,
ca_enable: r.ca_enable,
descrambling_ok,
});
}
_ => {}
}
Ok(out)
}
}
fn unix_to_mjd_bcd(unix_secs: u64) -> Option<[u8; UTC_TIME_LEN]> {
let secs = i64::try_from(unix_secs).ok()?;
broadcast_common::time::encode_mjd_bcd_utc(jiff::Timestamp::from_second(secs).ok()?)
}
fn system_utc() -> Option<[u8; UTC_TIME_LEN]> {
let now = std::time::SystemTime::now();
now.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|d| unix_to_mjd_bcd(d.as_secs()))
}
pub struct DateTime {
clock: fn() -> Option<[u8; UTC_TIME_LEN]>,
interval: u8,
since: Duration,
}
impl Default for DateTime {
fn default() -> Self {
Self::new()
}
}
impl DateTime {
#[must_use]
pub fn new() -> Self {
Self {
clock: system_utc,
interval: 0,
since: Duration::ZERO,
}
}
#[must_use]
pub fn with_clock(clock: fn() -> Option<[u8; UTC_TIME_LEN]>) -> Self {
Self {
clock,
interval: 0,
since: Duration::ZERO,
}
}
fn reply(&self) -> Option<dvb_ci::Result<Vec<u8>>> {
let utc_time = (self.clock)()?;
Some(ser(&CiDateTime {
length_form: dvb_ci::length::LengthForm::Minimal,
utc_time,
local_offset: None,
}))
}
}
impl Resource for DateTime {
fn id(&self) -> ResourceId {
DATE_TIME
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
if peek_tag(apdu) == Some(tag::DATE_TIME_ENQ) {
let enq = DateTimeEnq::parse(apdu)?;
self.interval = enq.response_interval;
self.since = Duration::ZERO;
match self.reply() {
Some(reply) => out.apdus.push(reply?),
None => out.notify.push(Notification::ClockUnrepresentable),
}
}
Ok(out)
}
fn tick(&mut self, elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
let mut out = ResourceOut::default();
if self.interval > 0 {
self.since += elapsed;
if self.since >= Duration::from_secs(u64::from(self.interval)) {
self.since = Duration::ZERO;
match self.reply() {
Some(reply) => out.apdus.push(reply?),
None => out.notify.push(Notification::ClockUnrepresentable),
}
}
}
Ok(out)
}
fn reset(&mut self) {
self.interval = 0;
self.since = Duration::ZERO;
}
}
#[derive(Debug, Default)]
pub struct Mmi {
chain: Option<MmiChain>,
}
pub const MAX_MMI_CHAIN_LEN: usize = 0xFFFF;
pub(crate) const APDU_TAG_LEN: usize = 3;
#[derive(Debug)]
struct MmiChain {
last: ApduTag,
body: Vec<u8>,
}
impl Mmi {
fn chain_more(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<()> {
let tail = apdu
.get(APDU_TAG_LEN..)
.ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
let (len, hdr) = dvb_ci::length::decode(tail)?;
let start = APDU_TAG_LEN + hdr;
let data = apdu
.get(start..start + len)
.ok_or(dvb_ci::Error::LengthTooLarge(len))?;
let mut chain = match self.chain.take() {
Some(c) if c.last == last => c,
_ => MmiChain {
last,
body: Vec::new(),
},
};
if chain.body.len() + data.len() > MAX_MMI_CHAIN_LEN {
return Err(dvb_ci::Error::LengthTooLarge(chain.body.len() + data.len()));
}
chain.body.extend_from_slice(data);
self.chain = Some(chain);
Ok(())
}
fn complete(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<Vec<u8>> {
let Some(chain) = self.chain.take().filter(|c| c.last == last) else {
return Ok(apdu.to_vec());
};
let tail = apdu
.get(APDU_TAG_LEN..)
.ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
let (len, hdr) = dvb_ci::length::decode(tail)?;
let start = APDU_TAG_LEN + hdr;
let data = apdu
.get(start..start + len)
.ok_or(dvb_ci::Error::LengthTooLarge(len))?;
let total = chain.body.len() + data.len();
let mut buf = vec![0u8; APDU_TAG_LEN + dvb_ci::length::encoded_len(total) + total];
buf[..APDU_TAG_LEN].copy_from_slice(&last.to_bytes());
let n = dvb_ci::length::encode_into(total, &mut buf[APDU_TAG_LEN..])?;
let body_at = APDU_TAG_LEN + n;
buf[body_at..body_at + chain.body.len()].copy_from_slice(&chain.body);
buf[body_at + chain.body.len()..].copy_from_slice(data);
Ok(buf)
}
}
impl Resource for Mmi {
fn id(&self) -> ResourceId {
MMI
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
match peek_tag(apdu) {
Some(t) if t == tag::ENQ => {
let e = Enq::parse(apdu)?;
out.notify.push(Notification::Mmi(MmiEvent::Enquiry {
prompt: text(e.text_chars),
blind: e.blind_answer,
answer_len: e.answer_text_length,
}));
}
Some(t) if t == tag::MENU_MORE => self.chain_more(apdu, tag::MENU_LAST)?,
Some(t) if t == tag::LIST_MORE => self.chain_more(apdu, tag::LIST_LAST)?,
Some(t) if t == tag::MENU_LAST => {
let full = self.complete(apdu, tag::MENU_LAST)?;
let m = Menu::parse(&full)?;
out.notify
.push(Notification::Mmi(MmiEvent::Menu(to_menu(&m))));
}
Some(t) if t == tag::LIST_LAST => {
let full = self.complete(apdu, tag::LIST_LAST)?;
let l = List::parse(&full)?;
out.notify
.push(Notification::Mmi(MmiEvent::List(to_menu(&l.0))));
}
Some(t) if t == tag::CLOSE_MMI => {
dvb_ci::objects::mmi_close::CloseMmi::parse(apdu)?;
out.notify.push(Notification::Mmi(MmiEvent::Close));
}
Some(t) if t == tag::DISPLAY_CONTROL => {
let dc = DisplayControl::parse(apdu)?;
let reply = match dc.cmd {
DisplayControlCmd::SetMmiMode => DisplayReply {
length_form: dvb_ci::length::LengthForm::Minimal,
reply_id: DisplayReplyId::MmiModeAck,
body: DisplayReplyBody::MmiModeAck(
dc.mmi_mode.unwrap_or(MmiMode::HighLevel),
),
},
_ => DisplayReply {
length_form: dvb_ci::length::LengthForm::Minimal,
reply_id: DisplayReplyId::UnknownDisplayControlCmd,
body: DisplayReplyBody::None,
},
};
out.apdus.push(ser(&reply)?);
}
_ => {}
}
Ok(out)
}
fn reset(&mut self) {
self.chain = None;
}
}
#[derive(Debug, Default)]
pub struct HostControl;
impl Resource for HostControl {
fn id(&self) -> ResourceId {
HOST_CONTROL
}
fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
if apdu.len() < APDU_TAG_LEN {
return Err(dvb_ci::Error::InvalidLength("short APDU"));
}
let mut out = ResourceOut::default();
let event = match peek_tag(apdu) {
Some(t) if t == tag::TUNE => {
let t = Tune::parse(apdu)?;
Some(HostControlEvent::Tune {
network_id: t.network_id,
original_network_id: t.original_network_id,
transport_stream_id: t.transport_stream_id,
service_id: t.service_id,
})
}
Some(t) if t == tag::REPLACE => {
let r = Replace::parse(apdu)?;
Some(HostControlEvent::Replace {
replacement_ref: r.replacement_ref,
replaced_pid: r.replaced_pid,
replacement_pid: r.replacement_pid,
})
}
Some(t) if t == tag::CLEAR_REPLACE => {
let c = ClearReplace::parse(apdu)?;
Some(HostControlEvent::ClearReplace {
replacement_ref: c.replacement_ref,
})
}
Some(t) if t == tag::ASK_RELEASE => {
AskRelease::parse(apdu)?;
Some(HostControlEvent::AskRelease)
}
_ => None,
};
if let Some(event) = event {
out.notify.push(Notification::HostControl(event));
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dvb_ci::objects::resource_manager::Profile;
use mpeg_ts::pid::Pid;
fn s<S: Serialize<Error = dvb_ci::Error>>(v: &S) -> Vec<u8> {
ser(v).expect("test value must serialize")
}
#[test]
fn on_open_sends_profile_enq() {
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
let out = rm.on_open().unwrap();
assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
}
#[test]
fn module_profile_triggers_profile_change_and_camready() {
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
rm.on_open().unwrap();
let empty_profile = s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![],
});
let o = rm.on_apdu(&empty_profile).unwrap();
assert!(o.notify.contains(&Notification::CamReady));
assert_eq!(o.apdus.len(), 1, "host sends profile_change");
assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE_CHANGE));
assert!(o.open.is_empty(), "host opens no sessions itself");
}
#[test]
fn answers_a_module_profile_enquiry_without_re_readying() {
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
rm.on_open().unwrap();
rm.on_apdu(&s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![APPLICATION_INFORMATION],
}))
.unwrap();
let o = rm.on_apdu(&s(&ProfileEnq::default())).unwrap();
assert_eq!(o.apdus.len(), 1);
assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE));
assert!(!o.notify.contains(&Notification::CamReady));
}
#[test]
fn resource_manager_reset_clears_latched_handshake_state() {
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
rm.on_open().unwrap();
let o = rm
.on_apdu(&s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![APPLICATION_INFORMATION],
}))
.unwrap();
assert!(o.notify.contains(&Notification::CamReady), "dirtied: ready");
assert!(
!rm.module_resources().is_empty(),
"dirtied: module_resources"
);
rm.reset();
assert!(
rm.module_resources().is_empty(),
"reset must clear module_resources"
);
rm.on_open().unwrap();
let o2 = rm
.on_apdu(&s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![],
}))
.unwrap();
assert!(
o2.notify.contains(&Notification::CamReady),
"a fresh handshake after reset() must fire CamReady again"
);
}
#[test]
fn mmi_surfaces_enquiry_and_close() {
let mut h = Mmi::default();
let enq = s(&Enq {
reserved: Default::default(),
length_form: dvb_ci::length::LengthForm::Minimal,
blind_answer: true,
answer_text_length: 4,
text_chars: b"PIN?",
});
assert_eq!(
h.on_apdu(&enq).unwrap().notify,
vec![Notification::Mmi(MmiEvent::Enquiry {
prompt: "PIN?".to_string(),
blind: true,
answer_len: 4,
})]
);
let close = [0x9F, 0x88, 0x00, 0x01, 0x00];
assert_eq!(
h.on_apdu(&close).unwrap().notify,
vec![Notification::Mmi(MmiEvent::Close)]
);
}
#[test]
fn mmi_surfaces_structured_menu_and_list() {
use dvb_ci::objects::mmi_high::{List, Menu, Text};
let txt = |s: &'static [u8]| Text {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
text_chars: s,
};
let mut h = Mmi::default();
let menu = s(&Menu {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
choice_nb: 2,
title: txt(b"AlphaCrypt"),
subtitle: txt(b"Module Mainmenu"),
bottom: txt(b"Select item and press OK"),
choices: vec![txt(b"Smartcard"), txt(b"Quit")],
});
assert_eq!(
h.on_apdu(&menu).unwrap().notify,
vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
title: "AlphaCrypt".to_string(),
subtitle: "Module Mainmenu".to_string(),
bottom: "Select item and press OK".to_string(),
choices: vec!["Smartcard".to_string(), "Quit".to_string()],
}))]
);
let list = s(&List(Menu {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
choice_nb: 0xFF,
title: txt(b"Entitlements"),
subtitle: txt(b""),
bottom: txt(b""),
choices: vec![txt(b"ORF AUT")],
}));
assert_eq!(
h.on_apdu(&list).unwrap().notify,
vec![Notification::Mmi(MmiEvent::List(MmiMenu {
title: "Entitlements".to_string(),
subtitle: String::new(),
bottom: String::new(),
choices: vec!["ORF AUT".to_string()],
}))]
);
}
fn chained(more: ApduTag, last: ApduTag, whole_last_apdu: &[u8], split: usize) -> [Vec<u8>; 2] {
let (len, hdr) = dvb_ci::length::decode(&whole_last_apdu[3..]).unwrap();
let body = &whole_last_apdu[3 + hdr..3 + hdr + len];
let part = |t: ApduTag, b: &[u8]| {
let mut v = t.to_bytes().to_vec();
let mut l = [0u8; 3];
let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
v.extend_from_slice(&l[..n]);
v.extend_from_slice(b);
v
};
[part(more, &body[..split]), part(last, &body[split..])]
}
#[test]
fn mmi_reassembles_a_menu_chained_over_menu_more_and_menu_last() {
use dvb_ci::objects::mmi_high::{Menu, Text};
let txt = |s: &'static [u8]| Text {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
text_chars: s,
};
let whole = s(&Menu {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
choice_nb: 2,
title: txt(b"AlphaCrypt"),
subtitle: txt(b"Module Mainmenu"),
bottom: txt(b"Select item and press OK"),
choices: vec![txt(b"Smartcard"), txt(b"Quit")],
});
let [first, second] = chained(tag::MENU_MORE, tag::MENU_LAST, &whole, 20);
let mut h = Mmi::default();
assert!(h.on_apdu(&first).unwrap().notify.is_empty());
assert_eq!(
h.on_apdu(&second).unwrap().notify,
vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
title: "AlphaCrypt".to_string(),
subtitle: "Module Mainmenu".to_string(),
bottom: "Select item and press OK".to_string(),
choices: vec!["Smartcard".to_string(), "Quit".to_string()],
}))]
);
}
#[test]
fn mmi_reassembles_a_list_chained_over_list_more_and_list_last() {
use dvb_ci::objects::mmi_high::{List, Menu, Text};
let txt = |s: &'static [u8]| Text {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
text_chars: s,
};
let whole = s(&List(Menu {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
choice_nb: 2,
title: txt(b"Entitlements"),
subtitle: txt(b""),
bottom: txt(b""),
choices: vec![txt(b"ORF AUT"), txt(b"ZDF")],
}));
let [first, second] = chained(tag::LIST_MORE, tag::LIST_LAST, &whole, 9);
let mut h = Mmi::default();
assert!(h.on_apdu(&first).unwrap().notify.is_empty());
assert_eq!(
h.on_apdu(&second).unwrap().notify,
vec![Notification::Mmi(MmiEvent::List(MmiMenu {
title: "Entitlements".to_string(),
subtitle: String::new(),
bottom: String::new(),
choices: vec!["ORF AUT".to_string(), "ZDF".to_string()],
}))]
);
}
#[test]
fn mmi_chain_past_the_cap_is_refused_with_length_too_large() {
fn menu_more(data_len: usize) -> Vec<u8> {
let mut apdu = tag::MENU_MORE.to_bytes().to_vec();
let mut len = [0u8; 3];
let coded = dvb_ci::length::encode_into(data_len, &mut len).unwrap();
apdu.extend_from_slice(&len[..coded]);
apdu.extend(std::iter::repeat_n(0x00, data_len));
apdu
}
let mut h = Mmi::default();
assert!(
h.on_apdu(&menu_more(MAX_MMI_CHAIN_LEN))
.unwrap()
.notify
.is_empty(),
"a chain exactly at the cap is still accepted"
);
let err = h
.on_apdu(&menu_more(1))
.expect_err("one byte past the chain cap must be refused");
assert_eq!(err, dvb_ci::Error::LengthTooLarge(MAX_MMI_CHAIN_LEN + 1));
}
#[test]
fn mmi_discards_a_partial_chain_on_reset() {
let mut h = Mmi::default();
let first = [0x9F, 0x88, 0x0A, 0x01, 0x02];
assert!(h.on_apdu(&first).unwrap().notify.is_empty());
h.reset();
assert!(h.chain.is_none());
}
#[test]
fn mmi_keeps_interleaved_chains_apart() {
use dvb_ci::objects::mmi_high::{List, Menu, Text};
let txt = |s: &'static [u8]| Text {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
text_chars: s,
};
let part = |t: ApduTag, b: &[u8]| {
let mut v = t.to_bytes().to_vec();
let mut l = [0u8; 3];
let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
v.extend_from_slice(&l[..n]);
v.extend_from_slice(b);
v
};
let whole = s(&List(Menu {
length_form: dvb_ci::length::LengthForm::Minimal,
more: false,
choice_nb: 1,
title: txt(b"Entitlements"),
subtitle: txt(b""),
bottom: txt(b""),
choices: vec![txt(b"ORF AUT")],
}));
let (len, hdr) = dvb_ci::length::decode(&whole[3..]).unwrap();
let body = &whole[3 + hdr..3 + hdr + len];
let mut h = Mmi::default();
assert!(
h.on_apdu(&part(tag::MENU_MORE, &[0xFF, 0xFF]))
.unwrap()
.notify
.is_empty()
);
assert!(
h.on_apdu(&part(tag::LIST_MORE, body))
.unwrap()
.notify
.is_empty()
);
assert_eq!(
h.on_apdu(&part(tag::LIST_LAST, &[])).unwrap().notify,
vec![Notification::Mmi(MmiEvent::List(MmiMenu {
title: "Entitlements".to_string(),
subtitle: String::new(),
bottom: String::new(),
choices: vec!["ORF AUT".to_string()],
}))],
"the abandoned menu chunk must not be part of the list body"
);
assert!(h.chain.is_none());
}
#[test]
fn mmi_answers_display_control_set_mmi_mode() {
use dvb_ci::objects::mmi_display::{DisplayControl, DisplayControlCmd, MmiMode};
let mut h = Mmi::default();
let dc = s(&DisplayControl {
length_form: dvb_ci::length::LengthForm::Minimal,
cmd: DisplayControlCmd::SetMmiMode,
mmi_mode: Some(MmiMode::HighLevel),
});
let out = h.on_apdu(&dc).unwrap();
assert_eq!(out.apdus, vec![vec![0x9F, 0x88, 0x02, 0x02, 0x01, 0x01]]);
assert!(out.notify.is_empty());
}
#[test]
fn profile_change_re_enquires() {
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
let out = rm
.on_apdu(&s(
&dvb_ci::objects::resource_manager::ProfileChange::default(),
))
.unwrap();
assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
}
#[test]
fn resource_manager_does_not_treat_an_unrelated_apdu_as_profile_change() {
use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationType};
let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
rm.on_open().unwrap();
rm.on_apdu(&s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![APPLICATION_INFORMATION],
}))
.unwrap();
let unrelated = s(&ApplicationInfo {
length_form: dvb_ci::length::LengthForm::Minimal,
application_type: ApplicationType::ConditionalAccess,
application_manufacturer: 0x1234,
manufacturer_code: 0x5678,
menu_string: b"Acme CAM",
});
assert_eq!(rm.on_apdu(&unrelated).unwrap(), ResourceOut::default());
assert_eq!(rm.module_resources(), &[APPLICATION_INFORMATION]);
let again = rm
.on_apdu(&s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![],
}))
.unwrap();
assert!(
!again.notify.contains(&Notification::CamReady),
"an unrelated APDU must not clear the ready/profile latch"
);
}
#[test]
fn conditional_access_ignores_an_unrelated_apdu() {
let mut h = ConditionalAccess;
let profile = s(&Profile {
length_form: dvb_ci::length::LengthForm::Minimal,
resources: vec![],
});
assert_eq!(h.on_apdu(&profile).unwrap(), ResourceOut::default());
}
#[test]
fn mmi_ignores_an_unrelated_apdu() {
let mut h = Mmi::default();
assert_eq!(
h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
ResourceOut::default()
);
assert!(h.chain.is_none());
}
#[test]
fn host_control_ignores_an_unrelated_apdu() {
let mut h = HostControl;
assert_eq!(
h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
ResourceOut::default()
);
}
#[test]
fn application_information_surfaces_notification() {
use dvb_ci::objects::application_info::ApplicationType;
let mut h = ApplicationInformation;
assert_eq!(
h.on_open().unwrap().apdus,
vec![s(&ApplicationInfoEnq::default())]
);
let ai = s(&ApplicationInfo {
length_form: dvb_ci::length::LengthForm::Minimal,
application_type: ApplicationType::ConditionalAccess,
application_manufacturer: 0x1234,
manufacturer_code: 0x5678,
menu_string: b"Acme CAM",
});
let out = h.on_apdu(&ai).unwrap();
assert_eq!(
out.notify,
vec![Notification::ApplicationInfo {
application_type: 0x01,
manufacturer: 0x1234,
code: 0x5678,
menu: "Acme CAM".to_string(),
}]
);
}
#[test]
fn host_control_surfaces_tune_replace_clear_and_ask_release() {
let mut h = HostControl;
assert_eq!(h.id(), HOST_CONTROL);
let tune = s(&Tune {
length_form: dvb_ci::length::LengthForm::Minimal,
network_id: 0x1122,
original_network_id: 0x3344,
transport_stream_id: 0x5566,
service_id: 0x7788,
});
assert_eq!(
h.on_apdu(&tune).unwrap().notify,
vec![Notification::HostControl(HostControlEvent::Tune {
network_id: 0x1122,
original_network_id: 0x3344,
transport_stream_id: 0x5566,
service_id: 0x7788,
})]
);
let replace = s(&Replace {
length_form: dvb_ci::length::LengthForm::Minimal,
replacement_ref: 0x07,
replaced_pid: Pid::from_const(0x0123),
replacement_pid: Pid::from_const(0x01FF),
replaced_reserved: Default::default(),
replacement_reserved: Default::default(),
});
assert_eq!(
h.on_apdu(&replace).unwrap().notify,
vec![Notification::HostControl(HostControlEvent::Replace {
replacement_ref: 0x07,
replaced_pid: Pid::from_const(0x0123),
replacement_pid: Pid::from_const(0x01FF),
})]
);
let clear = s(&ClearReplace {
length_form: dvb_ci::length::LengthForm::Minimal,
replacement_ref: 0x42,
});
assert_eq!(
h.on_apdu(&clear).unwrap().notify,
vec![Notification::HostControl(HostControlEvent::ClearReplace {
replacement_ref: 0x42,
})]
);
let ask = s(&AskRelease::default());
assert_eq!(
h.on_apdu(&ask).unwrap().notify,
vec![Notification::HostControl(HostControlEvent::AskRelease)]
);
assert!(h.on_apdu(&tune).unwrap().apdus.is_empty());
}
#[test]
fn mjd_bcd_encoding_is_correct() {
const SECS_PER_DAY: u64 = 86_400;
assert_eq!(unix_to_mjd_bcd(0), Some([0x9E, 0x8B, 0x00, 0x00, 0x00]));
let secs = SECS_PER_DAY + 13 * 3600 + 45 * 60 + 9;
assert_eq!(unix_to_mjd_bcd(secs), Some([0x9E, 0x8C, 0x13, 0x45, 0x09]));
}
#[test]
fn mjd_bcd_encoding_matches_day_arithmetic_across_the_range() {
const SECS_PER_DAY: u64 = 86_400;
const MJD_UNIX_EPOCH: u64 = 40_587;
const LAST_DAY: u64 = 65_535 - MJD_UNIX_EPOCH;
for day in (0..=LAST_DAY).step_by(37).chain([LAST_DAY]) {
let out = unix_to_mjd_bcd(day * SECS_PER_DAY + 86_399).unwrap();
let mjd = u16::from_be_bytes([out[0], out[1]]);
assert_eq!(u64::from(mjd), MJD_UNIX_EPOCH + day);
assert_eq!(out[2..], [0x23, 0x59, 0x59]);
}
}
#[test]
fn mjd_beyond_its_sixteen_bits_is_refused_not_wrapped() {
assert_eq!(
unix_to_mjd_bcd(2_155_507_200 + 86_399),
Some([0xFF, 0xFF, 0x23, 0x59, 0x59])
);
assert_eq!(unix_to_mjd_bcd(5_417_971_200), None);
}
#[test]
fn date_time_reports_an_unrepresentable_clock_instead_of_a_wrong_date() {
let mut h = DateTime::with_clock(|| None);
let out = h
.on_apdu(&s(&DateTimeEnq {
length_form: dvb_ci::length::LengthForm::Minimal,
response_interval: 0,
}))
.unwrap();
assert!(out.apdus.is_empty());
assert_eq!(out.notify, vec![Notification::ClockUnrepresentable]);
}
#[test]
fn system_clock_is_representable_today() {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
assert_eq!(system_utc(), unix_to_mjd_bcd(now));
assert!(system_utc().is_some());
}
#[test]
fn date_time_replies_to_enq_and_resends_on_interval() {
let fixed = || Some([0x9E, 0x7B, 0x00, 0x00, 0x00]);
let mut h = DateTime::with_clock(fixed);
let enq = s(&DateTimeEnq {
length_form: dvb_ci::length::LengthForm::Minimal,
response_interval: 5,
});
let out = h.on_apdu(&enq).unwrap();
assert_eq!(out.apdus.len(), 1);
assert_eq!(peek_tag(&out.apdus[0]), Some(tag::DATE_TIME));
assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
assert_eq!(h.tick(Duration::from_secs(3)).unwrap().apdus.len(), 1);
}
#[test]
fn date_time_interval_zero_does_not_resend() {
let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
h.on_apdu(&s(&DateTimeEnq {
length_form: dvb_ci::length::LengthForm::Minimal,
response_interval: 0,
}))
.unwrap();
assert!(h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty());
}
#[test]
fn date_time_reset_clears_interval_and_resend_timer() {
let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
h.on_apdu(&s(&DateTimeEnq {
length_form: dvb_ci::length::LengthForm::Minimal,
response_interval: 5,
}))
.unwrap();
assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
h.reset();
assert!(
h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty(),
"reset must clear the resend cadence from the previous module"
);
}
#[test]
fn conditional_access_surfaces_ca_info_and_pmt_reply() {
let mut h = ConditionalAccess;
assert_eq!(h.on_open().unwrap().apdus, vec![s(&CaInfoEnq::default())]);
let ci = s(&CaInfo {
length_form: dvb_ci::length::LengthForm::Minimal,
ca_system_ids: vec![0x0B00, 0x1800],
});
assert_eq!(
h.on_apdu(&ci).unwrap().notify,
vec![Notification::CaInfo {
ca_system_ids: vec![0x0B00, 0x1800],
}]
);
let reply = s(&CaPmtReply {
reserved_ca_enable: Default::default(),
reserved_version: Default::default(),
length_form: dvb_ci::length::LengthForm::Minimal,
program_number: 0x0042,
version_number: 0,
current_next_indicator: true,
ca_enable: Some(CaEnable::Possible),
streams: vec![],
});
assert_eq!(
h.on_apdu(&reply).unwrap().notify,
vec![Notification::CaPmtReply {
program_number: 0x0042,
ca_enable: Some(CaEnable::Possible),
descrambling_ok: true,
}]
);
}
#[test]
fn conditional_access_ca_pmt_reply_flag_clear_surfaces_none() {
let mut h = ConditionalAccess;
h.on_open().unwrap();
let reply = s(&CaPmtReply {
reserved_ca_enable: Default::default(),
reserved_version: Default::default(),
length_form: dvb_ci::length::LengthForm::Minimal,
program_number: 0x0007,
version_number: 0,
current_next_indicator: true,
ca_enable: None,
streams: vec![],
});
assert_eq!(
h.on_apdu(&reply).unwrap().notify,
vec![Notification::CaPmtReply {
program_number: 0x0007,
ca_enable: None,
descrambling_ok: false,
}]
);
}
#[test]
fn short_apdu_returns_err() {
for len in 0..3usize {
let buf = vec![0u8; len];
assert!(Mmi::default().on_apdu(&buf).is_err(), "Mmi len {len}");
assert!(
ResourceManager::new(vec![]).on_apdu(&buf).is_err(),
"RM len {len}"
);
assert!(
ApplicationInformation.on_apdu(&buf).is_err(),
"AI len {len}"
);
assert!(ConditionalAccess.on_apdu(&buf).is_err(), "CA len {len}");
assert!(DateTime::default().on_apdu(&buf).is_err(), "DT len {len}");
assert!(HostControl.on_apdu(&buf).is_err(), "HC len {len}");
}
}
#[test]
fn a_tag_only_apdu_is_accepted_by_every_resource() {
let out = ResourceManager::new(vec![RESOURCE_MANAGER])
.on_apdu(&tag::PROFILE_ENQ.to_bytes())
.unwrap();
assert_eq!(out.apdus.len(), 1, "profile_enq is answered");
assert_eq!(peek_tag(&out.apdus[0]), Some(tag::PROFILE));
assert_eq!(
ApplicationInformation
.on_apdu(&tag::CA_INFO.to_bytes())
.unwrap(),
ResourceOut::default(),
"an unrelated tag-only APDU is ignored, not an error"
);
assert_eq!(
ConditionalAccess
.on_apdu(&tag::APPLICATION_INFO.to_bytes())
.unwrap(),
ResourceOut::default()
);
assert_eq!(
DateTime::default()
.on_apdu(&tag::PROFILE_ENQ.to_bytes())
.unwrap(),
ResourceOut::default()
);
assert_eq!(
Mmi::default().on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
ResourceOut::default()
);
assert_eq!(
HostControl.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
ResourceOut::default()
);
}
}