1use std::time::Duration;
11
12use broadcast_core::{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.first_chunk::<APDU_TAG_LEN>()
65 .map(|&[a, b, c]| ApduTag::from_bytes(a, b, c))
66}
67
68#[derive(Debug, Default, Clone, PartialEq, Eq)]
70pub struct ResourceOut {
71 pub apdus: Vec<Vec<u8>>,
73 pub notify: Vec<Notification>,
75 pub open: Vec<ResourceId>,
77}
78
79pub trait Resource {
81 fn id(&self) -> ResourceId;
83 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
85 Ok(ResourceOut::default())
86 }
87 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut>;
89 fn tick(&mut self, _elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
91 Ok(ResourceOut::default())
92 }
93 fn reset(&mut self) {}
102}
103
104#[derive(Debug)]
108pub struct ResourceManager {
109 host_resources: Vec<ResourceId>,
110 module_resources: Vec<ResourceId>,
111 module_profiled: bool,
112 ready: bool,
113}
114
115impl ResourceManager {
116 #[must_use]
118 pub fn new(host_resources: Vec<ResourceId>) -> Self {
119 Self {
120 host_resources,
121 module_resources: Vec::new(),
122 module_profiled: false,
123 ready: false,
124 }
125 }
126
127 #[must_use]
129 pub fn module_resources(&self) -> &[ResourceId] {
130 &self.module_resources
131 }
132}
133
134impl Resource for ResourceManager {
135 fn id(&self) -> ResourceId {
136 RESOURCE_MANAGER
137 }
138
139 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
140 Ok(ResourceOut {
142 apdus: vec![ser(&ProfileEnq::default())?],
143 ..ResourceOut::default()
144 })
145 }
146
147 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
148 if apdu.len() < APDU_TAG_LEN {
149 return Err(dvb_ci::Error::InvalidLength("short APDU"));
150 }
151 let mut out = ResourceOut::default();
152 match peek_tag(apdu) {
153 Some(t) if t == tag::PROFILE_ENQ => {
155 out.apdus.push(ser(&Profile {
156 length_form: dvb_ci::length::LengthForm::Minimal,
157 resources: self.host_resources.clone(),
158 })?);
159 }
160 Some(t) if t == tag::PROFILE => {
162 let p = Profile::parse(apdu)?;
165 self.module_resources = p.resources;
166 self.module_profiled = true;
167 }
168 Some(t) if t == tag::PROFILE_CHANGE => {
170 out.apdus.push(ser(&ProfileEnq::default())?);
171 self.module_profiled = false;
172 self.ready = false;
173 }
174 _ => {}
175 }
176 if self.module_profiled && !self.ready {
190 self.ready = true;
191 out.apdus.push(ser(&ProfileChange::default())?);
192 out.notify.push(Notification::CamReady);
193 }
194 Ok(out)
195 }
196
197 fn reset(&mut self) {
203 self.module_resources.clear();
204 self.module_profiled = false;
205 self.ready = false;
206 }
207}
208
209#[derive(Debug, Default)]
212pub struct ApplicationInformation;
213
214impl Resource for ApplicationInformation {
215 fn id(&self) -> ResourceId {
216 APPLICATION_INFORMATION
217 }
218
219 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
220 Ok(ResourceOut {
221 apdus: vec![ser(&ApplicationInfoEnq::default())?],
222 ..ResourceOut::default()
223 })
224 }
225
226 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
227 if apdu.len() < APDU_TAG_LEN {
228 return Err(dvb_ci::Error::InvalidLength("short APDU"));
229 }
230 let mut out = ResourceOut::default();
231 if peek_tag(apdu) == Some(tag::APPLICATION_INFO) {
232 let ai = ApplicationInfo::parse(apdu)?;
233 out.notify.push(Notification::ApplicationInfo {
234 application_type: ai.application_type.to_u8(),
235 manufacturer: ai.application_manufacturer,
236 code: ai.manufacturer_code,
237 menu: String::from_utf8_lossy(ai.menu_string).into_owned(),
238 });
239 }
240 Ok(out)
241 }
242 }
244
245#[derive(Debug, Default)]
250pub struct ConditionalAccess;
251
252impl Resource for ConditionalAccess {
253 fn id(&self) -> ResourceId {
254 CONDITIONAL_ACCESS_SUPPORT
255 }
256
257 fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
258 Ok(ResourceOut {
259 apdus: vec![ser(&CaInfoEnq::default())?],
260 ..ResourceOut::default()
261 })
262 }
263
264 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
265 if apdu.len() < APDU_TAG_LEN {
266 return Err(dvb_ci::Error::InvalidLength("short APDU"));
267 }
268 let mut out = ResourceOut::default();
269 match peek_tag(apdu) {
270 Some(t) if t == tag::CA_INFO => {
271 let ci = CaInfo::parse(apdu)?;
274 out.notify.push(Notification::CaInfo {
275 ca_system_ids: ci.ca_system_ids,
276 });
277 }
278 Some(t) if t == tag::CA_PMT_REPLY => {
279 let r = CaPmtReply::parse(apdu)?;
282 let descrambling_ok = matches!(
290 r.ca_enable,
291 Some(
292 CaEnable::Possible
293 | CaEnable::PossiblePurchaseDialogue
294 | CaEnable::PossibleTechnicalDialogue
295 )
296 );
297 out.notify.push(Notification::CaPmtReply {
298 program_number: r.program_number,
299 ca_enable: r.ca_enable,
300 descrambling_ok,
301 });
302 }
303 _ => {}
304 }
305 Ok(out)
306 }
307 }
309
310fn unix_to_mjd_bcd(unix_secs: u64) -> Option<[u8; UTC_TIME_LEN]> {
315 let secs = i64::try_from(unix_secs).ok()?;
316 broadcast_common::time::encode_mjd_bcd_utc(jiff::Timestamp::from_second(secs).ok()?)
317}
318
319fn system_utc() -> Option<[u8; UTC_TIME_LEN]> {
323 let now = std::time::SystemTime::now();
324 now.duration_since(std::time::UNIX_EPOCH)
325 .ok()
326 .and_then(|d| unix_to_mjd_bcd(d.as_secs()))
327}
328
329pub struct DateTime {
333 clock: fn() -> Option<[u8; UTC_TIME_LEN]>,
334 interval: u8,
335 since: Duration,
336}
337
338impl Default for DateTime {
339 fn default() -> Self {
340 Self::new()
341 }
342}
343
344impl DateTime {
345 #[must_use]
347 pub fn new() -> Self {
348 Self {
349 clock: system_utc,
350 interval: 0,
351 since: Duration::ZERO,
352 }
353 }
354
355 #[must_use]
360 pub fn with_clock(clock: fn() -> Option<[u8; UTC_TIME_LEN]>) -> Self {
361 Self {
362 clock,
363 interval: 0,
364 since: Duration::ZERO,
365 }
366 }
367
368 fn reply(&self) -> Option<dvb_ci::Result<Vec<u8>>> {
369 let utc_time = (self.clock)()?;
370 Some(ser(&CiDateTime {
371 length_form: dvb_ci::length::LengthForm::Minimal,
372 utc_time,
373 local_offset: None,
374 }))
375 }
376}
377
378impl Resource for DateTime {
379 fn id(&self) -> ResourceId {
380 DATE_TIME
381 }
382
383 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
384 if apdu.len() < APDU_TAG_LEN {
385 return Err(dvb_ci::Error::InvalidLength("short APDU"));
386 }
387 let mut out = ResourceOut::default();
388 if peek_tag(apdu) == Some(tag::DATE_TIME_ENQ) {
389 let enq = DateTimeEnq::parse(apdu)?;
390 self.interval = enq.response_interval;
391 self.since = Duration::ZERO;
392 match self.reply() {
393 Some(reply) => out.apdus.push(reply?),
394 None => out.notify.push(Notification::ClockUnrepresentable),
395 }
396 }
397 Ok(out)
398 }
399
400 fn tick(&mut self, elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
401 let mut out = ResourceOut::default();
402 if self.interval > 0 {
403 self.since += elapsed;
404 if self.since >= Duration::from_secs(u64::from(self.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 }
412 Ok(out)
413 }
414
415 fn reset(&mut self) {
421 self.interval = 0;
422 self.since = Duration::ZERO;
423 }
424}
425
426#[derive(Debug, Default)]
434pub struct Mmi {
435 chain: Option<MmiChain>,
436}
437
438pub const MAX_MMI_CHAIN_LEN: usize = 0xFFFF;
441
442pub(crate) const APDU_TAG_LEN: usize = 3;
444
445#[derive(Debug)]
446struct MmiChain {
447 last: ApduTag,
448 body: Vec<u8>,
449}
450
451impl Mmi {
452 fn chain_more(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<()> {
453 let tail = apdu
454 .get(APDU_TAG_LEN..)
455 .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
456 let (len, hdr) = dvb_ci::length::decode(tail)?;
457 let start = APDU_TAG_LEN + hdr;
458 let data = apdu
459 .get(start..start + len)
460 .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
461 let mut chain = match self.chain.take() {
462 Some(c) if c.last == last => c,
463 _ => MmiChain {
464 last,
465 body: Vec::new(),
466 },
467 };
468 if chain.body.len() + data.len() > MAX_MMI_CHAIN_LEN {
469 return Err(dvb_ci::Error::LengthTooLarge(chain.body.len() + data.len()));
470 }
471 chain.body.extend_from_slice(data);
472 self.chain = Some(chain);
473 Ok(())
474 }
475
476 fn complete(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<Vec<u8>> {
480 let Some(chain) = self.chain.take().filter(|c| c.last == last) else {
481 return Ok(apdu.to_vec());
482 };
483 let tail = apdu
484 .get(APDU_TAG_LEN..)
485 .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
486 let (len, hdr) = dvb_ci::length::decode(tail)?;
487 let start = APDU_TAG_LEN + hdr;
488 let data = apdu
489 .get(start..start + len)
490 .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
491 let total = chain.body.len() + data.len();
492 let mut buf = vec![0u8; APDU_TAG_LEN + dvb_ci::length::encoded_len(total) + total];
493 buf[..APDU_TAG_LEN].copy_from_slice(&last.to_bytes());
494 let n = dvb_ci::length::encode_into(total, &mut buf[APDU_TAG_LEN..])?;
495 let body_at = APDU_TAG_LEN + n;
496 buf[body_at..body_at + chain.body.len()].copy_from_slice(&chain.body);
497 buf[body_at + chain.body.len()..].copy_from_slice(data);
498 Ok(buf)
499 }
500}
501
502impl Resource for Mmi {
503 fn id(&self) -> ResourceId {
504 MMI
505 }
506
507 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
508 if apdu.len() < APDU_TAG_LEN {
509 return Err(dvb_ci::Error::InvalidLength("short APDU"));
510 }
511 let mut out = ResourceOut::default();
512 match peek_tag(apdu) {
513 Some(t) if t == tag::ENQ => {
514 let e = Enq::parse(apdu)?;
517 out.notify.push(Notification::Mmi(MmiEvent::Enquiry {
518 prompt: text(e.text_chars),
519 blind: e.blind_answer,
520 answer_len: e.answer_text_length,
521 }));
522 }
523 Some(t) if t == tag::MENU_MORE => self.chain_more(apdu, tag::MENU_LAST)?,
524 Some(t) if t == tag::LIST_MORE => self.chain_more(apdu, tag::LIST_LAST)?,
525 Some(t) if t == tag::MENU_LAST => {
526 let full = self.complete(apdu, tag::MENU_LAST)?;
529 let m = Menu::parse(&full)?;
530 out.notify
531 .push(Notification::Mmi(MmiEvent::Menu(to_menu(&m))));
532 }
533 Some(t) if t == tag::LIST_LAST => {
534 let full = self.complete(apdu, tag::LIST_LAST)?;
537 let l = List::parse(&full)?;
538 out.notify
539 .push(Notification::Mmi(MmiEvent::List(to_menu(&l.0))));
540 }
541 Some(t) if t == tag::CLOSE_MMI => {
542 dvb_ci::objects::mmi_close::CloseMmi::parse(apdu)?;
543 out.notify.push(Notification::Mmi(MmiEvent::Close));
544 }
545 Some(t) if t == tag::DISPLAY_CONTROL => {
551 let dc = DisplayControl::parse(apdu)?;
554 let reply = match dc.cmd {
555 DisplayControlCmd::SetMmiMode => DisplayReply {
557 length_form: dvb_ci::length::LengthForm::Minimal,
558 reply_id: DisplayReplyId::MmiModeAck,
559 body: DisplayReplyBody::MmiModeAck(
560 dc.mmi_mode.unwrap_or(MmiMode::HighLevel),
561 ),
562 },
563 _ => DisplayReply {
566 length_form: dvb_ci::length::LengthForm::Minimal,
567 reply_id: DisplayReplyId::UnknownDisplayControlCmd,
568 body: DisplayReplyBody::None,
569 },
570 };
571 out.apdus.push(ser(&reply)?);
572 }
573 _ => {}
574 }
575 Ok(out)
576 }
577 fn reset(&mut self) {
578 self.chain = None;
579 }
580}
581
582#[derive(Debug, Default)]
589pub struct HostControl;
590
591impl Resource for HostControl {
592 fn id(&self) -> ResourceId {
593 HOST_CONTROL
594 }
595
596 fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
597 if apdu.len() < APDU_TAG_LEN {
598 return Err(dvb_ci::Error::InvalidLength("short APDU"));
599 }
600 let mut out = ResourceOut::default();
601 let event = match peek_tag(apdu) {
605 Some(t) if t == tag::TUNE => {
606 let t = Tune::parse(apdu)?;
607 Some(HostControlEvent::Tune {
608 network_id: t.network_id,
609 original_network_id: t.original_network_id,
610 transport_stream_id: t.transport_stream_id,
611 service_id: t.service_id,
612 })
613 }
614 Some(t) if t == tag::REPLACE => {
615 let r = Replace::parse(apdu)?;
616 Some(HostControlEvent::Replace {
617 replacement_ref: r.replacement_ref,
618 replaced_pid: r.replaced_pid,
619 replacement_pid: r.replacement_pid,
620 })
621 }
622 Some(t) if t == tag::CLEAR_REPLACE => {
623 let c = ClearReplace::parse(apdu)?;
624 Some(HostControlEvent::ClearReplace {
625 replacement_ref: c.replacement_ref,
626 })
627 }
628 Some(t) if t == tag::ASK_RELEASE => {
629 AskRelease::parse(apdu)?;
630 Some(HostControlEvent::AskRelease)
631 }
632 _ => None,
633 };
634 if let Some(event) = event {
635 out.notify.push(Notification::HostControl(event));
636 }
637 Ok(out)
638 }
639 }
641
642#[cfg(test)]
643mod tests {
644 use super::*;
645 use dvb_ci::objects::resource_manager::Profile;
646 use mpeg_ts::pid::Pid;
647
648 fn s<S: Serialize<Error = dvb_ci::Error>>(v: &S) -> Vec<u8> {
651 ser(v).expect("test value must serialize")
652 }
653
654 #[test]
655 fn on_open_sends_profile_enq() {
656 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
657 let out = rm.on_open().unwrap();
658 assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
659 }
660
661 #[test]
662 fn module_profile_triggers_profile_change_and_camready() {
663 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
669 rm.on_open().unwrap();
670 let empty_profile = s(&Profile {
671 length_form: dvb_ci::length::LengthForm::Minimal,
672 resources: vec![],
673 });
674 let o = rm.on_apdu(&empty_profile).unwrap();
675 assert!(o.notify.contains(&Notification::CamReady));
676 assert_eq!(o.apdus.len(), 1, "host sends profile_change");
677 assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE_CHANGE));
678 assert!(o.open.is_empty(), "host opens no sessions itself");
679 }
680
681 #[test]
682 fn answers_a_module_profile_enquiry_without_re_readying() {
683 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
684 rm.on_open().unwrap();
685 rm.on_apdu(&s(&Profile {
686 length_form: dvb_ci::length::LengthForm::Minimal,
687 resources: vec![APPLICATION_INFORMATION],
688 }))
689 .unwrap();
690 let o = rm.on_apdu(&s(&ProfileEnq::default())).unwrap();
692 assert_eq!(o.apdus.len(), 1);
693 assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE));
694 assert!(!o.notify.contains(&Notification::CamReady));
695 }
696
697 #[test]
703 fn resource_manager_reset_clears_latched_handshake_state() {
704 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
705 rm.on_open().unwrap();
706 let o = rm
707 .on_apdu(&s(&Profile {
708 length_form: dvb_ci::length::LengthForm::Minimal,
709 resources: vec![APPLICATION_INFORMATION],
710 }))
711 .unwrap();
712 assert!(o.notify.contains(&Notification::CamReady), "dirtied: ready");
713 assert!(
714 !rm.module_resources().is_empty(),
715 "dirtied: module_resources"
716 );
717
718 rm.reset();
719 assert!(
720 rm.module_resources().is_empty(),
721 "reset must clear module_resources"
722 );
723
724 rm.on_open().unwrap();
727 let o2 = rm
728 .on_apdu(&s(&Profile {
729 length_form: dvb_ci::length::LengthForm::Minimal,
730 resources: vec![],
731 }))
732 .unwrap();
733 assert!(
734 o2.notify.contains(&Notification::CamReady),
735 "a fresh handshake after reset() must fire CamReady again"
736 );
737 }
738
739 #[test]
740 fn mmi_surfaces_enquiry_and_close() {
741 let mut h = Mmi::default();
742 let enq = s(&Enq {
744 reserved: Default::default(),
745 length_form: dvb_ci::length::LengthForm::Minimal,
746 blind_answer: true,
747 answer_text_length: 4,
748 text_chars: b"PIN?",
749 });
750 assert_eq!(
751 h.on_apdu(&enq).unwrap().notify,
752 vec![Notification::Mmi(MmiEvent::Enquiry {
753 prompt: "PIN?".to_string(),
754 blind: true,
755 answer_len: 4,
756 })]
757 );
758 let close = [0x9F, 0x88, 0x00, 0x01, 0x00];
760 assert_eq!(
761 h.on_apdu(&close).unwrap().notify,
762 vec![Notification::Mmi(MmiEvent::Close)]
763 );
764 }
765
766 #[test]
767 fn mmi_surfaces_structured_menu_and_list() {
768 use dvb_ci::objects::mmi_high::{List, Menu, Text};
769 let txt = |s: &'static [u8]| Text {
770 length_form: dvb_ci::length::LengthForm::Minimal,
771 more: false,
772 text_chars: s,
773 };
774 let mut h = Mmi::default();
775 let menu = s(&Menu {
777 length_form: dvb_ci::length::LengthForm::Minimal,
778 more: false,
779 choice_nb: 2,
780 title: txt(b"AlphaCrypt"),
781 subtitle: txt(b"Module Mainmenu"),
782 bottom: txt(b"Select item and press OK"),
783 choices: vec![txt(b"Smartcard"), txt(b"Quit")],
784 });
785 assert_eq!(
786 h.on_apdu(&menu).unwrap().notify,
787 vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
788 title: "AlphaCrypt".to_string(),
789 subtitle: "Module Mainmenu".to_string(),
790 bottom: "Select item and press OK".to_string(),
791 choices: vec!["Smartcard".to_string(), "Quit".to_string()],
792 }))]
793 );
794 let list = s(&List(Menu {
796 length_form: dvb_ci::length::LengthForm::Minimal,
797 more: false,
798 choice_nb: 0xFF,
799 title: txt(b"Entitlements"),
800 subtitle: txt(b""),
801 bottom: txt(b""),
802 choices: vec![txt(b"ORF AUT")],
803 }));
804 assert_eq!(
805 h.on_apdu(&list).unwrap().notify,
806 vec![Notification::Mmi(MmiEvent::List(MmiMenu {
807 title: "Entitlements".to_string(),
808 subtitle: String::new(),
809 bottom: String::new(),
810 choices: vec!["ORF AUT".to_string()],
811 }))]
812 );
813 }
814
815 fn chained(more: ApduTag, last: ApduTag, whole_last_apdu: &[u8], split: usize) -> [Vec<u8>; 2] {
816 let (len, hdr) = dvb_ci::length::decode(&whole_last_apdu[3..]).unwrap();
817 let body = &whole_last_apdu[3 + hdr..3 + hdr + len];
818 let part = |t: ApduTag, b: &[u8]| {
819 let mut v = t.to_bytes().to_vec();
820 let mut l = [0u8; 3];
821 let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
822 v.extend_from_slice(&l[..n]);
823 v.extend_from_slice(b);
824 v
825 };
826 [part(more, &body[..split]), part(last, &body[split..])]
827 }
828
829 #[test]
830 fn mmi_reassembles_a_menu_chained_over_menu_more_and_menu_last() {
831 use dvb_ci::objects::mmi_high::{Menu, Text};
832 let txt = |s: &'static [u8]| Text {
833 length_form: dvb_ci::length::LengthForm::Minimal,
834 more: false,
835 text_chars: s,
836 };
837 let whole = s(&Menu {
838 length_form: dvb_ci::length::LengthForm::Minimal,
839 more: false,
840 choice_nb: 2,
841 title: txt(b"AlphaCrypt"),
842 subtitle: txt(b"Module Mainmenu"),
843 bottom: txt(b"Select item and press OK"),
844 choices: vec![txt(b"Smartcard"), txt(b"Quit")],
845 });
846 let [first, second] = chained(tag::MENU_MORE, tag::MENU_LAST, &whole, 20);
847 let mut h = Mmi::default();
848 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
849 assert_eq!(
850 h.on_apdu(&second).unwrap().notify,
851 vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
852 title: "AlphaCrypt".to_string(),
853 subtitle: "Module Mainmenu".to_string(),
854 bottom: "Select item and press OK".to_string(),
855 choices: vec!["Smartcard".to_string(), "Quit".to_string()],
856 }))]
857 );
858 }
859
860 #[test]
861 fn mmi_reassembles_a_list_chained_over_list_more_and_list_last() {
862 use dvb_ci::objects::mmi_high::{List, Menu, Text};
863 let txt = |s: &'static [u8]| Text {
864 length_form: dvb_ci::length::LengthForm::Minimal,
865 more: false,
866 text_chars: s,
867 };
868 let whole = s(&List(Menu {
869 length_form: dvb_ci::length::LengthForm::Minimal,
870 more: false,
871 choice_nb: 2,
872 title: txt(b"Entitlements"),
873 subtitle: txt(b""),
874 bottom: txt(b""),
875 choices: vec![txt(b"ORF AUT"), txt(b"ZDF")],
876 }));
877 let [first, second] = chained(tag::LIST_MORE, tag::LIST_LAST, &whole, 9);
878 let mut h = Mmi::default();
879 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
880 assert_eq!(
881 h.on_apdu(&second).unwrap().notify,
882 vec![Notification::Mmi(MmiEvent::List(MmiMenu {
883 title: "Entitlements".to_string(),
884 subtitle: String::new(),
885 bottom: String::new(),
886 choices: vec!["ORF AUT".to_string(), "ZDF".to_string()],
887 }))]
888 );
889 }
890
891 #[test]
895 fn mmi_chain_past_the_cap_is_refused_with_length_too_large() {
896 fn menu_more(data_len: usize) -> Vec<u8> {
897 let mut apdu = tag::MENU_MORE.to_bytes().to_vec();
898 let mut len = [0u8; 3];
899 let coded = dvb_ci::length::encode_into(data_len, &mut len).unwrap();
900 apdu.extend_from_slice(&len[..coded]);
901 apdu.extend(std::iter::repeat_n(0x00, data_len));
902 apdu
903 }
904
905 let mut h = Mmi::default();
906 assert!(
907 h.on_apdu(&menu_more(MAX_MMI_CHAIN_LEN))
908 .unwrap()
909 .notify
910 .is_empty(),
911 "a chain exactly at the cap is still accepted"
912 );
913 let err = h
914 .on_apdu(&menu_more(1))
915 .expect_err("one byte past the chain cap must be refused");
916 assert_eq!(err, dvb_ci::Error::LengthTooLarge(MAX_MMI_CHAIN_LEN + 1));
917 }
918
919 #[test]
920 fn mmi_discards_a_partial_chain_on_reset() {
921 let mut h = Mmi::default();
922 let first = [0x9F, 0x88, 0x0A, 0x01, 0x02];
923 assert!(h.on_apdu(&first).unwrap().notify.is_empty());
924 h.reset();
925 assert!(h.chain.is_none());
926 }
927
928 #[test]
931 fn mmi_keeps_interleaved_chains_apart() {
932 use dvb_ci::objects::mmi_high::{List, Menu, Text};
933 let txt = |s: &'static [u8]| Text {
934 length_form: dvb_ci::length::LengthForm::Minimal,
935 more: false,
936 text_chars: s,
937 };
938 let part = |t: ApduTag, b: &[u8]| {
939 let mut v = t.to_bytes().to_vec();
940 let mut l = [0u8; 3];
941 let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
942 v.extend_from_slice(&l[..n]);
943 v.extend_from_slice(b);
944 v
945 };
946 let whole = s(&List(Menu {
947 length_form: dvb_ci::length::LengthForm::Minimal,
948 more: false,
949 choice_nb: 1,
950 title: txt(b"Entitlements"),
951 subtitle: txt(b""),
952 bottom: txt(b""),
953 choices: vec![txt(b"ORF AUT")],
954 }));
955 let (len, hdr) = dvb_ci::length::decode(&whole[3..]).unwrap();
956 let body = &whole[3 + hdr..3 + hdr + len];
957
958 let mut h = Mmi::default();
959 assert!(
961 h.on_apdu(&part(tag::MENU_MORE, &[0xFF, 0xFF]))
962 .unwrap()
963 .notify
964 .is_empty()
965 );
966 assert!(
968 h.on_apdu(&part(tag::LIST_MORE, body))
969 .unwrap()
970 .notify
971 .is_empty()
972 );
973 assert_eq!(
974 h.on_apdu(&part(tag::LIST_LAST, &[])).unwrap().notify,
975 vec![Notification::Mmi(MmiEvent::List(MmiMenu {
976 title: "Entitlements".to_string(),
977 subtitle: String::new(),
978 bottom: String::new(),
979 choices: vec!["ORF AUT".to_string()],
980 }))],
981 "the abandoned menu chunk must not be part of the list body"
982 );
983 assert!(h.chain.is_none());
984 }
985
986 #[test]
987 fn mmi_answers_display_control_set_mmi_mode() {
988 use dvb_ci::objects::mmi_display::{DisplayControl, DisplayControlCmd, MmiMode};
989 let mut h = Mmi::default();
990 let dc = s(&DisplayControl {
991 length_form: dvb_ci::length::LengthForm::Minimal,
992 cmd: DisplayControlCmd::SetMmiMode,
993 mmi_mode: Some(MmiMode::HighLevel),
994 });
995 let out = h.on_apdu(&dc).unwrap();
996 assert_eq!(out.apdus, vec![vec![0x9F, 0x88, 0x02, 0x02, 0x01, 0x01]]);
998 assert!(out.notify.is_empty());
999 }
1000
1001 #[test]
1002 fn profile_change_re_enquires() {
1003 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
1004 let out = rm
1005 .on_apdu(&s(
1006 &dvb_ci::objects::resource_manager::ProfileChange::default(),
1007 ))
1008 .unwrap();
1009 assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
1010 }
1011
1012 #[test]
1016 fn resource_manager_does_not_treat_an_unrelated_apdu_as_profile_change() {
1017 use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationType};
1018
1019 let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
1020 rm.on_open().unwrap();
1021 rm.on_apdu(&s(&Profile {
1022 length_form: dvb_ci::length::LengthForm::Minimal,
1023 resources: vec![APPLICATION_INFORMATION],
1024 }))
1025 .unwrap();
1026
1027 let unrelated = s(&ApplicationInfo {
1028 length_form: dvb_ci::length::LengthForm::Minimal,
1029 application_type: ApplicationType::ConditionalAccess,
1030 application_manufacturer: 0x1234,
1031 manufacturer_code: 0x5678,
1032 menu_string: b"Acme CAM",
1033 });
1034 assert_eq!(rm.on_apdu(&unrelated).unwrap(), ResourceOut::default());
1035 assert_eq!(rm.module_resources(), &[APPLICATION_INFORMATION]);
1036
1037 let again = rm
1039 .on_apdu(&s(&Profile {
1040 length_form: dvb_ci::length::LengthForm::Minimal,
1041 resources: vec![],
1042 }))
1043 .unwrap();
1044 assert!(
1045 !again.notify.contains(&Notification::CamReady),
1046 "an unrelated APDU must not clear the ready/profile latch"
1047 );
1048 }
1049
1050 #[test]
1053 fn conditional_access_ignores_an_unrelated_apdu() {
1054 let mut h = ConditionalAccess;
1055 let profile = s(&Profile {
1056 length_form: dvb_ci::length::LengthForm::Minimal,
1057 resources: vec![],
1058 });
1059 assert_eq!(h.on_apdu(&profile).unwrap(), ResourceOut::default());
1060 }
1061
1062 #[test]
1065 fn mmi_ignores_an_unrelated_apdu() {
1066 let mut h = Mmi::default();
1067 assert_eq!(
1068 h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1069 ResourceOut::default()
1070 );
1071 assert!(h.chain.is_none());
1072 }
1073
1074 #[test]
1076 fn host_control_ignores_an_unrelated_apdu() {
1077 let mut h = HostControl;
1078 assert_eq!(
1079 h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1080 ResourceOut::default()
1081 );
1082 }
1083
1084 #[test]
1085 fn application_information_surfaces_notification() {
1086 use dvb_ci::objects::application_info::ApplicationType;
1087 let mut h = ApplicationInformation;
1088 assert_eq!(
1089 h.on_open().unwrap().apdus,
1090 vec![s(&ApplicationInfoEnq::default())]
1091 );
1092 let ai = s(&ApplicationInfo {
1093 length_form: dvb_ci::length::LengthForm::Minimal,
1094 application_type: ApplicationType::ConditionalAccess,
1095 application_manufacturer: 0x1234,
1096 manufacturer_code: 0x5678,
1097 menu_string: b"Acme CAM",
1098 });
1099 let out = h.on_apdu(&ai).unwrap();
1100 assert_eq!(
1101 out.notify,
1102 vec![Notification::ApplicationInfo {
1103 application_type: 0x01,
1104 manufacturer: 0x1234,
1105 code: 0x5678,
1106 menu: "Acme CAM".to_string(),
1107 }]
1108 );
1109 }
1110
1111 #[test]
1112 fn host_control_surfaces_tune_replace_clear_and_ask_release() {
1113 let mut h = HostControl;
1114 assert_eq!(h.id(), HOST_CONTROL);
1115
1116 let tune = s(&Tune {
1118 length_form: dvb_ci::length::LengthForm::Minimal,
1119 network_id: 0x1122,
1120 original_network_id: 0x3344,
1121 transport_stream_id: 0x5566,
1122 service_id: 0x7788,
1123 });
1124 assert_eq!(
1125 h.on_apdu(&tune).unwrap().notify,
1126 vec![Notification::HostControl(HostControlEvent::Tune {
1127 network_id: 0x1122,
1128 original_network_id: 0x3344,
1129 transport_stream_id: 0x5566,
1130 service_id: 0x7788,
1131 })]
1132 );
1133
1134 let replace = s(&Replace {
1136 length_form: dvb_ci::length::LengthForm::Minimal,
1137 replacement_ref: 0x07,
1138 replaced_pid: Pid::from_const(0x0123),
1139 replacement_pid: Pid::from_const(0x01FF),
1140 replaced_reserved: Default::default(),
1141 replacement_reserved: Default::default(),
1142 });
1143 assert_eq!(
1144 h.on_apdu(&replace).unwrap().notify,
1145 vec![Notification::HostControl(HostControlEvent::Replace {
1146 replacement_ref: 0x07,
1147 replaced_pid: Pid::from_const(0x0123),
1148 replacement_pid: Pid::from_const(0x01FF),
1149 })]
1150 );
1151
1152 let clear = s(&ClearReplace {
1154 length_form: dvb_ci::length::LengthForm::Minimal,
1155 replacement_ref: 0x42,
1156 });
1157 assert_eq!(
1158 h.on_apdu(&clear).unwrap().notify,
1159 vec![Notification::HostControl(HostControlEvent::ClearReplace {
1160 replacement_ref: 0x42,
1161 })]
1162 );
1163
1164 let ask = s(&AskRelease::default());
1166 assert_eq!(
1167 h.on_apdu(&ask).unwrap().notify,
1168 vec![Notification::HostControl(HostControlEvent::AskRelease)]
1169 );
1170
1171 assert!(h.on_apdu(&tune).unwrap().apdus.is_empty());
1173 }
1174
1175 #[test]
1176 fn mjd_bcd_encoding_is_correct() {
1177 const SECS_PER_DAY: u64 = 86_400;
1178 assert_eq!(unix_to_mjd_bcd(0), Some([0x9E, 0x8B, 0x00, 0x00, 0x00]));
1180 let secs = SECS_PER_DAY + 13 * 3600 + 45 * 60 + 9;
1182 assert_eq!(unix_to_mjd_bcd(secs), Some([0x9E, 0x8C, 0x13, 0x45, 0x09]));
1183 }
1184
1185 #[test]
1186 fn mjd_bcd_encoding_matches_day_arithmetic_across_the_range() {
1187 const SECS_PER_DAY: u64 = 86_400;
1188 const MJD_UNIX_EPOCH: u64 = 40_587;
1189 const LAST_DAY: u64 = 65_535 - MJD_UNIX_EPOCH;
1190 for day in (0..=LAST_DAY).step_by(37).chain([LAST_DAY]) {
1191 let out = unix_to_mjd_bcd(day * SECS_PER_DAY + 86_399).unwrap();
1192 let mjd = u16::from_be_bytes([out[0], out[1]]);
1193 assert_eq!(u64::from(mjd), MJD_UNIX_EPOCH + day);
1194 assert_eq!(out[2..], [0x23, 0x59, 0x59]);
1195 }
1196 }
1197
1198 #[test]
1199 fn mjd_beyond_its_sixteen_bits_is_refused_not_wrapped() {
1200 assert_eq!(
1203 unix_to_mjd_bcd(2_155_507_200 + 86_399),
1204 Some([0xFF, 0xFF, 0x23, 0x59, 0x59])
1205 );
1206 assert_eq!(unix_to_mjd_bcd(5_417_971_200), None);
1209 }
1210
1211 #[test]
1212 fn date_time_reports_an_unrepresentable_clock_instead_of_a_wrong_date() {
1213 let mut h = DateTime::with_clock(|| None);
1214 let out = h
1215 .on_apdu(&s(&DateTimeEnq {
1216 length_form: dvb_ci::length::LengthForm::Minimal,
1217 response_interval: 0,
1218 }))
1219 .unwrap();
1220 assert!(out.apdus.is_empty());
1221 assert_eq!(out.notify, vec![Notification::ClockUnrepresentable]);
1222 }
1223
1224 #[test]
1225 fn system_clock_is_representable_today() {
1226 let now = std::time::SystemTime::now()
1227 .duration_since(std::time::UNIX_EPOCH)
1228 .unwrap_or_default()
1229 .as_secs();
1230 assert_eq!(system_utc(), unix_to_mjd_bcd(now));
1231 assert!(system_utc().is_some());
1232 }
1233
1234 #[test]
1235 fn date_time_replies_to_enq_and_resends_on_interval() {
1236 let fixed = || Some([0x9E, 0x7B, 0x00, 0x00, 0x00]);
1237 let mut h = DateTime::with_clock(fixed);
1238 let enq = s(&DateTimeEnq {
1240 length_form: dvb_ci::length::LengthForm::Minimal,
1241 response_interval: 5,
1242 });
1243 let out = h.on_apdu(&enq).unwrap();
1244 assert_eq!(out.apdus.len(), 1);
1245 assert_eq!(peek_tag(&out.apdus[0]), Some(tag::DATE_TIME));
1246 assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1248 assert_eq!(h.tick(Duration::from_secs(3)).unwrap().apdus.len(), 1);
1250 }
1251
1252 #[test]
1253 fn date_time_interval_zero_does_not_resend() {
1254 let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1255 h.on_apdu(&s(&DateTimeEnq {
1256 length_form: dvb_ci::length::LengthForm::Minimal,
1257 response_interval: 0,
1258 }))
1259 .unwrap();
1260 assert!(h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty());
1261 }
1262
1263 #[test]
1268 fn date_time_reset_clears_interval_and_resend_timer() {
1269 let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1270 h.on_apdu(&s(&DateTimeEnq {
1271 length_form: dvb_ci::length::LengthForm::Minimal,
1272 response_interval: 5,
1273 }))
1274 .unwrap();
1275 assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1277
1278 h.reset();
1279 assert!(
1283 h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty(),
1284 "reset must clear the resend cadence from the previous module"
1285 );
1286 }
1287
1288 #[test]
1289 fn conditional_access_surfaces_ca_info_and_pmt_reply() {
1290 let mut h = ConditionalAccess;
1291 assert_eq!(h.on_open().unwrap().apdus, vec![s(&CaInfoEnq::default())]);
1292 let ci = s(&CaInfo {
1294 length_form: dvb_ci::length::LengthForm::Minimal,
1295 ca_system_ids: vec![0x0B00, 0x1800],
1296 });
1297 assert_eq!(
1298 h.on_apdu(&ci).unwrap().notify,
1299 vec![Notification::CaInfo {
1300 ca_system_ids: vec![0x0B00, 0x1800],
1301 }]
1302 );
1303 let reply = s(&CaPmtReply {
1305 reserved_ca_enable: Default::default(),
1306 reserved_version: Default::default(),
1307 length_form: dvb_ci::length::LengthForm::Minimal,
1308 program_number: 0x0042,
1309 version_number: 0,
1310 current_next_indicator: true,
1311 ca_enable: Some(CaEnable::Possible),
1312 streams: vec![],
1313 });
1314 assert_eq!(
1315 h.on_apdu(&reply).unwrap().notify,
1316 vec![Notification::CaPmtReply {
1317 program_number: 0x0042,
1318 ca_enable: Some(CaEnable::Possible),
1319 descrambling_ok: true,
1320 }]
1321 );
1322 }
1323
1324 #[test]
1325 fn conditional_access_ca_pmt_reply_flag_clear_surfaces_none() {
1326 let mut h = ConditionalAccess;
1327 h.on_open().unwrap();
1328 let reply = s(&CaPmtReply {
1330 reserved_ca_enable: Default::default(),
1331 reserved_version: Default::default(),
1332 length_form: dvb_ci::length::LengthForm::Minimal,
1333 program_number: 0x0007,
1334 version_number: 0,
1335 current_next_indicator: true,
1336 ca_enable: None,
1337 streams: vec![],
1338 });
1339 assert_eq!(
1340 h.on_apdu(&reply).unwrap().notify,
1341 vec![Notification::CaPmtReply {
1342 program_number: 0x0007,
1343 ca_enable: None,
1344 descrambling_ok: false,
1345 }]
1346 );
1347 }
1348
1349 #[test]
1350 fn short_apdu_returns_err() {
1351 for len in 0..3usize {
1352 let buf = vec![0u8; len];
1353 assert!(Mmi::default().on_apdu(&buf).is_err(), "Mmi len {len}");
1354 assert!(
1355 ResourceManager::new(vec![]).on_apdu(&buf).is_err(),
1356 "RM len {len}"
1357 );
1358 assert!(
1359 ApplicationInformation.on_apdu(&buf).is_err(),
1360 "AI len {len}"
1361 );
1362 assert!(ConditionalAccess.on_apdu(&buf).is_err(), "CA len {len}");
1363 assert!(DateTime::default().on_apdu(&buf).is_err(), "DT len {len}");
1364 assert!(HostControl.on_apdu(&buf).is_err(), "HC len {len}");
1365 }
1366 }
1367
1368 #[test]
1372 fn a_tag_only_apdu_is_accepted_by_every_resource() {
1373 let out = ResourceManager::new(vec![RESOURCE_MANAGER])
1374 .on_apdu(&tag::PROFILE_ENQ.to_bytes())
1375 .unwrap();
1376 assert_eq!(out.apdus.len(), 1, "profile_enq is answered");
1377 assert_eq!(peek_tag(&out.apdus[0]), Some(tag::PROFILE));
1378
1379 assert_eq!(
1380 ApplicationInformation
1381 .on_apdu(&tag::CA_INFO.to_bytes())
1382 .unwrap(),
1383 ResourceOut::default(),
1384 "an unrelated tag-only APDU is ignored, not an error"
1385 );
1386 assert_eq!(
1387 ConditionalAccess
1388 .on_apdu(&tag::APPLICATION_INFO.to_bytes())
1389 .unwrap(),
1390 ResourceOut::default()
1391 );
1392 assert_eq!(
1393 DateTime::default()
1394 .on_apdu(&tag::PROFILE_ENQ.to_bytes())
1395 .unwrap(),
1396 ResourceOut::default()
1397 );
1398 assert_eq!(
1399 Mmi::default().on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1400 ResourceOut::default()
1401 );
1402 assert_eq!(
1403 HostControl.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1404 ResourceOut::default()
1405 );
1406 }
1407}