1use mpeg_ts::pid::Pid;
7use std::collections::{BTreeSet, VecDeque};
8use std::io;
9use std::time::{Duration, Instant};
10
11use broadcast_core::Serialize;
12use dvb_ci::builder::{build_ca_pmt, build_ca_pmt_for_caids};
13use dvb_ci::objects::ca_pmt::{CaPmtCmdId, CaPmtListManagement};
14use dvb_si::tables::cat::CatSection;
15use dvb_si::tables::pmt::PmtSection;
16
17use broadcast_core::Parse;
18
19use crate::device::{CaDevice, MAX_CA_FRAME, SlotInfo};
20use crate::event::{Action, Event, HostRequest, HotPlug, MmiEvent, Notification};
21use crate::managed::{self, CaError, ManagedCa};
22use crate::stack::{CiStack, StackBounds};
23
24const MMI_CARD_ABSENT_KEYWORDS: &[&str] = &[
29 "no card",
30 "insert card",
31 "insert smart card",
32 "card removed",
33 "please insert",
34];
35
36const MMI_CARD_PRESENT_KEYWORDS: &[&str] = &["entitlement", "card valid", "subscription active"];
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct DriverBounds {
45 pub stack: StackBounds,
47 pub max_pending_notifications: usize,
54 pub slot_ready_grace: Duration,
59 pub slot_retry: Duration,
61}
62
63type Clock = Box<dyn Fn() -> Instant>;
68
69fn default_clock() -> Clock {
70 Box::new(Instant::now)
71}
72
73pub struct Driver<D: CaDevice> {
75 device: D,
76 bounds: DriverBounds,
77 stack: CiStack,
78 notifications: VecDeque<Notification>,
79 notifications_dropped: u64,
81 next_timer: Option<Duration>,
83 buf: Vec<u8>,
85 last_slot: Option<SlotInfo>,
92 last_caids: Option<BTreeSet<u16>>,
95 last_descrambling_ok: Option<bool>,
98 last_mmi_card_present: Option<bool>,
104 managed: ManagedCa,
107 last_pump: Option<Instant>,
112 clock: Clock,
114 requery_pending: Option<CaError>,
118 settle_until: Option<Instant>,
122 deferred_writes: Vec<Vec<u8>>,
125 slot_ready_deadline: Option<Instant>,
130}
131
132impl<D: CaDevice> Driver<D> {
133 #[must_use]
135 pub fn new(device: D, bounds: DriverBounds) -> Self {
136 Self {
137 device,
138 bounds,
139 stack: CiStack::new(bounds.stack),
140 notifications: VecDeque::new(),
141 notifications_dropped: 0,
142 next_timer: None,
143 buf: vec![0u8; MAX_CA_FRAME],
144 last_slot: None,
145 last_caids: None,
146 last_descrambling_ok: None,
147 last_mmi_card_present: None,
148 managed: ManagedCa::new(),
149 last_pump: None,
150 clock: default_clock(),
151 requery_pending: None,
152 settle_until: None,
153 deferred_writes: Vec::new(),
154 slot_ready_deadline: None,
155 }
156 }
157
158 #[must_use]
162 pub fn with_clock(mut self, clock: impl Fn() -> Instant + 'static) -> Self {
163 self.clock = Box::new(clock);
164 self
165 }
166
167 pub fn managed_ca(&self) -> &ManagedCa {
170 &self.managed
171 }
172
173 pub fn device(&self) -> &D {
175 &self.device
176 }
177
178 pub fn device_mut(&mut self) -> &mut D {
181 &mut self.device
182 }
183
184 pub fn next_timer(&self) -> Option<Duration> {
186 self.next_timer
187 }
188
189 pub fn take_notifications(&mut self) -> Vec<Notification> {
191 self.notifications.drain(..).collect()
192 }
193
194 pub fn notifications_dropped(&self) -> u64 {
200 self.notifications_dropped
201 }
202
203 fn push_notification(&mut self, n: Notification) {
206 if self.notifications.len() >= self.bounds.max_pending_notifications {
207 self.notifications.pop_front();
208 self.notifications_dropped += 1;
209 }
210 self.notifications.push_back(n);
211 }
212
213 pub fn init(&mut self) -> io::Result<()> {
215 let actions = self.stack.handle(Event::Host(HostRequest::Init));
216 self.run(actions)
217 }
218
219 pub fn send_ca_pmt(&mut self, ca_pmt: &[u8]) -> io::Result<()> {
222 let actions = self
223 .stack
224 .handle(Event::Host(HostRequest::SendCaPmt(ca_pmt)));
225 self.run(actions)
226 }
227
228 fn send_ca_pmt_checked(&mut self, ca_pmt: &[u8]) -> Result<(), CaError> {
229 let before = self.notifications.len();
230 let dropped_before = self.notifications_dropped;
231 self.send_ca_pmt(ca_pmt)?;
232 let start = before.saturating_sub((self.notifications_dropped - dropped_before) as usize);
233 let refusal = self.notifications.range(start..).find_map(|n| match n {
234 Notification::Error { detail } => Some(detail.clone()),
235 _ => None,
236 });
237 refusal.map_or(Ok(()), |detail| Err(CaError::NotSent { detail }))
238 }
239
240 pub fn descramble(&mut self, pmt_section: &[u8]) -> io::Result<()> {
246 let actions = self
247 .stack
248 .handle(Event::Host(HostRequest::Descramble(pmt_section)));
249 self.run(actions)
250 }
251
252 pub fn descramble_programs(&mut self, pmt_sections: &[&[u8]]) -> io::Result<()> {
255 let actions = self
256 .stack
257 .handle(Event::Host(HostRequest::DescramblePrograms(pmt_sections)));
258 self.run(actions)
259 }
260
261 pub fn add_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
264 let actions = self
265 .stack
266 .handle(Event::Host(HostRequest::AddProgram(pmt_section)));
267 self.run(actions)
268 }
269
270 pub fn remove_program(&mut self, pmt_section: &[u8]) -> io::Result<()> {
273 let actions = self
274 .stack
275 .handle(Event::Host(HostRequest::RemoveProgram(pmt_section)));
276 self.run(actions)
277 }
278
279 fn build_ca_pmt_filtered(
291 &self,
292 pmt: &PmtSection<'_>,
293 list_management: CaPmtListManagement,
294 cmd_id: CaPmtCmdId,
295 ) -> dvb_ci::builder::CaPmtBuilt {
296 let cam_caids = self.managed.cam_caids();
297 if cam_caids.is_empty() {
298 build_ca_pmt(pmt, list_management, cmd_id)
299 } else {
300 let allowed: Vec<u16> = cam_caids.iter().copied().collect();
301 build_ca_pmt_for_caids(pmt, &allowed, list_management, cmd_id)
302 }
303 }
304
305 fn build_service_bytes(
314 &self,
315 pmt: &PmtSection<'_>,
316 list_management: CaPmtListManagement,
317 cmd_id: CaPmtCmdId,
318 ) -> Result<(Vec<u8>, Vec<u8>), CaError> {
319 if !managed::pmt_has_ca(pmt) {
320 return Err(CaError::NoCaDescriptor {
321 program_number: pmt.program_number,
322 });
323 }
324 let built_bytes = self
326 .build_ca_pmt_filtered(pmt, list_management, cmd_id)
327 .to_bytes()?;
328 let mut pmt_raw = vec![0u8; pmt.serialized_len()];
329 let n = pmt.serialize_into(&mut pmt_raw)?;
330 pmt_raw.truncate(n);
331 Ok((built_bytes, pmt_raw))
332 }
333
334 pub fn add_service(&mut self, pmt: &PmtSection<'_>) -> Result<(), CaError> {
356 let list_management = if self.managed.is_empty() {
357 CaPmtListManagement::Only
358 } else {
359 CaPmtListManagement::Add
360 };
361 let cmd_id = CaPmtCmdId::OkDescrambling;
362 let (built_bytes, pmt_raw) = self.build_service_bytes(pmt, list_management, cmd_id)?;
363 self.send_ca_pmt_checked(&built_bytes)?;
364 self.managed.record(
365 pmt.program_number,
366 managed::service_of(pmt, cmd_id, built_bytes, pmt_raw),
367 );
368 Ok(())
369 }
370
371 pub fn update_service(&mut self, pmt: &PmtSection<'_>) -> Result<(), CaError> {
396 if !self.managed.services().contains_key(&pmt.program_number) {
397 return Err(CaError::NotManaged {
398 program_number: pmt.program_number,
399 });
400 }
401 let list_management = CaPmtListManagement::Update;
402 let cmd_id = CaPmtCmdId::OkDescrambling;
403 let (built_bytes, pmt_raw) = self.build_service_bytes(pmt, list_management, cmd_id)?;
404 self.send_ca_pmt_checked(&built_bytes)?;
405 self.managed.record(
406 pmt.program_number,
407 managed::service_of(pmt, cmd_id, built_bytes, pmt_raw),
408 );
409 Ok(())
410 }
411
412 pub fn remove_service(&mut self, program_number: u16) -> Result<(), CaError> {
426 let raw = self
427 .managed
428 .services()
429 .get(&program_number)
430 .map(|s| s.pmt_raw.clone());
431 let Some(raw) = raw else {
432 return Ok(());
433 };
434 self.remove_program(&raw)?;
435 self.managed.remove(program_number);
436 Ok(())
437 }
438
439 pub fn set_requery_interval(&mut self, interval: Duration) {
448 self.managed.set_requery_interval(interval);
449 }
450
451 pub fn set_cat(&mut self, cat: &CatSection<'_>) -> Result<(), CaError> {
466 let entries = cat.ca_descriptors().map_err(CaError::Cat)?;
467 self.managed.set_cat(&entries);
468 Ok(())
469 }
470
471 #[must_use]
475 pub fn emm_pids(&self) -> &[Pid] {
476 self.managed.emm_pids()
477 }
478
479 #[must_use]
482 pub fn descramble_pids(&self) -> &[Pid] {
483 self.managed.descramble_pids()
484 }
485
486 #[must_use]
491 pub fn ca_pids(&self) -> &[Pid] {
492 self.managed.ca_pids()
493 }
494
495 #[must_use]
503 pub fn required_pids(&self) -> Vec<Pid> {
504 self.managed.required_pids()
505 }
506
507 pub fn mmi_menu_answer(&mut self, choice_ref: u8) -> io::Result<()> {
509 let actions = self
510 .stack
511 .handle(Event::Host(HostRequest::MmiMenuAnswer(choice_ref)));
512 self.run(actions)
513 }
514
515 pub fn mmi_enquiry_answer(&mut self, text: &[u8]) -> io::Result<()> {
517 let actions = self
518 .stack
519 .handle(Event::Host(HostRequest::MmiEnquiryAnswer(text)));
520 self.run(actions)
521 }
522
523 pub fn mmi_cancel(&mut self) -> io::Result<()> {
525 let actions = self.stack.handle(Event::Host(HostRequest::MmiCancel));
526 self.run(actions)
527 }
528
529 pub fn enter_menu(&mut self) -> io::Result<()> {
532 let actions = self.stack.handle(Event::Host(HostRequest::EnterMenu));
533 self.run(actions)
534 }
535
536 pub fn pump(&mut self, timeout: Duration) -> io::Result<bool> {
545 let now = (self.clock)();
556 let measured = self.last_pump.is_some();
557 let mut elapsed = self
558 .last_pump
559 .map_or(timeout, |prev| now.saturating_duration_since(prev));
560 self.last_pump = Some(now);
561
562 if let Some(until) = self.settle_until {
567 if now < until {
568 self.run(vec![Action::QuerySlot])?;
569 return Ok(false);
570 }
571 self.settle_until = None;
572 let mut pending = std::mem::take(&mut self.deferred_writes).into_iter();
573 while let Some(w) = pending.next() {
574 match self.device.write(&w) {
575 Ok(()) => {}
576 Err(e)
581 if e.kind() == io::ErrorKind::InvalidInput
582 && self.slot_ready_deadline.is_some_and(|d| now < d) =>
583 {
584 self.deferred_writes = std::iter::once(w).chain(pending).collect();
585 self.settle_until = Some(now + self.bounds.slot_retry);
586 return Ok(false);
587 }
588 Err(e) => return Err(e),
589 }
590 }
591 self.slot_ready_deadline = None;
592 elapsed = Duration::ZERO;
595 }
596
597 self.run(vec![Action::QuerySlot])?;
598 if self.device.poll(timeout)? {
599 let n = self.device.read(&mut self.buf)?;
600 if n > 0 {
601 let actions = self.stack.handle(Event::Readable(&self.buf[..n]));
605 self.run(actions)?;
606 if measured && !elapsed.is_zero() {
607 let actions = self.stack.handle(Event::Tick { elapsed });
608 self.run(actions)?;
609 self.requery_tick(elapsed)?;
610 }
611 return Ok(true);
612 }
613 }
614 let actions = self.stack.handle(Event::Tick { elapsed });
615 self.run(actions)?;
616 self.requery_tick(elapsed)?;
617 Ok(false)
618 }
619
620 fn requery_tick(&mut self, elapsed: Duration) -> io::Result<()> {
664 if let Some(err) = self.requery_pending.take() {
668 return Err(io::Error::other(err));
669 }
670 if !self.managed.tick(elapsed) {
671 return Ok(());
672 }
673 let mut ca_pmts: Vec<(Vec<u8>, Vec<u8>)> =
674 Vec::with_capacity(self.managed.services().len());
675 for s in self.managed.services().values() {
676 let outcome: Result<(Vec<u8>, Vec<u8>), CaError> = (|| {
681 let pmt = PmtSection::parse(&s.pmt_raw).map_err(CaError::PmtParse)?;
682 let query = self
683 .build_ca_pmt_filtered(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
684 .to_bytes()?;
685 let ok_descrambling = self
686 .build_ca_pmt_filtered(
687 &pmt,
688 CaPmtListManagement::Update,
689 CaPmtCmdId::OkDescrambling,
690 )
691 .to_bytes()?;
692 Ok((query, ok_descrambling))
693 })();
694 match outcome {
695 Ok(pair) => ca_pmts.push(pair),
696 Err(err) => {
697 self.requery_pending = Some(err);
701 }
702 }
703 }
704 for (query, ok_descrambling) in ca_pmts {
705 self.send_ca_pmt(&query)?;
706 self.send_ca_pmt(&ok_descrambling)?;
707 }
708 if let Some(err) = self.requery_pending.take() {
709 return Err(io::Error::other(err));
710 }
711 Ok(())
712 }
713
714 pub fn pump_with<F: FnMut(&Notification)>(
723 &mut self,
724 timeout: Duration,
725 mut handler: F,
726 ) -> io::Result<bool> {
727 let progressed = self.pump(timeout)?;
728 for n in self.take_notifications() {
729 handler(&n);
730 }
731 Ok(progressed)
732 }
733
734 pub fn pump_hotplug<F: FnMut(HotPlug)>(
738 &mut self,
739 timeout: Duration,
740 mut handler: F,
741 ) -> io::Result<bool> {
742 self.pump_with(timeout, |n| {
743 if let Some(h) = n.hotplug() {
744 handler(h);
745 }
746 })
747 }
748
749 fn run(&mut self, actions: Vec<Action>) -> io::Result<()> {
751 for action in actions {
752 match action {
753 Action::Write(bytes) => {
754 if self.settle_until.is_some() {
755 self.deferred_writes.push(bytes);
756 } else {
757 self.device.write(&bytes)?;
758 }
759 }
760 Action::Reset => {
761 self.device.reset()?;
762 self.deferred_writes.clear();
765 let settle = self.device.reset_settle();
766 let now = (self.clock)();
767 self.settle_until = (!settle.is_zero()).then(|| now + settle);
768 self.slot_ready_deadline =
769 (!settle.is_zero()).then(|| now + settle + self.bounds.slot_ready_grace);
770 }
771 Action::QuerySlot => {
772 let info = self.device.slot_info()?;
773 self.handle_slot_info(info)?;
774 }
775 Action::SetTimer { after } => self.next_timer = Some(after),
776 Action::Notify(n) => {
777 let inferred = self.infer_card(&n);
778 self.push_notification(n);
779 for note in inferred {
780 self.push_notification(note);
781 }
782 }
783 }
784 }
785 Ok(())
786 }
787
788 fn handle_slot_info(&mut self, info: SlotInfo) -> io::Result<()> {
795 let prev = self.last_slot.replace(info);
796 match prev {
797 Some(prev) if !prev.module_present && info.module_present => {
798 self.push_notification(Notification::HotPlug(HotPlug::CamPresent));
799 self.reset_module_state();
800 let actions = self.stack.handle(Event::Host(HostRequest::Init));
804 self.run(actions)?;
805 }
806 Some(prev) if prev.module_present && !info.module_present => {
807 self.push_notification(Notification::HotPlug(HotPlug::CamRemoved));
808 self.reset_module_state();
809 }
810 _ => {}
811 }
812 Ok(())
813 }
814
815 fn reset_module_state(&mut self) {
825 self.stack = CiStack::new(self.bounds.stack);
826 self.settle_until = None;
827 self.slot_ready_deadline = None;
828 self.deferred_writes.clear();
829 self.next_timer = None;
830 self.last_caids = None;
831 self.last_descrambling_ok = None;
832 self.last_mmi_card_present = None;
833 self.managed.clear();
834 }
835
836 fn infer_card(&mut self, note: &Notification) -> Vec<Notification> {
843 match note {
844 Notification::CaInfo { ca_system_ids } => {
845 let new_set: BTreeSet<u16> = ca_system_ids.iter().copied().collect();
846 let mut out = Vec::new();
847 if let Some(prev) = &self.last_caids {
848 if prev.is_empty() && !new_set.is_empty() {
849 out.push(Notification::HotPlug(HotPlug::CardInserted));
850 } else if !prev.is_empty() && new_set.is_empty() {
851 out.push(Notification::HotPlug(HotPlug::CardRemoved));
852 } else if !prev.is_empty() && !new_set.is_empty() && *prev != new_set {
853 out.push(Notification::HotPlug(HotPlug::CardChanged));
854 }
855 }
856 self.managed.set_cam_caids(new_set.clone());
860 self.last_caids = Some(new_set);
861 out
862 }
863 Notification::CaPmtReply {
864 program_number,
865 ca_enable,
866 descrambling_ok,
867 } => {
868 let mut out = Vec::new();
869 if let Some(prev) = self.last_descrambling_ok {
870 if !prev && *descrambling_ok {
871 out.push(Notification::HotPlug(HotPlug::CardInserted));
872 } else if prev && !*descrambling_ok {
873 out.push(Notification::HotPlug(HotPlug::CardRemoved));
874 }
875 }
876 self.last_descrambling_ok = Some(*descrambling_ok);
877 if let Some((v, ok)) =
881 self.managed
882 .record_reply(*program_number, *ca_enable, *descrambling_ok)
883 {
884 out.push(Notification::Entitlement {
885 program_number: *program_number,
886 ca_enable: v,
887 descrambling_ok: ok,
888 });
889 }
890 out
891 }
892 Notification::Mmi(ev) => {
893 let present = Self::mmi_text(ev).and_then(|text| {
894 let lower = text.to_lowercase();
895 if MMI_CARD_ABSENT_KEYWORDS.iter().any(|k| lower.contains(k)) {
896 Some(false)
897 } else if MMI_CARD_PRESENT_KEYWORDS.iter().any(|k| lower.contains(k)) {
898 Some(true)
899 } else {
900 None
901 }
902 });
903 match present {
904 Some(p) if self.last_mmi_card_present != Some(p) => {
906 self.last_mmi_card_present = Some(p);
907 vec![Notification::HotPlug(if p {
908 HotPlug::CardInserted
909 } else {
910 HotPlug::CardRemoved
911 })]
912 }
913 _ => Vec::new(),
914 }
915 }
916 _ => Vec::new(),
917 }
918 }
919
920 fn mmi_text(ev: &MmiEvent) -> Option<String> {
924 match ev {
925 MmiEvent::Menu(m) | MmiEvent::List(m) => {
926 let mut s = format!("{} {} {}", m.title, m.subtitle, m.bottom);
927 for choice in &m.choices {
928 s.push(' ');
929 s.push_str(choice);
930 }
931 Some(s)
932 }
933 MmiEvent::Enquiry { prompt, .. } => Some(prompt.clone()),
934 MmiEvent::Close => None,
935 }
936 }
937}
938
939#[cfg(test)]
940pub(crate) mod tests {
941 use super::*;
942 use crate::device::{DeviceOp, MockCaDevice};
943 use crate::event::{HostControlEvent, HotPlug, Notification};
944 use crate::test_support::*;
945 use broadcast_core::Serialize;
946 use dvb_ci::tpdu::tags;
947
948 pub(crate) fn ser<S: Serialize>(s: &S) -> Vec<u8> {
949 let mut b = vec![0u8; s.serialized_len()];
950 match s.serialize_into(&mut b) {
951 Ok(n) => b.truncate(n),
952 Err(_) => b.clear(),
953 }
954 b
955 }
956
957 #[derive(Clone)]
963 pub(crate) struct TestClock(std::rc::Rc<std::cell::Cell<Instant>>);
964
965 impl TestClock {
966 pub(crate) fn new() -> Self {
967 Self(std::rc::Rc::new(std::cell::Cell::new(Instant::now())))
968 }
969
970 pub(crate) fn advance(&self, d: Duration) {
972 self.0.set(self.0.get() + d);
973 }
974
975 pub(crate) fn as_fn(&self) -> impl Fn() -> Instant + 'static {
977 let cell = self.0.clone();
978 move || cell.get()
979 }
980 }
981
982 fn r_data(tcid: u8, spdu: &[u8]) -> Vec<u8> {
985 use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
986 let mut v = vec![tpdu_tags::DATA_LAST, (1 + spdu.len()) as u8, tcid];
987 v.extend_from_slice(spdu);
988 v.extend_from_slice(&[tpdu_tags::SB, 0x02, tcid, SbValue::new(false).0]);
989 v
990 }
991
992 pub(crate) fn r_apdu(session_nb: u16, apdu: &[u8]) -> Vec<u8> {
995 use dvb_ci::spdu::SessionNumber;
996 let mut spdu = ser(&SessionNumber {
997 length_form: dvb_ci::length::LengthForm::Minimal,
998 session_nb,
999 });
1000 spdu.extend_from_slice(apdu);
1001 r_data(1, &spdu)
1002 }
1003
1004 pub(crate) fn sb() -> Vec<u8> {
1007 use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
1008 vec![tpdu_tags::SB, 0x02, 0x01, SbValue::new(false).0]
1009 }
1010
1011 pub(crate) fn feed(d: &mut Driver<MockCaDevice>, frame: Vec<u8>) {
1014 d.device_mut().inbound.push_back(frame);
1015 d.pump(Duration::from_millis(10)).unwrap();
1016 for _ in 0..8 {
1017 d.device_mut().inbound.push_back(sb());
1018 d.pump(Duration::from_millis(10)).unwrap();
1019 }
1020 }
1021
1022 pub(crate) fn driver_with_sessions() -> Driver<MockCaDevice> {
1026 use dvb_ci::objects::resource_manager::Profile;
1027 use dvb_ci::resource::{
1028 APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, HOST_CONTROL, MMI,
1029 RESOURCE_MANAGER,
1030 };
1031 use dvb_ci::spdu::{CreateSessionResponse, OpenSessionRequest, SessionStatus};
1032
1033 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1034 d.init().unwrap();
1035 feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1037 feed(
1039 &mut d,
1040 r_data(
1041 1,
1042 &ser(&OpenSessionRequest {
1043 length_form: dvb_ci::length::LengthForm::Minimal,
1044 resource: RESOURCE_MANAGER,
1045 }),
1046 ),
1047 );
1048 feed(
1051 &mut d,
1052 r_apdu(
1053 1,
1054 &ser(&Profile {
1055 length_form: dvb_ci::length::LengthForm::Minimal,
1056 resources: vec![
1057 APPLICATION_INFORMATION,
1058 CONDITIONAL_ACCESS_SUPPORT,
1059 MMI,
1060 HOST_CONTROL,
1061 ],
1062 }),
1063 ),
1064 );
1065 for (nb, res) in [
1067 (2u16, APPLICATION_INFORMATION),
1068 (3, CONDITIONAL_ACCESS_SUPPORT),
1069 (4, MMI),
1070 (5, HOST_CONTROL),
1071 ] {
1072 feed(
1073 &mut d,
1074 r_data(
1075 1,
1076 &ser(&CreateSessionResponse {
1077 length_form: dvb_ci::length::LengthForm::Minimal,
1078 status: SessionStatus::Ok,
1079 resource: res,
1080 session_nb: nb,
1081 }),
1082 ),
1083 );
1084 }
1085 d
1086 }
1087
1088 const RM_SESSION: u16 = 1;
1092 pub(crate) const CA_SESSION: u16 = 3;
1093 const MMI_SESSION: u16 = 4;
1094 const HOST_CONTROL_SESSION: u16 = 5;
1095
1096 #[test]
1097 fn host_control_tune_apdu_surfaces_notification_via_driver() {
1098 use dvb_ci::objects::host_control::Tune;
1099
1100 let mut d = driver_with_sessions();
1101 let hc_nb = HOST_CONTROL_SESSION;
1102 d.take_notifications(); let tune = Tune {
1106 length_form: dvb_ci::length::LengthForm::Minimal,
1107 network_id: 0x1122,
1108 original_network_id: 0x3344,
1109 transport_stream_id: 0x5566,
1110 service_id: 0x7788,
1111 };
1112 feed(&mut d, r_apdu(hc_nb, &ser(&tune)));
1113
1114 let notes = d.take_notifications();
1116 assert!(
1117 notes.contains(&Notification::HostControl(HostControlEvent::Tune {
1118 network_id: 0x1122,
1119 original_network_id: 0x3344,
1120 transport_stream_id: 0x5566,
1121 service_id: 0x7788,
1122 })),
1123 "expected HostControl(Tune) notification, got {notes:?}"
1124 );
1125 }
1126
1127 #[test]
1130 fn padded_tune_from_the_cam_surfaces_an_error_notification() {
1131 let mut d = driver_with_sessions();
1132 d.take_notifications();
1133 let padded = [
1135 0x9F, 0x84, 0x00, 0x09, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xEE,
1136 ];
1137 feed(&mut d, r_apdu(HOST_CONTROL_SESSION, &padded));
1138 let notes = d.take_notifications();
1139 assert!(
1140 notes.iter().any(
1141 |n| matches!(n, Notification::Error { detail } if detail.contains("trailing bytes"))
1142 ),
1143 "expected an Error notification naming the trailing bytes, got {notes:?}"
1144 );
1145 assert!(
1146 !notes
1147 .iter()
1148 .any(|n| matches!(n, Notification::HostControl(_))),
1149 "a refused tune must not also surface as a HostControl event: {notes:?}"
1150 );
1151 }
1152
1153 #[test]
1156 fn malformed_mmi_apdu_from_the_cam_surfaces_an_error_notification() {
1157 let mut d = driver_with_sessions();
1158 d.take_notifications();
1159 feed(&mut d, r_apdu(MMI_SESSION, &[0x9F, 0x88, 0x07, 0x01, 0x00]));
1161 let notes = d.take_notifications();
1162 assert!(
1163 notes
1164 .iter()
1165 .any(|n| matches!(n, Notification::Error { .. })),
1166 "expected an Error notification, got {notes:?}"
1167 );
1168 }
1169
1170 #[test]
1171 fn profile_reply_advertises_host_control() {
1172 use broadcast_core::Parse;
1173 use dvb_ci::objects::resource_manager::{Profile, ProfileEnq};
1174 use dvb_ci::resource::{HOST_CONTROL, RESOURCE_MANAGER};
1175
1176 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1177 d.init().unwrap();
1178 feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1179 feed(
1180 &mut d,
1181 r_data(
1182 1,
1183 &ser(&dvb_ci::spdu::OpenSessionRequest {
1184 length_form: dvb_ci::length::LengthForm::Minimal,
1185 resource: RESOURCE_MANAGER,
1186 }),
1187 ),
1188 );
1189 feed(&mut d, r_apdu(RM_SESSION, &ser(&ProfileEnq::default())));
1191
1192 let want = dvb_ci::tag::PROFILE.to_bytes();
1195 let found = d.device().ops.iter().any(|op| {
1196 if let DeviceOp::Write(w) = op
1197 && let Some(pos) = w.windows(3).position(|x| x == want)
1198 && let Ok(p) = Profile::parse(&w[pos..])
1199 {
1200 return p.resources.contains(&HOST_CONTROL);
1201 }
1202 false
1203 });
1204 assert!(found, "profile reply must advertise HOST_CONTROL");
1205 }
1206
1207 #[test]
1208 fn mmi_menu_answ_and_answ_are_byte_exact_on_the_mmi_session() {
1209 use dvb_ci::objects::mmi_high::{Answ, AnswId, MenuAnsw};
1210
1211 let mut d = driver_with_sessions();
1212 let mmi_nb = MMI_SESSION;
1213
1214 d.mmi_menu_answer(2).unwrap();
1217 d.device_mut().inbound.push_back(sb());
1218 d.pump(Duration::from_millis(10)).unwrap();
1219 assert_apdu_on_session(
1220 &d,
1221 mmi_nb,
1222 &ser(&MenuAnsw {
1223 length_form: dvb_ci::length::LengthForm::Minimal,
1224 choice_ref: 2,
1225 }),
1226 );
1227
1228 d.mmi_enquiry_answer(b"1234").unwrap();
1230 d.device_mut().inbound.push_back(sb());
1231 d.pump(Duration::from_millis(10)).unwrap();
1232 assert_apdu_on_session(
1233 &d,
1234 mmi_nb,
1235 &ser(&Answ {
1236 length_form: dvb_ci::length::LengthForm::Minimal,
1237 answ_id: AnswId::Answer,
1238 text_chars: b"1234",
1239 }),
1240 );
1241 }
1242
1243 fn assert_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) {
1246 use dvb_ci::spdu::SessionNumber;
1247 let mut want = ser(&SessionNumber {
1248 length_form: dvb_ci::length::LengthForm::Minimal,
1249 session_nb,
1250 });
1251 want.extend_from_slice(apdu);
1252 let hit = d.device().ops.iter().any(|op| match op {
1253 DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1254 _ => false,
1255 });
1256 assert!(
1257 hit,
1258 "expected APDU {apdu:02X?} on session {session_nb} (session-prefixed {want:02X?}) in writes"
1259 );
1260 }
1261
1262 fn count_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) -> usize {
1266 use dvb_ci::spdu::SessionNumber;
1267 let mut want = ser(&SessionNumber {
1268 length_form: dvb_ci::length::LengthForm::Minimal,
1269 session_nb,
1270 });
1271 want.extend_from_slice(apdu);
1272 d.device()
1273 .ops
1274 .iter()
1275 .filter(|op| match op {
1276 DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1277 _ => false,
1278 })
1279 .count()
1280 }
1281
1282 struct SettleDevice {
1285 inner: MockCaDevice,
1286 settle: Duration,
1287 }
1288
1289 impl CaDevice for SettleDevice {
1290 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1291 self.inner.read(buf)
1292 }
1293 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1294 self.inner.write(buf)
1295 }
1296 fn reset(&mut self) -> io::Result<()> {
1297 self.inner.reset()
1298 }
1299 fn reset_settle(&self) -> Duration {
1300 self.settle
1301 }
1302 fn slot_info(&mut self) -> io::Result<SlotInfo> {
1303 self.inner.slot_info()
1304 }
1305 fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1306 self.inner.poll(timeout)
1307 }
1308 }
1309
1310 const SETTLE: Duration = Duration::from_secs(3);
1311
1312 fn settling_driver(clock: &TestClock) -> Driver<SettleDevice> {
1313 Driver::new(
1314 SettleDevice {
1315 inner: MockCaDevice::new([]),
1316 settle: SETTLE,
1317 },
1318 DRIVER,
1319 )
1320 .with_clock(clock.as_fn())
1321 }
1322
1323 fn create_tc_writes(d: &Driver<SettleDevice>) -> usize {
1324 d.device()
1325 .inner
1326 .ops
1327 .iter()
1328 .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1329 .count()
1330 }
1331
1332 struct NotRunningDevice {
1336 inner: SettleDevice,
1337 refusals_left: u32,
1338 refused: u32,
1339 }
1340
1341 impl CaDevice for NotRunningDevice {
1342 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1343 self.inner.read(buf)
1344 }
1345 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1346 if self.refusals_left > 0 {
1347 self.refusals_left -= 1;
1348 self.refused += 1;
1349 return Err(io::Error::from(io::ErrorKind::InvalidInput));
1350 }
1351 self.inner.write(buf)
1352 }
1353 fn reset(&mut self) -> io::Result<()> {
1354 self.inner.reset()
1355 }
1356 fn reset_settle(&self) -> Duration {
1357 self.inner.reset_settle()
1358 }
1359 fn slot_info(&mut self) -> io::Result<SlotInfo> {
1360 self.inner.slot_info()
1361 }
1362 fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1363 self.inner.poll(timeout)
1364 }
1365 }
1366
1367 fn not_running_driver(clock: &TestClock, refusals: u32) -> Driver<NotRunningDevice> {
1368 Driver::new(
1369 NotRunningDevice {
1370 inner: SettleDevice {
1371 inner: MockCaDevice::new([]),
1372 settle: SETTLE,
1373 },
1374 refusals_left: refusals,
1375 refused: 0,
1376 },
1377 DRIVER,
1378 )
1379 .with_clock(clock.as_fn())
1380 }
1381
1382 fn create_tc_count(d: &Driver<NotRunningDevice>) -> usize {
1383 d.device()
1384 .inner
1385 .inner
1386 .ops
1387 .iter()
1388 .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1389 .count()
1390 }
1391
1392 #[test]
1397 fn post_reset_einval_is_retried_until_the_slot_is_running() {
1398 let clock = TestClock::new();
1399 let mut d = not_running_driver(&clock, 3);
1400 d.init().unwrap();
1401 clock.advance(SETTLE + Duration::from_millis(100));
1402 for _ in 0..10 {
1403 d.pump(Duration::from_millis(10))
1404 .expect("a not-yet-RUNNING slot (EINVAL) must be retried, not reported");
1405 if create_tc_count(&d) == 1 {
1406 break;
1407 }
1408 clock.advance(Duration::from_millis(300));
1409 }
1410 assert_eq!(d.device().refused, 3, "the three refusals were consumed");
1411 assert_eq!(create_tc_count(&d), 1, "Create_T_C delivered exactly once");
1412 }
1413
1414 #[test]
1417 fn post_reset_einval_is_reported_once_the_grace_window_has_passed() {
1418 let clock = TestClock::new();
1419 let mut d = not_running_driver(&clock, u32::MAX);
1420 let start = clock.0.get();
1421 d.init().unwrap();
1422 clock.advance(SETTLE + Duration::from_millis(100));
1423 let mut failure = None;
1424 for _ in 0..80 {
1425 match d.pump(Duration::from_millis(10)) {
1426 Ok(_) => clock.advance(Duration::from_millis(300)),
1427 Err(e) => {
1428 failure = Some(e);
1429 break;
1430 }
1431 }
1432 }
1433 let e = failure.expect("a slot that never runs must eventually be reported");
1434 assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
1435 assert!(
1436 clock.0.get() >= start + SETTLE + SLOT_READY_GRACE,
1437 "reported before the grace window ended"
1438 );
1439 assert_eq!(create_tc_count(&d), 0);
1440 }
1441
1442 #[test]
1447 fn requery_armed_before_the_handshake_sends_nothing() {
1448 let clock = TestClock::new();
1449 let mut d = Driver::new(MockCaDevice::new([]), DRIVER).with_clock(clock.as_fn());
1450 d.set_requery_interval(Duration::from_secs(10));
1451 d.init().unwrap();
1452 for _ in 0..40 {
1453 clock.advance(Duration::from_secs(1));
1454 d.pump(Duration::from_millis(100)).unwrap();
1455 }
1456 let ca_pmt_tag = [0x9F, 0x80, 0x32];
1457 let ca_pmt_writes = d
1458 .device()
1459 .ops
1460 .iter()
1461 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == ca_pmt_tag)))
1462 .count();
1463 assert_eq!(
1464 ca_pmt_writes, 0,
1465 "re-query wrote a ca_pmt before any service"
1466 );
1467 }
1468
1469 #[test]
1472 fn reset_does_not_block_pump() {
1473 let clock = TestClock::new();
1474 let mut d = settling_driver(&clock);
1475 let t = std::time::Instant::now();
1476 d.init().unwrap();
1477 d.pump(Duration::from_millis(10)).unwrap();
1478 assert!(t.elapsed() < Duration::from_secs(1), "reset/pump blocked");
1479 assert_eq!(d.device().inner.ops[0], DeviceOp::Reset);
1480 }
1481
1482 #[test]
1486 fn no_transport_traffic_until_settle_elapsed() {
1487 let clock = TestClock::new();
1488 let mut d = settling_driver(&clock);
1489 d.device_mut()
1490 .inner
1491 .inbound
1492 .push_back(vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1493 d.init().unwrap();
1494 for _ in 0..5 {
1495 clock.advance(Duration::from_millis(500));
1496 d.pump(Duration::from_millis(10)).unwrap();
1497 }
1498 assert_eq!(create_tc_writes(&d), 0);
1500 assert_eq!(
1501 d.device().inner.inbound.len(),
1502 1,
1503 "frame read while settling"
1504 );
1505
1506 clock.advance(Duration::from_millis(600));
1507 d.pump(Duration::from_millis(10)).unwrap();
1508 assert_eq!(create_tc_writes(&d), 1);
1509
1510 let mut z = Driver::new(MockCaDevice::new([]), DRIVER);
1511 z.init().unwrap();
1512 assert_eq!(
1513 d.device().inner.written()[..3],
1514 z.device().written()[..3],
1515 "post-settle Create_T_C differs from the zero-settle sequence"
1516 );
1517 assert!(d.device().inner.inbound.is_empty());
1520 }
1521
1522 #[test]
1525 fn second_reset_restarts_settle() {
1526 let clock = TestClock::new();
1527 let mut d = settling_driver(&clock);
1528 d.init().unwrap();
1529 clock.advance(Duration::from_secs(2));
1530 d.pump(Duration::from_millis(10)).unwrap();
1531 d.init().unwrap(); clock.advance(Duration::from_secs(2)); d.pump(Duration::from_millis(10)).unwrap();
1534 assert_eq!(create_tc_writes(&d), 0, "first deadline wrongly honoured");
1535 clock.advance(Duration::from_millis(1500)); d.pump(Duration::from_millis(10)).unwrap();
1537 assert_eq!(create_tc_writes(&d), 1);
1538 }
1539
1540 #[test]
1543 fn slot_sampling_continues_while_settling() {
1544 let clock = TestClock::new();
1545 let mut d = settling_driver(&clock);
1546 d.init().unwrap();
1547 d.take_notifications();
1548 d.device_mut().inner.slot.module_present = false;
1549 clock.advance(Duration::from_millis(500));
1550 d.pump(Duration::from_millis(10)).unwrap();
1551 let notes = d.take_notifications();
1552 assert!(
1553 notes
1554 .iter()
1555 .any(|n| matches!(n, Notification::HotPlug(HotPlug::CamRemoved))),
1556 "{notes:?}"
1557 );
1558 assert_eq!(create_tc_writes(&d), 0);
1559 }
1560
1561 #[test]
1562 fn init_drives_reset_slotinfo_and_create_tc_to_device() {
1563 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1564 d.init().unwrap();
1565 let ops = &d.device().ops;
1566 assert_eq!(ops[0], DeviceOp::Reset);
1567 assert_eq!(ops[1], DeviceOp::SlotInfo);
1568 assert!(matches!(&ops[2], DeviceOp::Write(w) if w[0] == tags::CREATE_T_C));
1569 }
1570
1571 #[test]
1572 fn reads_reply_then_polls_on_pump() {
1573 let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1575 let clock = TestClock::new();
1576 let mut d = Driver::new(dev, DRIVER).with_clock(clock.as_fn());
1577 d.init().unwrap();
1578 assert!(d.pump(Duration::from_millis(100)).unwrap());
1580 clock.advance(Duration::from_millis(100));
1585 assert!(!d.pump(Duration::from_millis(100)).unwrap());
1587 let last = d.device().ops.last().unwrap();
1588 assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1589 }
1590
1591 #[test]
1597 fn pump_advances_the_stack_clock_by_real_elapsed_time_not_by_timeout() {
1598 let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1599 let clock = TestClock::new();
1600 let mut d = Driver::new(dev, DRIVER).with_clock(clock.as_fn());
1601 d.init().unwrap();
1602 assert!(d.pump(Duration::from_secs(1)).unwrap());
1603
1604 clock.advance(Duration::from_millis(1));
1608 assert!(!d.pump(Duration::from_secs(1)).unwrap());
1609 assert!(
1610 d.device().ops.last().is_none_or(|op| !matches!(
1611 op,
1612 DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)
1613 )),
1614 "must not poll after only 1ms of real elapsed time, regardless of the 1s `timeout` argument"
1615 );
1616
1617 clock.advance(Duration::from_millis(100));
1618 assert!(!d.pump(Duration::from_secs(1)).unwrap());
1619 let last = d.device().ops.last().unwrap();
1620 assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1621 }
1622
1623 #[test]
1626 fn cam_insert_edge_emits_cam_present_once_and_redrives_handshake() {
1627 let mut dev = MockCaDevice::new([]);
1628 dev.slot = SlotInfo {
1629 num: 0,
1630 module_ready: false,
1631 module_present: false,
1632 };
1633 let mut d = Driver::new(dev, DRIVER);
1634 d.init().unwrap();
1635 let notes = d.take_notifications();
1638 assert!(
1639 !notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1640 "baseline observation must not fire CamPresent, got {notes:?}"
1641 );
1642 let resets_before = d
1643 .device()
1644 .ops
1645 .iter()
1646 .filter(|o| **o == DeviceOp::Reset)
1647 .count();
1648
1649 d.device_mut().slot = SlotInfo {
1651 num: 0,
1652 module_ready: true,
1653 module_present: true,
1654 };
1655 d.pump(Duration::from_millis(10)).unwrap();
1656
1657 let notes = d.take_notifications();
1658 let cam_present_count = notes
1659 .iter()
1660 .filter(|n| **n == Notification::HotPlug(HotPlug::CamPresent))
1661 .count();
1662 assert_eq!(
1663 cam_present_count, 1,
1664 "expected exactly one CamPresent, got {notes:?}"
1665 );
1666 let resets_after = d
1668 .device()
1669 .ops
1670 .iter()
1671 .filter(|o| **o == DeviceOp::Reset)
1672 .count();
1673 assert_eq!(
1674 resets_after,
1675 resets_before + 1,
1676 "expected one fresh Reset on re-insert"
1677 );
1678 assert!(
1679 matches!(d.device().ops.last(), Some(DeviceOp::Write(w)) if w[0] == tags::CREATE_T_C),
1680 "expected the handshake re-driven (CREATE_T_C written), got {:?}",
1681 d.device().ops.last()
1682 );
1683 }
1684
1685 #[test]
1686 fn cam_remove_edge_emits_cam_removed_and_re_insert_re_handshakes() {
1687 let mut d = driver_with_sessions();
1688 d.take_notifications();
1689
1690 d.device_mut().slot.module_present = false;
1692 d.pump(Duration::from_millis(10)).unwrap();
1693 let notes = d.take_notifications();
1694 assert!(
1695 notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
1696 "expected CamRemoved, got {notes:?}"
1697 );
1698
1699 d.mmi_menu_answer(0).unwrap();
1703 let notes = d.take_notifications();
1704 assert!(
1705 notes
1706 .iter()
1707 .any(|n| matches!(n, Notification::Error { .. })),
1708 "expected no open MMI session after teardown, got {notes:?}"
1709 );
1710
1711 let resets_before = d
1713 .device()
1714 .ops
1715 .iter()
1716 .filter(|o| **o == DeviceOp::Reset)
1717 .count();
1718 d.device_mut().slot.module_present = true;
1719 d.device_mut().slot.module_ready = true;
1720 d.pump(Duration::from_millis(10)).unwrap();
1721 let notes = d.take_notifications();
1722 assert!(
1723 notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1724 "expected CamPresent on re-insert, got {notes:?}"
1725 );
1726 let resets_after = d
1727 .device()
1728 .ops
1729 .iter()
1730 .filter(|o| **o == DeviceOp::Reset)
1731 .count();
1732 assert_eq!(resets_after, resets_before + 1, "expected a fresh Reset");
1733 }
1734
1735 #[test]
1736 fn slot_status_unchanged_across_polls_emits_no_hotplug_notifications() {
1737 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
1738 d.init().unwrap();
1739 d.take_notifications();
1740
1741 for _ in 0..5 {
1742 d.pump(Duration::from_millis(10)).unwrap();
1743 }
1744 let notes = d.take_notifications();
1745 assert!(
1746 !notes.iter().any(|n| matches!(
1747 n,
1748 Notification::HotPlug(HotPlug::CamPresent | HotPlug::CamRemoved)
1749 )),
1750 "unchanged slot status must not emit hot-plug notifications, got {notes:?}"
1751 );
1752 }
1753
1754 #[test]
1755 fn ca_info_caid_set_change_infers_card_inserted_then_changed() {
1756 use dvb_ci::objects::ca_info::CaInfo;
1757
1758 let mut d = driver_with_sessions();
1759 d.take_notifications();
1760
1761 feed(
1763 &mut d,
1764 r_apdu(
1765 CA_SESSION,
1766 &ser(&CaInfo {
1767 length_form: dvb_ci::length::LengthForm::Minimal,
1768 ca_system_ids: vec![],
1769 }),
1770 ),
1771 );
1772 let notes = d.take_notifications();
1773 assert!(
1774 !notes.iter().any(|n| matches!(
1775 n,
1776 Notification::HotPlug(
1777 HotPlug::CardInserted | HotPlug::CardChanged | HotPlug::CardRemoved
1778 )
1779 )),
1780 "first ca_info must only establish the baseline, got {notes:?}"
1781 );
1782
1783 feed(
1785 &mut d,
1786 r_apdu(
1787 CA_SESSION,
1788 &ser(&CaInfo {
1789 length_form: dvb_ci::length::LengthForm::Minimal,
1790 ca_system_ids: vec![0x0B00],
1791 }),
1792 ),
1793 );
1794 let notes = d.take_notifications();
1795 assert!(
1796 notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1797 "expected CardInserted, got {notes:?}"
1798 );
1799
1800 feed(
1802 &mut d,
1803 r_apdu(
1804 CA_SESSION,
1805 &ser(&CaInfo {
1806 length_form: dvb_ci::length::LengthForm::Minimal,
1807 ca_system_ids: vec![0x1800],
1808 }),
1809 ),
1810 );
1811 let notes = d.take_notifications();
1812 assert!(
1813 notes.contains(&Notification::HotPlug(HotPlug::CardChanged)),
1814 "expected CardChanged, got {notes:?}"
1815 );
1816 }
1817
1818 #[test]
1819 fn ca_pmt_reply_descrambling_transition_infers_card_present_then_removed() {
1820 use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1821
1822 fn reply(ca_enable: Option<CaEnable>) -> CaPmtReply {
1823 CaPmtReply {
1824 reserved_ca_enable: Default::default(),
1825 reserved_version: Default::default(),
1826 length_form: dvb_ci::length::LengthForm::Minimal,
1827 program_number: 1,
1828 version_number: 1,
1829 current_next_indicator: true,
1830 ca_enable,
1831 streams: vec![],
1832 }
1833 }
1834
1835 let mut d = driver_with_sessions();
1836 d.take_notifications();
1837
1838 feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1840 let notes = d.take_notifications();
1841 assert!(
1842 !notes.iter().any(|n| matches!(
1843 n,
1844 Notification::HotPlug(HotPlug::CardInserted | HotPlug::CardRemoved)
1845 )),
1846 "first ca_pmt_reply must only establish the baseline, got {notes:?}"
1847 );
1848
1849 feed(
1851 &mut d,
1852 r_apdu(CA_SESSION, &ser(&reply(Some(CaEnable::Possible)))),
1853 );
1854 let notes = d.take_notifications();
1855 assert!(
1856 notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1857 "expected CardInserted, got {notes:?}"
1858 );
1859
1860 feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1862 let notes = d.take_notifications();
1863 assert!(
1864 notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1865 "expected CardRemoved, got {notes:?}"
1866 );
1867 }
1868
1869 #[test]
1870 fn ca_pmt_reply_surfaces_typed_ca_enable() {
1871 use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1872
1873 let mut d = driver_with_sessions();
1874 d.take_notifications();
1875
1876 feed(
1879 &mut d,
1880 r_apdu(
1881 CA_SESSION,
1882 &ser(&CaPmtReply {
1883 reserved_ca_enable: Default::default(),
1884 reserved_version: Default::default(),
1885 length_form: dvb_ci::length::LengthForm::Minimal,
1886 program_number: 7,
1887 version_number: 1,
1888 current_next_indicator: true,
1889 ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1890 streams: vec![],
1891 }),
1892 ),
1893 );
1894 let notes = d.take_notifications();
1895 assert!(
1896 notes.contains(&Notification::CaPmtReply {
1897 program_number: 7,
1898 ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1899 descrambling_ok: true,
1900 }),
1901 "expected typed ca_enable on CaPmtReply, got {notes:?}"
1902 );
1903 }
1904
1905 #[test]
1906 fn ca_pmt_reply_flag_clear_surfaces_none() {
1907 use dvb_ci::objects::ca_pmt_reply::CaPmtReply;
1908
1909 let mut d = driver_with_sessions();
1910 d.take_notifications();
1911
1912 feed(
1915 &mut d,
1916 r_apdu(
1917 CA_SESSION,
1918 &ser(&CaPmtReply {
1919 reserved_ca_enable: Default::default(),
1920 reserved_version: Default::default(),
1921 length_form: dvb_ci::length::LengthForm::Minimal,
1922 program_number: 7,
1923 version_number: 1,
1924 current_next_indicator: true,
1925 ca_enable: None,
1926 streams: vec![],
1927 }),
1928 ),
1929 );
1930 let notes = d.take_notifications();
1931 assert!(
1932 notes.contains(&Notification::CaPmtReply {
1933 program_number: 7,
1934 ca_enable: None,
1935 descrambling_ok: false,
1936 }),
1937 "expected ca_enable None on flag-clear CaPmtReply, got {notes:?}"
1938 );
1939 }
1940
1941 #[test]
1942 fn mmi_no_card_text_infers_card_removed() {
1943 use dvb_ci::objects::mmi_high::Enq;
1944
1945 let mut d = driver_with_sessions();
1946 d.take_notifications();
1947
1948 feed(
1949 &mut d,
1950 r_apdu(
1951 MMI_SESSION,
1952 &ser(&Enq {
1953 reserved: Default::default(),
1954 length_form: dvb_ci::length::LengthForm::Minimal,
1955 blind_answer: false,
1956 answer_text_length: 0,
1957 text_chars: b"NO CARD detected - please insert your smart card",
1958 }),
1959 ),
1960 );
1961
1962 let notes = d.take_notifications();
1963 assert!(
1964 notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1965 "expected CardRemoved inferred from MMI 'no card' text, got {notes:?}"
1966 );
1967 }
1968
1969 #[test]
1972 fn mmi_card_keyword_heuristic_is_edge_triggered() {
1973 use dvb_ci::objects::mmi_high::Enq;
1974
1975 let enq = |text: &'static [u8]| {
1976 r_apdu(
1977 MMI_SESSION,
1978 &ser(&Enq {
1979 reserved: Default::default(),
1980 length_form: dvb_ci::length::LengthForm::Minimal,
1981 blind_answer: false,
1982 answer_text_length: 0,
1983 text_chars: text,
1984 }),
1985 )
1986 };
1987 let mut d = driver_with_sessions();
1988 d.take_notifications();
1989 let count = |notes: &[Notification], hp: HotPlug| {
1990 notes
1991 .iter()
1992 .filter(|n| **n == Notification::HotPlug(hp))
1993 .count()
1994 };
1995
1996 for _ in 0..3 {
1998 feed(&mut d, enq(b"No card - please insert your smart card"));
1999 }
2000 let notes = d.take_notifications();
2001 assert_eq!(count(¬es, HotPlug::CardRemoved), 1, "{notes:?}");
2002 assert_eq!(count(¬es, HotPlug::CardInserted), 0);
2003
2004 for _ in 0..2 {
2006 feed(&mut d, enq(b"Your entitlement is valid"));
2007 }
2008 let notes = d.take_notifications();
2009 assert_eq!(count(¬es, HotPlug::CardInserted), 1, "{notes:?}");
2010 assert_eq!(count(¬es, HotPlug::CardRemoved), 0);
2011
2012 feed(&mut d, enq(b"Card removed"));
2014 feed(&mut d, enq(b"Card removed"));
2015 let notes = d.take_notifications();
2016 assert_eq!(count(¬es, HotPlug::CardRemoved), 1, "{notes:?}");
2017 }
2018
2019 #[test]
2020 fn pump_hotplug_delivers_cam_present_via_closure_exactly_once() {
2021 let mut dev = MockCaDevice::new([]);
2022 dev.slot = SlotInfo {
2023 num: 0,
2024 module_ready: false,
2025 module_present: false,
2026 };
2027 let mut d = Driver::new(dev, DRIVER);
2028 d.init().unwrap();
2029 d.take_notifications(); d.device_mut().slot = SlotInfo {
2033 num: 0,
2034 module_ready: true,
2035 module_present: true,
2036 };
2037
2038 let mut seen = Vec::new();
2039 d.pump_hotplug(Duration::from_millis(10), |hp| seen.push(hp))
2040 .unwrap();
2041
2042 assert_eq!(
2043 seen,
2044 vec![HotPlug::CamPresent],
2045 "expected the closure to receive HotPlug::CamPresent exactly once, got {seen:?}"
2046 );
2047 }
2048
2049 pub(crate) fn ca_descriptor(ca_system_id: u16, pid: Pid) -> [u8; 6] {
2054 [
2055 0x09,
2056 0x04,
2057 (ca_system_id >> 8) as u8,
2058 ca_system_id as u8,
2059 0xE0 | ((pid.value() >> 8) as u8 & 0x1F),
2060 pid.value() as u8,
2061 ]
2062 }
2063
2064 pub(crate) fn build_ca_pmt_fixture(program_number: u16) -> Vec<u8> {
2081 const VIACCESS: u16 = 0x0500;
2082 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2083 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2084
2085 let mut body = Vec::new();
2086 body.push(0x02); body.push(0); body.push(0);
2089 body.extend_from_slice(&program_number.to_be_bytes());
2090 body.push(0xC3); body.push(0x00); body.push(0x00); body.push(0xE0 | 0x01); body.push(0x00);
2095 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2096 body.push(prog_ca.len() as u8);
2097 body.extend_from_slice(&prog_ca);
2098 body.push(0x1B);
2100 body.push(0xE0 | 0x01);
2101 body.push(0x00);
2102 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2103 body.push(es0_ca.len() as u8);
2104 body.extend_from_slice(&es0_ca);
2105 body.push(0x0F);
2107 body.push(0xE0 | 0x01);
2108 body.push(0x01);
2109 body.push(0xF0);
2110 body.push(0x00);
2111
2112 let section_length = body.len() - 3 + 4;
2113 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2114 body[2] = section_length as u8;
2115 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2116 body.extend_from_slice(&crc.to_be_bytes());
2117 body
2118 }
2119
2120 pub(crate) fn build_ca_pmt_fixture_dedicated_pcr(program_number: u16) -> Vec<u8> {
2127 const VIACCESS: u16 = 0x0500;
2128 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2129 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2130
2131 let mut body = Vec::new();
2132 body.push(0x02); body.push(0); body.push(0);
2135 body.extend_from_slice(&program_number.to_be_bytes());
2136 body.push(0xC3); body.push(0x00); body.push(0x00); body.push(0xE0); body.push(0xFF); body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2142 body.push(prog_ca.len() as u8);
2143 body.extend_from_slice(&prog_ca);
2144 body.push(0x1B);
2146 body.push(0xE0 | 0x01);
2147 body.push(0x00);
2148 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2149 body.push(es0_ca.len() as u8);
2150 body.extend_from_slice(&es0_ca);
2151 body.push(0x0F);
2153 body.push(0xE0 | 0x01);
2154 body.push(0x01);
2155 body.push(0xF0);
2156 body.push(0x00);
2157
2158 let section_length = body.len() - 3 + 4;
2159 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2160 body[2] = section_length as u8;
2161 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2162 body.extend_from_slice(&crc.to_be_bytes());
2163 body
2164 }
2165
2166 pub(crate) fn build_clear_pmt_fixture(program_number: u16) -> Vec<u8> {
2170 let mut body = Vec::new();
2171 body.push(0x02);
2172 body.push(0);
2173 body.push(0);
2174 body.extend_from_slice(&program_number.to_be_bytes());
2175 body.push(0xC3);
2176 body.push(0x00);
2177 body.push(0x00);
2178 body.push(0xE0 | 0x01);
2179 body.push(0x00);
2180 body.push(0xF0); body.push(0x00);
2182 body.push(0x1B);
2184 body.push(0xE0 | 0x01);
2185 body.push(0x00);
2186 body.push(0xF0);
2187 body.push(0x00);
2188
2189 let section_length = body.len() - 3 + 4;
2190 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2191 body[2] = section_length as u8;
2192 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2193 body.extend_from_slice(&crc.to_be_bytes());
2194 body
2195 }
2196
2197 #[test]
2198 fn add_service_builds_and_sends_ca_pmt_matching_builder_oracle() {
2199 use broadcast_core::Parse;
2200
2201 let mut d = driver_with_sessions();
2202 d.take_notifications();
2203
2204 let pmt_bytes = build_ca_pmt_fixture(1546);
2205 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2206
2207 d.add_service(&pmt).unwrap();
2208 d.device_mut().inbound.push_back(sb());
2209 d.pump(Duration::from_millis(10)).unwrap();
2210
2211 let expected = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2215 .to_bytes()
2216 .unwrap();
2217 assert_apdu_on_session(&d, CA_SESSION, &expected);
2218
2219 let svc = d
2221 .managed_ca()
2222 .services()
2223 .get(&1546)
2224 .expect("program_number 1546 must be tracked after add_service");
2225 assert_eq!(
2226 svc.es_pids,
2227 vec![Pid::from_const(0x0100), Pid::from_const(0x0101)]
2228 );
2229 assert_eq!(
2230 svc.ca_pids,
2231 vec![Pid::from_const(0x0064), Pid::from_const(0x0065)]
2232 );
2233 assert_eq!(svc.cmd, CaPmtCmdId::OkDescrambling);
2234 assert_eq!(svc.last_ca_enable, None);
2235 }
2236
2237 #[test]
2238 fn add_service_rejects_pmt_without_ca_descriptor() {
2239 use broadcast_core::Parse;
2240
2241 let mut d = driver_with_sessions();
2242 let pmt_bytes = build_clear_pmt_fixture(999);
2243 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2244
2245 let err = d.add_service(&pmt).unwrap_err();
2246 assert!(
2247 matches!(
2248 err,
2249 CaError::NoCaDescriptor {
2250 program_number: 999
2251 }
2252 ),
2253 "expected NoCaDescriptor{{program_number: 999}}, got {err:?}"
2254 );
2255 assert!(
2256 d.managed_ca().services().is_empty(),
2257 "a rejected PMT must not be recorded"
2258 );
2259 }
2260
2261 #[test]
2273 fn requery_tick_serialize_failure_errors_from_pump_instead_of_panicking() {
2274 use broadcast_core::Parse;
2275
2276 let clock = TestClock::new();
2277 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2278
2279 let good_bytes = build_ca_pmt_fixture(1);
2282 let good = PmtSection::parse(&good_bytes).unwrap();
2283 assert_eq!(good.program_number, 1, "fixture precondition");
2284 d.add_service(&good).unwrap();
2285
2286 let pmt_bytes = build_ca_pmt_fixture(1546);
2291 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2292 let built = d
2293 .build_ca_pmt_filtered(
2294 &pmt,
2295 CaPmtListManagement::Update,
2296 CaPmtCmdId::OkDescrambling,
2297 )
2298 .to_bytes()
2299 .expect("fixture precondition: the good PMT encodes");
2300 let corrupt_raw = pmt_bytes[..pmt_bytes.len() - 6].to_vec();
2301 d.managed.record(
2302 1546,
2303 managed::service_of(&pmt, CaPmtCmdId::OkDescrambling, built, corrupt_raw),
2304 );
2305 d.take_notifications();
2306 for _ in 0..16 {
2310 d.device_mut().inbound.push_back(sb());
2311 d.pump(Duration::from_millis(10)).unwrap();
2312 }
2313 d.set_requery_interval(Duration::from_secs(5));
2314
2315 clock.advance(Duration::from_secs(5));
2319 let err = d
2320 .pump(Duration::ZERO)
2321 .expect_err("re-query of a corrupt stored PMT must error, not panic");
2322 assert!(
2323 matches!(
2324 err.get_ref(),
2325 Some(e) if e.downcast_ref::<CaError>()
2326 .is_some_and(|ca| matches!(ca, CaError::PmtParse(_)))
2327 ),
2328 "expected CaError::PmtParse from the corrupt stored bytes, got {err:?}"
2329 );
2330 assert!(
2331 err.to_string().contains("stored PMT re-parse failed"),
2332 "error must name the re-parse failure, got: {err}"
2333 );
2334 assert!(d.pump(Duration::ZERO).is_ok());
2338 clock.advance(Duration::from_secs(5));
2339 let err2 = d
2340 .pump(Duration::ZERO)
2341 .expect_err("the corrupt service must fail every re-query");
2342 assert!(
2343 err2.to_string().contains("stored PMT re-parse failed"),
2344 "failure must persist, got: {err2}"
2345 );
2346 }
2347
2348 fn corrupt_ca_section_ctor() -> PmtSection<'static> {
2354 const LOOP: usize = 5004;
2355 let mut prog_info: Vec<u8> = Vec::with_capacity(LOOP);
2356 for _ in 0..LOOP / 6 {
2357 prog_info.extend_from_slice(&[0x09u8, 0x04, 0x0B, 0x00, 0xE1, 0x00]);
2359 }
2360 assert_eq!(prog_info.len(), LOOP);
2361 PmtSection::new(
2362 1,
2363 dvb_si::tables::SectionVersion::new(1, true, 0, 0),
2364 Pid::from_const(0x0200),
2365 dvb_si::descriptors::DescriptorLoop::new(Box::leak(prog_info.into_boxed_slice())),
2366 Vec::new(),
2367 )
2368 }
2369
2370 #[test]
2375 fn add_service_serialize_failure_returns_err_instead_of_panicking() {
2376 let mut d = driver_with_sessions();
2377 d.managed.set_cam_caids([0x0B00u16].into_iter().collect());
2378 let pmt = corrupt_ca_section_ctor();
2379 let err = d
2380 .add_service(&pmt)
2381 .expect_err("a ca_pmt with no valid encoding must error, not panic");
2382 assert!(
2383 matches!(err, CaError::Serialize(_)),
2384 "expected CaError::Serialize, got {err:?}"
2385 );
2386 assert!(
2387 d.managed_ca().services().is_empty(),
2388 "a rejected PMT must not be recorded"
2389 );
2390 }
2391
2392 #[test]
2393 fn add_service_second_call_uses_add_list_management() {
2394 use broadcast_core::Parse;
2395
2396 let mut d = driver_with_sessions();
2397 d.take_notifications();
2398
2399 let pmt1_bytes = build_ca_pmt_fixture(1546);
2400 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2401 d.add_service(&pmt1).unwrap();
2402 d.device_mut().inbound.push_back(sb());
2403 d.pump(Duration::from_millis(10)).unwrap();
2404
2405 let pmt2_bytes = build_ca_pmt_fixture(1547);
2406 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2407 d.add_service(&pmt2).unwrap();
2408 d.device_mut().inbound.push_back(sb());
2409 d.pump(Duration::from_millis(10)).unwrap();
2410
2411 let expected2 = build_ca_pmt(&pmt2, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling)
2413 .to_bytes()
2414 .unwrap();
2415 assert_apdu_on_session(&d, CA_SESSION, &expected2);
2416
2417 assert_eq!(d.managed_ca().services().len(), 2);
2418 }
2419
2420 fn build_ca_pmt_fixture_two_caids(program_number: u16) -> Vec<u8> {
2431 const VIACCESS: u16 = 0x0500;
2432 const NAGRA: u16 = 0x1800;
2433 let prog_ca_a = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2434 let prog_ca_b = ca_descriptor(NAGRA, Pid::from_const(0x0066));
2435 let mut prog_ca = Vec::new();
2436 prog_ca.extend_from_slice(&prog_ca_a);
2437 prog_ca.extend_from_slice(&prog_ca_b);
2438
2439 let mut body = Vec::new();
2440 body.push(0x02); body.push(0);
2442 body.push(0);
2443 body.extend_from_slice(&program_number.to_be_bytes());
2444 body.push(0xC3);
2445 body.push(0x00);
2446 body.push(0x00);
2447 body.push(0xE0 | 0x01); body.push(0x00);
2449 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2450 body.push(prog_ca.len() as u8);
2451 body.extend_from_slice(&prog_ca);
2452 body.push(0x0F);
2455 body.push(0xE0 | 0x01);
2456 body.push(0x00);
2457 body.push(0xF0);
2458 body.push(0x00);
2459
2460 let section_length = body.len() - 3 + 4;
2461 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2462 body[2] = section_length as u8;
2463 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2464 body.extend_from_slice(&crc.to_be_bytes());
2465 body
2466 }
2467
2468 #[test]
2469 fn add_service_filters_ca_descriptors_to_cam_advertised_caids() {
2470 use broadcast_core::Parse;
2471 use dvb_ci::objects::ca_info::CaInfo;
2472
2473 let mut d = driver_with_sessions();
2474 d.take_notifications();
2475
2476 feed(
2479 &mut d,
2480 r_apdu(
2481 CA_SESSION,
2482 &ser(&CaInfo {
2483 length_form: dvb_ci::length::LengthForm::Minimal,
2484 ca_system_ids: vec![0x0500],
2485 }),
2486 ),
2487 );
2488 d.take_notifications();
2489
2490 let pmt_bytes = build_ca_pmt_fixture_two_caids(1560);
2491 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2492
2493 let expected_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2498 &pmt,
2499 &[0x0500],
2500 CaPmtListManagement::Only,
2501 CaPmtCmdId::OkDescrambling,
2502 )
2503 .to_bytes()
2504 .unwrap();
2505 let unfiltered = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2506 .to_bytes()
2507 .unwrap();
2508 assert_ne!(
2509 expected_filtered, unfiltered,
2510 "precondition: the fixture's two CAIDs must make filtered != unfiltered"
2511 );
2512 let sends_filtered_before = count_apdu_on_session(&d, CA_SESSION, &expected_filtered);
2513 let sends_unfiltered_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered);
2514
2515 d.add_service(&pmt).unwrap();
2516 d.device_mut().inbound.push_back(sb());
2517 d.pump(Duration::from_millis(10)).unwrap();
2518
2519 assert_eq!(
2520 count_apdu_on_session(&d, CA_SESSION, &expected_filtered),
2521 sends_filtered_before + 1,
2522 "add_service must send the CAID-filtered ca_pmt"
2523 );
2524 assert_eq!(
2525 count_apdu_on_session(&d, CA_SESSION, &unfiltered),
2526 sends_unfiltered_before,
2527 "add_service must NOT send the unfiltered ca_pmt once the CAM's CAIDs are known"
2528 );
2529 }
2530
2531 #[test]
2532 fn requery_timer_filters_ca_descriptors_to_cam_advertised_caids() {
2533 use broadcast_core::Parse;
2534 use dvb_ci::objects::ca_info::CaInfo;
2535
2536 let clock = TestClock::new();
2537 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2538 d.set_requery_interval(Duration::from_secs(10));
2541 d.take_notifications();
2542
2543 let pmt_bytes = build_ca_pmt_fixture_two_caids(1561);
2544 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2545 d.add_service(&pmt).unwrap();
2548 d.device_mut().inbound.push_back(sb());
2549 clock.advance(Duration::from_millis(10));
2550 d.pump(Duration::from_millis(10)).unwrap();
2551
2552 feed(
2554 &mut d,
2555 r_apdu(
2556 CA_SESSION,
2557 &ser(&CaInfo {
2558 length_form: dvb_ci::length::LengthForm::Minimal,
2559 ca_system_ids: vec![0x0500],
2560 }),
2561 ),
2562 );
2563 d.take_notifications();
2564
2565 let expected_query_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2568 &pmt,
2569 &[0x0500],
2570 CaPmtListManagement::Update,
2571 CaPmtCmdId::Query,
2572 )
2573 .to_bytes()
2574 .unwrap();
2575 let expected_ok_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2576 &pmt,
2577 &[0x0500],
2578 CaPmtListManagement::Update,
2579 CaPmtCmdId::OkDescrambling,
2580 )
2581 .to_bytes()
2582 .unwrap();
2583 let unfiltered_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2584 .to_bytes()
2585 .unwrap();
2586 let unfiltered_ok = build_ca_pmt(
2587 &pmt,
2588 CaPmtListManagement::Update,
2589 CaPmtCmdId::OkDescrambling,
2590 )
2591 .to_bytes()
2592 .unwrap();
2593 assert_ne!(
2594 expected_query_filtered, unfiltered_query,
2595 "precondition: the fixture's two CAIDs must make filtered != unfiltered (query)"
2596 );
2597 assert_ne!(
2598 expected_ok_filtered, unfiltered_ok,
2599 "precondition: the fixture's two CAIDs must make filtered != unfiltered (ok_descrambling)"
2600 );
2601 let sends_query_before = count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered);
2602 let sends_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered);
2603 let sends_unfiltered_query_before =
2604 count_apdu_on_session(&d, CA_SESSION, &unfiltered_query);
2605 let sends_unfiltered_ok_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok);
2606
2607 clock.advance(Duration::from_secs(11));
2608 d.pump(Duration::from_secs(11)).unwrap();
2609 feed(&mut d, sb());
2610
2611 assert_eq!(
2612 count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered),
2613 sends_query_before + 1,
2614 "the re-query `query` half must be CAID-filtered to the CAM's advertised CAIDs"
2615 );
2616 assert_eq!(
2617 count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered),
2618 sends_ok_before + 1,
2619 "the re-query `ok_descrambling` half must be CAID-filtered to the CAM's advertised CAIDs"
2620 );
2621 assert_eq!(
2622 count_apdu_on_session(&d, CA_SESSION, &unfiltered_query),
2623 sends_unfiltered_query_before,
2624 "the re-query resend must NOT be the unfiltered `query` ca_pmt"
2625 );
2626 assert_eq!(
2627 count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok),
2628 sends_unfiltered_ok_before,
2629 "the re-query resend must NOT be the unfiltered `ok_descrambling` ca_pmt"
2630 );
2631 }
2632
2633 pub(crate) fn build_cat_fixture(descriptors: &[u8]) -> Vec<u8> {
2643 const EXTENSION_HEADER_LEN: u16 = 5;
2644 const CRC_LEN: u16 = 4;
2645 let section_length = EXTENSION_HEADER_LEN + descriptors.len() as u16 + CRC_LEN;
2646 let mut v = Vec::new();
2647 v.push(0x01); v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
2649 v.push((section_length & 0xFF) as u8);
2650 v.extend_from_slice(&[0xFF, 0xFF]); v.push(0xC1); v.push(0x00); v.push(0x00); v.extend_from_slice(descriptors);
2655 let crc = broadcast_common::crc32_mpeg2::compute(&v);
2656 v.extend_from_slice(&crc.to_be_bytes());
2657 v
2658 }
2659
2660 #[test]
2661 fn set_cat_computes_emm_pids_as_cat_inter_ca_info_caids() {
2662 use broadcast_core::Parse;
2663 use dvb_ci::objects::ca_info::CaInfo;
2664 use dvb_si::tables::cat::CatSection;
2665
2666 let mut d = driver_with_sessions();
2667 d.take_notifications();
2668
2669 feed(
2671 &mut d,
2672 r_apdu(
2673 CA_SESSION,
2674 &ser(&CaInfo {
2675 length_form: dvb_ci::length::LengthForm::Minimal,
2676 ca_system_ids: vec![0x0648, 0x0100],
2677 }),
2678 ),
2679 );
2680 d.take_notifications();
2681
2682 let mut descriptors = Vec::new();
2685 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2686 descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2687 let cat_bytes = build_cat_fixture(&descriptors);
2688 let cat = CatSection::parse(&cat_bytes).unwrap();
2689
2690 d.set_cat(&cat).unwrap();
2691
2692 assert_eq!(
2693 d.emm_pids(),
2694 &[Pid::from_const(0x1FF0)],
2695 "0x0500 -> 0x1FF1 must be excluded: the CAM never advertised CAID 0x0500"
2696 );
2697 }
2698
2699 #[test]
2700 fn set_cat_before_ca_info_is_not_an_error_and_recomputes_once_ca_info_arrives() {
2701 use broadcast_core::Parse;
2702 use dvb_ci::objects::ca_info::CaInfo;
2703 use dvb_si::tables::cat::CatSection;
2704
2705 let mut d = driver_with_sessions();
2706 d.take_notifications();
2707
2708 let mut descriptors = Vec::new();
2709 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2710 descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2711 let cat_bytes = build_cat_fixture(&descriptors);
2712 let cat = CatSection::parse(&cat_bytes).unwrap();
2713
2714 d.set_cat(&cat).unwrap();
2717 assert!(
2718 d.emm_pids().is_empty(),
2719 "emm_pids must be empty before any ca_info arrives, got {:?}",
2720 d.emm_pids()
2721 );
2722
2723 feed(
2726 &mut d,
2727 r_apdu(
2728 CA_SESSION,
2729 &ser(&CaInfo {
2730 length_form: dvb_ci::length::LengthForm::Minimal,
2731 ca_system_ids: vec![0x0648, 0x0100],
2732 }),
2733 ),
2734 );
2735 d.take_notifications();
2736
2737 assert_eq!(
2738 d.emm_pids(),
2739 &[Pid::from_const(0x1FF0)],
2740 "emm_pids must recompute once ca_info arrives, using the CAT stored by the earlier set_cat"
2741 );
2742 }
2743
2744 #[test]
2750 fn set_cat_emm_pids_dedups_when_two_caids_share_one_emm_pid() {
2751 use broadcast_core::Parse;
2752 use dvb_ci::objects::ca_info::CaInfo;
2753 use dvb_si::tables::cat::CatSection;
2754
2755 let mut d = driver_with_sessions();
2756 d.take_notifications();
2757
2758 feed(
2760 &mut d,
2761 r_apdu(
2762 CA_SESSION,
2763 &ser(&CaInfo {
2764 length_form: dvb_ci::length::LengthForm::Minimal,
2765 ca_system_ids: vec![0x0648, 0x0100],
2766 }),
2767 ),
2768 );
2769 d.take_notifications();
2770
2771 let mut descriptors = Vec::new();
2773 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2774 descriptors.extend_from_slice(&ca_descriptor(0x0100, Pid::from_const(0x1FF0)));
2775 let cat_bytes = build_cat_fixture(&descriptors);
2776 let cat = CatSection::parse(&cat_bytes).unwrap();
2777
2778 d.set_cat(&cat).unwrap();
2779
2780 assert_eq!(
2781 d.emm_pids(),
2782 &[Pid::from_const(0x1FF0)],
2783 "0x1FF0 must appear exactly once even though two CAM-advertised CAIDs map to it, got {:?}",
2784 d.emm_pids()
2785 );
2786 }
2787
2788 fn build_ca_pmt_fixture_distinct_pids(program_number: u16) -> Vec<u8> {
2792 const VIACCESS: u16 = 0x0500;
2793 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0074));
2794 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0075));
2795
2796 let mut body = Vec::new();
2797 body.push(0x02); body.push(0);
2799 body.push(0);
2800 body.extend_from_slice(&program_number.to_be_bytes());
2801 body.push(0xC3);
2802 body.push(0x00);
2803 body.push(0x00);
2804 body.push(0xE0 | 0x02); body.push(0x00);
2806 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2807 body.push(prog_ca.len() as u8);
2808 body.extend_from_slice(&prog_ca);
2809 body.push(0x1B);
2811 body.push(0xE0 | 0x02);
2812 body.push(0x00);
2813 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2814 body.push(es0_ca.len() as u8);
2815 body.extend_from_slice(&es0_ca);
2816 body.push(0x0F);
2818 body.push(0xE0 | 0x02);
2819 body.push(0x01);
2820 body.push(0xF0);
2821 body.push(0x00);
2822
2823 let section_length = body.len() - 3 + 4;
2824 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2825 body[2] = section_length as u8;
2826 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2827 body.extend_from_slice(&crc.to_be_bytes());
2828 body
2829 }
2830
2831 #[test]
2832 fn descramble_pids_is_the_union_of_active_services_es_pids() {
2833 use broadcast_core::Parse;
2834
2835 let mut d = driver_with_sessions();
2836 d.take_notifications();
2837
2838 assert!(
2839 d.descramble_pids().is_empty(),
2840 "no service added yet: descramble_pids must be empty"
2841 );
2842
2843 let pmt1_bytes = build_ca_pmt_fixture(1546);
2844 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2845 d.add_service(&pmt1).unwrap();
2846 d.device_mut().inbound.push_back(sb());
2847 d.pump(Duration::from_millis(10)).unwrap();
2848
2849 assert_eq!(
2850 d.descramble_pids(),
2851 &[Pid::from_const(0x0100), Pid::from_const(0x0101)]
2852 );
2853
2854 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
2855 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2856 d.add_service(&pmt2).unwrap();
2857 d.device_mut().inbound.push_back(sb());
2858 d.pump(Duration::from_millis(10)).unwrap();
2859
2860 assert_eq!(
2862 d.descramble_pids(),
2863 &[
2864 Pid::from_const(0x0100),
2865 Pid::from_const(0x0101),
2866 Pid::from_const(0x0200),
2867 Pid::from_const(0x0201)
2868 ],
2869 "descramble_pids must be the union across both added services"
2870 );
2871 }
2872
2873 pub(crate) fn ca_pmt_reply_for(
2878 program_number: u16,
2879 ca_enable: Option<dvb_ci::objects::ca_pmt_reply::CaEnable>,
2880 ) -> dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2881 dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2882 length_form: dvb_ci::length::LengthForm::Minimal,
2883 program_number,
2884 version_number: 1,
2885 current_next_indicator: true,
2886 ca_enable,
2887 streams: vec![],
2888 reserved_version: Default::default(),
2889 reserved_ca_enable: Default::default(),
2890 }
2891 }
2892
2893 #[test]
2894 fn requery_timer_resends_ca_pmt_then_reply_change_emits_one_entitlement() {
2895 use broadcast_core::Parse;
2896 use dvb_ci::objects::ca_pmt_reply::CaEnable;
2897
2898 let clock = TestClock::new();
2899 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2900 d.set_requery_interval(Duration::from_secs(10));
2903 d.take_notifications();
2904
2905 let pmt_bytes = build_ca_pmt_fixture(1546);
2906 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2907 d.add_service(&pmt).unwrap();
2908 d.device_mut().inbound.push_back(sb());
2909 clock.advance(Duration::from_millis(10));
2910 d.pump(Duration::from_millis(10)).unwrap();
2911 d.take_notifications();
2912
2913 let expected_initial_ca_pmt =
2917 build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2918 .to_bytes()
2919 .unwrap();
2920 assert_apdu_on_session(&d, CA_SESSION, &expected_initial_ca_pmt);
2921
2922 let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2928 .to_bytes()
2929 .unwrap();
2930 let expected_ok_descrambling = build_ca_pmt(
2931 &pmt,
2932 CaPmtListManagement::Update,
2933 CaPmtCmdId::OkDescrambling,
2934 )
2935 .to_bytes()
2936 .unwrap();
2937 let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
2938 let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
2939
2940 let mut all_notes = Vec::new();
2941
2942 feed(
2946 &mut d,
2947 r_apdu(
2948 CA_SESSION,
2949 &ser(&ca_pmt_reply_for(
2950 1546,
2951 Some(CaEnable::NotPossibleNoEntitlement),
2952 )),
2953 ),
2954 );
2955 all_notes.extend(d.take_notifications());
2956
2957 clock.advance(Duration::from_secs(11));
2967 d.pump(Duration::from_secs(11)).unwrap();
2968 all_notes.extend(d.take_notifications());
2969 feed(&mut d, sb());
2970
2971 assert_eq!(
2972 count_apdu_on_session(&d, CA_SESSION, &expected_query),
2973 query_sends_before + 1,
2974 "expected the re-query timer to resend the `query` half exactly once"
2975 );
2976 assert_eq!(
2977 count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
2978 ok_sends_before + 1,
2979 "expected the re-query timer to resend the `ok_descrambling` half exactly once"
2980 );
2981
2982 feed(
2985 &mut d,
2986 r_apdu(
2987 CA_SESSION,
2988 &ser(&ca_pmt_reply_for(1546, Some(CaEnable::Possible))),
2989 ),
2990 );
2991 all_notes.extend(d.take_notifications());
2992
2993 let hits = all_notes
2994 .iter()
2995 .filter(|n| {
2996 matches!(
2997 n,
2998 Notification::Entitlement {
2999 program_number: 1546,
3000 ca_enable: CaEnable::Possible,
3001 descrambling_ok: true,
3002 }
3003 )
3004 })
3005 .count();
3006 assert_eq!(
3007 hits, 1,
3008 "expected exactly one Entitlement{{program_number:1546, ca_enable:Possible, descrambling_ok:true}}, got {all_notes:?}"
3009 );
3010 }
3011
3012 #[test]
3013 fn requery_timer_unchanged_reply_across_two_requeries_emits_no_entitlement() {
3014 use broadcast_core::Parse;
3015 use dvb_ci::objects::ca_pmt_reply::CaEnable;
3016
3017 let mut d = driver_with_sessions();
3018 d.set_requery_interval(Duration::from_secs(10));
3021 d.take_notifications();
3022
3023 let pmt_bytes = build_ca_pmt_fixture(1547);
3024 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3025 d.add_service(&pmt).unwrap();
3026 d.device_mut().inbound.push_back(sb());
3027 d.pump(Duration::from_millis(10)).unwrap();
3028 d.take_notifications();
3029
3030 feed(
3034 &mut d,
3035 r_apdu(
3036 CA_SESSION,
3037 &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3038 ),
3039 );
3040 d.take_notifications();
3041
3042 for _ in 0..2 {
3045 d.pump(Duration::from_secs(11)).unwrap();
3046 d.take_notifications();
3047 feed(
3048 &mut d,
3049 r_apdu(
3050 CA_SESSION,
3051 &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3052 ),
3053 );
3054 let notes = d.take_notifications();
3055 assert!(
3056 !notes
3057 .iter()
3058 .any(|n| matches!(n, Notification::Entitlement { .. })),
3059 "unchanged status across a re-query must not emit Entitlement, got {notes:?}"
3060 );
3061 }
3062 }
3063
3064 #[test]
3065 fn requery_reply_withdrawn_to_none_emits_no_entitlement() {
3066 use broadcast_core::Parse;
3067 use dvb_ci::objects::ca_pmt_reply::CaEnable;
3068
3069 let mut d = driver_with_sessions();
3070 d.take_notifications();
3071
3072 let pmt_bytes = build_ca_pmt_fixture(1548);
3073 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3074 d.add_service(&pmt).unwrap();
3075 d.device_mut().inbound.push_back(sb());
3076 d.pump(Duration::from_millis(10)).unwrap();
3077 d.take_notifications();
3078
3079 feed(
3081 &mut d,
3082 r_apdu(
3083 CA_SESSION,
3084 &ser(&ca_pmt_reply_for(1548, Some(CaEnable::Possible))),
3085 ),
3086 );
3087 d.take_notifications();
3088
3089 feed(
3093 &mut d,
3094 r_apdu(CA_SESSION, &ser(&ca_pmt_reply_for(1548, None))),
3095 );
3096 let notes = d.take_notifications();
3097 assert!(
3098 !notes
3099 .iter()
3100 .any(|n| matches!(n, Notification::Entitlement { .. })),
3101 "ca_enable transitioning to None must not emit Entitlement, got {notes:?}"
3102 );
3103 }
3104
3105 #[test]
3106 fn requery_disabled_by_default_sends_nothing() {
3107 use broadcast_core::Parse;
3108
3109 let mut d = driver_with_sessions();
3113 d.take_notifications();
3114
3115 let pmt_bytes = build_ca_pmt_fixture(1549);
3116 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3117 d.add_service(&pmt).unwrap();
3118 d.device_mut().inbound.push_back(sb());
3119 d.pump(Duration::from_millis(10)).unwrap();
3120
3121 let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
3124 .to_bytes()
3125 .unwrap();
3126 let expected_ok_descrambling = build_ca_pmt(
3127 &pmt,
3128 CaPmtListManagement::Update,
3129 CaPmtCmdId::OkDescrambling,
3130 )
3131 .to_bytes()
3132 .unwrap();
3133 let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
3134 let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
3135
3136 d.pump(Duration::from_secs(1_000_000)).unwrap();
3138 feed(&mut d, sb());
3139 feed(&mut d, sb());
3140 assert_eq!(
3141 count_apdu_on_session(&d, CA_SESSION, &expected_query),
3142 query_sends_before,
3143 "the default (Duration::ZERO) must never send a re-query `query`"
3144 );
3145 assert_eq!(
3146 count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
3147 ok_sends_before,
3148 "the default (Duration::ZERO) must never send a re-query `ok_descrambling`"
3149 );
3150 }
3151
3152 #[test]
3153 fn set_requery_interval_zero_disables_resend_after_being_enabled() {
3154 use broadcast_core::Parse;
3155
3156 let mut d = driver_with_sessions();
3157 d.set_requery_interval(Duration::from_secs(5));
3160 d.set_requery_interval(Duration::ZERO);
3161 d.take_notifications();
3162
3163 let pmt_bytes = build_ca_pmt_fixture(1549);
3164 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3165 d.add_service(&pmt).unwrap();
3166 d.device_mut().inbound.push_back(sb());
3167 d.pump(Duration::from_millis(10)).unwrap();
3168
3169 let expected_ca_pmt = build_ca_pmt(
3173 &pmt,
3174 CaPmtListManagement::Update,
3175 CaPmtCmdId::OkDescrambling,
3176 )
3177 .to_bytes()
3178 .unwrap();
3179 let sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3180
3181 d.pump(Duration::from_secs(1000)).unwrap();
3183 feed(&mut d, sb());
3184 feed(&mut d, sb());
3185
3186 let sends_after = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3187 assert_eq!(
3188 sends_after, sends_before,
3189 "Duration::ZERO must disable the re-query resend"
3190 );
3191 }
3192
3193 #[test]
3194 fn requery_timer_resends_every_active_service_not_just_one() {
3195 use broadcast_core::Parse;
3196
3197 let clock = TestClock::new();
3198 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3199 d.set_requery_interval(Duration::from_secs(10));
3202 d.take_notifications();
3203
3204 let pmt1_bytes = build_ca_pmt_fixture(1546);
3207 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3208 d.add_service(&pmt1).unwrap();
3209 d.device_mut().inbound.push_back(sb());
3210 clock.advance(Duration::from_millis(10));
3211 d.pump(Duration::from_millis(10)).unwrap();
3212
3213 let pmt2_bytes = build_ca_pmt_fixture(1547);
3214 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3215 d.add_service(&pmt2).unwrap();
3216 d.device_mut().inbound.push_back(sb());
3217 clock.advance(Duration::from_millis(10));
3218 d.pump(Duration::from_millis(10)).unwrap();
3219 d.take_notifications();
3220
3221 let expected1_query = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3227 .to_bytes()
3228 .unwrap();
3229 let expected1_ok = build_ca_pmt(
3230 &pmt1,
3231 CaPmtListManagement::Update,
3232 CaPmtCmdId::OkDescrambling,
3233 )
3234 .to_bytes()
3235 .unwrap();
3236 let expected2_query = build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3237 .to_bytes()
3238 .unwrap();
3239 let expected2_ok = build_ca_pmt(
3240 &pmt2,
3241 CaPmtListManagement::Update,
3242 CaPmtCmdId::OkDescrambling,
3243 )
3244 .to_bytes()
3245 .unwrap();
3246 let sends_before1_query = count_apdu_on_session(&d, CA_SESSION, &expected1_query);
3247 let sends_before1_ok = count_apdu_on_session(&d, CA_SESSION, &expected1_ok);
3248 let sends_before2_query = count_apdu_on_session(&d, CA_SESSION, &expected2_query);
3249 let sends_before2_ok = count_apdu_on_session(&d, CA_SESSION, &expected2_ok);
3250
3251 clock.advance(Duration::from_secs(11));
3257 d.pump(Duration::from_secs(11)).unwrap();
3258 feed(&mut d, sb());
3259 feed(&mut d, sb());
3260
3261 assert_eq!(
3262 count_apdu_on_session(&d, CA_SESSION, &expected1_query),
3263 sends_before1_query + 1,
3264 "expected service 1546's `query` resent exactly once on the shared tick"
3265 );
3266 assert_eq!(
3267 count_apdu_on_session(&d, CA_SESSION, &expected1_ok),
3268 sends_before1_ok + 1,
3269 "expected service 1546's `ok_descrambling` resent exactly once on the shared tick"
3270 );
3271 assert_eq!(
3272 count_apdu_on_session(&d, CA_SESSION, &expected2_query),
3273 sends_before2_query + 1,
3274 "expected service 1547's `query` resent exactly once on the shared tick"
3275 );
3276 assert_eq!(
3277 count_apdu_on_session(&d, CA_SESSION, &expected2_ok),
3278 sends_before2_ok + 1,
3279 "expected service 1547's `ok_descrambling` resent exactly once on the shared tick"
3280 );
3281 }
3282
3283 #[test]
3287 fn requery_after_remove_resends_only_the_surviving_service() {
3288 use broadcast_core::Parse;
3289
3290 let clock = TestClock::new();
3291 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3292 d.set_requery_interval(Duration::from_secs(10));
3295 d.take_notifications();
3296
3297 let pmt1_bytes = build_ca_pmt_fixture(1546);
3298 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3299 d.add_service(&pmt1).unwrap();
3300 d.device_mut().inbound.push_back(sb());
3301 clock.advance(Duration::from_millis(10));
3302 d.pump(Duration::from_millis(10)).unwrap();
3303
3304 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3305 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3306 d.add_service(&pmt2).unwrap();
3307 d.device_mut().inbound.push_back(sb());
3308 clock.advance(Duration::from_millis(10));
3309 d.pump(Duration::from_millis(10)).unwrap();
3310
3311 d.remove_service(1546).unwrap();
3313 d.device_mut().inbound.push_back(sb());
3314 clock.advance(Duration::from_millis(10));
3315 d.pump(Duration::from_millis(10)).unwrap();
3316 d.take_notifications();
3317
3318 let expected_survivor_query =
3324 build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3325 .to_bytes()
3326 .unwrap();
3327 let expected_survivor_ok = build_ca_pmt(
3328 &pmt2,
3329 CaPmtListManagement::Update,
3330 CaPmtCmdId::OkDescrambling,
3331 )
3332 .to_bytes()
3333 .unwrap();
3334 let expected_removed_query =
3335 build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3336 .to_bytes()
3337 .unwrap();
3338 let expected_removed_ok = build_ca_pmt(
3339 &pmt1,
3340 CaPmtListManagement::Update,
3341 CaPmtCmdId::OkDescrambling,
3342 )
3343 .to_bytes()
3344 .unwrap();
3345 let sends_survivor_query_before =
3346 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query);
3347 let sends_survivor_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok);
3348 let sends_removed_query_before =
3349 count_apdu_on_session(&d, CA_SESSION, &expected_removed_query);
3350 let sends_removed_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok);
3351
3352 clock.advance(Duration::from_secs(11));
3353 d.pump(Duration::from_secs(11)).unwrap();
3354 feed(&mut d, sb());
3355
3356 assert_eq!(
3357 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query),
3358 sends_survivor_query_before + 1,
3359 "the surviving service's `query` must be re-sent"
3360 );
3361 assert_eq!(
3362 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok),
3363 sends_survivor_ok_before + 1,
3364 "the surviving service's `ok_descrambling` must be re-sent"
3365 );
3366 assert_eq!(
3367 count_apdu_on_session(&d, CA_SESSION, &expected_removed_query),
3368 sends_removed_query_before,
3369 "the removed service's `query` must NOT be re-sent"
3370 );
3371 assert_eq!(
3372 count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok),
3373 sends_removed_ok_before,
3374 "the removed service's `ok_descrambling` must NOT be re-sent"
3375 );
3376 }
3377
3378 #[test]
3381 fn remove_service_sends_update_not_selected_and_drops_from_managed_state() {
3382 use broadcast_core::Parse;
3383
3384 let mut d = driver_with_sessions();
3385 d.take_notifications();
3386
3387 let pmt1_bytes = build_ca_pmt_fixture(1546);
3391 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3392 d.add_service(&pmt1).unwrap();
3393 d.device_mut().inbound.push_back(sb());
3394 d.pump(Duration::from_millis(10)).unwrap();
3395
3396 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3397 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3398 d.add_service(&pmt2).unwrap();
3399 d.device_mut().inbound.push_back(sb());
3400 d.pump(Duration::from_millis(10)).unwrap();
3401
3402 d.remove_service(1546).unwrap();
3403 d.device_mut().inbound.push_back(sb());
3404 d.pump(Duration::from_millis(10)).unwrap();
3405
3406 let expected = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3410 .to_bytes()
3411 .unwrap();
3412 assert_apdu_on_session(&d, CA_SESSION, &expected);
3413
3414 assert_eq!(
3415 d.descramble_pids(),
3416 &[Pid::from_const(0x0200), Pid::from_const(0x0201)],
3417 "1546's ES PIDs must be gone; 1547's must remain"
3418 );
3419 assert!(
3420 d.managed_ca().services().get(&1546).is_none(),
3421 "1546 must no longer be tracked"
3422 );
3423 assert!(
3424 d.managed_ca().services().get(&1547).is_some(),
3425 "1547 must remain tracked"
3426 );
3427 }
3428
3429 #[test]
3430 fn remove_service_of_untracked_program_is_a_no_op() {
3431 let mut d = driver_with_sessions();
3432 d.take_notifications();
3433
3434 let ops_before = d.device().ops.len();
3435 d.remove_service(0xFFFF).unwrap();
3436 assert_eq!(
3437 d.device().ops.len(),
3438 ops_before,
3439 "removing an untracked program must not send anything to the device"
3440 );
3441 assert!(
3442 d.managed_ca().services().is_empty(),
3443 "removing an untracked program must not disturb the (empty) managed set"
3444 );
3445 }
3446
3447 #[test]
3448 fn cam_removed_edge_clears_managed_state() {
3449 use broadcast_core::Parse;
3450 use dvb_ci::objects::ca_info::CaInfo;
3451 use dvb_si::tables::cat::CatSection;
3452
3453 let mut d = driver_with_sessions();
3454 d.take_notifications();
3455
3456 let pmt_bytes = build_ca_pmt_fixture(1546);
3457 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3458 d.add_service(&pmt).unwrap();
3459 d.device_mut().inbound.push_back(sb());
3460 d.pump(Duration::from_millis(10)).unwrap();
3461
3462 feed(
3465 &mut d,
3466 r_apdu(
3467 CA_SESSION,
3468 &ser(&CaInfo {
3469 length_form: dvb_ci::length::LengthForm::Minimal,
3470 ca_system_ids: vec![0x0648],
3471 }),
3472 ),
3473 );
3474 d.take_notifications();
3475 let mut descriptors = Vec::new();
3476 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
3477 let cat_bytes = build_cat_fixture(&descriptors);
3478 let cat = CatSection::parse(&cat_bytes).unwrap();
3479 d.set_cat(&cat).unwrap();
3480
3481 assert!(
3482 !d.managed_ca().services().is_empty(),
3483 "precondition: a service is tracked"
3484 );
3485 assert!(
3486 !d.descramble_pids().is_empty(),
3487 "precondition: descramble_pids populated"
3488 );
3489 assert!(!d.emm_pids().is_empty(), "precondition: emm_pids populated");
3490
3491 d.device_mut().slot.module_present = false;
3493 d.pump(Duration::from_millis(10)).unwrap();
3494 let notes = d.take_notifications();
3495 assert!(
3496 notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
3497 "expected CamRemoved, got {notes:?}"
3498 );
3499
3500 assert!(
3501 d.managed_ca().services().is_empty(),
3502 "services must be cleared on CamRemoved"
3503 );
3504 assert!(
3505 d.descramble_pids().is_empty(),
3506 "descramble_pids must be cleared on CamRemoved"
3507 );
3508 assert!(
3509 d.emm_pids().is_empty(),
3510 "emm_pids must be cleared on CamRemoved"
3511 );
3512 }
3513
3514 #[test]
3515 fn update_service_not_managed_returns_not_managed_and_sends_nothing() {
3516 use broadcast_core::Parse;
3517
3518 let mut d = driver_with_sessions();
3519 d.take_notifications();
3520
3521 let pmt_bytes = build_clear_pmt_fixture(9999);
3522 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3523
3524 let before = d.device().ops.len();
3525 let err = d
3526 .update_service(&pmt)
3527 .expect_err("unknown program must error");
3528 assert!(
3529 matches!(
3530 err,
3531 CaError::NotManaged {
3532 program_number: 9999
3533 }
3534 ),
3535 "got {err:?}"
3536 );
3537 assert_eq!(d.device().ops.len(), before, "must send nothing");
3538 assert!(d.managed_ca().services().is_empty());
3539 }
3540
3541 #[test]
3542 fn update_service_no_ca_descriptor_leaves_record_unchanged() {
3543 use broadcast_core::Parse;
3544
3545 let mut d = driver_with_sessions();
3546 d.take_notifications();
3547
3548 let pmt_bytes = build_ca_pmt_fixture(1546);
3549 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3550 d.add_service(&pmt).unwrap();
3551
3552 let svc_before = d.managed_ca().services().get(&1546).unwrap().clone();
3553
3554 let clear_bytes = build_clear_pmt_fixture(1546);
3555 let clear_pmt = PmtSection::parse(&clear_bytes).unwrap();
3556 let err = d
3557 .update_service(&clear_pmt)
3558 .expect_err("CA-free PMT must error");
3559 assert!(
3560 matches!(
3561 err,
3562 CaError::NoCaDescriptor {
3563 program_number: 1546
3564 }
3565 ),
3566 "got {err:?}"
3567 );
3568
3569 let svc_after = d.managed_ca().services().get(&1546).unwrap();
3570 assert_eq!(svc_before, *svc_after, "record must be unchanged");
3571 }
3572
3573 #[test]
3579 fn update_service_sends_one_update_ca_pmt_with_the_new_pids_and_replaces_only_that_record() {
3580 use broadcast_core::Parse;
3581
3582 let mut d = driver_with_sessions();
3583 d.take_notifications();
3584
3585 let a_bytes = build_ca_pmt_fixture(1546);
3586 let a = PmtSection::parse(&a_bytes).unwrap();
3587 d.add_service(&a).unwrap();
3588 d.device_mut().inbound.push_back(sb());
3589 d.pump(Duration::from_millis(10)).unwrap();
3590
3591 let b_bytes = build_ca_pmt_fixture_dedicated_pcr(1547);
3592 let b = PmtSection::parse(&b_bytes).unwrap();
3593 d.add_service(&b).unwrap();
3594 d.device_mut().inbound.push_back(sb());
3595 d.pump(Duration::from_millis(10)).unwrap();
3596
3597 let a_old_record = d.managed_ca().services().get(&1546).unwrap().clone();
3598 let b_record_before = d.managed_ca().services().get(&1547).unwrap().clone();
3599 assert_eq!(
3600 a_old_record.ca_pids,
3601 vec![Pid::from_const(0x0064), Pid::from_const(0x0065)],
3602 "fixture sanity: A starts on the 0x0064/0x0065 ECM PIDs"
3603 );
3604
3605 let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3607 let a2 = PmtSection::parse(&a2_bytes).unwrap();
3608 let update = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::OkDescrambling)
3609 .to_bytes()
3610 .unwrap();
3611 let writes_before = d.device().ops.len();
3612
3613 d.update_service(&a2).unwrap();
3614 d.device_mut().inbound.push_back(sb());
3615 d.pump(Duration::from_millis(10)).unwrap();
3616
3617 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &update), 1);
3619 let new_ca_pmt_writes = d.device().ops[writes_before..]
3620 .iter()
3621 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3622 .count();
3623 assert_eq!(new_ca_pmt_writes, 1, "exactly one ca_pmt APDU may be sent");
3624
3625 let new_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0074));
3627 let old_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0064));
3628 assert!(update.windows(new_prog_ca.len()).any(|x| x == new_prog_ca));
3629 assert!(!update.windows(old_prog_ca.len()).any(|x| x == old_prog_ca));
3630
3631 let a_new_record = d.managed_ca().services().get(&1546).unwrap();
3633 assert_eq!(
3634 a_new_record.ca_pids,
3635 vec![Pid::from_const(0x0074), Pid::from_const(0x0075)]
3636 );
3637 assert_eq!(a_new_record.built_ca_pmt, update);
3638 assert_ne!(a_new_record.built_ca_pmt, a_old_record.built_ca_pmt);
3639 assert_ne!(a_new_record.pmt_raw, a_old_record.pmt_raw);
3640 assert_eq!(
3641 a_new_record.pmt_raw, a2_bytes,
3642 "raw PMT must be the new section"
3643 );
3644
3645 assert_eq!(
3647 *d.managed_ca().services().get(&1547).unwrap(),
3648 b_record_before
3649 );
3650 assert_eq!(d.managed_ca().services().len(), 2);
3651 }
3652
3653 #[test]
3656 fn remove_service_after_update_service_uses_the_new_pmt() {
3657 use broadcast_core::Parse;
3658
3659 let mut d = driver_with_sessions();
3660 d.take_notifications();
3661
3662 let a_bytes = build_ca_pmt_fixture(1546);
3663 let a = PmtSection::parse(&a_bytes).unwrap();
3664 d.add_service(&a).unwrap();
3665 d.device_mut().inbound.push_back(sb());
3666 d.pump(Duration::from_millis(10)).unwrap();
3667 let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3668 let a2 = PmtSection::parse(&a2_bytes).unwrap();
3669 d.update_service(&a2).unwrap();
3670 d.device_mut().inbound.push_back(sb());
3671 d.pump(Duration::from_millis(10)).unwrap();
3672
3673 d.remove_service(1546).unwrap();
3674 d.device_mut().inbound.push_back(sb());
3675 d.pump(Duration::from_millis(10)).unwrap();
3676
3677 let removal_new = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3678 .to_bytes()
3679 .unwrap();
3680 let removal_old = build_ca_pmt(&a, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3681 .to_bytes()
3682 .unwrap();
3683 assert_ne!(
3684 removal_new, removal_old,
3685 "fixture sanity: the two PMTs differ"
3686 );
3687 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_new), 1);
3688 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_old), 0);
3689 assert!(d.managed_ca().services().is_empty());
3690 }
3691
3692 #[test]
3695 fn update_service_filters_caids_like_add_service() {
3696 use broadcast_core::Parse;
3697
3698 let mut d = driver_with_sessions();
3699 d.take_notifications();
3700
3701 let two_caids = build_ca_pmt_fixture_two_caids(1546);
3702 let pmt = PmtSection::parse(&two_caids).unwrap();
3703 d.add_service(&pmt).unwrap();
3704 let added = d
3705 .managed_ca()
3706 .services()
3707 .get(&1546)
3708 .unwrap()
3709 .built_ca_pmt
3710 .clone();
3711
3712 d.update_service(&pmt).unwrap();
3713 let updated = d
3714 .managed_ca()
3715 .services()
3716 .get(&1546)
3717 .unwrap()
3718 .built_ca_pmt
3719 .clone();
3720
3721 assert_eq!(added.len(), updated.len());
3723 let diff: Vec<usize> = (0..added.len())
3724 .filter(|&i| added[i] != updated[i])
3725 .collect();
3726 assert_eq!(
3727 diff.len(),
3728 1,
3729 "only list_management may differ, got offsets {diff:?}"
3730 );
3731 assert_eq!(updated[diff[0]], 0x05, "list_management must be update");
3732 }
3733
3734 #[test]
3735 fn update_service_serialize_failure_leaves_record_unchanged() {
3736 let mut d = driver_with_sessions();
3737 let pmt_bytes = build_ca_pmt_fixture(1);
3739 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3740 d.add_service(&pmt).unwrap();
3741
3742 let svc_before = d.managed_ca().services().get(&1).unwrap().clone();
3743
3744 let corrupt = corrupt_ca_section_ctor();
3745 let err = d
3746 .update_service(&corrupt)
3747 .expect_err("unencodable PMT must error");
3748 assert!(
3749 matches!(err, CaError::Serialize(_)),
3750 "expected CaError::Serialize, got {err:?}"
3751 );
3752
3753 let svc_after = d.managed_ca().services().get(&1).unwrap();
3754 assert_eq!(svc_before, *svc_after, "record must be unchanged");
3755 }
3756
3757 #[test]
3758 fn add_service_without_an_open_ca_session_errors_and_records_nothing() {
3759 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3760 let pmt_bytes = build_ca_pmt_fixture(1546);
3761 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3762 let result = d.add_service(&pmt);
3763 let wrote_ca_pmt = d.device().ops.iter().any(|op| match op {
3764 DeviceOp::Write(w) => w.windows(3).any(|x| x == [0x9F, 0x80, 0x32]),
3765 _ => false,
3766 });
3767 assert!(!wrote_ca_pmt, "precondition: nothing can have been sent");
3768 assert!(matches!(result, Err(CaError::NotSent { .. })), "{result:?}");
3769 assert!(d.managed_ca().services().is_empty());
3770 }
3771
3772 #[test]
3773 fn setup_timeout_is_followed_by_a_new_create_t_c() {
3774 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3775 let clock = TestClock::new();
3776 d = d.with_clock(clock.as_fn());
3777 d.init().unwrap();
3778 for _ in 0..60 {
3779 clock.advance(Duration::from_millis(100));
3780 d.pump(Duration::from_millis(100)).unwrap();
3781 }
3782 let create_t_c = d
3783 .device()
3784 .ops
3785 .iter()
3786 .filter(|op| matches!(op, DeviceOp::Write(w) if w.first() == Some(&tags::CREATE_T_C)))
3787 .count();
3788 assert!(
3789 create_t_c > 1,
3790 "6 s of a silent CAM produced {create_t_c} Create_T_C"
3791 );
3792 }
3793
3794 #[test]
3795 fn readable_pumps_still_advance_the_requery_timer() {
3796 let clock = TestClock::new();
3797 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3798 let pmt_bytes = build_ca_pmt_fixture(1546);
3799 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3800 d.add_service(&pmt).unwrap();
3801 d.set_requery_interval(Duration::from_secs(1));
3802 d.pump(Duration::from_millis(10)).unwrap();
3803 let ca_pmt_writes = |d: &Driver<MockCaDevice>| {
3804 d.device()
3805 .ops
3806 .iter()
3807 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3808 .count()
3809 };
3810 let before = ca_pmt_writes(&d);
3811 for _ in 0..8 {
3812 clock.advance(Duration::from_millis(500));
3813 d.device_mut().inbound.push_back(sb());
3814 d.pump(Duration::from_millis(10)).unwrap();
3815 }
3816 assert!(
3817 ca_pmt_writes(&d) > before,
3818 "4 s passed with a 1 s requery interval but no re-query was sent"
3819 );
3820 }
3821
3822 #[test]
3831 fn pending_notifications_are_bounded_and_the_overflow_counted() {
3832 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
3833 d.pump(Duration::from_millis(1)).unwrap();
3834 d.take_notifications();
3835
3836 d.device_mut().slot.module_present = false;
3837 d.pump(Duration::from_millis(1)).unwrap();
3838
3839 let overflow = 16;
3840 for _ in 0..(MAX_PENDING_NOTIFICATIONS + overflow) {
3841 d.device_mut().inbound.push_back(vec![0xFF, 0x00]);
3842 d.pump(Duration::from_millis(1)).unwrap();
3843 }
3844
3845 let notes = d.take_notifications();
3846 assert_eq!(
3847 notes.len(),
3848 MAX_PENDING_NOTIFICATIONS,
3849 "the pending queue must stay at its cap under a notification flood"
3850 );
3851 assert_eq!(
3852 d.notifications_dropped(),
3853 (overflow + 1) as u64,
3854 "the CAM-removed notification and the oldest errors are the ones discarded"
3855 );
3856 assert!(
3857 notes
3858 .iter()
3859 .all(|n| matches!(n, Notification::Error { .. })),
3860 "the discarded entries must be the oldest ones, not the newest"
3861 );
3862 }
3863
3864 #[test]
3865 fn read_buffer_covers_the_largest_legal_device_frame() {
3866 struct BufferProbe(Option<usize>);
3867
3868 impl CaDevice for BufferProbe {
3869 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3870 self.0 = Some(buf.len());
3871 Ok(0)
3872 }
3873 fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3874 Ok(())
3875 }
3876 fn reset(&mut self) -> io::Result<()> {
3877 Ok(())
3878 }
3879 fn slot_info(&mut self) -> io::Result<SlotInfo> {
3880 Ok(SlotInfo {
3881 num: 0,
3882 module_ready: true,
3883 module_present: true,
3884 })
3885 }
3886 fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3887 Ok(true)
3888 }
3889 }
3890
3891 let mut d = Driver::new(BufferProbe(None), DRIVER);
3892 d.pump(Duration::from_millis(1))
3893 .expect("a readable device with no frame is not an error");
3894 assert_eq!(
3895 d.device().0,
3896 Some(MAX_CA_FRAME),
3897 "the read buffer must cover the largest legal device frame"
3898 );
3899 }
3900
3901 #[test]
3906 fn a_legal_oversized_tpdu_is_read_without_an_io_error() {
3907 const DATA_LEN: usize = 5000;
3908
3909 struct OversizedFrameDevice(Option<Vec<u8>>);
3910
3911 impl CaDevice for OversizedFrameDevice {
3912 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3913 let Some(frame) = self.0.take() else {
3914 return Ok(0);
3915 };
3916 if frame.len() > buf.len() {
3917 return Err(io::Error::new(
3918 io::ErrorKind::InvalidData,
3919 "TPDU larger than the read buffer; dropped, not truncated",
3920 ));
3921 }
3922 let n = frame.len();
3923 buf[..n].copy_from_slice(&frame);
3924 Ok(n)
3925 }
3926 fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3927 Ok(())
3928 }
3929 fn reset(&mut self) -> io::Result<()> {
3930 Ok(())
3931 }
3932 fn slot_info(&mut self) -> io::Result<SlotInfo> {
3933 Ok(SlotInfo {
3934 num: 0,
3935 module_ready: true,
3936 module_present: true,
3937 })
3938 }
3939 fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3940 Ok(self.0.is_some())
3941 }
3942 }
3943
3944 let mut frame = vec![tags::DATA_LAST];
3945 let mut length = [0u8; 4];
3946 let coded = dvb_ci::length::encode_into(1 + DATA_LEN, &mut length)
3947 .expect("a legal EN 50221 length");
3948 frame.extend_from_slice(&length[..coded]);
3949 frame.push(0x01);
3950 frame.extend(std::iter::repeat_n(0xAB, DATA_LEN));
3951
3952 let mut d = Driver::new(OversizedFrameDevice(Some(frame)), DRIVER);
3953 assert!(
3954 d.pump(Duration::from_millis(1)).is_ok(),
3955 "a legal {DATA_LEN}-byte TPDU must not fail the read"
3956 );
3957 assert!(
3958 d.device().0.is_none(),
3959 "the frame must have been taken off the device, not refused"
3960 );
3961 }
3962
3963 const APP_INFO_SESSION: u16 = 2;
3966
3967 fn ca_pmt_for(
3968 pmt: &PmtSection<'_>,
3969 list_management: CaPmtListManagement,
3970 cmd_id: CaPmtCmdId,
3971 ) -> Vec<u8> {
3972 let bytes = build_ca_pmt(pmt, list_management, cmd_id)
3973 .to_bytes()
3974 .unwrap();
3975 assert_eq!(&bytes[..3], &[0x9F, 0x80, 0x32], "ca_pmt APDU tag");
3976 let parsed = dvb_ci::objects::ca_pmt::CaPmt::parse(&bytes).unwrap();
3977 assert_eq!(parsed.list_management, list_management);
3978 assert_eq!(parsed.cmd_id, Some(cmd_id));
3979 assert_eq!(parsed.program_number, 1546);
3980 bytes
3981 }
3982
3983 #[test]
3984 fn descramble_writes_the_ok_descrambling_ca_pmt() {
3985 let mut d = driver_with_sessions();
3986 d.take_notifications();
3987 let pmt_bytes = build_ca_pmt_fixture(1546);
3988 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3989
3990 d.descramble(&pmt_bytes).unwrap();
3991 d.device_mut().inbound.push_back(sb());
3992 d.pump(Duration::from_millis(10)).unwrap();
3993
3994 assert_apdu_on_session(
3995 &d,
3996 CA_SESSION,
3997 &ca_pmt_for(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling),
3998 );
3999 }
4000
4001 #[test]
4002 fn descramble_programs_writes_the_ca_pmt_list() {
4003 let mut d = driver_with_sessions();
4004 d.take_notifications();
4005 let pmt_bytes = build_ca_pmt_fixture(1546);
4006 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4007
4008 d.descramble_programs(&[&pmt_bytes]).unwrap();
4009 d.device_mut().inbound.push_back(sb());
4010 d.pump(Duration::from_millis(10)).unwrap();
4011
4012 assert_apdu_on_session(
4013 &d,
4014 CA_SESSION,
4015 &ca_pmt_for(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling),
4016 );
4017 }
4018
4019 #[test]
4020 fn add_program_writes_the_add_ca_pmt() {
4021 let mut d = driver_with_sessions();
4022 d.take_notifications();
4023 let pmt_bytes = build_ca_pmt_fixture(1546);
4024 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4025
4026 d.add_program(&pmt_bytes).unwrap();
4027 d.device_mut().inbound.push_back(sb());
4028 d.pump(Duration::from_millis(10)).unwrap();
4029
4030 assert_apdu_on_session(
4031 &d,
4032 CA_SESSION,
4033 &ca_pmt_for(&pmt, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling),
4034 );
4035 }
4036
4037 #[test]
4038 fn ca_pids_lists_the_programme_and_es_ca_descriptor_pids() {
4039 let mut d = driver_with_sessions();
4040 let pmt_bytes = build_ca_pmt_fixture(1546);
4041 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4042 d.add_service(&pmt).unwrap();
4043
4044 assert_eq!(
4045 d.ca_pids(),
4046 [Pid::from_const(0x0064), Pid::from_const(0x0065)]
4047 );
4048 }
4049
4050 #[test]
4051 fn enter_menu_and_mmi_cancel_write_their_apdus() {
4052 use dvb_ci::objects::application_info::EnterMenu;
4053 use dvb_ci::objects::mmi_high::{Answ, AnswId};
4054
4055 let mut d = driver_with_sessions();
4056 d.take_notifications();
4057
4058 d.enter_menu().unwrap();
4059 d.device_mut().inbound.push_back(sb());
4060 d.pump(Duration::from_millis(10)).unwrap();
4061 assert_apdu_on_session(&d, APP_INFO_SESSION, &ser(&EnterMenu::default()));
4062
4063 d.mmi_cancel().unwrap();
4064 d.device_mut().inbound.push_back(sb());
4065 d.pump(Duration::from_millis(10)).unwrap();
4066 assert_apdu_on_session(
4067 &d,
4068 MMI_SESSION,
4069 &ser(&Answ {
4070 length_form: dvb_ci::length::LengthForm::Minimal,
4071 answ_id: AnswId::Cancel,
4072 text_chars: &[],
4073 }),
4074 );
4075 }
4076
4077 #[test]
4078 fn next_timer_is_none_until_a_write_arms_the_poll_cadence() {
4079 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4080 assert_eq!(d.next_timer(), None);
4081 d.init().unwrap();
4082 assert_eq!(
4083 d.next_timer(),
4084 Some(crate::test_support::DEFAULT_REPLY_TIMEOUT),
4085 "the outstanding Create_T_C arms the reply timer"
4086 );
4087 assert!(d.next_timer().is_some_and(|d| d > Duration::ZERO));
4088 }
4089
4090 #[test]
4093 fn the_settle_deadline_flushes_writes_at_the_exact_instant() {
4094 let clock = TestClock::new();
4095 let mut d = settling_driver(&clock);
4096 d.init().unwrap();
4097
4098 clock.advance(SETTLE - Duration::from_nanos(1));
4099 d.pump(Duration::from_millis(10)).unwrap();
4100 assert_eq!(
4101 create_tc_writes(&d),
4102 0,
4103 "1ns before the deadline the slot is still settling"
4104 );
4105
4106 clock.advance(Duration::from_nanos(1));
4107 d.pump(Duration::from_millis(10)).unwrap();
4108 assert_eq!(
4109 create_tc_writes(&d),
4110 1,
4111 "at the deadline the deferred write flushes"
4112 );
4113 }
4114
4115 #[test]
4118 fn an_einval_at_the_grace_deadline_is_reported() {
4119 let clock = TestClock::new();
4120 let mut d = not_running_driver(&clock, 1);
4121 d.init().unwrap();
4122 clock.advance(SETTLE + SLOT_READY_GRACE);
4123 let err = d
4124 .pump(Duration::from_millis(10))
4125 .expect_err("at the deadline the refusal must be reported");
4126 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
4127 }
4128
4129 #[test]
4132 fn an_einval_retry_waits_slot_retry_before_the_next_attempt() {
4133 let clock = TestClock::new();
4134 let mut d = not_running_driver(&clock, u32::MAX);
4135 d.init().unwrap();
4136 clock.advance(SETTLE + Duration::from_millis(100));
4137 d.pump(Duration::from_millis(10)).unwrap();
4138 assert_eq!(d.device().refused, 1);
4139
4140 clock.advance(Duration::from_millis(100));
4141 d.pump(Duration::from_millis(10)).unwrap();
4142 assert_eq!(d.device().refused, 1, "the retry waits for SLOT_RETRY");
4143
4144 clock.advance(Duration::from_millis(200));
4145 d.pump(Duration::from_millis(10)).unwrap();
4146 assert_eq!(d.device().refused, 2, "the retry fires after SLOT_RETRY");
4147 }
4148
4149 struct ReadBreaksDevice(MockCaDevice);
4151
4152 impl CaDevice for ReadBreaksDevice {
4153 fn read(&mut self, _buf: &mut [u8]) -> io::Result<usize> {
4154 Ok(0)
4155 }
4156 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
4157 self.0.write(buf)
4158 }
4159 fn reset(&mut self) -> io::Result<()> {
4160 self.0.reset()
4161 }
4162 fn reset_settle(&self) -> Duration {
4163 self.0.reset_settle()
4164 }
4165 fn slot_info(&mut self) -> io::Result<SlotInfo> {
4166 self.0.slot_info()
4167 }
4168 fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
4169 Ok(true)
4170 }
4171 }
4172
4173 #[test]
4175 fn a_readiness_edge_with_no_bytes_is_not_a_frame() {
4176 let mut d = Driver::new(ReadBreaksDevice(MockCaDevice::new([])), DRIVER);
4177 d.init().unwrap();
4178 assert!(
4179 !d.pump(Duration::from_millis(10)).unwrap(),
4180 "a zero-byte read is not a processed frame"
4181 );
4182 }
4183
4184 #[test]
4187 fn an_old_refusal_in_a_full_queue_is_not_reported_for_a_healthy_send() {
4188 let mut d = driver_with_sessions();
4189 for _ in 0..MAX_PENDING_NOTIFICATIONS + 5 {
4190 d.push_notification(Notification::CamReady);
4191 }
4192 d.push_notification(Notification::Error {
4193 detail: "an earlier failure".to_string(),
4194 });
4195 assert_eq!(d.notifications.len(), MAX_PENDING_NOTIFICATIONS);
4196 assert!(d.notifications_dropped() > 0);
4197
4198 let pmt_bytes = build_ca_pmt_fixture(1546);
4199 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4200 d.add_service(&pmt)
4201 .expect("a healthy send must not inherit an older refusal");
4202 }
4203
4204 #[test]
4206 fn a_refusal_produced_by_this_call_is_reported() {
4207 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4208 d.init().unwrap();
4209 let pmt_bytes = build_ca_pmt_fixture(1546);
4210 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
4211 let err = d
4212 .add_service(&pmt)
4213 .expect_err("no open CA session means the ca_pmt was not handed over");
4214 assert!(
4215 matches!(err, CaError::NotSent { .. }),
4216 "expected CaError::NotSent, got {err:?}"
4217 );
4218 }
4219
4220 fn ca_info(ids: &[u16]) -> Notification {
4221 Notification::CaInfo {
4222 ca_system_ids: ids.to_vec(),
4223 }
4224 }
4225
4226 fn ca_pmt_reply(descrambling_ok: bool) -> Notification {
4227 Notification::CaPmtReply {
4228 program_number: 1546,
4229 ca_enable: None,
4230 descrambling_ok,
4231 }
4232 }
4233
4234 #[test]
4235 fn infer_card_follows_the_ca_info_edges() {
4236 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4237 assert!(d.infer_card(&ca_info(&[])).is_empty());
4238 assert_eq!(
4239 d.infer_card(&ca_info(&[0x0500])),
4240 vec![Notification::HotPlug(HotPlug::CardInserted)]
4241 );
4242 assert!(
4243 d.infer_card(&ca_info(&[0x0500])).is_empty(),
4244 "the same CAID set repeated is not an edge"
4245 );
4246 assert_eq!(
4247 d.infer_card(&ca_info(&[0x0500, 0x0B00])),
4248 vec![Notification::HotPlug(HotPlug::CardChanged)]
4249 );
4250 assert_eq!(
4251 d.infer_card(&ca_info(&[])),
4252 vec![Notification::HotPlug(HotPlug::CardRemoved)]
4253 );
4254 }
4255
4256 #[test]
4257 fn infer_card_follows_the_descrambling_reply_edges() {
4258 let mut d = Driver::new(MockCaDevice::new([]), DRIVER);
4259 assert!(d.infer_card(&ca_pmt_reply(false)).is_empty());
4260 assert_eq!(
4261 d.infer_card(&ca_pmt_reply(true)),
4262 vec![Notification::HotPlug(HotPlug::CardInserted)]
4263 );
4264 assert!(
4265 d.infer_card(&ca_pmt_reply(true)).is_empty(),
4266 "the same state repeated is not an edge"
4267 );
4268 assert_eq!(
4269 d.infer_card(&ca_pmt_reply(false)),
4270 vec![Notification::HotPlug(HotPlug::CardRemoved)]
4271 );
4272 }
4273}