1use std::time::Duration;
11
12use broadcast_common::{Parse, Serialize};
13use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationInfoEnq};
14use dvb_ci::objects::ca_info::{CaInfo, CaInfoEnq};
15use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
16use dvb_ci::objects::date_time::{DateTime as CiDateTime, DateTimeEnq, UTC_TIME_LEN};
17use dvb_ci::objects::host_control::{AskRelease, ClearReplace, Replace, Tune};
18use dvb_ci::objects::mmi_display::{
19 DisplayControl, DisplayControlCmd, DisplayReply, DisplayReplyBody, DisplayReplyId, MmiMode,
20};
21use dvb_ci::objects::mmi_high::{Enq, List, Menu};
22use dvb_ci::objects::resource_manager::{Profile, ProfileChange, ProfileEnq};
23use dvb_ci::resource::{
24 APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, DATE_TIME, HOST_CONTROL, MMI,
25 RESOURCE_MANAGER, ResourceId,
26};
27use dvb_ci::tag::{self, ApduTag};
28
29use crate::event::{HostControlEvent, MmiEvent, MmiMenu, Notification};
30
31fn text(chars: &[u8]) -> String {
34 String::from_utf8_lossy(chars).into_owned()
35}
36
37fn to_menu(m: &Menu<'_>) -> MmiMenu {
41 MmiMenu {
42 title: text(m.title.text_chars),
43 subtitle: text(m.subtitle.text_chars),
44 bottom: text(m.bottom.text_chars),
45 choices: m.choices.iter().map(|c| text(c.text_chars)).collect(),
46 }
47}
48
49pub(crate) fn ser<S: Serialize<Error = dvb_ci::Error>>(s: &S) -> dvb_ci::Result<Vec<u8>> {
59 s.try_to_bytes()
60}
61
62pub(crate) fn peek_tag(apdu: &[u8]) -> Option<ApduTag> {
64 (apdu.len() >= 3).then(|| ApduTag::from_bytes(apdu[0], apdu[1], apdu[2]))
65}
66
67#[derive(Debug, Default, Clone, PartialEq, Eq)]
69pub struct ResourceOut {
70 pub apdus: Vec<Vec<u8>>,
72 pub notify: Vec<Notification>,
74 pub open: Vec<ResourceId>,
76}
77
78pub trait Resource {
80 fn id(&self) -> ResourceId;
82 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
84 Ok(ResourceOut::default())
85 }
86 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut>;
88 fn tick(&mut self, _elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
90 Ok(ResourceOut::default())
91 }
92 fn reset(&mut self) {}
101}
102
103#[derive(Debug)]
107pub struct ResourceManager {
108 host_resources: Vec<ResourceId>,
109 module_resources: Vec<ResourceId>,
110 module_profiled: bool,
111 ready: bool,
112}
113
114impl ResourceManager {
115 #[must_use]
117 pub fn new(host_resources: Vec<ResourceId>) -> Self {
118 Self {
119 host_resources,
120 module_resources: Vec::new(),
121 module_profiled: false,
122 ready: false,
123 }
124 }
125
126 #[must_use]
128 pub fn module_resources(&self) -> &[ResourceId] {
129 &self.module_resources
130 }
131}
132
133impl Resource for ResourceManager {
134 fn id(&self) -> ResourceId {
135 RESOURCE_MANAGER
136 }
137
138 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
139 Ok(ResourceOut {
141 apdus: vec![ser(&ProfileEnq::default())?],
142 ..ResourceOut::default()
143 })
144 }
145
146 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
147 if apdu.len() < APDU_TAG_LEN {
148 return Err(dvb_ci::Error::InvalidLength("short APDU"));
149 }
150 let mut out = ResourceOut::default();
151 match peek_tag(apdu) {
152 Some(t) if t == tag::PROFILE_ENQ => {
154 out.apdus.push(ser(&Profile {
155 length_form: dvb_ci::length::LengthForm::Minimal,
156 resources: self.host_resources.clone(),
157 })?);
158 }
159 Some(t) if t == tag::PROFILE => {
161 let p = Profile::parse(apdu)?;
164 self.module_resources = p.resources;
165 self.module_profiled = true;
166 }
167 Some(t) if t == tag::PROFILE_CHANGE => {
169 out.apdus.push(ser(&ProfileEnq::default())?);
170 self.module_profiled = false;
171 self.ready = false;
172 }
173 _ => {}
174 }
175 if self.module_profiled && !self.ready {
189 self.ready = true;
190 out.apdus.push(ser(&ProfileChange::default())?);
191 out.notify.push(Notification::CamReady);
192 }
193 Ok(out)
194 }
195
196 fn reset(&mut self) {
202 self.module_resources.clear();
203 self.module_profiled = false;
204 self.ready = false;
205 }
206}
207
208#[derive(Debug, Default)]
211pub struct ApplicationInformation;
212
213impl Resource for ApplicationInformation {
214 fn id(&self) -> ResourceId {
215 APPLICATION_INFORMATION
216 }
217
218 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
219 Ok(ResourceOut {
220 apdus: vec![ser(&ApplicationInfoEnq::default())?],
221 ..ResourceOut::default()
222 })
223 }
224
225 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
226 if apdu.len() < APDU_TAG_LEN {
227 return Err(dvb_ci::Error::InvalidLength("short APDU"));
228 }
229 let mut out = ResourceOut::default();
230 if peek_tag(apdu) == Some(tag::APPLICATION_INFO) {
231 let ai = ApplicationInfo::parse(apdu)?;
232 out.notify.push(Notification::ApplicationInfo {
233 application_type: ai.application_type.to_u8(),
234 manufacturer: ai.application_manufacturer,
235 code: ai.manufacturer_code,
236 menu: String::from_utf8_lossy(ai.menu_string).into_owned(),
237 });
238 }
239 Ok(out)
240 }
241 }
243
244#[derive(Debug, Default)]
249pub struct ConditionalAccess;
250
251impl Resource for ConditionalAccess {
252 fn id(&self) -> ResourceId {
253 CONDITIONAL_ACCESS_SUPPORT
254 }
255
256 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
257 Ok(ResourceOut {
258 apdus: vec![ser(&CaInfoEnq::default())?],
259 ..ResourceOut::default()
260 })
261 }
262
263 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
264 if apdu.len() < APDU_TAG_LEN {
265 return Err(dvb_ci::Error::InvalidLength("short APDU"));
266 }
267 let mut out = ResourceOut::default();
268 match peek_tag(apdu) {
269 Some(t) if t == tag::CA_INFO => {
270 let ci = CaInfo::parse(apdu)?;
273 out.notify.push(Notification::CaInfo {
274 ca_system_ids: ci.ca_system_ids,
275 });
276 }
277 Some(t) if t == tag::CA_PMT_REPLY => {
278 let r = CaPmtReply::parse(apdu)?;
281 let descrambling_ok = matches!(
289 r.ca_enable,
290 Some(
291 CaEnable::Possible
292 | CaEnable::PossiblePurchaseDialogue
293 | CaEnable::PossibleTechnicalDialogue
294 )
295 );
296 out.notify.push(Notification::CaPmtReply {
297 program_number: r.program_number,
298 ca_enable: r.ca_enable,
299 descrambling_ok,
300 });
301 }
302 _ => {}
303 }
304 Ok(out)
305 }
306 }
308
309const SECS_PER_DAY: u64 = 86_400;
310const MJD_UNIX_EPOCH: u64 = 40_587;
312
313fn bcd(v: u64) -> u8 {
314 (((v / 10) << 4) | (v % 10)) as u8
315}
316
317fn unix_to_mjd_bcd(unix_secs: u64) -> Option<[u8; UTC_TIME_LEN]> {
322 let mjd = u16::try_from(MJD_UNIX_EPOCH + unix_secs / SECS_PER_DAY).ok()?;
323 let sod = unix_secs % SECS_PER_DAY;
324 Some([
325 (mjd >> 8) as u8,
326 mjd as u8,
327 bcd(sod / 3600),
328 bcd((sod % 3600) / 60),
329 bcd(sod % 60),
330 ])
331}
332
333fn system_utc() -> Option<[u8; UTC_TIME_LEN]> {
337 let now = std::time::SystemTime::now();
338 now.duration_since(std::time::UNIX_EPOCH)
339 .ok()
340 .and_then(|d| unix_to_mjd_bcd(d.as_secs()))
341}
342
343pub struct DateTime {
347 clock: fn() -> Option<[u8; UTC_TIME_LEN]>,
348 interval: u8,
349 since: Duration,
350}
351
352impl Default for DateTime {
353 fn default() -> Self {
354 Self::new()
355 }
356}
357
358impl DateTime {
359 #[must_use]
361 pub fn new() -> Self {
362 Self {
363 clock: system_utc,
364 interval: 0,
365 since: Duration::ZERO,
366 }
367 }
368
369 #[must_use]
374 pub fn with_clock(clock: fn() -> Option<[u8; UTC_TIME_LEN]>) -> Self {
375 Self {
376 clock,
377 interval: 0,
378 since: Duration::ZERO,
379 }
380 }
381
382 fn reply(&self) -> Option<dvb_ci::Result<Vec<u8>>> {
383 let utc_time = (self.clock)()?;
384 Some(ser(&CiDateTime {
385 length_form: dvb_ci::length::LengthForm::Minimal,
386 utc_time,
387 local_offset: None,
388 }))
389 }
390}
391
392impl Resource for DateTime {
393 fn id(&self) -> ResourceId {
394 DATE_TIME
395 }
396
397 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
398 if apdu.len() < APDU_TAG_LEN {
399 return Err(dvb_ci::Error::InvalidLength("short APDU"));
400 }
401 let mut out = ResourceOut::default();
402 if peek_tag(apdu) == Some(tag::DATE_TIME_ENQ) {
403 let enq = DateTimeEnq::parse(apdu)?;
404 self.interval = enq.response_interval;
405 self.since = Duration::ZERO;
406 match self.reply() {
407 Some(reply) => out.apdus.push(reply?),
408 None => out.notify.push(Notification::ClockUnrepresentable),
409 }
410 }
411 Ok(out)
412 }
413
414 fn tick(&mut self, elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
415 let mut out = ResourceOut::default();
416 if self.interval > 0 {
417 self.since += elapsed;
418 if self.since >= Duration::from_secs(u64::from(self.interval)) {
419 self.since = Duration::ZERO;
420 match self.reply() {
421 Some(reply) => out.apdus.push(reply?),
422 None => out.notify.push(Notification::ClockUnrepresentable),
423 }
424 }
425 }
426 Ok(out)
427 }
428
429 fn reset(&mut self) {
435 self.interval = 0;
436 self.since = Duration::ZERO;
437 }
438}
439
440#[derive(Debug, Default)]
448pub struct Mmi {
449 chain: Option<MmiChain>,
450}
451
452pub const MAX_MMI_CHAIN_LEN: usize = 0xFFFF;
455
456const APDU_TAG_LEN: usize = 3;
457
458#[derive(Debug)]
459struct MmiChain {
460 last: ApduTag,
461 body: Vec<u8>,
462}
463
464impl Mmi {
465 fn chain_more(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<()> {
466 let tail = apdu
467 .get(APDU_TAG_LEN..)
468 .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
469 let (len, hdr) = dvb_ci::length::decode(tail)?;
470 let start = APDU_TAG_LEN + hdr;
471 let data = apdu
472 .get(start..start + len)
473 .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
474 let mut chain = match self.chain.take() {
475 Some(c) if c.last == last => c,
476 _ => MmiChain {
477 last,
478 body: Vec::new(),
479 },
480 };
481 if chain.body.len() + data.len() > MAX_MMI_CHAIN_LEN {
482 return Err(dvb_ci::Error::LengthTooLarge(chain.body.len() + data.len()));
483 }
484 chain.body.extend_from_slice(data);
485 self.chain = Some(chain);
486 Ok(())
487 }
488
489 fn complete(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<Vec<u8>> {
493 let Some(chain) = self.chain.take().filter(|c| c.last == last) else {
494 return Ok(apdu.to_vec());
495 };
496 let tail = apdu
497 .get(APDU_TAG_LEN..)
498 .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
499 let (len, hdr) = dvb_ci::length::decode(tail)?;
500 let start = APDU_TAG_LEN + hdr;
501 let data = apdu
502 .get(start..start + len)
503 .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
504 let total = chain.body.len() + data.len();
505 let mut buf = vec![0u8; APDU_TAG_LEN + dvb_ci::length::encoded_len(total) + total];
506 buf[..APDU_TAG_LEN].copy_from_slice(&last.to_bytes());
507 let n = dvb_ci::length::encode_into(total, &mut buf[APDU_TAG_LEN..])?;
508 let body_at = APDU_TAG_LEN + n;
509 buf[body_at..body_at + chain.body.len()].copy_from_slice(&chain.body);
510 buf[body_at + chain.body.len()..].copy_from_slice(data);
511 Ok(buf)
512 }
513}
514
515impl Resource for Mmi {
516 fn id(&self) -> ResourceId {
517 MMI
518 }
519
520 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
521 if apdu.len() < APDU_TAG_LEN {
522 return Err(dvb_ci::Error::InvalidLength("short APDU"));
523 }
524 let mut out = ResourceOut::default();
525 match peek_tag(apdu) {
526 Some(t) if t == tag::ENQ => {
527 let e = Enq::parse(apdu)?;
530 out.notify.push(Notification::Mmi(MmiEvent::Enquiry {
531 prompt: text(e.text_chars),
532 blind: e.blind_answer,
533 answer_len: e.answer_text_length,
534 }));
535 }
536 Some(t) if t == tag::MENU_MORE => self.chain_more(apdu, tag::MENU_LAST)?,
537 Some(t) if t == tag::LIST_MORE => self.chain_more(apdu, tag::LIST_LAST)?,
538 Some(t) if t == tag::MENU_LAST => {
539 let full = self.complete(apdu, tag::MENU_LAST)?;
542 let m = Menu::parse(&full)?;
543 out.notify
544 .push(Notification::Mmi(MmiEvent::Menu(to_menu(&m))));
545 }
546 Some(t) if t == tag::LIST_LAST => {
547 let full = self.complete(apdu, tag::LIST_LAST)?;
550 let l = List::parse(&full)?;
551 out.notify
552 .push(Notification::Mmi(MmiEvent::List(to_menu(&l.0))));
553 }
554 Some(t) if t == tag::CLOSE_MMI => {
555 dvb_ci::objects::mmi_close::CloseMmi::parse(apdu)?;
556 out.notify.push(Notification::Mmi(MmiEvent::Close));
557 }
558 Some(t) if t == tag::DISPLAY_CONTROL => {
564 let dc = DisplayControl::parse(apdu)?;
567 let reply = match dc.cmd {
568 DisplayControlCmd::SetMmiMode => DisplayReply {
570 length_form: dvb_ci::length::LengthForm::Minimal,
571 reply_id: DisplayReplyId::MmiModeAck,
572 body: DisplayReplyBody::MmiModeAck(
573 dc.mmi_mode.unwrap_or(MmiMode::HighLevel),
574 ),
575 },
576 _ => DisplayReply {
579 length_form: dvb_ci::length::LengthForm::Minimal,
580 reply_id: DisplayReplyId::UnknownDisplayControlCmd,
581 body: DisplayReplyBody::None,
582 },
583 };
584 out.apdus.push(ser(&reply)?);
585 }
586 _ => {}
587 }
588 Ok(out)
589 }
590 fn reset(&mut self) {
591 self.chain = None;
592 }
593}
594
595#[derive(Debug, Default)]
602pub struct HostControl;
603
604impl Resource for HostControl {
605 fn id(&self) -> ResourceId {
606 HOST_CONTROL
607 }
608
609 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
610 if apdu.len() < APDU_TAG_LEN {
611 return Err(dvb_ci::Error::InvalidLength("short APDU"));
612 }
613 let mut out = ResourceOut::default();
614 let event = match peek_tag(apdu) {
618 Some(t) if t == tag::TUNE => {
619 let t = Tune::parse(apdu)?;
620 Some(HostControlEvent::Tune {
621 network_id: t.network_id,
622 original_network_id: t.original_network_id,
623 transport_stream_id: t.transport_stream_id,
624 service_id: t.service_id,
625 })
626 }
627 Some(t) if t == tag::REPLACE => {
628 let r = Replace::parse(apdu)?;
629 Some(HostControlEvent::Replace {
630 replacement_ref: r.replacement_ref,
631 replaced_pid: r.replaced_pid,
632 replacement_pid: r.replacement_pid,
633 })
634 }
635 Some(t) if t == tag::CLEAR_REPLACE => {
636 let c = ClearReplace::parse(apdu)?;
637 Some(HostControlEvent::ClearReplace {
638 replacement_ref: c.replacement_ref,
639 })
640 }
641 Some(t) if t == tag::ASK_RELEASE => {
642 AskRelease::parse(apdu)?;
643 Some(HostControlEvent::AskRelease)
644 }
645 _ => None,
646 };
647 if let Some(event) = event {
648 out.notify.push(Notification::HostControl(event));
649 }
650 Ok(out)
651 }
652 }
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658 use dvb_ci::objects::resource_manager::Profile;
659 use mpeg_ts::pid::Pid;
660
661 fn s<S: Serialize<Error = dvb_ci::Error>>(v: &S) -> Vec<u8> {
664 ser(v).expect("test value must serialize")
665 }
666
667 #[test]
668 fn on_open_sends_profile_enq() {
669 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
670 let out = rm.on_open().unwrap();
671 assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
672 }
673
674 #[test]
675 fn module_profile_triggers_profile_change_and_camready() {
676 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
682 rm.on_open().unwrap();
683 let empty_profile = s(&Profile {
684 length_form: dvb_ci::length::LengthForm::Minimal,
685 resources: vec![],
686 });
687 let o = rm.on_apdu(&empty_profile).unwrap();
688 assert!(o.notify.contains(&Notification::CamReady));
689 assert_eq!(o.apdus.len(), 1, "host sends profile_change");
690 assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE_CHANGE));
691 assert!(o.open.is_empty(), "host opens no sessions itself");
692 }
693
694 #[test]
695 fn answers_a_module_profile_enquiry_without_re_readying() {
696 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
697 rm.on_open().unwrap();
698 rm.on_apdu(&s(&Profile {
699 length_form: dvb_ci::length::LengthForm::Minimal,
700 resources: vec![APPLICATION_INFORMATION],
701 }))
702 .unwrap();
703 let o = rm.on_apdu(&s(&ProfileEnq::default())).unwrap();
705 assert_eq!(o.apdus.len(), 1);
706 assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE));
707 assert!(!o.notify.contains(&Notification::CamReady));
708 }
709
710 #[test]
716 fn resource_manager_reset_clears_latched_handshake_state() {
717 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
718 rm.on_open().unwrap();
719 let o = rm
720 .on_apdu(&s(&Profile {
721 length_form: dvb_ci::length::LengthForm::Minimal,
722 resources: vec![APPLICATION_INFORMATION],
723 }))
724 .unwrap();
725 assert!(o.notify.contains(&Notification::CamReady), "dirtied: ready");
726 assert!(
727 !rm.module_resources().is_empty(),
728 "dirtied: module_resources"
729 );
730
731 rm.reset();
732 assert!(
733 rm.module_resources().is_empty(),
734 "reset must clear module_resources"
735 );
736
737 rm.on_open().unwrap();
740 let o2 = rm
741 .on_apdu(&s(&Profile {
742 length_form: dvb_ci::length::LengthForm::Minimal,
743 resources: vec![],
744 }))
745 .unwrap();
746 assert!(
747 o2.notify.contains(&Notification::CamReady),
748 "a fresh handshake after reset() must fire CamReady again"
749 );
750 }
751
752 #[test]
753 fn mmi_surfaces_enquiry_and_close() {
754 let mut h = Mmi::default();
755 let enq = s(&Enq {
757 reserved: Default::default(),
758 length_form: dvb_ci::length::LengthForm::Minimal,
759 blind_answer: true,
760 answer_text_length: 4,
761 text_chars: b"PIN?",
762 });
763 assert_eq!(
764 h.on_apdu(&enq).unwrap().notify,
765 vec![Notification::Mmi(MmiEvent::Enquiry {
766 prompt: "PIN?".to_string(),
767 blind: true,
768 answer_len: 4,
769 })]
770 );
771 let close = [0x9F, 0x88, 0x00, 0x01, 0x00];
773 assert_eq!(
774 h.on_apdu(&close).unwrap().notify,
775 vec![Notification::Mmi(MmiEvent::Close)]
776 );
777 }
778
779 #[test]
780 fn mmi_surfaces_structured_menu_and_list() {
781 use dvb_ci::objects::mmi_high::{List, Menu, Text};
782 let txt = |s: &'static [u8]| Text {
783 length_form: dvb_ci::length::LengthForm::Minimal,
784 more: false,
785 text_chars: s,
786 };
787 let mut h = Mmi::default();
788 let menu = s(&Menu {
790 length_form: dvb_ci::length::LengthForm::Minimal,
791 more: false,
792 choice_nb: 2,
793 title: txt(b"AlphaCrypt"),
794 subtitle: txt(b"Module Mainmenu"),
795 bottom: txt(b"Select item and press OK"),
796 choices: vec![txt(b"Smartcard"), txt(b"Quit")],
797 });
798 assert_eq!(
799 h.on_apdu(&menu).unwrap().notify,
800 vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
801 title: "AlphaCrypt".to_string(),
802 subtitle: "Module Mainmenu".to_string(),
803 bottom: "Select item and press OK".to_string(),
804 choices: vec!["Smartcard".to_string(), "Quit".to_string()],
805 }))]
806 );
807 let list = s(&List(Menu {
809 length_form: dvb_ci::length::LengthForm::Minimal,
810 more: false,
811 choice_nb: 0xFF,
812 title: txt(b"Entitlements"),
813 subtitle: txt(b""),
814 bottom: txt(b""),
815 choices: vec![txt(b"ORF AUT")],
816 }));
817 assert_eq!(
818 h.on_apdu(&list).unwrap().notify,
819 vec![Notification::Mmi(MmiEvent::List(MmiMenu {
820 title: "Entitlements".to_string(),
821 subtitle: String::new(),
822 bottom: String::new(),
823 choices: vec!["ORF AUT".to_string()],
824 }))]
825 );
826 }
827
828 fn chained(more: ApduTag, last: ApduTag, whole_last_apdu: &[u8], split: usize) -> [Vec<u8>; 2] {
829 let (len, hdr) = dvb_ci::length::decode(&whole_last_apdu[3..]).unwrap();
830 let body = &whole_last_apdu[3 + hdr..3 + hdr + len];
831 let part = |t: ApduTag, b: &[u8]| {
832 let mut v = t.to_bytes().to_vec();
833 let mut l = [0u8; 3];
834 let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
835 v.extend_from_slice(&l[..n]);
836 v.extend_from_slice(b);
837 v
838 };
839 [part(more, &body[..split]), part(last, &body[split..])]
840 }
841
842 #[test]
843 fn mmi_reassembles_a_menu_chained_over_menu_more_and_menu_last() {
844 use dvb_ci::objects::mmi_high::{Menu, Text};
845 let txt = |s: &'static [u8]| Text {
846 length_form: dvb_ci::length::LengthForm::Minimal,
847 more: false,
848 text_chars: s,
849 };
850 let whole = s(&Menu {
851 length_form: dvb_ci::length::LengthForm::Minimal,
852 more: false,
853 choice_nb: 2,
854 title: txt(b"AlphaCrypt"),
855 subtitle: txt(b"Module Mainmenu"),
856 bottom: txt(b"Select item and press OK"),
857 choices: vec![txt(b"Smartcard"), txt(b"Quit")],
858 });
859 let [first, second] = chained(tag::MENU_MORE, tag::MENU_LAST, &whole, 20);
860 let mut h = Mmi::default();
861 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
862 assert_eq!(
863 h.on_apdu(&second).unwrap().notify,
864 vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
865 title: "AlphaCrypt".to_string(),
866 subtitle: "Module Mainmenu".to_string(),
867 bottom: "Select item and press OK".to_string(),
868 choices: vec!["Smartcard".to_string(), "Quit".to_string()],
869 }))]
870 );
871 }
872
873 #[test]
874 fn mmi_reassembles_a_list_chained_over_list_more_and_list_last() {
875 use dvb_ci::objects::mmi_high::{List, Menu, Text};
876 let txt = |s: &'static [u8]| Text {
877 length_form: dvb_ci::length::LengthForm::Minimal,
878 more: false,
879 text_chars: s,
880 };
881 let whole = s(&List(Menu {
882 length_form: dvb_ci::length::LengthForm::Minimal,
883 more: false,
884 choice_nb: 2,
885 title: txt(b"Entitlements"),
886 subtitle: txt(b""),
887 bottom: txt(b""),
888 choices: vec![txt(b"ORF AUT"), txt(b"ZDF")],
889 }));
890 let [first, second] = chained(tag::LIST_MORE, tag::LIST_LAST, &whole, 9);
891 let mut h = Mmi::default();
892 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
893 assert_eq!(
894 h.on_apdu(&second).unwrap().notify,
895 vec![Notification::Mmi(MmiEvent::List(MmiMenu {
896 title: "Entitlements".to_string(),
897 subtitle: String::new(),
898 bottom: String::new(),
899 choices: vec!["ORF AUT".to_string(), "ZDF".to_string()],
900 }))]
901 );
902 }
903
904 #[test]
905 fn mmi_discards_a_partial_chain_on_reset() {
906 let mut h = Mmi::default();
907 let first = [0x9F, 0x88, 0x0A, 0x01, 0x02];
908 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
909 h.reset();
910 assert!(h.chain.is_none());
911 }
912
913 #[test]
914 fn mmi_answers_display_control_set_mmi_mode() {
915 use dvb_ci::objects::mmi_display::{DisplayControl, DisplayControlCmd, MmiMode};
916 let mut h = Mmi::default();
917 let dc = s(&DisplayControl {
918 length_form: dvb_ci::length::LengthForm::Minimal,
919 cmd: DisplayControlCmd::SetMmiMode,
920 mmi_mode: Some(MmiMode::HighLevel),
921 });
922 let out = h.on_apdu(&dc).unwrap();
923 assert_eq!(out.apdus, vec![vec![0x9F, 0x88, 0x02, 0x02, 0x01, 0x01]]);
925 assert!(out.notify.is_empty());
926 }
927
928 #[test]
929 fn profile_change_re_enquires() {
930 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
931 let out = rm
932 .on_apdu(&s(
933 &dvb_ci::objects::resource_manager::ProfileChange::default(),
934 ))
935 .unwrap();
936 assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
937 }
938
939 #[test]
940 fn application_information_surfaces_notification() {
941 use dvb_ci::objects::application_info::ApplicationType;
942 let mut h = ApplicationInformation;
943 assert_eq!(
944 h.on_open().unwrap().apdus,
945 vec![s(&ApplicationInfoEnq::default())]
946 );
947 let ai = s(&ApplicationInfo {
948 length_form: dvb_ci::length::LengthForm::Minimal,
949 application_type: ApplicationType::ConditionalAccess,
950 application_manufacturer: 0x1234,
951 manufacturer_code: 0x5678,
952 menu_string: b"Acme CAM",
953 });
954 let out = h.on_apdu(&ai).unwrap();
955 assert_eq!(
956 out.notify,
957 vec![Notification::ApplicationInfo {
958 application_type: 0x01,
959 manufacturer: 0x1234,
960 code: 0x5678,
961 menu: "Acme CAM".to_string(),
962 }]
963 );
964 }
965
966 #[test]
967 fn host_control_surfaces_tune_replace_clear_and_ask_release() {
968 let mut h = HostControl;
969 assert_eq!(h.id(), HOST_CONTROL);
970
971 let tune = s(&Tune {
973 length_form: dvb_ci::length::LengthForm::Minimal,
974 network_id: 0x1122,
975 original_network_id: 0x3344,
976 transport_stream_id: 0x5566,
977 service_id: 0x7788,
978 });
979 assert_eq!(
980 h.on_apdu(&tune).unwrap().notify,
981 vec![Notification::HostControl(HostControlEvent::Tune {
982 network_id: 0x1122,
983 original_network_id: 0x3344,
984 transport_stream_id: 0x5566,
985 service_id: 0x7788,
986 })]
987 );
988
989 let replace = s(&Replace {
991 length_form: dvb_ci::length::LengthForm::Minimal,
992 replacement_ref: 0x07,
993 replaced_pid: Pid::from_const(0x0123),
994 replacement_pid: Pid::from_const(0x01FF),
995 replaced_reserved: Default::default(),
996 replacement_reserved: Default::default(),
997 });
998 assert_eq!(
999 h.on_apdu(&replace).unwrap().notify,
1000 vec![Notification::HostControl(HostControlEvent::Replace {
1001 replacement_ref: 0x07,
1002 replaced_pid: Pid::from_const(0x0123),
1003 replacement_pid: Pid::from_const(0x01FF),
1004 })]
1005 );
1006
1007 let clear = s(&ClearReplace {
1009 length_form: dvb_ci::length::LengthForm::Minimal,
1010 replacement_ref: 0x42,
1011 });
1012 assert_eq!(
1013 h.on_apdu(&clear).unwrap().notify,
1014 vec![Notification::HostControl(HostControlEvent::ClearReplace {
1015 replacement_ref: 0x42,
1016 })]
1017 );
1018
1019 let ask = s(&AskRelease::default());
1021 assert_eq!(
1022 h.on_apdu(&ask).unwrap().notify,
1023 vec![Notification::HostControl(HostControlEvent::AskRelease)]
1024 );
1025
1026 assert!(h.on_apdu(&tune).unwrap().apdus.is_empty());
1028 }
1029
1030 #[test]
1031 fn mjd_bcd_encoding_is_correct() {
1032 assert_eq!(unix_to_mjd_bcd(0), Some([0x9E, 0x8B, 0x00, 0x00, 0x00]));
1034 let secs = SECS_PER_DAY + 13 * 3600 + 45 * 60 + 9;
1036 assert_eq!(unix_to_mjd_bcd(secs), Some([0x9E, 0x8C, 0x13, 0x45, 0x09]));
1037 }
1038
1039 #[test]
1040 fn mjd_beyond_its_sixteen_bits_is_refused_not_wrapped() {
1041 assert_eq!(
1044 unix_to_mjd_bcd(2_155_507_200 + 86_399),
1045 Some([0xFF, 0xFF, 0x23, 0x59, 0x59])
1046 );
1047 assert_eq!(unix_to_mjd_bcd(5_417_971_200), None);
1050 }
1051
1052 #[test]
1053 fn date_time_reports_an_unrepresentable_clock_instead_of_a_wrong_date() {
1054 let mut h = DateTime::with_clock(|| None);
1055 let out = h
1056 .on_apdu(&s(&DateTimeEnq {
1057 length_form: dvb_ci::length::LengthForm::Minimal,
1058 response_interval: 0,
1059 }))
1060 .unwrap();
1061 assert!(out.apdus.is_empty());
1062 assert_eq!(out.notify, vec![Notification::ClockUnrepresentable]);
1063 }
1064
1065 #[test]
1066 fn system_clock_is_representable_today() {
1067 let now = std::time::SystemTime::now()
1068 .duration_since(std::time::UNIX_EPOCH)
1069 .unwrap_or_default()
1070 .as_secs();
1071 assert_eq!(system_utc(), unix_to_mjd_bcd(now));
1072 assert!(system_utc().is_some());
1073 }
1074
1075 #[test]
1076 fn date_time_replies_to_enq_and_resends_on_interval() {
1077 let fixed = || Some([0x9E, 0x7B, 0x00, 0x00, 0x00]);
1078 let mut h = DateTime::with_clock(fixed);
1079 let enq = s(&DateTimeEnq {
1081 length_form: dvb_ci::length::LengthForm::Minimal,
1082 response_interval: 5,
1083 });
1084 let out = h.on_apdu(&enq).unwrap();
1085 assert_eq!(out.apdus.len(), 1);
1086 assert_eq!(peek_tag(&out.apdus[0]), Some(tag::DATE_TIME));
1087 assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1089 assert_eq!(h.tick(Duration::from_secs(3)).unwrap().apdus.len(), 1);
1091 }
1092
1093 #[test]
1094 fn date_time_interval_zero_does_not_resend() {
1095 let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1096 h.on_apdu(&s(&DateTimeEnq {
1097 length_form: dvb_ci::length::LengthForm::Minimal,
1098 response_interval: 0,
1099 }))
1100 .unwrap();
1101 assert!(h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty());
1102 }
1103
1104 #[test]
1109 fn date_time_reset_clears_interval_and_resend_timer() {
1110 let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1111 h.on_apdu(&s(&DateTimeEnq {
1112 length_form: dvb_ci::length::LengthForm::Minimal,
1113 response_interval: 5,
1114 }))
1115 .unwrap();
1116 assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1118
1119 h.reset();
1120 assert!(
1124 h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty(),
1125 "reset must clear the resend cadence from the previous module"
1126 );
1127 }
1128
1129 #[test]
1130 fn conditional_access_surfaces_ca_info_and_pmt_reply() {
1131 let mut h = ConditionalAccess;
1132 assert_eq!(h.on_open().unwrap().apdus, vec![s(&CaInfoEnq::default())]);
1133 let ci = s(&CaInfo {
1135 length_form: dvb_ci::length::LengthForm::Minimal,
1136 ca_system_ids: vec![0x0B00, 0x1800],
1137 });
1138 assert_eq!(
1139 h.on_apdu(&ci).unwrap().notify,
1140 vec![Notification::CaInfo {
1141 ca_system_ids: vec![0x0B00, 0x1800],
1142 }]
1143 );
1144 let reply = s(&CaPmtReply {
1146 reserved_ca_enable: Default::default(),
1147 reserved_version: Default::default(),
1148 length_form: dvb_ci::length::LengthForm::Minimal,
1149 program_number: 0x0042,
1150 version_number: 0,
1151 current_next_indicator: true,
1152 ca_enable: Some(CaEnable::Possible),
1153 streams: vec![],
1154 });
1155 assert_eq!(
1156 h.on_apdu(&reply).unwrap().notify,
1157 vec![Notification::CaPmtReply {
1158 program_number: 0x0042,
1159 ca_enable: Some(CaEnable::Possible),
1160 descrambling_ok: true,
1161 }]
1162 );
1163 }
1164
1165 #[test]
1166 fn conditional_access_ca_pmt_reply_flag_clear_surfaces_none() {
1167 let mut h = ConditionalAccess;
1168 h.on_open().unwrap();
1169 let reply = s(&CaPmtReply {
1171 reserved_ca_enable: Default::default(),
1172 reserved_version: Default::default(),
1173 length_form: dvb_ci::length::LengthForm::Minimal,
1174 program_number: 0x0007,
1175 version_number: 0,
1176 current_next_indicator: true,
1177 ca_enable: None,
1178 streams: vec![],
1179 });
1180 assert_eq!(
1181 h.on_apdu(&reply).unwrap().notify,
1182 vec![Notification::CaPmtReply {
1183 program_number: 0x0007,
1184 ca_enable: None,
1185 descrambling_ok: false,
1186 }]
1187 );
1188 }
1189
1190 #[test]
1191 fn short_apdu_returns_err() {
1192 for len in 0..3usize {
1193 let buf = vec![0u8; len];
1194 assert!(Mmi::default().on_apdu(&buf).is_err(), "Mmi len {len}");
1195 assert!(
1196 ResourceManager::new(vec![]).on_apdu(&buf).is_err(),
1197 "RM len {len}"
1198 );
1199 assert!(
1200 ApplicationInformation.on_apdu(&buf).is_err(),
1201 "AI len {len}"
1202 );
1203 assert!(ConditionalAccess.on_apdu(&buf).is_err(), "CA len {len}");
1204 assert!(DateTime::default().on_apdu(&buf).is_err(), "DT len {len}");
1205 assert!(HostControl.on_apdu(&buf).is_err(), "HC len {len}");
1206 }
1207 }
1208}