1use mpeg_ts::pid::Pid;
7use std::collections::{BTreeSet, VecDeque};
8use std::io;
9use std::time::{Duration, Instant};
10
11use broadcast_common::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_common::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;
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
42pub const MAX_PENDING_NOTIFICATIONS: usize = 1024;
53
54type Clock = Box<dyn Fn() -> Instant>;
59
60fn default_clock() -> Clock {
61 Box::new(Instant::now)
62}
63
64pub struct Driver<D: CaDevice> {
66 device: D,
67 stack: CiStack,
68 notifications: VecDeque<Notification>,
69 notifications_dropped: u64,
71 next_timer: Option<Duration>,
73 buf: Vec<u8>,
75 last_slot: Option<SlotInfo>,
82 last_caids: Option<BTreeSet<u16>>,
85 last_descrambling_ok: Option<bool>,
88 last_mmi_card_present: Option<bool>,
94 managed: ManagedCa,
97 last_pump: Option<Instant>,
102 clock: Clock,
104 requery_pending: Option<CaError>,
108 settle_until: Option<Instant>,
112 deferred_writes: Vec<Vec<u8>>,
115 slot_ready_deadline: Option<Instant>,
120}
121
122const SLOT_READY_GRACE: Duration = Duration::from_secs(12);
130const SLOT_RETRY: Duration = Duration::from_millis(250);
132
133impl<D: CaDevice> Driver<D> {
134 #[must_use]
136 pub fn new(device: D) -> Self {
137 Self {
138 device,
139 stack: CiStack::new(),
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() == 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 + 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 + 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();
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 broadcast_common::Serialize;
945 use dvb_ci::tpdu::tags;
946
947 pub(crate) fn ser<S: Serialize>(s: &S) -> Vec<u8> {
948 let mut b = vec![0u8; s.serialized_len()];
949 match s.serialize_into(&mut b) {
950 Ok(n) => b.truncate(n),
951 Err(_) => b.clear(),
952 }
953 b
954 }
955
956 #[derive(Clone)]
962 pub(crate) struct TestClock(std::rc::Rc<std::cell::Cell<Instant>>);
963
964 impl TestClock {
965 pub(crate) fn new() -> Self {
966 Self(std::rc::Rc::new(std::cell::Cell::new(Instant::now())))
967 }
968
969 pub(crate) fn advance(&self, d: Duration) {
971 self.0.set(self.0.get() + d);
972 }
973
974 pub(crate) fn as_fn(&self) -> impl Fn() -> Instant + 'static {
976 let cell = self.0.clone();
977 move || cell.get()
978 }
979 }
980
981 fn r_data(tcid: u8, spdu: &[u8]) -> Vec<u8> {
984 use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
985 let mut v = vec![tpdu_tags::DATA_LAST, (1 + spdu.len()) as u8, tcid];
986 v.extend_from_slice(spdu);
987 v.extend_from_slice(&[tpdu_tags::SB, 0x02, tcid, SbValue::new(false).0]);
988 v
989 }
990
991 pub(crate) fn r_apdu(session_nb: u16, apdu: &[u8]) -> Vec<u8> {
994 use dvb_ci::spdu::SessionNumber;
995 let mut spdu = ser(&SessionNumber {
996 length_form: dvb_ci::length::LengthForm::Minimal,
997 session_nb,
998 });
999 spdu.extend_from_slice(apdu);
1000 r_data(1, &spdu)
1001 }
1002
1003 pub(crate) fn sb() -> Vec<u8> {
1006 use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
1007 vec![tpdu_tags::SB, 0x02, 0x01, SbValue::new(false).0]
1008 }
1009
1010 pub(crate) fn feed(d: &mut Driver<MockCaDevice>, frame: Vec<u8>) {
1013 d.device_mut().inbound.push_back(frame);
1014 d.pump(Duration::from_millis(10)).unwrap();
1015 for _ in 0..8 {
1016 d.device_mut().inbound.push_back(sb());
1017 d.pump(Duration::from_millis(10)).unwrap();
1018 }
1019 }
1020
1021 pub(crate) fn driver_with_sessions() -> Driver<MockCaDevice> {
1025 use dvb_ci::objects::resource_manager::Profile;
1026 use dvb_ci::resource::{
1027 APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, HOST_CONTROL, MMI,
1028 RESOURCE_MANAGER,
1029 };
1030 use dvb_ci::spdu::{CreateSessionResponse, OpenSessionRequest, SessionStatus};
1031
1032 let mut d = Driver::new(MockCaDevice::new([]));
1033 d.init().unwrap();
1034 feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1036 feed(
1038 &mut d,
1039 r_data(
1040 1,
1041 &ser(&OpenSessionRequest {
1042 length_form: dvb_ci::length::LengthForm::Minimal,
1043 resource: RESOURCE_MANAGER,
1044 }),
1045 ),
1046 );
1047 feed(
1050 &mut d,
1051 r_apdu(
1052 1,
1053 &ser(&Profile {
1054 length_form: dvb_ci::length::LengthForm::Minimal,
1055 resources: vec![
1056 APPLICATION_INFORMATION,
1057 CONDITIONAL_ACCESS_SUPPORT,
1058 MMI,
1059 HOST_CONTROL,
1060 ],
1061 }),
1062 ),
1063 );
1064 for (nb, res) in [
1066 (2u16, APPLICATION_INFORMATION),
1067 (3, CONDITIONAL_ACCESS_SUPPORT),
1068 (4, MMI),
1069 (5, HOST_CONTROL),
1070 ] {
1071 feed(
1072 &mut d,
1073 r_data(
1074 1,
1075 &ser(&CreateSessionResponse {
1076 length_form: dvb_ci::length::LengthForm::Minimal,
1077 status: SessionStatus::Ok,
1078 resource: res,
1079 session_nb: nb,
1080 }),
1081 ),
1082 );
1083 }
1084 d
1085 }
1086
1087 const RM_SESSION: u16 = 1;
1091 pub(crate) const CA_SESSION: u16 = 3;
1092 const MMI_SESSION: u16 = 4;
1093 const HOST_CONTROL_SESSION: u16 = 5;
1094
1095 #[test]
1096 fn host_control_tune_apdu_surfaces_notification_via_driver() {
1097 use dvb_ci::objects::host_control::Tune;
1098
1099 let mut d = driver_with_sessions();
1100 let hc_nb = HOST_CONTROL_SESSION;
1101 d.take_notifications(); let tune = Tune {
1105 length_form: dvb_ci::length::LengthForm::Minimal,
1106 network_id: 0x1122,
1107 original_network_id: 0x3344,
1108 transport_stream_id: 0x5566,
1109 service_id: 0x7788,
1110 };
1111 feed(&mut d, r_apdu(hc_nb, &ser(&tune)));
1112
1113 let notes = d.take_notifications();
1115 assert!(
1116 notes.contains(&Notification::HostControl(HostControlEvent::Tune {
1117 network_id: 0x1122,
1118 original_network_id: 0x3344,
1119 transport_stream_id: 0x5566,
1120 service_id: 0x7788,
1121 })),
1122 "expected HostControl(Tune) notification, got {notes:?}"
1123 );
1124 }
1125
1126 #[test]
1129 fn padded_tune_from_the_cam_surfaces_an_error_notification() {
1130 let mut d = driver_with_sessions();
1131 d.take_notifications();
1132 let padded = [
1134 0x9F, 0x84, 0x00, 0x09, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0xEE,
1135 ];
1136 feed(&mut d, r_apdu(HOST_CONTROL_SESSION, &padded));
1137 let notes = d.take_notifications();
1138 assert!(
1139 notes.iter().any(
1140 |n| matches!(n, Notification::Error { detail } if detail.contains("trailing bytes"))
1141 ),
1142 "expected an Error notification naming the trailing bytes, got {notes:?}"
1143 );
1144 assert!(
1145 !notes
1146 .iter()
1147 .any(|n| matches!(n, Notification::HostControl(_))),
1148 "a refused tune must not also surface as a HostControl event: {notes:?}"
1149 );
1150 }
1151
1152 #[test]
1155 fn malformed_mmi_apdu_from_the_cam_surfaces_an_error_notification() {
1156 let mut d = driver_with_sessions();
1157 d.take_notifications();
1158 feed(&mut d, r_apdu(MMI_SESSION, &[0x9F, 0x88, 0x07, 0x01, 0x00]));
1160 let notes = d.take_notifications();
1161 assert!(
1162 notes
1163 .iter()
1164 .any(|n| matches!(n, Notification::Error { .. })),
1165 "expected an Error notification, got {notes:?}"
1166 );
1167 }
1168
1169 #[test]
1170 fn profile_reply_advertises_host_control() {
1171 use broadcast_common::Parse;
1172 use dvb_ci::objects::resource_manager::{Profile, ProfileEnq};
1173 use dvb_ci::resource::{HOST_CONTROL, RESOURCE_MANAGER};
1174
1175 let mut d = Driver::new(MockCaDevice::new([]));
1176 d.init().unwrap();
1177 feed(&mut d, vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1178 feed(
1179 &mut d,
1180 r_data(
1181 1,
1182 &ser(&dvb_ci::spdu::OpenSessionRequest {
1183 length_form: dvb_ci::length::LengthForm::Minimal,
1184 resource: RESOURCE_MANAGER,
1185 }),
1186 ),
1187 );
1188 feed(&mut d, r_apdu(RM_SESSION, &ser(&ProfileEnq::default())));
1190
1191 let want = dvb_ci::tag::PROFILE.to_bytes();
1194 let found = d.device().ops.iter().any(|op| {
1195 if let DeviceOp::Write(w) = op
1196 && let Some(pos) = w.windows(3).position(|x| x == want)
1197 && let Ok(p) = Profile::parse(&w[pos..])
1198 {
1199 return p.resources.contains(&HOST_CONTROL);
1200 }
1201 false
1202 });
1203 assert!(found, "profile reply must advertise HOST_CONTROL");
1204 }
1205
1206 #[test]
1207 fn mmi_menu_answ_and_answ_are_byte_exact_on_the_mmi_session() {
1208 use dvb_ci::objects::mmi_high::{Answ, AnswId, MenuAnsw};
1209
1210 let mut d = driver_with_sessions();
1211 let mmi_nb = MMI_SESSION;
1212
1213 d.mmi_menu_answer(2).unwrap();
1216 d.device_mut().inbound.push_back(sb());
1217 d.pump(Duration::from_millis(10)).unwrap();
1218 assert_apdu_on_session(
1219 &d,
1220 mmi_nb,
1221 &ser(&MenuAnsw {
1222 length_form: dvb_ci::length::LengthForm::Minimal,
1223 choice_ref: 2,
1224 }),
1225 );
1226
1227 d.mmi_enquiry_answer(b"1234").unwrap();
1229 d.device_mut().inbound.push_back(sb());
1230 d.pump(Duration::from_millis(10)).unwrap();
1231 assert_apdu_on_session(
1232 &d,
1233 mmi_nb,
1234 &ser(&Answ {
1235 length_form: dvb_ci::length::LengthForm::Minimal,
1236 answ_id: AnswId::Answer,
1237 text_chars: b"1234",
1238 }),
1239 );
1240 }
1241
1242 fn assert_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) {
1245 use dvb_ci::spdu::SessionNumber;
1246 let mut want = ser(&SessionNumber {
1247 length_form: dvb_ci::length::LengthForm::Minimal,
1248 session_nb,
1249 });
1250 want.extend_from_slice(apdu);
1251 let hit = d.device().ops.iter().any(|op| match op {
1252 DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1253 _ => false,
1254 });
1255 assert!(
1256 hit,
1257 "expected APDU {apdu:02X?} on session {session_nb} (session-prefixed {want:02X?}) in writes"
1258 );
1259 }
1260
1261 fn count_apdu_on_session(d: &Driver<MockCaDevice>, session_nb: u16, apdu: &[u8]) -> usize {
1265 use dvb_ci::spdu::SessionNumber;
1266 let mut want = ser(&SessionNumber {
1267 length_form: dvb_ci::length::LengthForm::Minimal,
1268 session_nb,
1269 });
1270 want.extend_from_slice(apdu);
1271 d.device()
1272 .ops
1273 .iter()
1274 .filter(|op| match op {
1275 DeviceOp::Write(w) => w.windows(want.len()).any(|x| x == want.as_slice()),
1276 _ => false,
1277 })
1278 .count()
1279 }
1280
1281 struct SettleDevice {
1284 inner: MockCaDevice,
1285 settle: Duration,
1286 }
1287
1288 impl CaDevice for SettleDevice {
1289 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1290 self.inner.read(buf)
1291 }
1292 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1293 self.inner.write(buf)
1294 }
1295 fn reset(&mut self) -> io::Result<()> {
1296 self.inner.reset()
1297 }
1298 fn reset_settle(&self) -> Duration {
1299 self.settle
1300 }
1301 fn slot_info(&mut self) -> io::Result<SlotInfo> {
1302 self.inner.slot_info()
1303 }
1304 fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1305 self.inner.poll(timeout)
1306 }
1307 }
1308
1309 const SETTLE: Duration = Duration::from_secs(3);
1310
1311 fn settling_driver(clock: &TestClock) -> Driver<SettleDevice> {
1312 Driver::new(SettleDevice {
1313 inner: MockCaDevice::new([]),
1314 settle: SETTLE,
1315 })
1316 .with_clock(clock.as_fn())
1317 }
1318
1319 fn create_tc_writes(d: &Driver<SettleDevice>) -> usize {
1320 d.device()
1321 .inner
1322 .ops
1323 .iter()
1324 .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1325 .count()
1326 }
1327
1328 struct NotRunningDevice {
1332 inner: SettleDevice,
1333 refusals_left: u32,
1334 refused: u32,
1335 }
1336
1337 impl CaDevice for NotRunningDevice {
1338 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1339 self.inner.read(buf)
1340 }
1341 fn write(&mut self, buf: &[u8]) -> io::Result<()> {
1342 if self.refusals_left > 0 {
1343 self.refusals_left -= 1;
1344 self.refused += 1;
1345 return Err(io::Error::from(io::ErrorKind::InvalidInput));
1346 }
1347 self.inner.write(buf)
1348 }
1349 fn reset(&mut self) -> io::Result<()> {
1350 self.inner.reset()
1351 }
1352 fn reset_settle(&self) -> Duration {
1353 self.inner.reset_settle()
1354 }
1355 fn slot_info(&mut self) -> io::Result<SlotInfo> {
1356 self.inner.slot_info()
1357 }
1358 fn poll(&mut self, timeout: Duration) -> io::Result<bool> {
1359 self.inner.poll(timeout)
1360 }
1361 }
1362
1363 fn not_running_driver(clock: &TestClock, refusals: u32) -> Driver<NotRunningDevice> {
1364 Driver::new(NotRunningDevice {
1365 inner: SettleDevice {
1366 inner: MockCaDevice::new([]),
1367 settle: SETTLE,
1368 },
1369 refusals_left: refusals,
1370 refused: 0,
1371 })
1372 .with_clock(clock.as_fn())
1373 }
1374
1375 fn create_tc_count(d: &Driver<NotRunningDevice>) -> usize {
1376 d.device()
1377 .inner
1378 .inner
1379 .ops
1380 .iter()
1381 .filter(|o| matches!(o, DeviceOp::Write(w) if w[0] == tags::CREATE_T_C))
1382 .count()
1383 }
1384
1385 #[test]
1390 fn post_reset_einval_is_retried_until_the_slot_is_running() {
1391 let clock = TestClock::new();
1392 let mut d = not_running_driver(&clock, 3);
1393 d.init().unwrap();
1394 clock.advance(SETTLE + Duration::from_millis(100));
1395 for _ in 0..10 {
1396 d.pump(Duration::from_millis(10))
1397 .expect("a not-yet-RUNNING slot (EINVAL) must be retried, not reported");
1398 if create_tc_count(&d) == 1 {
1399 break;
1400 }
1401 clock.advance(Duration::from_millis(300));
1402 }
1403 assert_eq!(d.device().refused, 3, "the three refusals were consumed");
1404 assert_eq!(create_tc_count(&d), 1, "Create_T_C delivered exactly once");
1405 }
1406
1407 #[test]
1410 fn post_reset_einval_is_reported_once_the_grace_window_has_passed() {
1411 let clock = TestClock::new();
1412 let mut d = not_running_driver(&clock, u32::MAX);
1413 let start = clock.0.get();
1414 d.init().unwrap();
1415 clock.advance(SETTLE + Duration::from_millis(100));
1416 let mut failure = None;
1417 for _ in 0..80 {
1418 match d.pump(Duration::from_millis(10)) {
1419 Ok(_) => clock.advance(Duration::from_millis(300)),
1420 Err(e) => {
1421 failure = Some(e);
1422 break;
1423 }
1424 }
1425 }
1426 let e = failure.expect("a slot that never runs must eventually be reported");
1427 assert_eq!(e.kind(), io::ErrorKind::InvalidInput);
1428 assert!(
1429 clock.0.get() >= start + SETTLE + SLOT_READY_GRACE,
1430 "reported before the grace window ended"
1431 );
1432 assert_eq!(create_tc_count(&d), 0);
1433 }
1434
1435 #[test]
1440 fn requery_armed_before_the_handshake_sends_nothing() {
1441 let clock = TestClock::new();
1442 let mut d = Driver::new(MockCaDevice::new([])).with_clock(clock.as_fn());
1443 d.set_requery_interval(Duration::from_secs(10));
1444 d.init().unwrap();
1445 for _ in 0..40 {
1446 clock.advance(Duration::from_secs(1));
1447 d.pump(Duration::from_millis(100)).unwrap();
1448 }
1449 let ca_pmt_tag = [0x9F, 0x80, 0x32];
1450 let ca_pmt_writes = d
1451 .device()
1452 .ops
1453 .iter()
1454 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == ca_pmt_tag)))
1455 .count();
1456 assert_eq!(
1457 ca_pmt_writes, 0,
1458 "re-query wrote a ca_pmt before any service"
1459 );
1460 }
1461
1462 #[test]
1465 fn reset_does_not_block_pump() {
1466 let clock = TestClock::new();
1467 let mut d = settling_driver(&clock);
1468 let t = std::time::Instant::now();
1469 d.init().unwrap();
1470 d.pump(Duration::from_millis(10)).unwrap();
1471 assert!(t.elapsed() < Duration::from_secs(1), "reset/pump blocked");
1472 assert_eq!(d.device().inner.ops[0], DeviceOp::Reset);
1473 }
1474
1475 #[test]
1479 fn no_transport_traffic_until_settle_elapsed() {
1480 let clock = TestClock::new();
1481 let mut d = settling_driver(&clock);
1482 d.device_mut()
1483 .inner
1484 .inbound
1485 .push_back(vec![tags::C_T_C_REPLY, 0x01, 0x01]);
1486 d.init().unwrap();
1487 for _ in 0..5 {
1488 clock.advance(Duration::from_millis(500));
1489 d.pump(Duration::from_millis(10)).unwrap();
1490 }
1491 assert_eq!(create_tc_writes(&d), 0);
1493 assert_eq!(
1494 d.device().inner.inbound.len(),
1495 1,
1496 "frame read while settling"
1497 );
1498
1499 clock.advance(Duration::from_millis(600));
1500 d.pump(Duration::from_millis(10)).unwrap();
1501 assert_eq!(create_tc_writes(&d), 1);
1502
1503 let mut z = Driver::new(MockCaDevice::new([]));
1504 z.init().unwrap();
1505 assert_eq!(
1506 d.device().inner.written()[..3],
1507 z.device().written()[..3],
1508 "post-settle Create_T_C differs from the zero-settle sequence"
1509 );
1510 assert!(d.device().inner.inbound.is_empty());
1513 }
1514
1515 #[test]
1518 fn second_reset_restarts_settle() {
1519 let clock = TestClock::new();
1520 let mut d = settling_driver(&clock);
1521 d.init().unwrap();
1522 clock.advance(Duration::from_secs(2));
1523 d.pump(Duration::from_millis(10)).unwrap();
1524 d.init().unwrap(); clock.advance(Duration::from_secs(2)); d.pump(Duration::from_millis(10)).unwrap();
1527 assert_eq!(create_tc_writes(&d), 0, "first deadline wrongly honoured");
1528 clock.advance(Duration::from_millis(1500)); d.pump(Duration::from_millis(10)).unwrap();
1530 assert_eq!(create_tc_writes(&d), 1);
1531 }
1532
1533 #[test]
1536 fn slot_sampling_continues_while_settling() {
1537 let clock = TestClock::new();
1538 let mut d = settling_driver(&clock);
1539 d.init().unwrap();
1540 d.take_notifications();
1541 d.device_mut().inner.slot.module_present = false;
1542 clock.advance(Duration::from_millis(500));
1543 d.pump(Duration::from_millis(10)).unwrap();
1544 let notes = d.take_notifications();
1545 assert!(
1546 notes
1547 .iter()
1548 .any(|n| matches!(n, Notification::HotPlug(HotPlug::CamRemoved))),
1549 "{notes:?}"
1550 );
1551 assert_eq!(create_tc_writes(&d), 0);
1552 }
1553
1554 #[test]
1555 fn init_drives_reset_slotinfo_and_create_tc_to_device() {
1556 let mut d = Driver::new(MockCaDevice::new([]));
1557 d.init().unwrap();
1558 let ops = &d.device().ops;
1559 assert_eq!(ops[0], DeviceOp::Reset);
1560 assert_eq!(ops[1], DeviceOp::SlotInfo);
1561 assert!(matches!(&ops[2], DeviceOp::Write(w) if w[0] == tags::CREATE_T_C));
1562 }
1563
1564 #[test]
1565 fn reads_reply_then_polls_on_pump() {
1566 let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1568 let clock = TestClock::new();
1569 let mut d = Driver::new(dev).with_clock(clock.as_fn());
1570 d.init().unwrap();
1571 assert!(d.pump(Duration::from_millis(100)).unwrap());
1573 clock.advance(Duration::from_millis(100));
1578 assert!(!d.pump(Duration::from_millis(100)).unwrap());
1580 let last = d.device().ops.last().unwrap();
1581 assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1582 }
1583
1584 #[test]
1590 fn pump_advances_the_stack_clock_by_real_elapsed_time_not_by_timeout() {
1591 let dev = MockCaDevice::new([vec![tags::C_T_C_REPLY, 0x01, 0x01]]);
1592 let clock = TestClock::new();
1593 let mut d = Driver::new(dev).with_clock(clock.as_fn());
1594 d.init().unwrap();
1595 assert!(d.pump(Duration::from_secs(1)).unwrap());
1596
1597 clock.advance(Duration::from_millis(1));
1601 assert!(!d.pump(Duration::from_secs(1)).unwrap());
1602 assert!(
1603 d.device().ops.last().is_none_or(|op| !matches!(
1604 op,
1605 DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)
1606 )),
1607 "must not poll after only 1ms of real elapsed time, regardless of the 1s `timeout` argument"
1608 );
1609
1610 clock.advance(Duration::from_millis(100));
1611 assert!(!d.pump(Duration::from_secs(1)).unwrap());
1612 let last = d.device().ops.last().unwrap();
1613 assert!(matches!(last, DeviceOp::Write(w) if w.first() == Some(&tags::DATA_LAST)));
1614 }
1615
1616 #[test]
1619 fn cam_insert_edge_emits_cam_present_once_and_redrives_handshake() {
1620 let mut dev = MockCaDevice::new([]);
1621 dev.slot = SlotInfo {
1622 num: 0,
1623 module_ready: false,
1624 module_present: false,
1625 };
1626 let mut d = Driver::new(dev);
1627 d.init().unwrap();
1628 let notes = d.take_notifications();
1631 assert!(
1632 !notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1633 "baseline observation must not fire CamPresent, got {notes:?}"
1634 );
1635 let resets_before = d
1636 .device()
1637 .ops
1638 .iter()
1639 .filter(|o| **o == DeviceOp::Reset)
1640 .count();
1641
1642 d.device_mut().slot = SlotInfo {
1644 num: 0,
1645 module_ready: true,
1646 module_present: true,
1647 };
1648 d.pump(Duration::from_millis(10)).unwrap();
1649
1650 let notes = d.take_notifications();
1651 let cam_present_count = notes
1652 .iter()
1653 .filter(|n| **n == Notification::HotPlug(HotPlug::CamPresent))
1654 .count();
1655 assert_eq!(
1656 cam_present_count, 1,
1657 "expected exactly one CamPresent, got {notes:?}"
1658 );
1659 let resets_after = d
1661 .device()
1662 .ops
1663 .iter()
1664 .filter(|o| **o == DeviceOp::Reset)
1665 .count();
1666 assert_eq!(
1667 resets_after,
1668 resets_before + 1,
1669 "expected one fresh Reset on re-insert"
1670 );
1671 assert!(
1672 matches!(d.device().ops.last(), Some(DeviceOp::Write(w)) if w[0] == tags::CREATE_T_C),
1673 "expected the handshake re-driven (CREATE_T_C written), got {:?}",
1674 d.device().ops.last()
1675 );
1676 }
1677
1678 #[test]
1679 fn cam_remove_edge_emits_cam_removed_and_re_insert_re_handshakes() {
1680 let mut d = driver_with_sessions();
1681 d.take_notifications();
1682
1683 d.device_mut().slot.module_present = false;
1685 d.pump(Duration::from_millis(10)).unwrap();
1686 let notes = d.take_notifications();
1687 assert!(
1688 notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
1689 "expected CamRemoved, got {notes:?}"
1690 );
1691
1692 d.mmi_menu_answer(0).unwrap();
1696 let notes = d.take_notifications();
1697 assert!(
1698 notes
1699 .iter()
1700 .any(|n| matches!(n, Notification::Error { .. })),
1701 "expected no open MMI session after teardown, got {notes:?}"
1702 );
1703
1704 let resets_before = d
1706 .device()
1707 .ops
1708 .iter()
1709 .filter(|o| **o == DeviceOp::Reset)
1710 .count();
1711 d.device_mut().slot.module_present = true;
1712 d.device_mut().slot.module_ready = true;
1713 d.pump(Duration::from_millis(10)).unwrap();
1714 let notes = d.take_notifications();
1715 assert!(
1716 notes.contains(&Notification::HotPlug(HotPlug::CamPresent)),
1717 "expected CamPresent on re-insert, got {notes:?}"
1718 );
1719 let resets_after = d
1720 .device()
1721 .ops
1722 .iter()
1723 .filter(|o| **o == DeviceOp::Reset)
1724 .count();
1725 assert_eq!(resets_after, resets_before + 1, "expected a fresh Reset");
1726 }
1727
1728 #[test]
1729 fn slot_status_unchanged_across_polls_emits_no_hotplug_notifications() {
1730 let mut d = Driver::new(MockCaDevice::new([]));
1731 d.init().unwrap();
1732 d.take_notifications();
1733
1734 for _ in 0..5 {
1735 d.pump(Duration::from_millis(10)).unwrap();
1736 }
1737 let notes = d.take_notifications();
1738 assert!(
1739 !notes.iter().any(|n| matches!(
1740 n,
1741 Notification::HotPlug(HotPlug::CamPresent | HotPlug::CamRemoved)
1742 )),
1743 "unchanged slot status must not emit hot-plug notifications, got {notes:?}"
1744 );
1745 }
1746
1747 #[test]
1748 fn ca_info_caid_set_change_infers_card_inserted_then_changed() {
1749 use dvb_ci::objects::ca_info::CaInfo;
1750
1751 let mut d = driver_with_sessions();
1752 d.take_notifications();
1753
1754 feed(
1756 &mut d,
1757 r_apdu(
1758 CA_SESSION,
1759 &ser(&CaInfo {
1760 length_form: dvb_ci::length::LengthForm::Minimal,
1761 ca_system_ids: vec![],
1762 }),
1763 ),
1764 );
1765 let notes = d.take_notifications();
1766 assert!(
1767 !notes.iter().any(|n| matches!(
1768 n,
1769 Notification::HotPlug(
1770 HotPlug::CardInserted | HotPlug::CardChanged | HotPlug::CardRemoved
1771 )
1772 )),
1773 "first ca_info must only establish the baseline, got {notes:?}"
1774 );
1775
1776 feed(
1778 &mut d,
1779 r_apdu(
1780 CA_SESSION,
1781 &ser(&CaInfo {
1782 length_form: dvb_ci::length::LengthForm::Minimal,
1783 ca_system_ids: vec![0x0B00],
1784 }),
1785 ),
1786 );
1787 let notes = d.take_notifications();
1788 assert!(
1789 notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1790 "expected CardInserted, got {notes:?}"
1791 );
1792
1793 feed(
1795 &mut d,
1796 r_apdu(
1797 CA_SESSION,
1798 &ser(&CaInfo {
1799 length_form: dvb_ci::length::LengthForm::Minimal,
1800 ca_system_ids: vec![0x1800],
1801 }),
1802 ),
1803 );
1804 let notes = d.take_notifications();
1805 assert!(
1806 notes.contains(&Notification::HotPlug(HotPlug::CardChanged)),
1807 "expected CardChanged, got {notes:?}"
1808 );
1809 }
1810
1811 #[test]
1812 fn ca_pmt_reply_descrambling_transition_infers_card_present_then_removed() {
1813 use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1814
1815 fn reply(ca_enable: Option<CaEnable>) -> CaPmtReply {
1816 CaPmtReply {
1817 reserved_ca_enable: Default::default(),
1818 reserved_version: Default::default(),
1819 length_form: dvb_ci::length::LengthForm::Minimal,
1820 program_number: 1,
1821 version_number: 1,
1822 current_next_indicator: true,
1823 ca_enable,
1824 streams: vec![],
1825 }
1826 }
1827
1828 let mut d = driver_with_sessions();
1829 d.take_notifications();
1830
1831 feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1833 let notes = d.take_notifications();
1834 assert!(
1835 !notes.iter().any(|n| matches!(
1836 n,
1837 Notification::HotPlug(HotPlug::CardInserted | HotPlug::CardRemoved)
1838 )),
1839 "first ca_pmt_reply must only establish the baseline, got {notes:?}"
1840 );
1841
1842 feed(
1844 &mut d,
1845 r_apdu(CA_SESSION, &ser(&reply(Some(CaEnable::Possible)))),
1846 );
1847 let notes = d.take_notifications();
1848 assert!(
1849 notes.contains(&Notification::HotPlug(HotPlug::CardInserted)),
1850 "expected CardInserted, got {notes:?}"
1851 );
1852
1853 feed(&mut d, r_apdu(CA_SESSION, &ser(&reply(None))));
1855 let notes = d.take_notifications();
1856 assert!(
1857 notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1858 "expected CardRemoved, got {notes:?}"
1859 );
1860 }
1861
1862 #[test]
1863 fn ca_pmt_reply_surfaces_typed_ca_enable() {
1864 use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
1865
1866 let mut d = driver_with_sessions();
1867 d.take_notifications();
1868
1869 feed(
1872 &mut d,
1873 r_apdu(
1874 CA_SESSION,
1875 &ser(&CaPmtReply {
1876 reserved_ca_enable: Default::default(),
1877 reserved_version: Default::default(),
1878 length_form: dvb_ci::length::LengthForm::Minimal,
1879 program_number: 7,
1880 version_number: 1,
1881 current_next_indicator: true,
1882 ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1883 streams: vec![],
1884 }),
1885 ),
1886 );
1887 let notes = d.take_notifications();
1888 assert!(
1889 notes.contains(&Notification::CaPmtReply {
1890 program_number: 7,
1891 ca_enable: Some(CaEnable::PossibleTechnicalDialogue),
1892 descrambling_ok: true,
1893 }),
1894 "expected typed ca_enable on CaPmtReply, got {notes:?}"
1895 );
1896 }
1897
1898 #[test]
1899 fn ca_pmt_reply_flag_clear_surfaces_none() {
1900 use dvb_ci::objects::ca_pmt_reply::CaPmtReply;
1901
1902 let mut d = driver_with_sessions();
1903 d.take_notifications();
1904
1905 feed(
1908 &mut d,
1909 r_apdu(
1910 CA_SESSION,
1911 &ser(&CaPmtReply {
1912 reserved_ca_enable: Default::default(),
1913 reserved_version: Default::default(),
1914 length_form: dvb_ci::length::LengthForm::Minimal,
1915 program_number: 7,
1916 version_number: 1,
1917 current_next_indicator: true,
1918 ca_enable: None,
1919 streams: vec![],
1920 }),
1921 ),
1922 );
1923 let notes = d.take_notifications();
1924 assert!(
1925 notes.contains(&Notification::CaPmtReply {
1926 program_number: 7,
1927 ca_enable: None,
1928 descrambling_ok: false,
1929 }),
1930 "expected ca_enable None on flag-clear CaPmtReply, got {notes:?}"
1931 );
1932 }
1933
1934 #[test]
1935 fn mmi_no_card_text_infers_card_removed() {
1936 use dvb_ci::objects::mmi_high::Enq;
1937
1938 let mut d = driver_with_sessions();
1939 d.take_notifications();
1940
1941 feed(
1942 &mut d,
1943 r_apdu(
1944 MMI_SESSION,
1945 &ser(&Enq {
1946 reserved: Default::default(),
1947 length_form: dvb_ci::length::LengthForm::Minimal,
1948 blind_answer: false,
1949 answer_text_length: 0,
1950 text_chars: b"NO CARD detected - please insert your smart card",
1951 }),
1952 ),
1953 );
1954
1955 let notes = d.take_notifications();
1956 assert!(
1957 notes.contains(&Notification::HotPlug(HotPlug::CardRemoved)),
1958 "expected CardRemoved inferred from MMI 'no card' text, got {notes:?}"
1959 );
1960 }
1961
1962 #[test]
1965 fn mmi_card_keyword_heuristic_is_edge_triggered() {
1966 use dvb_ci::objects::mmi_high::Enq;
1967
1968 let enq = |text: &'static [u8]| {
1969 r_apdu(
1970 MMI_SESSION,
1971 &ser(&Enq {
1972 reserved: Default::default(),
1973 length_form: dvb_ci::length::LengthForm::Minimal,
1974 blind_answer: false,
1975 answer_text_length: 0,
1976 text_chars: text,
1977 }),
1978 )
1979 };
1980 let mut d = driver_with_sessions();
1981 d.take_notifications();
1982 let count = |notes: &[Notification], hp: HotPlug| {
1983 notes
1984 .iter()
1985 .filter(|n| **n == Notification::HotPlug(hp))
1986 .count()
1987 };
1988
1989 for _ in 0..3 {
1991 feed(&mut d, enq(b"No card - please insert your smart card"));
1992 }
1993 let notes = d.take_notifications();
1994 assert_eq!(count(¬es, HotPlug::CardRemoved), 1, "{notes:?}");
1995 assert_eq!(count(¬es, HotPlug::CardInserted), 0);
1996
1997 for _ in 0..2 {
1999 feed(&mut d, enq(b"Your entitlement is valid"));
2000 }
2001 let notes = d.take_notifications();
2002 assert_eq!(count(¬es, HotPlug::CardInserted), 1, "{notes:?}");
2003 assert_eq!(count(¬es, HotPlug::CardRemoved), 0);
2004
2005 feed(&mut d, enq(b"Card removed"));
2007 feed(&mut d, enq(b"Card removed"));
2008 let notes = d.take_notifications();
2009 assert_eq!(count(¬es, HotPlug::CardRemoved), 1, "{notes:?}");
2010 }
2011
2012 #[test]
2013 fn pump_hotplug_delivers_cam_present_via_closure_exactly_once() {
2014 let mut dev = MockCaDevice::new([]);
2015 dev.slot = SlotInfo {
2016 num: 0,
2017 module_ready: false,
2018 module_present: false,
2019 };
2020 let mut d = Driver::new(dev);
2021 d.init().unwrap();
2022 d.take_notifications(); d.device_mut().slot = SlotInfo {
2026 num: 0,
2027 module_ready: true,
2028 module_present: true,
2029 };
2030
2031 let mut seen = Vec::new();
2032 d.pump_hotplug(Duration::from_millis(10), |hp| seen.push(hp))
2033 .unwrap();
2034
2035 assert_eq!(
2036 seen,
2037 vec![HotPlug::CamPresent],
2038 "expected the closure to receive HotPlug::CamPresent exactly once, got {seen:?}"
2039 );
2040 }
2041
2042 pub(crate) fn ca_descriptor(ca_system_id: u16, pid: Pid) -> [u8; 6] {
2047 [
2048 0x09,
2049 0x04,
2050 (ca_system_id >> 8) as u8,
2051 ca_system_id as u8,
2052 0xE0 | ((pid.value() >> 8) as u8 & 0x1F),
2053 pid.value() as u8,
2054 ]
2055 }
2056
2057 pub(crate) fn build_ca_pmt_fixture(program_number: u16) -> Vec<u8> {
2074 const VIACCESS: u16 = 0x0500;
2075 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2076 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2077
2078 let mut body = Vec::new();
2079 body.push(0x02); body.push(0); body.push(0);
2082 body.extend_from_slice(&program_number.to_be_bytes());
2083 body.push(0xC3); body.push(0x00); body.push(0x00); body.push(0xE0 | 0x01); body.push(0x00);
2088 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2089 body.push(prog_ca.len() as u8);
2090 body.extend_from_slice(&prog_ca);
2091 body.push(0x1B);
2093 body.push(0xE0 | 0x01);
2094 body.push(0x00);
2095 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2096 body.push(es0_ca.len() as u8);
2097 body.extend_from_slice(&es0_ca);
2098 body.push(0x0F);
2100 body.push(0xE0 | 0x01);
2101 body.push(0x01);
2102 body.push(0xF0);
2103 body.push(0x00);
2104
2105 let section_length = body.len() - 3 + 4;
2106 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2107 body[2] = section_length as u8;
2108 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2109 body.extend_from_slice(&crc.to_be_bytes());
2110 body
2111 }
2112
2113 pub(crate) fn build_ca_pmt_fixture_dedicated_pcr(program_number: u16) -> Vec<u8> {
2120 const VIACCESS: u16 = 0x0500;
2121 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2122 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0065));
2123
2124 let mut body = Vec::new();
2125 body.push(0x02); body.push(0); body.push(0);
2128 body.extend_from_slice(&program_number.to_be_bytes());
2129 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));
2135 body.push(prog_ca.len() as u8);
2136 body.extend_from_slice(&prog_ca);
2137 body.push(0x1B);
2139 body.push(0xE0 | 0x01);
2140 body.push(0x00);
2141 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2142 body.push(es0_ca.len() as u8);
2143 body.extend_from_slice(&es0_ca);
2144 body.push(0x0F);
2146 body.push(0xE0 | 0x01);
2147 body.push(0x01);
2148 body.push(0xF0);
2149 body.push(0x00);
2150
2151 let section_length = body.len() - 3 + 4;
2152 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2153 body[2] = section_length as u8;
2154 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2155 body.extend_from_slice(&crc.to_be_bytes());
2156 body
2157 }
2158
2159 pub(crate) fn build_clear_pmt_fixture(program_number: u16) -> Vec<u8> {
2163 let mut body = Vec::new();
2164 body.push(0x02);
2165 body.push(0);
2166 body.push(0);
2167 body.extend_from_slice(&program_number.to_be_bytes());
2168 body.push(0xC3);
2169 body.push(0x00);
2170 body.push(0x00);
2171 body.push(0xE0 | 0x01);
2172 body.push(0x00);
2173 body.push(0xF0); body.push(0x00);
2175 body.push(0x1B);
2177 body.push(0xE0 | 0x01);
2178 body.push(0x00);
2179 body.push(0xF0);
2180 body.push(0x00);
2181
2182 let section_length = body.len() - 3 + 4;
2183 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2184 body[2] = section_length as u8;
2185 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2186 body.extend_from_slice(&crc.to_be_bytes());
2187 body
2188 }
2189
2190 #[test]
2191 fn add_service_builds_and_sends_ca_pmt_matching_builder_oracle() {
2192 use broadcast_common::Parse;
2193
2194 let mut d = driver_with_sessions();
2195 d.take_notifications();
2196
2197 let pmt_bytes = build_ca_pmt_fixture(1546);
2198 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2199
2200 d.add_service(&pmt).unwrap();
2201 d.device_mut().inbound.push_back(sb());
2202 d.pump(Duration::from_millis(10)).unwrap();
2203
2204 let expected = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2208 .to_bytes()
2209 .unwrap();
2210 assert_apdu_on_session(&d, CA_SESSION, &expected);
2211
2212 let svc = d
2214 .managed_ca()
2215 .services()
2216 .get(&1546)
2217 .expect("program_number 1546 must be tracked after add_service");
2218 assert_eq!(
2219 svc.es_pids,
2220 vec![Pid::from_const(0x0100), Pid::from_const(0x0101)]
2221 );
2222 assert_eq!(
2223 svc.ca_pids,
2224 vec![Pid::from_const(0x0064), Pid::from_const(0x0065)]
2225 );
2226 assert_eq!(svc.cmd, CaPmtCmdId::OkDescrambling);
2227 assert_eq!(svc.last_ca_enable, None);
2228 }
2229
2230 #[test]
2231 fn add_service_rejects_pmt_without_ca_descriptor() {
2232 use broadcast_common::Parse;
2233
2234 let mut d = driver_with_sessions();
2235 let pmt_bytes = build_clear_pmt_fixture(999);
2236 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2237
2238 let err = d.add_service(&pmt).unwrap_err();
2239 assert!(
2240 matches!(
2241 err,
2242 CaError::NoCaDescriptor {
2243 program_number: 999
2244 }
2245 ),
2246 "expected NoCaDescriptor{{program_number: 999}}, got {err:?}"
2247 );
2248 assert!(
2249 d.managed_ca().services().is_empty(),
2250 "a rejected PMT must not be recorded"
2251 );
2252 }
2253
2254 #[test]
2266 fn requery_tick_serialize_failure_errors_from_pump_instead_of_panicking() {
2267 use broadcast_common::Parse;
2268
2269 let clock = TestClock::new();
2270 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2271
2272 let good_bytes = build_ca_pmt_fixture(1);
2275 let good = PmtSection::parse(&good_bytes).unwrap();
2276 assert_eq!(good.program_number, 1, "fixture precondition");
2277 d.add_service(&good).unwrap();
2278
2279 let pmt_bytes = build_ca_pmt_fixture(1546);
2284 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2285 let built = d
2286 .build_ca_pmt_filtered(
2287 &pmt,
2288 CaPmtListManagement::Update,
2289 CaPmtCmdId::OkDescrambling,
2290 )
2291 .to_bytes()
2292 .expect("fixture precondition: the good PMT encodes");
2293 let corrupt_raw = pmt_bytes[..pmt_bytes.len() - 6].to_vec();
2294 d.managed.record(
2295 1546,
2296 managed::service_of(&pmt, CaPmtCmdId::OkDescrambling, built, corrupt_raw),
2297 );
2298 d.take_notifications();
2299 for _ in 0..16 {
2303 d.device_mut().inbound.push_back(sb());
2304 d.pump(Duration::from_millis(10)).unwrap();
2305 }
2306 d.set_requery_interval(Duration::from_secs(5));
2307
2308 clock.advance(Duration::from_secs(5));
2312 let err = d
2313 .pump(Duration::ZERO)
2314 .expect_err("re-query of a corrupt stored PMT must error, not panic");
2315 assert!(
2316 matches!(
2317 err.get_ref(),
2318 Some(e) if e.downcast_ref::<CaError>()
2319 .is_some_and(|ca| matches!(ca, CaError::PmtParse(_)))
2320 ),
2321 "expected CaError::PmtParse from the corrupt stored bytes, got {err:?}"
2322 );
2323 assert!(
2324 err.to_string().contains("stored PMT re-parse failed"),
2325 "error must name the re-parse failure, got: {err}"
2326 );
2327 assert!(d.pump(Duration::ZERO).is_ok());
2331 clock.advance(Duration::from_secs(5));
2332 let err2 = d
2333 .pump(Duration::ZERO)
2334 .expect_err("the corrupt service must fail every re-query");
2335 assert!(
2336 err2.to_string().contains("stored PMT re-parse failed"),
2337 "failure must persist, got: {err2}"
2338 );
2339 }
2340
2341 fn corrupt_ca_section_ctor() -> PmtSection<'static> {
2347 const LOOP: usize = 5000;
2348 let mut prog_info: Vec<u8> = Vec::with_capacity(LOOP);
2349 for _ in 0..LOOP / 4 {
2350 prog_info.extend_from_slice(&[0x09u8, 0x02, 0x0B, 0x00]);
2352 }
2353 assert_eq!(prog_info.len(), LOOP);
2354 PmtSection::new(
2355 1,
2356 dvb_si::tables::SectionVersion::new(1, true, 0, 0),
2357 Pid::from_const(0x0200),
2358 dvb_si::descriptors::DescriptorLoop::new(Box::leak(prog_info.into_boxed_slice())),
2359 Vec::new(),
2360 )
2361 }
2362
2363 #[test]
2368 fn add_service_serialize_failure_returns_err_instead_of_panicking() {
2369 let mut d = driver_with_sessions();
2370 d.managed.set_cam_caids([0x0B00u16].into_iter().collect());
2371 let pmt = corrupt_ca_section_ctor();
2372 let err = d
2373 .add_service(&pmt)
2374 .expect_err("a ca_pmt with no valid encoding must error, not panic");
2375 assert!(
2376 matches!(err, CaError::Serialize(_)),
2377 "expected CaError::Serialize, got {err:?}"
2378 );
2379 assert!(
2380 d.managed_ca().services().is_empty(),
2381 "a rejected PMT must not be recorded"
2382 );
2383 }
2384
2385 #[test]
2386 fn add_service_second_call_uses_add_list_management() {
2387 use broadcast_common::Parse;
2388
2389 let mut d = driver_with_sessions();
2390 d.take_notifications();
2391
2392 let pmt1_bytes = build_ca_pmt_fixture(1546);
2393 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2394 d.add_service(&pmt1).unwrap();
2395 d.device_mut().inbound.push_back(sb());
2396 d.pump(Duration::from_millis(10)).unwrap();
2397
2398 let pmt2_bytes = build_ca_pmt_fixture(1547);
2399 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2400 d.add_service(&pmt2).unwrap();
2401 d.device_mut().inbound.push_back(sb());
2402 d.pump(Duration::from_millis(10)).unwrap();
2403
2404 let expected2 = build_ca_pmt(&pmt2, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling)
2406 .to_bytes()
2407 .unwrap();
2408 assert_apdu_on_session(&d, CA_SESSION, &expected2);
2409
2410 assert_eq!(d.managed_ca().services().len(), 2);
2411 }
2412
2413 fn build_ca_pmt_fixture_two_caids(program_number: u16) -> Vec<u8> {
2424 const VIACCESS: u16 = 0x0500;
2425 const NAGRA: u16 = 0x1800;
2426 let prog_ca_a = ca_descriptor(VIACCESS, Pid::from_const(0x0064));
2427 let prog_ca_b = ca_descriptor(NAGRA, Pid::from_const(0x0066));
2428 let mut prog_ca = Vec::new();
2429 prog_ca.extend_from_slice(&prog_ca_a);
2430 prog_ca.extend_from_slice(&prog_ca_b);
2431
2432 let mut body = Vec::new();
2433 body.push(0x02); body.push(0);
2435 body.push(0);
2436 body.extend_from_slice(&program_number.to_be_bytes());
2437 body.push(0xC3);
2438 body.push(0x00);
2439 body.push(0x00);
2440 body.push(0xE0 | 0x01); body.push(0x00);
2442 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2443 body.push(prog_ca.len() as u8);
2444 body.extend_from_slice(&prog_ca);
2445 body.push(0x0F);
2448 body.push(0xE0 | 0x01);
2449 body.push(0x00);
2450 body.push(0xF0);
2451 body.push(0x00);
2452
2453 let section_length = body.len() - 3 + 4;
2454 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2455 body[2] = section_length as u8;
2456 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2457 body.extend_from_slice(&crc.to_be_bytes());
2458 body
2459 }
2460
2461 #[test]
2462 fn add_service_filters_ca_descriptors_to_cam_advertised_caids() {
2463 use broadcast_common::Parse;
2464 use dvb_ci::objects::ca_info::CaInfo;
2465
2466 let mut d = driver_with_sessions();
2467 d.take_notifications();
2468
2469 feed(
2472 &mut d,
2473 r_apdu(
2474 CA_SESSION,
2475 &ser(&CaInfo {
2476 length_form: dvb_ci::length::LengthForm::Minimal,
2477 ca_system_ids: vec![0x0500],
2478 }),
2479 ),
2480 );
2481 d.take_notifications();
2482
2483 let pmt_bytes = build_ca_pmt_fixture_two_caids(1560);
2484 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2485
2486 let expected_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2491 &pmt,
2492 &[0x0500],
2493 CaPmtListManagement::Only,
2494 CaPmtCmdId::OkDescrambling,
2495 )
2496 .to_bytes()
2497 .unwrap();
2498 let unfiltered = build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2499 .to_bytes()
2500 .unwrap();
2501 assert_ne!(
2502 expected_filtered, unfiltered,
2503 "precondition: the fixture's two CAIDs must make filtered != unfiltered"
2504 );
2505 let sends_filtered_before = count_apdu_on_session(&d, CA_SESSION, &expected_filtered);
2506 let sends_unfiltered_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered);
2507
2508 d.add_service(&pmt).unwrap();
2509 d.device_mut().inbound.push_back(sb());
2510 d.pump(Duration::from_millis(10)).unwrap();
2511
2512 assert_eq!(
2513 count_apdu_on_session(&d, CA_SESSION, &expected_filtered),
2514 sends_filtered_before + 1,
2515 "add_service must send the CAID-filtered ca_pmt"
2516 );
2517 assert_eq!(
2518 count_apdu_on_session(&d, CA_SESSION, &unfiltered),
2519 sends_unfiltered_before,
2520 "add_service must NOT send the unfiltered ca_pmt once the CAM's CAIDs are known"
2521 );
2522 }
2523
2524 #[test]
2525 fn requery_timer_filters_ca_descriptors_to_cam_advertised_caids() {
2526 use broadcast_common::Parse;
2527 use dvb_ci::objects::ca_info::CaInfo;
2528
2529 let clock = TestClock::new();
2530 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2531 d.set_requery_interval(Duration::from_secs(10));
2534 d.take_notifications();
2535
2536 let pmt_bytes = build_ca_pmt_fixture_two_caids(1561);
2537 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2538 d.add_service(&pmt).unwrap();
2541 d.device_mut().inbound.push_back(sb());
2542 clock.advance(Duration::from_millis(10));
2543 d.pump(Duration::from_millis(10)).unwrap();
2544
2545 feed(
2547 &mut d,
2548 r_apdu(
2549 CA_SESSION,
2550 &ser(&CaInfo {
2551 length_form: dvb_ci::length::LengthForm::Minimal,
2552 ca_system_ids: vec![0x0500],
2553 }),
2554 ),
2555 );
2556 d.take_notifications();
2557
2558 let expected_query_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2561 &pmt,
2562 &[0x0500],
2563 CaPmtListManagement::Update,
2564 CaPmtCmdId::Query,
2565 )
2566 .to_bytes()
2567 .unwrap();
2568 let expected_ok_filtered = dvb_ci::builder::build_ca_pmt_for_caids(
2569 &pmt,
2570 &[0x0500],
2571 CaPmtListManagement::Update,
2572 CaPmtCmdId::OkDescrambling,
2573 )
2574 .to_bytes()
2575 .unwrap();
2576 let unfiltered_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2577 .to_bytes()
2578 .unwrap();
2579 let unfiltered_ok = build_ca_pmt(
2580 &pmt,
2581 CaPmtListManagement::Update,
2582 CaPmtCmdId::OkDescrambling,
2583 )
2584 .to_bytes()
2585 .unwrap();
2586 assert_ne!(
2587 expected_query_filtered, unfiltered_query,
2588 "precondition: the fixture's two CAIDs must make filtered != unfiltered (query)"
2589 );
2590 assert_ne!(
2591 expected_ok_filtered, unfiltered_ok,
2592 "precondition: the fixture's two CAIDs must make filtered != unfiltered (ok_descrambling)"
2593 );
2594 let sends_query_before = count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered);
2595 let sends_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered);
2596 let sends_unfiltered_query_before =
2597 count_apdu_on_session(&d, CA_SESSION, &unfiltered_query);
2598 let sends_unfiltered_ok_before = count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok);
2599
2600 clock.advance(Duration::from_secs(11));
2601 d.pump(Duration::from_secs(11)).unwrap();
2602 feed(&mut d, sb());
2603
2604 assert_eq!(
2605 count_apdu_on_session(&d, CA_SESSION, &expected_query_filtered),
2606 sends_query_before + 1,
2607 "the re-query `query` half must be CAID-filtered to the CAM's advertised CAIDs"
2608 );
2609 assert_eq!(
2610 count_apdu_on_session(&d, CA_SESSION, &expected_ok_filtered),
2611 sends_ok_before + 1,
2612 "the re-query `ok_descrambling` half must be CAID-filtered to the CAM's advertised CAIDs"
2613 );
2614 assert_eq!(
2615 count_apdu_on_session(&d, CA_SESSION, &unfiltered_query),
2616 sends_unfiltered_query_before,
2617 "the re-query resend must NOT be the unfiltered `query` ca_pmt"
2618 );
2619 assert_eq!(
2620 count_apdu_on_session(&d, CA_SESSION, &unfiltered_ok),
2621 sends_unfiltered_ok_before,
2622 "the re-query resend must NOT be the unfiltered `ok_descrambling` ca_pmt"
2623 );
2624 }
2625
2626 pub(crate) fn build_cat_fixture(descriptors: &[u8]) -> Vec<u8> {
2636 const EXTENSION_HEADER_LEN: u16 = 5;
2637 const CRC_LEN: u16 = 4;
2638 let section_length = EXTENSION_HEADER_LEN + descriptors.len() as u16 + CRC_LEN;
2639 let mut v = Vec::new();
2640 v.push(0x01); v.push(0xB0 | ((section_length >> 8) as u8 & 0x0F));
2642 v.push((section_length & 0xFF) as u8);
2643 v.extend_from_slice(&[0xFF, 0xFF]); v.push(0xC1); v.push(0x00); v.push(0x00); v.extend_from_slice(descriptors);
2648 let crc = broadcast_common::crc32_mpeg2::compute(&v);
2649 v.extend_from_slice(&crc.to_be_bytes());
2650 v
2651 }
2652
2653 #[test]
2654 fn set_cat_computes_emm_pids_as_cat_inter_ca_info_caids() {
2655 use broadcast_common::Parse;
2656 use dvb_ci::objects::ca_info::CaInfo;
2657 use dvb_si::tables::cat::CatSection;
2658
2659 let mut d = driver_with_sessions();
2660 d.take_notifications();
2661
2662 feed(
2664 &mut d,
2665 r_apdu(
2666 CA_SESSION,
2667 &ser(&CaInfo {
2668 length_form: dvb_ci::length::LengthForm::Minimal,
2669 ca_system_ids: vec![0x0648, 0x0100],
2670 }),
2671 ),
2672 );
2673 d.take_notifications();
2674
2675 let mut descriptors = Vec::new();
2678 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2679 descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2680 let cat_bytes = build_cat_fixture(&descriptors);
2681 let cat = CatSection::parse(&cat_bytes).unwrap();
2682
2683 d.set_cat(&cat).unwrap();
2684
2685 assert_eq!(
2686 d.emm_pids(),
2687 &[Pid::from_const(0x1FF0)],
2688 "0x0500 -> 0x1FF1 must be excluded: the CAM never advertised CAID 0x0500"
2689 );
2690 }
2691
2692 #[test]
2693 fn set_cat_before_ca_info_is_not_an_error_and_recomputes_once_ca_info_arrives() {
2694 use broadcast_common::Parse;
2695 use dvb_ci::objects::ca_info::CaInfo;
2696 use dvb_si::tables::cat::CatSection;
2697
2698 let mut d = driver_with_sessions();
2699 d.take_notifications();
2700
2701 let mut descriptors = Vec::new();
2702 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2703 descriptors.extend_from_slice(&ca_descriptor(0x0500, Pid::from_const(0x1FF1)));
2704 let cat_bytes = build_cat_fixture(&descriptors);
2705 let cat = CatSection::parse(&cat_bytes).unwrap();
2706
2707 d.set_cat(&cat).unwrap();
2710 assert!(
2711 d.emm_pids().is_empty(),
2712 "emm_pids must be empty before any ca_info arrives, got {:?}",
2713 d.emm_pids()
2714 );
2715
2716 feed(
2719 &mut d,
2720 r_apdu(
2721 CA_SESSION,
2722 &ser(&CaInfo {
2723 length_form: dvb_ci::length::LengthForm::Minimal,
2724 ca_system_ids: vec![0x0648, 0x0100],
2725 }),
2726 ),
2727 );
2728 d.take_notifications();
2729
2730 assert_eq!(
2731 d.emm_pids(),
2732 &[Pid::from_const(0x1FF0)],
2733 "emm_pids must recompute once ca_info arrives, using the CAT stored by the earlier set_cat"
2734 );
2735 }
2736
2737 #[test]
2743 fn set_cat_emm_pids_dedups_when_two_caids_share_one_emm_pid() {
2744 use broadcast_common::Parse;
2745 use dvb_ci::objects::ca_info::CaInfo;
2746 use dvb_si::tables::cat::CatSection;
2747
2748 let mut d = driver_with_sessions();
2749 d.take_notifications();
2750
2751 feed(
2753 &mut d,
2754 r_apdu(
2755 CA_SESSION,
2756 &ser(&CaInfo {
2757 length_form: dvb_ci::length::LengthForm::Minimal,
2758 ca_system_ids: vec![0x0648, 0x0100],
2759 }),
2760 ),
2761 );
2762 d.take_notifications();
2763
2764 let mut descriptors = Vec::new();
2766 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
2767 descriptors.extend_from_slice(&ca_descriptor(0x0100, Pid::from_const(0x1FF0)));
2768 let cat_bytes = build_cat_fixture(&descriptors);
2769 let cat = CatSection::parse(&cat_bytes).unwrap();
2770
2771 d.set_cat(&cat).unwrap();
2772
2773 assert_eq!(
2774 d.emm_pids(),
2775 &[Pid::from_const(0x1FF0)],
2776 "0x1FF0 must appear exactly once even though two CAM-advertised CAIDs map to it, got {:?}",
2777 d.emm_pids()
2778 );
2779 }
2780
2781 fn build_ca_pmt_fixture_distinct_pids(program_number: u16) -> Vec<u8> {
2785 const VIACCESS: u16 = 0x0500;
2786 let prog_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0074));
2787 let es0_ca = ca_descriptor(VIACCESS, Pid::from_const(0x0075));
2788
2789 let mut body = Vec::new();
2790 body.push(0x02); body.push(0);
2792 body.push(0);
2793 body.extend_from_slice(&program_number.to_be_bytes());
2794 body.push(0xC3);
2795 body.push(0x00);
2796 body.push(0x00);
2797 body.push(0xE0 | 0x02); body.push(0x00);
2799 body.push(0xF0 | ((prog_ca.len() >> 8) as u8 & 0x0F));
2800 body.push(prog_ca.len() as u8);
2801 body.extend_from_slice(&prog_ca);
2802 body.push(0x1B);
2804 body.push(0xE0 | 0x02);
2805 body.push(0x00);
2806 body.push(0xF0 | ((es0_ca.len() >> 8) as u8 & 0x0F));
2807 body.push(es0_ca.len() as u8);
2808 body.extend_from_slice(&es0_ca);
2809 body.push(0x0F);
2811 body.push(0xE0 | 0x02);
2812 body.push(0x01);
2813 body.push(0xF0);
2814 body.push(0x00);
2815
2816 let section_length = body.len() - 3 + 4;
2817 body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
2818 body[2] = section_length as u8;
2819 let crc = broadcast_common::crc32_mpeg2::compute(&body);
2820 body.extend_from_slice(&crc.to_be_bytes());
2821 body
2822 }
2823
2824 #[test]
2825 fn descramble_pids_is_the_union_of_active_services_es_pids() {
2826 use broadcast_common::Parse;
2827
2828 let mut d = driver_with_sessions();
2829 d.take_notifications();
2830
2831 assert!(
2832 d.descramble_pids().is_empty(),
2833 "no service added yet: descramble_pids must be empty"
2834 );
2835
2836 let pmt1_bytes = build_ca_pmt_fixture(1546);
2837 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
2838 d.add_service(&pmt1).unwrap();
2839 d.device_mut().inbound.push_back(sb());
2840 d.pump(Duration::from_millis(10)).unwrap();
2841
2842 assert_eq!(
2843 d.descramble_pids(),
2844 &[Pid::from_const(0x0100), Pid::from_const(0x0101)]
2845 );
2846
2847 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
2848 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
2849 d.add_service(&pmt2).unwrap();
2850 d.device_mut().inbound.push_back(sb());
2851 d.pump(Duration::from_millis(10)).unwrap();
2852
2853 assert_eq!(
2855 d.descramble_pids(),
2856 &[
2857 Pid::from_const(0x0100),
2858 Pid::from_const(0x0101),
2859 Pid::from_const(0x0200),
2860 Pid::from_const(0x0201)
2861 ],
2862 "descramble_pids must be the union across both added services"
2863 );
2864 }
2865
2866 pub(crate) fn ca_pmt_reply_for(
2871 program_number: u16,
2872 ca_enable: Option<dvb_ci::objects::ca_pmt_reply::CaEnable>,
2873 ) -> dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2874 dvb_ci::objects::ca_pmt_reply::CaPmtReply {
2875 length_form: dvb_ci::length::LengthForm::Minimal,
2876 program_number,
2877 version_number: 1,
2878 current_next_indicator: true,
2879 ca_enable,
2880 streams: vec![],
2881 reserved_version: Default::default(),
2882 reserved_ca_enable: Default::default(),
2883 }
2884 }
2885
2886 #[test]
2887 fn requery_timer_resends_ca_pmt_then_reply_change_emits_one_entitlement() {
2888 use broadcast_common::Parse;
2889 use dvb_ci::objects::ca_pmt_reply::CaEnable;
2890
2891 let clock = TestClock::new();
2892 let mut d = driver_with_sessions().with_clock(clock.as_fn());
2893 d.set_requery_interval(Duration::from_secs(10));
2896 d.take_notifications();
2897
2898 let pmt_bytes = build_ca_pmt_fixture(1546);
2899 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
2900 d.add_service(&pmt).unwrap();
2901 d.device_mut().inbound.push_back(sb());
2902 clock.advance(Duration::from_millis(10));
2903 d.pump(Duration::from_millis(10)).unwrap();
2904 d.take_notifications();
2905
2906 let expected_initial_ca_pmt =
2910 build_ca_pmt(&pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
2911 .to_bytes()
2912 .unwrap();
2913 assert_apdu_on_session(&d, CA_SESSION, &expected_initial_ca_pmt);
2914
2915 let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
2921 .to_bytes()
2922 .unwrap();
2923 let expected_ok_descrambling = build_ca_pmt(
2924 &pmt,
2925 CaPmtListManagement::Update,
2926 CaPmtCmdId::OkDescrambling,
2927 )
2928 .to_bytes()
2929 .unwrap();
2930 let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
2931 let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
2932
2933 let mut all_notes = Vec::new();
2934
2935 feed(
2939 &mut d,
2940 r_apdu(
2941 CA_SESSION,
2942 &ser(&ca_pmt_reply_for(
2943 1546,
2944 Some(CaEnable::NotPossibleNoEntitlement),
2945 )),
2946 ),
2947 );
2948 all_notes.extend(d.take_notifications());
2949
2950 clock.advance(Duration::from_secs(11));
2960 d.pump(Duration::from_secs(11)).unwrap();
2961 all_notes.extend(d.take_notifications());
2962 feed(&mut d, sb());
2963
2964 assert_eq!(
2965 count_apdu_on_session(&d, CA_SESSION, &expected_query),
2966 query_sends_before + 1,
2967 "expected the re-query timer to resend the `query` half exactly once"
2968 );
2969 assert_eq!(
2970 count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
2971 ok_sends_before + 1,
2972 "expected the re-query timer to resend the `ok_descrambling` half exactly once"
2973 );
2974
2975 feed(
2978 &mut d,
2979 r_apdu(
2980 CA_SESSION,
2981 &ser(&ca_pmt_reply_for(1546, Some(CaEnable::Possible))),
2982 ),
2983 );
2984 all_notes.extend(d.take_notifications());
2985
2986 let hits = all_notes
2987 .iter()
2988 .filter(|n| {
2989 matches!(
2990 n,
2991 Notification::Entitlement {
2992 program_number: 1546,
2993 ca_enable: CaEnable::Possible,
2994 descrambling_ok: true,
2995 }
2996 )
2997 })
2998 .count();
2999 assert_eq!(
3000 hits, 1,
3001 "expected exactly one Entitlement{{program_number:1546, ca_enable:Possible, descrambling_ok:true}}, got {all_notes:?}"
3002 );
3003 }
3004
3005 #[test]
3006 fn requery_timer_unchanged_reply_across_two_requeries_emits_no_entitlement() {
3007 use broadcast_common::Parse;
3008 use dvb_ci::objects::ca_pmt_reply::CaEnable;
3009
3010 let mut d = driver_with_sessions();
3011 d.set_requery_interval(Duration::from_secs(10));
3014 d.take_notifications();
3015
3016 let pmt_bytes = build_ca_pmt_fixture(1547);
3017 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3018 d.add_service(&pmt).unwrap();
3019 d.device_mut().inbound.push_back(sb());
3020 d.pump(Duration::from_millis(10)).unwrap();
3021 d.take_notifications();
3022
3023 feed(
3027 &mut d,
3028 r_apdu(
3029 CA_SESSION,
3030 &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3031 ),
3032 );
3033 d.take_notifications();
3034
3035 for _ in 0..2 {
3038 d.pump(Duration::from_secs(11)).unwrap();
3039 d.take_notifications();
3040 feed(
3041 &mut d,
3042 r_apdu(
3043 CA_SESSION,
3044 &ser(&ca_pmt_reply_for(1547, Some(CaEnable::Possible))),
3045 ),
3046 );
3047 let notes = d.take_notifications();
3048 assert!(
3049 !notes
3050 .iter()
3051 .any(|n| matches!(n, Notification::Entitlement { .. })),
3052 "unchanged status across a re-query must not emit Entitlement, got {notes:?}"
3053 );
3054 }
3055 }
3056
3057 #[test]
3058 fn requery_reply_withdrawn_to_none_emits_no_entitlement() {
3059 use broadcast_common::Parse;
3060 use dvb_ci::objects::ca_pmt_reply::CaEnable;
3061
3062 let mut d = driver_with_sessions();
3063 d.take_notifications();
3064
3065 let pmt_bytes = build_ca_pmt_fixture(1548);
3066 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3067 d.add_service(&pmt).unwrap();
3068 d.device_mut().inbound.push_back(sb());
3069 d.pump(Duration::from_millis(10)).unwrap();
3070 d.take_notifications();
3071
3072 feed(
3074 &mut d,
3075 r_apdu(
3076 CA_SESSION,
3077 &ser(&ca_pmt_reply_for(1548, Some(CaEnable::Possible))),
3078 ),
3079 );
3080 d.take_notifications();
3081
3082 feed(
3086 &mut d,
3087 r_apdu(CA_SESSION, &ser(&ca_pmt_reply_for(1548, None))),
3088 );
3089 let notes = d.take_notifications();
3090 assert!(
3091 !notes
3092 .iter()
3093 .any(|n| matches!(n, Notification::Entitlement { .. })),
3094 "ca_enable transitioning to None must not emit Entitlement, got {notes:?}"
3095 );
3096 }
3097
3098 #[test]
3099 fn requery_disabled_by_default_sends_nothing() {
3100 use broadcast_common::Parse;
3101
3102 let mut d = driver_with_sessions();
3106 d.take_notifications();
3107
3108 let pmt_bytes = build_ca_pmt_fixture(1549);
3109 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3110 d.add_service(&pmt).unwrap();
3111 d.device_mut().inbound.push_back(sb());
3112 d.pump(Duration::from_millis(10)).unwrap();
3113
3114 let expected_query = build_ca_pmt(&pmt, CaPmtListManagement::Update, CaPmtCmdId::Query)
3117 .to_bytes()
3118 .unwrap();
3119 let expected_ok_descrambling = build_ca_pmt(
3120 &pmt,
3121 CaPmtListManagement::Update,
3122 CaPmtCmdId::OkDescrambling,
3123 )
3124 .to_bytes()
3125 .unwrap();
3126 let query_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_query);
3127 let ok_sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling);
3128
3129 d.pump(Duration::from_secs(1_000_000)).unwrap();
3131 feed(&mut d, sb());
3132 feed(&mut d, sb());
3133 assert_eq!(
3134 count_apdu_on_session(&d, CA_SESSION, &expected_query),
3135 query_sends_before,
3136 "the default (Duration::ZERO) must never send a re-query `query`"
3137 );
3138 assert_eq!(
3139 count_apdu_on_session(&d, CA_SESSION, &expected_ok_descrambling),
3140 ok_sends_before,
3141 "the default (Duration::ZERO) must never send a re-query `ok_descrambling`"
3142 );
3143 }
3144
3145 #[test]
3146 fn set_requery_interval_zero_disables_resend_after_being_enabled() {
3147 use broadcast_common::Parse;
3148
3149 let mut d = driver_with_sessions();
3150 d.set_requery_interval(Duration::from_secs(5));
3153 d.set_requery_interval(Duration::ZERO);
3154 d.take_notifications();
3155
3156 let pmt_bytes = build_ca_pmt_fixture(1549);
3157 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3158 d.add_service(&pmt).unwrap();
3159 d.device_mut().inbound.push_back(sb());
3160 d.pump(Duration::from_millis(10)).unwrap();
3161
3162 let expected_ca_pmt = build_ca_pmt(
3166 &pmt,
3167 CaPmtListManagement::Update,
3168 CaPmtCmdId::OkDescrambling,
3169 )
3170 .to_bytes()
3171 .unwrap();
3172 let sends_before = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3173
3174 d.pump(Duration::from_secs(1000)).unwrap();
3176 feed(&mut d, sb());
3177 feed(&mut d, sb());
3178
3179 let sends_after = count_apdu_on_session(&d, CA_SESSION, &expected_ca_pmt);
3180 assert_eq!(
3181 sends_after, sends_before,
3182 "Duration::ZERO must disable the re-query resend"
3183 );
3184 }
3185
3186 #[test]
3187 fn requery_timer_resends_every_active_service_not_just_one() {
3188 use broadcast_common::Parse;
3189
3190 let clock = TestClock::new();
3191 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3192 d.set_requery_interval(Duration::from_secs(10));
3195 d.take_notifications();
3196
3197 let pmt1_bytes = build_ca_pmt_fixture(1546);
3200 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3201 d.add_service(&pmt1).unwrap();
3202 d.device_mut().inbound.push_back(sb());
3203 clock.advance(Duration::from_millis(10));
3204 d.pump(Duration::from_millis(10)).unwrap();
3205
3206 let pmt2_bytes = build_ca_pmt_fixture(1547);
3207 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3208 d.add_service(&pmt2).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 d.take_notifications();
3213
3214 let expected1_query = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3220 .to_bytes()
3221 .unwrap();
3222 let expected1_ok = build_ca_pmt(
3223 &pmt1,
3224 CaPmtListManagement::Update,
3225 CaPmtCmdId::OkDescrambling,
3226 )
3227 .to_bytes()
3228 .unwrap();
3229 let expected2_query = build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3230 .to_bytes()
3231 .unwrap();
3232 let expected2_ok = build_ca_pmt(
3233 &pmt2,
3234 CaPmtListManagement::Update,
3235 CaPmtCmdId::OkDescrambling,
3236 )
3237 .to_bytes()
3238 .unwrap();
3239 let sends_before1_query = count_apdu_on_session(&d, CA_SESSION, &expected1_query);
3240 let sends_before1_ok = count_apdu_on_session(&d, CA_SESSION, &expected1_ok);
3241 let sends_before2_query = count_apdu_on_session(&d, CA_SESSION, &expected2_query);
3242 let sends_before2_ok = count_apdu_on_session(&d, CA_SESSION, &expected2_ok);
3243
3244 clock.advance(Duration::from_secs(11));
3250 d.pump(Duration::from_secs(11)).unwrap();
3251 feed(&mut d, sb());
3252 feed(&mut d, sb());
3253
3254 assert_eq!(
3255 count_apdu_on_session(&d, CA_SESSION, &expected1_query),
3256 sends_before1_query + 1,
3257 "expected service 1546's `query` resent exactly once on the shared tick"
3258 );
3259 assert_eq!(
3260 count_apdu_on_session(&d, CA_SESSION, &expected1_ok),
3261 sends_before1_ok + 1,
3262 "expected service 1546's `ok_descrambling` resent exactly once on the shared tick"
3263 );
3264 assert_eq!(
3265 count_apdu_on_session(&d, CA_SESSION, &expected2_query),
3266 sends_before2_query + 1,
3267 "expected service 1547's `query` resent exactly once on the shared tick"
3268 );
3269 assert_eq!(
3270 count_apdu_on_session(&d, CA_SESSION, &expected2_ok),
3271 sends_before2_ok + 1,
3272 "expected service 1547's `ok_descrambling` resent exactly once on the shared tick"
3273 );
3274 }
3275
3276 #[test]
3280 fn requery_after_remove_resends_only_the_surviving_service() {
3281 use broadcast_common::Parse;
3282
3283 let clock = TestClock::new();
3284 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3285 d.set_requery_interval(Duration::from_secs(10));
3288 d.take_notifications();
3289
3290 let pmt1_bytes = build_ca_pmt_fixture(1546);
3291 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3292 d.add_service(&pmt1).unwrap();
3293 d.device_mut().inbound.push_back(sb());
3294 clock.advance(Duration::from_millis(10));
3295 d.pump(Duration::from_millis(10)).unwrap();
3296
3297 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3298 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3299 d.add_service(&pmt2).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 d.remove_service(1546).unwrap();
3306 d.device_mut().inbound.push_back(sb());
3307 clock.advance(Duration::from_millis(10));
3308 d.pump(Duration::from_millis(10)).unwrap();
3309 d.take_notifications();
3310
3311 let expected_survivor_query =
3317 build_ca_pmt(&pmt2, CaPmtListManagement::Update, CaPmtCmdId::Query)
3318 .to_bytes()
3319 .unwrap();
3320 let expected_survivor_ok = build_ca_pmt(
3321 &pmt2,
3322 CaPmtListManagement::Update,
3323 CaPmtCmdId::OkDescrambling,
3324 )
3325 .to_bytes()
3326 .unwrap();
3327 let expected_removed_query =
3328 build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::Query)
3329 .to_bytes()
3330 .unwrap();
3331 let expected_removed_ok = build_ca_pmt(
3332 &pmt1,
3333 CaPmtListManagement::Update,
3334 CaPmtCmdId::OkDescrambling,
3335 )
3336 .to_bytes()
3337 .unwrap();
3338 let sends_survivor_query_before =
3339 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query);
3340 let sends_survivor_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok);
3341 let sends_removed_query_before =
3342 count_apdu_on_session(&d, CA_SESSION, &expected_removed_query);
3343 let sends_removed_ok_before = count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok);
3344
3345 clock.advance(Duration::from_secs(11));
3346 d.pump(Duration::from_secs(11)).unwrap();
3347 feed(&mut d, sb());
3348
3349 assert_eq!(
3350 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_query),
3351 sends_survivor_query_before + 1,
3352 "the surviving service's `query` must be re-sent"
3353 );
3354 assert_eq!(
3355 count_apdu_on_session(&d, CA_SESSION, &expected_survivor_ok),
3356 sends_survivor_ok_before + 1,
3357 "the surviving service's `ok_descrambling` must be re-sent"
3358 );
3359 assert_eq!(
3360 count_apdu_on_session(&d, CA_SESSION, &expected_removed_query),
3361 sends_removed_query_before,
3362 "the removed service's `query` must NOT be re-sent"
3363 );
3364 assert_eq!(
3365 count_apdu_on_session(&d, CA_SESSION, &expected_removed_ok),
3366 sends_removed_ok_before,
3367 "the removed service's `ok_descrambling` must NOT be re-sent"
3368 );
3369 }
3370
3371 #[test]
3374 fn remove_service_sends_update_not_selected_and_drops_from_managed_state() {
3375 use broadcast_common::Parse;
3376
3377 let mut d = driver_with_sessions();
3378 d.take_notifications();
3379
3380 let pmt1_bytes = build_ca_pmt_fixture(1546);
3384 let pmt1 = PmtSection::parse(&pmt1_bytes).unwrap();
3385 d.add_service(&pmt1).unwrap();
3386 d.device_mut().inbound.push_back(sb());
3387 d.pump(Duration::from_millis(10)).unwrap();
3388
3389 let pmt2_bytes = build_ca_pmt_fixture_distinct_pids(1547);
3390 let pmt2 = PmtSection::parse(&pmt2_bytes).unwrap();
3391 d.add_service(&pmt2).unwrap();
3392 d.device_mut().inbound.push_back(sb());
3393 d.pump(Duration::from_millis(10)).unwrap();
3394
3395 d.remove_service(1546).unwrap();
3396 d.device_mut().inbound.push_back(sb());
3397 d.pump(Duration::from_millis(10)).unwrap();
3398
3399 let expected = build_ca_pmt(&pmt1, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3403 .to_bytes()
3404 .unwrap();
3405 assert_apdu_on_session(&d, CA_SESSION, &expected);
3406
3407 assert_eq!(
3408 d.descramble_pids(),
3409 &[Pid::from_const(0x0200), Pid::from_const(0x0201)],
3410 "1546's ES PIDs must be gone; 1547's must remain"
3411 );
3412 assert!(
3413 d.managed_ca().services().get(&1546).is_none(),
3414 "1546 must no longer be tracked"
3415 );
3416 assert!(
3417 d.managed_ca().services().get(&1547).is_some(),
3418 "1547 must remain tracked"
3419 );
3420 }
3421
3422 #[test]
3423 fn remove_service_of_untracked_program_is_a_no_op() {
3424 let mut d = driver_with_sessions();
3425 d.take_notifications();
3426
3427 let ops_before = d.device().ops.len();
3428 d.remove_service(0xFFFF).unwrap();
3429 assert_eq!(
3430 d.device().ops.len(),
3431 ops_before,
3432 "removing an untracked program must not send anything to the device"
3433 );
3434 assert!(
3435 d.managed_ca().services().is_empty(),
3436 "removing an untracked program must not disturb the (empty) managed set"
3437 );
3438 }
3439
3440 #[test]
3441 fn cam_removed_edge_clears_managed_state() {
3442 use broadcast_common::Parse;
3443 use dvb_ci::objects::ca_info::CaInfo;
3444 use dvb_si::tables::cat::CatSection;
3445
3446 let mut d = driver_with_sessions();
3447 d.take_notifications();
3448
3449 let pmt_bytes = build_ca_pmt_fixture(1546);
3450 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3451 d.add_service(&pmt).unwrap();
3452 d.device_mut().inbound.push_back(sb());
3453 d.pump(Duration::from_millis(10)).unwrap();
3454
3455 feed(
3458 &mut d,
3459 r_apdu(
3460 CA_SESSION,
3461 &ser(&CaInfo {
3462 length_form: dvb_ci::length::LengthForm::Minimal,
3463 ca_system_ids: vec![0x0648],
3464 }),
3465 ),
3466 );
3467 d.take_notifications();
3468 let mut descriptors = Vec::new();
3469 descriptors.extend_from_slice(&ca_descriptor(0x0648, Pid::from_const(0x1FF0)));
3470 let cat_bytes = build_cat_fixture(&descriptors);
3471 let cat = CatSection::parse(&cat_bytes).unwrap();
3472 d.set_cat(&cat).unwrap();
3473
3474 assert!(
3475 !d.managed_ca().services().is_empty(),
3476 "precondition: a service is tracked"
3477 );
3478 assert!(
3479 !d.descramble_pids().is_empty(),
3480 "precondition: descramble_pids populated"
3481 );
3482 assert!(!d.emm_pids().is_empty(), "precondition: emm_pids populated");
3483
3484 d.device_mut().slot.module_present = false;
3486 d.pump(Duration::from_millis(10)).unwrap();
3487 let notes = d.take_notifications();
3488 assert!(
3489 notes.contains(&Notification::HotPlug(HotPlug::CamRemoved)),
3490 "expected CamRemoved, got {notes:?}"
3491 );
3492
3493 assert!(
3494 d.managed_ca().services().is_empty(),
3495 "services must be cleared on CamRemoved"
3496 );
3497 assert!(
3498 d.descramble_pids().is_empty(),
3499 "descramble_pids must be cleared on CamRemoved"
3500 );
3501 assert!(
3502 d.emm_pids().is_empty(),
3503 "emm_pids must be cleared on CamRemoved"
3504 );
3505 }
3506
3507 #[test]
3508 fn update_service_not_managed_returns_not_managed_and_sends_nothing() {
3509 use broadcast_common::Parse;
3510
3511 let mut d = driver_with_sessions();
3512 d.take_notifications();
3513
3514 let pmt_bytes = build_clear_pmt_fixture(9999);
3515 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3516
3517 let before = d.device().ops.len();
3518 let err = d
3519 .update_service(&pmt)
3520 .expect_err("unknown program must error");
3521 assert!(
3522 matches!(
3523 err,
3524 CaError::NotManaged {
3525 program_number: 9999
3526 }
3527 ),
3528 "got {err:?}"
3529 );
3530 assert_eq!(d.device().ops.len(), before, "must send nothing");
3531 assert!(d.managed_ca().services().is_empty());
3532 }
3533
3534 #[test]
3535 fn update_service_no_ca_descriptor_leaves_record_unchanged() {
3536 use broadcast_common::Parse;
3537
3538 let mut d = driver_with_sessions();
3539 d.take_notifications();
3540
3541 let pmt_bytes = build_ca_pmt_fixture(1546);
3542 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3543 d.add_service(&pmt).unwrap();
3544
3545 let svc_before = d.managed_ca().services().get(&1546).unwrap().clone();
3546
3547 let clear_bytes = build_clear_pmt_fixture(1546);
3548 let clear_pmt = PmtSection::parse(&clear_bytes).unwrap();
3549 let err = d
3550 .update_service(&clear_pmt)
3551 .expect_err("CA-free PMT must error");
3552 assert!(
3553 matches!(
3554 err,
3555 CaError::NoCaDescriptor {
3556 program_number: 1546
3557 }
3558 ),
3559 "got {err:?}"
3560 );
3561
3562 let svc_after = d.managed_ca().services().get(&1546).unwrap();
3563 assert_eq!(svc_before, *svc_after, "record must be unchanged");
3564 }
3565
3566 #[test]
3572 fn update_service_sends_one_update_ca_pmt_with_the_new_pids_and_replaces_only_that_record() {
3573 use broadcast_common::Parse;
3574
3575 let mut d = driver_with_sessions();
3576 d.take_notifications();
3577
3578 let a_bytes = build_ca_pmt_fixture(1546);
3579 let a = PmtSection::parse(&a_bytes).unwrap();
3580 d.add_service(&a).unwrap();
3581 d.device_mut().inbound.push_back(sb());
3582 d.pump(Duration::from_millis(10)).unwrap();
3583
3584 let b_bytes = build_ca_pmt_fixture_dedicated_pcr(1547);
3585 let b = PmtSection::parse(&b_bytes).unwrap();
3586 d.add_service(&b).unwrap();
3587 d.device_mut().inbound.push_back(sb());
3588 d.pump(Duration::from_millis(10)).unwrap();
3589
3590 let a_old_record = d.managed_ca().services().get(&1546).unwrap().clone();
3591 let b_record_before = d.managed_ca().services().get(&1547).unwrap().clone();
3592 assert_eq!(
3593 a_old_record.ca_pids,
3594 vec![Pid::from_const(0x0064), Pid::from_const(0x0065)],
3595 "fixture sanity: A starts on the 0x0064/0x0065 ECM PIDs"
3596 );
3597
3598 let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3600 let a2 = PmtSection::parse(&a2_bytes).unwrap();
3601 let update = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::OkDescrambling)
3602 .to_bytes()
3603 .unwrap();
3604 let writes_before = d.device().ops.len();
3605
3606 d.update_service(&a2).unwrap();
3607 d.device_mut().inbound.push_back(sb());
3608 d.pump(Duration::from_millis(10)).unwrap();
3609
3610 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &update), 1);
3612 let new_ca_pmt_writes = d.device().ops[writes_before..]
3613 .iter()
3614 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3615 .count();
3616 assert_eq!(new_ca_pmt_writes, 1, "exactly one ca_pmt APDU may be sent");
3617
3618 let new_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0074));
3620 let old_prog_ca = ca_descriptor(0x0500, Pid::from_const(0x0064));
3621 assert!(update.windows(new_prog_ca.len()).any(|x| x == new_prog_ca));
3622 assert!(!update.windows(old_prog_ca.len()).any(|x| x == old_prog_ca));
3623
3624 let a_new_record = d.managed_ca().services().get(&1546).unwrap();
3626 assert_eq!(
3627 a_new_record.ca_pids,
3628 vec![Pid::from_const(0x0074), Pid::from_const(0x0075)]
3629 );
3630 assert_eq!(a_new_record.built_ca_pmt, update);
3631 assert_ne!(a_new_record.built_ca_pmt, a_old_record.built_ca_pmt);
3632 assert_ne!(a_new_record.pmt_raw, a_old_record.pmt_raw);
3633 assert_eq!(
3634 a_new_record.pmt_raw, a2_bytes,
3635 "raw PMT must be the new section"
3636 );
3637
3638 assert_eq!(
3640 *d.managed_ca().services().get(&1547).unwrap(),
3641 b_record_before
3642 );
3643 assert_eq!(d.managed_ca().services().len(), 2);
3644 }
3645
3646 #[test]
3649 fn remove_service_after_update_service_uses_the_new_pmt() {
3650 use broadcast_common::Parse;
3651
3652 let mut d = driver_with_sessions();
3653 d.take_notifications();
3654
3655 let a_bytes = build_ca_pmt_fixture(1546);
3656 let a = PmtSection::parse(&a_bytes).unwrap();
3657 d.add_service(&a).unwrap();
3658 d.device_mut().inbound.push_back(sb());
3659 d.pump(Duration::from_millis(10)).unwrap();
3660 let a2_bytes = build_ca_pmt_fixture_distinct_pids(1546);
3661 let a2 = PmtSection::parse(&a2_bytes).unwrap();
3662 d.update_service(&a2).unwrap();
3663 d.device_mut().inbound.push_back(sb());
3664 d.pump(Duration::from_millis(10)).unwrap();
3665
3666 d.remove_service(1546).unwrap();
3667 d.device_mut().inbound.push_back(sb());
3668 d.pump(Duration::from_millis(10)).unwrap();
3669
3670 let removal_new = build_ca_pmt(&a2, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3671 .to_bytes()
3672 .unwrap();
3673 let removal_old = build_ca_pmt(&a, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
3674 .to_bytes()
3675 .unwrap();
3676 assert_ne!(
3677 removal_new, removal_old,
3678 "fixture sanity: the two PMTs differ"
3679 );
3680 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_new), 1);
3681 assert_eq!(count_apdu_on_session(&d, CA_SESSION, &removal_old), 0);
3682 assert!(d.managed_ca().services().is_empty());
3683 }
3684
3685 #[test]
3688 fn update_service_filters_caids_like_add_service() {
3689 use broadcast_common::Parse;
3690
3691 let mut d = driver_with_sessions();
3692 d.take_notifications();
3693
3694 let two_caids = build_ca_pmt_fixture_two_caids(1546);
3695 let pmt = PmtSection::parse(&two_caids).unwrap();
3696 d.add_service(&pmt).unwrap();
3697 let added = d
3698 .managed_ca()
3699 .services()
3700 .get(&1546)
3701 .unwrap()
3702 .built_ca_pmt
3703 .clone();
3704
3705 d.update_service(&pmt).unwrap();
3706 let updated = d
3707 .managed_ca()
3708 .services()
3709 .get(&1546)
3710 .unwrap()
3711 .built_ca_pmt
3712 .clone();
3713
3714 assert_eq!(added.len(), updated.len());
3716 let diff: Vec<usize> = (0..added.len())
3717 .filter(|&i| added[i] != updated[i])
3718 .collect();
3719 assert_eq!(
3720 diff.len(),
3721 1,
3722 "only list_management may differ, got offsets {diff:?}"
3723 );
3724 assert_eq!(updated[diff[0]], 0x05, "list_management must be update");
3725 }
3726
3727 #[test]
3728 fn update_service_serialize_failure_leaves_record_unchanged() {
3729 let mut d = driver_with_sessions();
3730 let pmt_bytes = build_ca_pmt_fixture(1);
3732 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3733 d.add_service(&pmt).unwrap();
3734
3735 let svc_before = d.managed_ca().services().get(&1).unwrap().clone();
3736
3737 let corrupt = corrupt_ca_section_ctor();
3738 let err = d
3739 .update_service(&corrupt)
3740 .expect_err("unencodable PMT must error");
3741 assert!(
3742 matches!(err, CaError::Serialize(_)),
3743 "expected CaError::Serialize, got {err:?}"
3744 );
3745
3746 let svc_after = d.managed_ca().services().get(&1).unwrap();
3747 assert_eq!(svc_before, *svc_after, "record must be unchanged");
3748 }
3749
3750 #[test]
3751 fn add_service_without_an_open_ca_session_errors_and_records_nothing() {
3752 let mut d = Driver::new(MockCaDevice::new([]));
3753 let pmt_bytes = build_ca_pmt_fixture(1546);
3754 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3755 let result = d.add_service(&pmt);
3756 let wrote_ca_pmt = d.device().ops.iter().any(|op| match op {
3757 DeviceOp::Write(w) => w.windows(3).any(|x| x == [0x9F, 0x80, 0x32]),
3758 _ => false,
3759 });
3760 assert!(!wrote_ca_pmt, "precondition: nothing can have been sent");
3761 assert!(matches!(result, Err(CaError::NotSent { .. })), "{result:?}");
3762 assert!(d.managed_ca().services().is_empty());
3763 }
3764
3765 #[test]
3766 fn setup_timeout_is_followed_by_a_new_create_t_c() {
3767 let mut d = Driver::new(MockCaDevice::new([]));
3768 let clock = TestClock::new();
3769 d = d.with_clock(clock.as_fn());
3770 d.init().unwrap();
3771 for _ in 0..60 {
3772 clock.advance(Duration::from_millis(100));
3773 d.pump(Duration::from_millis(100)).unwrap();
3774 }
3775 let create_t_c = d
3776 .device()
3777 .ops
3778 .iter()
3779 .filter(|op| matches!(op, DeviceOp::Write(w) if w.first() == Some(&tags::CREATE_T_C)))
3780 .count();
3781 assert!(
3782 create_t_c > 1,
3783 "6 s of a silent CAM produced {create_t_c} Create_T_C"
3784 );
3785 }
3786
3787 #[test]
3788 fn readable_pumps_still_advance_the_requery_timer() {
3789 let clock = TestClock::new();
3790 let mut d = driver_with_sessions().with_clock(clock.as_fn());
3791 let pmt_bytes = build_ca_pmt_fixture(1546);
3792 let pmt = PmtSection::parse(&pmt_bytes).unwrap();
3793 d.add_service(&pmt).unwrap();
3794 d.set_requery_interval(Duration::from_secs(1));
3795 d.pump(Duration::from_millis(10)).unwrap();
3796 let ca_pmt_writes = |d: &Driver<MockCaDevice>| {
3797 d.device()
3798 .ops
3799 .iter()
3800 .filter(|op| matches!(op, DeviceOp::Write(w) if w.windows(3).any(|x| x == [0x9F, 0x80, 0x32])))
3801 .count()
3802 };
3803 let before = ca_pmt_writes(&d);
3804 for _ in 0..8 {
3805 clock.advance(Duration::from_millis(500));
3806 d.device_mut().inbound.push_back(sb());
3807 d.pump(Duration::from_millis(10)).unwrap();
3808 }
3809 assert!(
3810 ca_pmt_writes(&d) > before,
3811 "4 s passed with a 1 s requery interval but no re-query was sent"
3812 );
3813 }
3814
3815 #[test]
3824 fn pending_notifications_are_bounded_and_the_overflow_counted() {
3825 let mut d = Driver::new(MockCaDevice::new([]));
3826 d.pump(Duration::from_millis(1)).unwrap();
3827 d.take_notifications();
3828
3829 d.device_mut().slot.module_present = false;
3830 d.pump(Duration::from_millis(1)).unwrap();
3831
3832 let overflow = 16;
3833 for _ in 0..(MAX_PENDING_NOTIFICATIONS + overflow) {
3834 d.device_mut().inbound.push_back(vec![0xFF, 0x00]);
3835 d.pump(Duration::from_millis(1)).unwrap();
3836 }
3837
3838 let notes = d.take_notifications();
3839 assert_eq!(
3840 notes.len(),
3841 MAX_PENDING_NOTIFICATIONS,
3842 "the pending queue must stay at its cap under a notification flood"
3843 );
3844 assert_eq!(
3845 d.notifications_dropped(),
3846 (overflow + 1) as u64,
3847 "the CAM-removed notification and the oldest errors are the ones discarded"
3848 );
3849 assert!(
3850 notes
3851 .iter()
3852 .all(|n| matches!(n, Notification::Error { .. })),
3853 "the discarded entries must be the oldest ones, not the newest"
3854 );
3855 }
3856
3857 #[test]
3858 fn read_buffer_covers_the_largest_legal_device_frame() {
3859 struct BufferProbe(Option<usize>);
3860
3861 impl CaDevice for BufferProbe {
3862 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3863 self.0 = Some(buf.len());
3864 Ok(0)
3865 }
3866 fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3867 Ok(())
3868 }
3869 fn reset(&mut self) -> io::Result<()> {
3870 Ok(())
3871 }
3872 fn slot_info(&mut self) -> io::Result<SlotInfo> {
3873 Ok(SlotInfo {
3874 num: 0,
3875 module_ready: true,
3876 module_present: true,
3877 })
3878 }
3879 fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3880 Ok(true)
3881 }
3882 }
3883
3884 let mut d = Driver::new(BufferProbe(None));
3885 d.pump(Duration::from_millis(1))
3886 .expect("a readable device with no frame is not an error");
3887 assert_eq!(
3888 d.device().0,
3889 Some(MAX_CA_FRAME),
3890 "the read buffer must cover the largest legal device frame"
3891 );
3892 }
3893
3894 #[test]
3899 fn a_legal_oversized_tpdu_is_read_without_an_io_error() {
3900 const DATA_LEN: usize = 5000;
3901
3902 struct OversizedFrameDevice(Option<Vec<u8>>);
3903
3904 impl CaDevice for OversizedFrameDevice {
3905 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3906 let Some(frame) = self.0.take() else {
3907 return Ok(0);
3908 };
3909 if frame.len() > buf.len() {
3910 return Err(io::Error::new(
3911 io::ErrorKind::InvalidData,
3912 "TPDU larger than the read buffer; dropped, not truncated",
3913 ));
3914 }
3915 let n = frame.len();
3916 buf[..n].copy_from_slice(&frame);
3917 Ok(n)
3918 }
3919 fn write(&mut self, _buf: &[u8]) -> io::Result<()> {
3920 Ok(())
3921 }
3922 fn reset(&mut self) -> io::Result<()> {
3923 Ok(())
3924 }
3925 fn slot_info(&mut self) -> io::Result<SlotInfo> {
3926 Ok(SlotInfo {
3927 num: 0,
3928 module_ready: true,
3929 module_present: true,
3930 })
3931 }
3932 fn poll(&mut self, _timeout: Duration) -> io::Result<bool> {
3933 Ok(self.0.is_some())
3934 }
3935 }
3936
3937 let mut frame = vec![tags::DATA_LAST];
3938 let mut length = [0u8; 4];
3939 let coded = dvb_ci::length::encode_into(1 + DATA_LEN, &mut length)
3940 .expect("a legal EN 50221 length");
3941 frame.extend_from_slice(&length[..coded]);
3942 frame.push(0x01);
3943 frame.extend(std::iter::repeat_n(0xAB, DATA_LEN));
3944
3945 let mut d = Driver::new(OversizedFrameDevice(Some(frame)));
3946 assert!(
3947 d.pump(Duration::from_millis(1)).is_ok(),
3948 "a legal {DATA_LEN}-byte TPDU must not fail the read"
3949 );
3950 assert!(
3951 d.device().0.is_none(),
3952 "the frame must have been taken off the device, not refused"
3953 );
3954 }
3955}