Skip to main content

dvb_ci_runtime/
stack.rs

1//! The CI protocol stack — composes the transport + session layers and the
2//! resource state machines (Resource Manager, application_information,
3//! conditional_access, date_time, mmi, host_control) into one sans-IO core.
4//!
5//! [`CiStack::handle`] is the pure entry point: feed it an [`Event`], get back
6//! the [`Action`]s the driver must perform. No I/O, threads, or clock here.
7
8use crate::event::{Action, Event, HostRequest, Notification};
9use crate::resource::{
10    ApplicationInformation, ConditionalAccess, DateTime, HostControl, Mmi, Resource,
11    ResourceManager, ResourceOut,
12};
13use crate::session::{SessionLayer, SessionOut};
14use crate::transport::{Out as TransportOut, TcState, Transport};
15
16use broadcast_common::Parse;
17use dvb_ci::builder::{build_ca_pmt, build_ca_pmt_for_caids};
18use dvb_ci::objects::ca_pmt::{CaPmtCmdId, CaPmtListManagement};
19use dvb_ci::objects::mmi_high::{Answ, AnswId, MenuAnsw};
20use dvb_ci::resource::{
21    APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, DATE_TIME, HOST_CONTROL, MMI,
22    RESOURCE_MANAGER, ResourceId,
23};
24use dvb_si::tables::pmt::PmtSection;
25
26/// Convert a serialize failure into the host-facing error notification the
27/// stack already uses for every other internal error (transport errors,
28/// `build_ca_pmt_bytes` failures): non-fatal and informational, never a panic
29/// or a silently dropped action.
30fn err_action(e: dvb_ci::Error) -> Action {
31    Action::Notify(Notification::Error {
32        detail: e.to_string(),
33    })
34}
35
36/// The composed EN 50221 protocol core.
37pub struct CiStack {
38    transport: Transport,
39    session: SessionLayer,
40    /// Application-layer resource handlers, dispatched by `ResourceId`.
41    resources: Vec<Box<dyn Resource>>,
42    /// Resources the host **provides** — the module opens sessions to these, so
43    /// the host accepts an incoming `open_session_request` for them
44    /// (resource_manager, date_time). Module-provided resources are opened the
45    /// other way, by the host's `create_session` (#340).
46    host_provided: Vec<ResourceId>,
47    /// `CA_system_id`s the CAM advertised in its `ca_info` (the descramble
48    /// filter set; empty until `ca_info` arrives).
49    cam_caids: Vec<u16>,
50}
51
52impl Default for CiStack {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58impl CiStack {
59    /// New stack on transport connection `t_c_id = 1`. The host advertises the
60    /// Resource Manager and registers the RM + application_information +
61    /// conditional_access handlers.
62    #[must_use]
63    pub fn new() -> Self {
64        // The host *provides* all six resources it implements; the module opens
65        // a session to each (module → host `open_session_request`, host accepts),
66        // and this is the list the RM advertises in its `profile` reply. Verified
67        // on hardware (#340, live AlphaCrypt): the module opens sessions only to
68        // resources the host advertises here — so application_information,
69        // conditional_access and mmi MUST be advertised, or the module never
70        // opens them and `ca_info` never arrives. (The earlier host-initiated
71        // `create_session`/`open_session_request` for these was wrong: the module
72        // rejects/ignores it.)
73        let host_provided = vec![
74            RESOURCE_MANAGER,
75            APPLICATION_INFORMATION,
76            CONDITIONAL_ACCESS_SUPPORT,
77            DATE_TIME,
78            MMI,
79            HOST_CONTROL,
80        ];
81        Self {
82            transport: Transport::new(1),
83            session: SessionLayer::new(),
84            resources: vec![
85                Box::new(ResourceManager::new(host_provided.clone())),
86                Box::new(ApplicationInformation),
87                Box::new(ConditionalAccess),
88                Box::new(DateTime::new()),
89                Box::new(Mmi::default()),
90                Box::new(HostControl),
91            ],
92            host_provided,
93            cam_caids: Vec::new(),
94        }
95    }
96
97    /// Register an additional resource handler.
98    pub fn register(&mut self, resource: Box<dyn Resource>) -> &mut Self {
99        self.resources.push(resource);
100        self
101    }
102
103    /// Index of the registered handler for `resource`, if any.
104    fn handler_index(&self, resource: ResourceId) -> Option<usize> {
105        self.resources.iter().position(|r| r.id() == resource)
106    }
107
108    /// The pure sans-IO entry point.
109    pub fn handle(&mut self, event: Event<'_>) -> Vec<Action> {
110        match event {
111            Event::Host(HostRequest::Init) => {
112                // r10-W-19: rebuild every piece of stack-level state Init
113                // is responsible for, not just the transport connection —
114                // otherwise a stale session table / cached CAIDs from
115                // whatever was connected before survive into the new
116                // handshake (a `session_nb` the old CAM had open could
117                // alias one a newly-inserted CAM later opens for a
118                // DIFFERENT resource, since `SessionLayer` has no way to
119                // know the old binding is stale).
120                self.session = SessionLayer::new();
121                self.cam_caids = Vec::new();
122                // r10-W-19: also reset each resource handler's own internal
123                // state (e.g. the Resource Manager's `ready`/`module_profiled`
124                // latch, date_time's resend timer) — otherwise a re-inserted
125                // CAM's fresh handshake runs against state a PREVIOUS module
126                // left behind.
127                for r in &mut self.resources {
128                    r.reset();
129                }
130                let mut actions = vec![Action::Reset, Action::QuerySlot];
131                let out = self.transport.init();
132                actions.extend(self.emit_transport(out));
133                actions
134            }
135            Event::Tick { elapsed } => {
136                let out = self.transport.tick(elapsed);
137                let mut actions = self.emit_transport(out);
138                // One tick per resource handler, not per open session: a
139                // resource reached over several sessions would otherwise have
140                // its own timer run once per session (audit a20-44; the
141                // session layer now also keeps one session per resource).
142                let mut ticked: Vec<usize> = Vec::new();
143                for (session_nb, resource) in self.session.sessions() {
144                    if let Some(i) = self.handler_index(resource) {
145                        if ticked.contains(&i) {
146                            continue;
147                        }
148                        ticked.push(i);
149                        match self.resources[i].tick(elapsed) {
150                            Ok(out) => actions.extend(self.process_resource_out(session_nb, out)),
151                            Err(e) => actions.push(err_action(e)),
152                        }
153                    }
154                }
155                actions
156            }
157            Event::Readable(frame) => {
158                let out = self.transport.on_frame(frame);
159                self.emit_transport(out)
160            }
161            Event::Host(HostRequest::SendCaPmt(apdu)) => {
162                self.send_to_resource(CONDITIONAL_ACCESS_SUPPORT, apdu)
163            }
164            Event::Host(HostRequest::Descramble(pmt)) => self.descramble(pmt),
165            Event::Host(HostRequest::DescramblePrograms(pmts)) => self.descramble_programs(pmts),
166            Event::Host(HostRequest::AddProgram(pmt)) => self.add_program(pmt),
167            Event::Host(HostRequest::RemoveProgram(pmt)) => self.remove_program(pmt),
168            Event::Host(HostRequest::EnterMenu) => {
169                match crate::resource::ser(&dvb_ci::objects::application_info::EnterMenu::default())
170                {
171                    Ok(apdu) => self.send_to_resource(APPLICATION_INFORMATION, &apdu),
172                    Err(e) => vec![err_action(e)],
173                }
174            }
175            Event::Host(HostRequest::MmiMenuAnswer(choice_ref)) => {
176                match crate::resource::ser(&MenuAnsw {
177                    length_form: dvb_ci::length::LengthForm::Minimal,
178                    choice_ref,
179                }) {
180                    Ok(apdu) => self.send_to_resource(MMI, &apdu),
181                    Err(e) => vec![err_action(e)],
182                }
183            }
184            Event::Host(HostRequest::MmiEnquiryAnswer(text)) => {
185                match crate::resource::ser(&Answ {
186                    length_form: dvb_ci::length::LengthForm::Minimal,
187                    answ_id: AnswId::Answer,
188                    text_chars: text,
189                }) {
190                    Ok(apdu) => self.send_to_resource(MMI, &apdu),
191                    Err(e) => vec![err_action(e)],
192                }
193            }
194            Event::Host(HostRequest::MmiCancel) => match crate::resource::ser(&Answ {
195                length_form: dvb_ci::length::LengthForm::Minimal,
196                answ_id: AnswId::Cancel,
197                text_chars: &[],
198            }) {
199                Ok(apdu) => self.send_to_resource(MMI, &apdu),
200                Err(e) => vec![err_action(e)],
201            },
202            Event::Host(HostRequest::Shutdown) => {
203                // r10-W-19: previously a complete no-op — this is the
204                // symmetric teardown to `Init`'s build-up, so a later
205                // `Init` starts genuinely clean rather than compounding
206                // onto whatever this shutdown should have cleared out
207                // (stale sessions, cached CAIDs, an `Active` transport
208                // connection the module no longer expects to hear from,
209                // and now each resource's own latched state, r10-W-19).
210                self.transport = Transport::new(1);
211                self.session = SessionLayer::new();
212                self.cam_caids = Vec::new();
213                for r in &mut self.resources {
214                    r.reset();
215                }
216                vec![Action::Reset]
217            }
218        }
219    }
220
221    /// React to a CA notification as it is surfaced: cache the CAM's CAIDs from
222    /// `ca_info`, and complete a pending [`HostRequest::Descramble`] by sending
223    /// `ok_descrambling` when the `ca_pmt_reply` says descrambling is possible.
224    fn on_ca_notification(&mut self, note: &Notification) -> Vec<Action> {
225        // Cache the CAM's advertised CAIDs so a later `descramble` can filter the
226        // `ca_pmt` to them. (The `ca_pmt_reply` outcome is surfaced to the host as
227        // `Notification::CaPmtReply`; no follow-up SPDU is needed — we send
228        // `ok_descrambling` up front.)
229        if let Notification::CaInfo { ca_system_ids } = note {
230            self.cam_caids = ca_system_ids.clone();
231        }
232        Vec::new()
233    }
234
235    /// Begin a [`HostRequest::Descramble`]: build a CAID-filtered `ca_pmt` with
236    /// `cmd_id = ok_descrambling` and send it.
237    ///
238    /// We do NOT send a `query` first: a real AlphaCrypt/Irdeto module does not
239    /// reply to a `ca_pmt` query (verified live — the query was sent and the
240    /// module stayed silent, so a query→reply→ok flow stalls forever). The
241    /// module descrambles directly on `ok_descrambling` and reports the outcome
242    /// via `ca_pmt_reply` (surfaced as `Notification::CaPmtReply`). This matches
243    /// what oscam / libdvben50221 do in practice.
244    fn descramble(&mut self, pmt: &[u8]) -> Vec<Action> {
245        self.send_ca_pmt_for(pmt, CaPmtListManagement::Only, CaPmtCmdId::OkDescrambling)
246    }
247
248    /// Descramble a **set** of programmes in one CA-PMT list (§8.4.3.4): the
249    /// first programme is sent `list_management = first` (or `only` if it is the
250    /// sole programme), the interior ones `more`, the last `last`; all with
251    /// `cmd_id = ok_descrambling`. Replaces any previously selected set. The
252    /// per-programme `ca_pmt`s are serialised one-per-module-turn by the
253    /// transport queue.
254    fn descramble_programs(&mut self, pmts: &[&[u8]]) -> Vec<Action> {
255        let mut actions = Vec::new();
256        let n = pmts.len();
257        for (i, pmt) in pmts.iter().enumerate() {
258            let lm = match (n, i) {
259                (1, _) => CaPmtListManagement::Only,
260                (_, 0) => CaPmtListManagement::First,
261                (_, i) if i == n - 1 => CaPmtListManagement::Last,
262                _ => CaPmtListManagement::More,
263            };
264            actions.extend(self.send_ca_pmt_for(pmt, lm, CaPmtCmdId::OkDescrambling));
265        }
266        actions
267    }
268
269    /// Add one programme to the descrambled set without re-listing the rest
270    /// (`list_management = add`, `cmd_id = ok_descrambling`).
271    fn add_program(&mut self, pmt: &[u8]) -> Vec<Action> {
272        self.send_ca_pmt_for(pmt, CaPmtListManagement::Add, CaPmtCmdId::OkDescrambling)
273    }
274
275    /// Remove one programme from the descrambled set (`list_management = update`,
276    /// `cmd_id = not_selected` — tells the CAM to stop descrambling it).
277    fn remove_program(&mut self, pmt: &[u8]) -> Vec<Action> {
278        self.send_ca_pmt_for(pmt, CaPmtListManagement::Update, CaPmtCmdId::NotSelected)
279    }
280
281    /// Build a CAID-filtered `ca_pmt` for `pmt` with the given list-management +
282    /// command id and send it on the conditional-access session.
283    fn send_ca_pmt_for(
284        &mut self,
285        pmt: &[u8],
286        list_management: CaPmtListManagement,
287        cmd_id: CaPmtCmdId,
288    ) -> Vec<Action> {
289        match self.build_ca_pmt_bytes(pmt, list_management, cmd_id) {
290            Ok(bytes) => self.send_to_resource(CONDITIONAL_ACCESS_SUPPORT, &bytes),
291            Err(detail) => vec![Action::Notify(Notification::Error { detail })],
292        }
293    }
294
295    /// Build a CAID-filtered `ca_pmt` APDU for `pmt` with the given
296    /// list-management + command id. Filters to the CAM's advertised CAIDs once
297    /// `ca_info` is known; falls back to all `CA_descriptor`s before then.
298    fn build_ca_pmt_bytes(
299        &self,
300        pmt: &[u8],
301        list_management: CaPmtListManagement,
302        cmd_id: CaPmtCmdId,
303    ) -> Result<Vec<u8>, String> {
304        let parsed = PmtSection::parse(pmt).map_err(|e| format!("invalid PMT: {e}"))?;
305        let built = if self.cam_caids.is_empty() {
306            build_ca_pmt(&parsed, list_management, cmd_id)
307        } else {
308            build_ca_pmt_for_caids(&parsed, &self.cam_caids, list_management, cmd_id)
309        };
310        // r10-W-20: `try_to_bytes`, not `to_bytes` — the projection of a
311        // corrupt (or CAM-influenced) PMT can have no valid `ca_pmt`
312        // encoding; surface it as the stack's `Notification::Error`, never
313        // a panic.
314        built
315            .to_bytes()
316            .map_err(|e| format!("ca_pmt serialization failed: {e}"))
317    }
318
319    /// Send an APDU to the open session bound to `resource` (if any).
320    fn send_to_resource(&mut self, resource: ResourceId, apdu: &[u8]) -> Vec<Action> {
321        let nb = self.session.session_for(resource);
322        match nb {
323            Some(_) if self.transport.state() != TcState::Active => {
324                vec![Action::Notify(Notification::Error {
325                    detail: "transport connection is not active".to_owned(),
326                })]
327            }
328            Some(nb) => match self.session.send_apdu(nb, apdu) {
329                Ok(spdu) => {
330                    let out = self.transport.send_spdu(&spdu);
331                    self.emit_transport(out)
332                }
333                Err(e) => vec![err_action(e)],
334            },
335            None => vec![Action::Notify(Notification::Error {
336                detail: format!("no open session for resource {}", resource.name()),
337            })],
338        }
339    }
340
341    /// Convert a transport [`Out`](TransportOut) into actions, driving any
342    /// reassembled SPDUs up through the session layer.
343    fn emit_transport(&mut self, out: TransportOut) -> Vec<Action> {
344        let mut actions = Vec::new();
345        for w in out.writes {
346            actions.push(Action::Write(w));
347        }
348        if let Some(after) = out.timer {
349            actions.push(Action::SetTimer { after });
350        }
351        if let Some(err) = out.error {
352            actions.push(Action::Notify(Notification::Error {
353                detail: err.to_string(),
354            }));
355        }
356        for spdu in out.spdus {
357            actions.extend(self.drive_session(&spdu));
358        }
359        actions
360    }
361
362    /// Feed one SPDU to the session layer and convert its output to actions.
363    fn drive_session(&mut self, spdu: &[u8]) -> Vec<Action> {
364        // The module opens sessions to **host-provided** resources
365        // (resource_manager, date_time); the host accepts those. Module-provided
366        // resources (application_information, conditional_access, mmi) are opened
367        // the other way — by the host's `create_session` (#340) — so an incoming
368        // `open_session_request` for them is *not* accepted here.
369        let host_provided = self.host_provided.clone();
370        let SessionOut {
371            spdus,
372            apdus,
373            opened,
374            closed,
375        } = match self.session.on_spdu(spdu, |r| host_provided.contains(&r)) {
376            Ok(out) => out,
377            Err(e) => return vec![err_action(e)],
378        };
379
380        let mut actions = Vec::new();
381        // Session-layer SPDUs (e.g. open_session_response) go down the transport.
382        for s in spdus {
383            actions.extend(self.send_spdu_actions(&s));
384        }
385        for (session_nb, resource) in opened {
386            actions.push(Action::Notify(Notification::SessionOpened { resource }));
387            // Drive the resource handler's on_open (e.g. RM sends profile_enq).
388            if let Some(i) = self.handler_index(resource) {
389                match self.resources[i].on_open() {
390                    Ok(out) => actions.extend(self.process_resource_out(session_nb, out)),
391                    Err(e) => actions.push(err_action(e)),
392                }
393            }
394        }
395        for session_nb in closed {
396            actions.push(Action::Notify(Notification::SessionClosed { session_nb }));
397        }
398        // Route each APDU to the resource handler bound to its session.
399        for (session_nb, apdu) in apdus {
400            if let Some(resource) = self.session.resource_of(session_nb)
401                && let Some(i) = self.handler_index(resource)
402            {
403                match self.resources[i].on_apdu(&apdu) {
404                    Ok(out) => actions.extend(self.process_resource_out(session_nb, out)),
405                    Err(e) => actions.push(err_action(e)),
406                }
407            }
408        }
409        actions
410    }
411
412    /// Wrap an SPDU as a `T_Data_Last` and collect the resulting actions.
413    fn send_spdu_actions(&mut self, spdu: &[u8]) -> Vec<Action> {
414        let t = self.transport.send_spdu(spdu);
415        let mut actions = Vec::new();
416        for w in t.writes {
417            actions.push(Action::Write(w));
418        }
419        if let Some(after) = t.timer {
420            actions.push(Action::SetTimer { after });
421        }
422        actions
423    }
424
425    /// Convert a [`ResourceOut`] into actions: send its APDUs on `session_nb`,
426    /// surface its notifications, and open any module resources it requested.
427    fn process_resource_out(&mut self, session_nb: u16, out: ResourceOut) -> Vec<Action> {
428        let mut actions = Vec::new();
429        for apdu in out.apdus {
430            match self.session.send_apdu(session_nb, &apdu) {
431                Ok(spdu) => actions.extend(self.send_spdu_actions(&spdu)),
432                Err(e) => actions.push(err_action(e)),
433            }
434        }
435        for note in out.notify {
436            // Drive the auto-descramble sequence off the CA notifications.
437            let follow = self.on_ca_notification(&note);
438            actions.push(Action::Notify(note));
439            actions.extend(follow);
440        }
441        for resource in out.open {
442            match self.session.create_session(resource) {
443                Ok(spdu) => actions.extend(self.send_spdu_actions(&spdu)),
444                Err(e) => actions.push(err_action(e)),
445            }
446        }
447        actions
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use crate::transport::DEFAULT_POLL_INTERVAL;
455    use broadcast_common::Serialize;
456    use dvb_ci::resource::RESOURCE_MANAGER;
457    use dvb_ci::spdu::{OpenSessionRequest, tags as spdu_tags};
458    use dvb_ci::tpdu::{SbValue, tags as tpdu_tags};
459    use std::time::Duration;
460
461    fn ser<S: Serialize>(s: &S) -> Vec<u8> {
462        let mut b = vec![0u8; s.serialized_len()];
463        match s.serialize_into(&mut b) {
464            Ok(n) => b.truncate(n),
465            Err(_) => b.clear(),
466        }
467        b
468    }
469
470    /// Wrap an SPDU as a module→host `T_Data_Last` R_TPDU (+ T_SB, DA clear).
471    fn r_data(tcid: u8, spdu: &[u8]) -> Vec<u8> {
472        let mut v = vec![tpdu_tags::DATA_LAST, (1 + spdu.len()) as u8, tcid];
473        v.extend_from_slice(spdu);
474        v.extend_from_slice(&[tpdu_tags::SB, 0x02, tcid, SbValue::new(false).0]);
475        v
476    }
477
478    #[test]
479    fn init_resets_and_opens_transport() {
480        let mut s = CiStack::new();
481        let a = s.handle(Event::Host(HostRequest::Init));
482        assert_eq!(a[0], Action::Reset);
483        assert_eq!(a[1], Action::QuerySlot);
484        assert!(matches!(&a[2], Action::Write(w) if w[0] == tpdu_tags::CREATE_T_C));
485    }
486
487    /// r10-W-19: `Shutdown` was previously a complete no-op — it must now
488    /// reset the device and clear every piece of stack-level state `Init`
489    /// builds up (session table, cached CAIDs, the transport connection).
490    #[test]
491    fn shutdown_resets_device_and_clears_stack_state() {
492        let mut s = CiStack::new();
493        s.handle(Event::Host(HostRequest::Init));
494        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
495        let osr = ser(&OpenSessionRequest {
496            length_form: dvb_ci::length::LengthForm::Minimal,
497            resource: RESOURCE_MANAGER,
498        });
499        s.handle(Event::Readable(&r_data(1, &osr)));
500        assert!(!s.session.is_empty(), "precondition: a session is open");
501        assert_eq!(s.transport.state(), crate::transport::TcState::Active);
502
503        let actions = s.handle(Event::Host(HostRequest::Shutdown));
504        assert_eq!(actions, vec![Action::Reset]);
505        assert!(
506            s.session.is_empty(),
507            "Shutdown must clear the session table"
508        );
509        assert_eq!(
510            s.transport.state(),
511            crate::transport::TcState::Idle,
512            "Shutdown must tear down the transport connection"
513        );
514    }
515
516    /// r10-W-19: `Init` must rebuild the session table and cached CAIDs,
517    /// not just the transport — otherwise a session_nb the PREVIOUS module
518    /// had open (never explicitly closed, e.g. a hot-plug swap) survives
519    /// into the new handshake and could alias whatever the new module
520    /// opens under the same number for a different resource.
521    #[test]
522    fn init_clears_stale_session_state_from_a_previous_connection() {
523        let mut s = CiStack::new();
524        s.handle(Event::Host(HostRequest::Init));
525        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
526        let osr = ser(&OpenSessionRequest {
527            length_form: dvb_ci::length::LengthForm::Minimal,
528            resource: RESOURCE_MANAGER,
529        });
530        s.handle(Event::Readable(&r_data(1, &osr)));
531        assert!(
532            !s.session.is_empty(),
533            "precondition: a stale session is open"
534        );
535
536        // Re-init (e.g. a hot-plug re-handshake) without an intervening
537        // Shutdown — the stale state must still not survive.
538        s.handle(Event::Host(HostRequest::Init));
539        assert!(
540            s.session.is_empty(),
541            "Init must not inherit the previous connection's session table"
542        );
543    }
544
545    /// r10-W-19: `Init` must also reset each resource handler's own internal
546    /// state, not just the session table — otherwise the Resource Manager's
547    /// `ready` flag stays latched `true` from the FIRST handshake, and a
548    /// second `profile` (module re-sent after a hot-plug re-insert) never
549    /// re-opens the `profile_change`/`CamReady` gate (`resource.rs`'s
550    /// `ready` field), so the module idles forever after a re-insert.
551    #[test]
552    fn re_init_after_a_completed_handshake_fires_cam_ready_again() {
553        let mut s = CiStack::new();
554        s.handle(Event::Host(HostRequest::Init));
555        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
556        let osr = ser(&OpenSessionRequest {
557            length_form: dvb_ci::length::LengthForm::Minimal,
558            resource: RESOURCE_MANAGER,
559        });
560        s.handle(Event::Readable(&r_data(1, &osr)));
561        let first = s.handle(Event::Readable(&r_apdu(
562            1,
563            &ser(&dvb_ci::objects::resource_manager::Profile {
564                length_form: dvb_ci::length::LengthForm::Minimal,
565                resources: vec![],
566            }),
567        )));
568        assert!(
569            first
570                .iter()
571                .any(|a| matches!(a, Action::Notify(Notification::CamReady))),
572            "precondition: the first handshake fires CamReady"
573        );
574
575        // Re-init (a hot-plug re-handshake), then re-run the RM handshake
576        // exactly as the first time (the fresh SessionLayer allocates
577        // session_nb 1 again).
578        s.handle(Event::Host(HostRequest::Init));
579        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
580        let osr2 = ser(&OpenSessionRequest {
581            length_form: dvb_ci::length::LengthForm::Minimal,
582            resource: RESOURCE_MANAGER,
583        });
584        s.handle(Event::Readable(&r_data(1, &osr2)));
585        let second = s.handle(Event::Readable(&r_apdu(
586            1,
587            &ser(&dvb_ci::objects::resource_manager::Profile {
588                length_form: dvb_ci::length::LengthForm::Minimal,
589                resources: vec![],
590            }),
591        )));
592        assert!(
593            second
594                .iter()
595                .any(|a| matches!(a, Action::Notify(Notification::CamReady))),
596            "a fresh handshake after Init must fire CamReady again \
597             (pre-fix: ResourceManager.ready stayed latched from the first \
598             handshake, so profile_change/CamReady never re-fired)"
599        );
600    }
601
602    #[test]
603    fn full_pipeline_opens_a_session_for_a_provided_resource() {
604        let mut s = CiStack::new();
605        s.handle(Event::Host(HostRequest::Init));
606        // module accepts the transport connection
607        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
608        // module opens a session to the host's resource_manager (carried in an
609        // R_TPDU data block)
610        let osr = ser(&OpenSessionRequest {
611            length_form: dvb_ci::length::LengthForm::Minimal,
612            resource: RESOURCE_MANAGER,
613        });
614        let actions = s.handle(Event::Readable(&r_data(1, &osr)));
615
616        // a SessionOpened notification surfaced...
617        assert!(actions.iter().any(|x| matches!(
618            x,
619            Action::Notify(Notification::SessionOpened {
620                resource
621            }) if *resource == RESOURCE_MANAGER
622        )));
623        // ...and an open_session_response was written back down (inside a TPDU).
624        let wrote_osr = actions.iter().any(|x| match x {
625            Action::Write(w) => w
626                .windows(1)
627                .any(|_| w.contains(&spdu_tags::OPEN_SESSION_RESPONSE)),
628            _ => false,
629        });
630        assert!(wrote_osr, "open_session_response must be sent down");
631
632        // and the session is tracked + a valid response decodes
633        let nb = (1u16..16).find(|&n| s.session.resource_of(n).is_some());
634        assert!(nb.is_some());
635    }
636
637    #[test]
638    fn tick_drives_poll_when_active() {
639        let mut s = CiStack::new();
640        s.handle(Event::Host(HostRequest::Init));
641        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
642        let a = s.handle(Event::Tick {
643            elapsed: DEFAULT_POLL_INTERVAL,
644        });
645        assert!(
646            a.iter()
647                .any(|x| matches!(x, Action::Write(w) if w.first() == Some(&tpdu_tags::DATA_LAST)))
648        );
649    }
650
651    // --- #334: the auto-descramble (query -> reply -> ok) sequence ---
652
653    /// Feed standalone `T_SB`s (data_available = 0) — the module acking each host
654    /// block — until the stack stops writing, collecting every action. This
655    /// drains the transport's one-block-per-turn outbound queue (#337).
656    fn pump_sbs(s: &mut CiStack) -> Vec<Action> {
657        let mut all = Vec::new();
658        for _ in 0..16 {
659            let a = s.handle(Event::Readable(&[
660                tpdu_tags::SB,
661                0x02,
662                0x01,
663                SbValue::new(false).0,
664            ]));
665            let wrote = a.iter().any(|x| matches!(x, Action::Write(_)));
666            all.extend(a);
667            if !wrote {
668                break;
669            }
670        }
671        all
672    }
673
674    /// Wrap an APDU for delivery on `session_nb` (session_number prefix), then as
675    /// a module→host R_TPDU.
676    fn r_apdu(session_nb: u16, apdu: &[u8]) -> Vec<u8> {
677        use dvb_ci::spdu::SessionNumber;
678        let mut spdu = ser(&SessionNumber {
679            length_form: dvb_ci::length::LengthForm::Minimal,
680            session_nb,
681        });
682        spdu.extend_from_slice(apdu);
683        r_data(1, &spdu)
684    }
685
686    /// Minimal PMT: program_info has one CA_descriptor (CAID 0x0B00) + a non-CA
687    /// descriptor; one clear ES. Mirrors the dvb-ci builder fixture.
688    fn build_pmt() -> Vec<u8> {
689        let prog_ca = [0x09u8, 0x04, 0x0B, 0x00, 0xE1, 0x00];
690        let reg = [0x05u8, 0x04, b'H', b'D', b'M', b'V'];
691        let mut program_info = Vec::new();
692        program_info.extend_from_slice(&prog_ca);
693        program_info.extend_from_slice(&reg);
694        let lang = [0x0Au8, 0x04, b'e', b'n', b'g', 0x00];
695
696        let mut body = Vec::new();
697        body.push(0x02); // table_id
698        body.push(0);
699        body.push(0); // section_length placeholder
700        body.extend_from_slice(&[0x00, 0x01]); // program_number 1
701        body.push(0xC3); // version 1, current_next 1
702        body.push(0x00);
703        body.push(0x00);
704        body.push(0xE0 | 0x02); // PCR_PID 0x0200
705        body.push(0x00);
706        let pil = program_info.len();
707        body.push(0xF0 | ((pil >> 8) as u8 & 0x0F));
708        body.push(pil as u8);
709        body.extend_from_slice(&program_info);
710        // one clear ES
711        body.push(0x03);
712        body.push(0xE0 | 0x02);
713        body.push(0x01);
714        body.push(0xF0 | ((lang.len() >> 8) as u8 & 0x0F));
715        body.push(lang.len() as u8);
716        body.extend_from_slice(&lang);
717
718        let section_length = body.len() - 3 + 4;
719        body[1] = 0xB0 | ((section_length >> 8) as u8 & 0x0F);
720        body[2] = section_length as u8;
721        let crc = broadcast_common::crc32_mpeg2::compute(&body);
722        body.extend_from_slice(&crc.to_be_bytes());
723        body
724    }
725
726    /// Drive the full handshake to open conditional-access + mmi sessions with
727    /// the CAM's CAIDs learned, following the real flow (#340): module opens RM →
728    /// host sends `profile_change` and `create_session`s the module-provided
729    /// resources → module accepts each with `create_session_response`.
730    fn stack_with_ca_session() -> CiStack {
731        use dvb_ci::objects::ca_info::CaInfo;
732        use dvb_ci::objects::resource_manager::Profile;
733        use dvb_ci::resource::{APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, MMI};
734        use dvb_ci::spdu::{CreateSessionResponse, OpenSessionRequest, SessionStatus};
735
736        let mut s = CiStack::new();
737        s.handle(Event::Host(HostRequest::Init));
738        s.handle(Event::Readable(&[tpdu_tags::C_T_C_REPLY, 0x01, 0x01]));
739        // module opens the host's resource_manager → RM session 1
740        s.handle(Event::Readable(&r_data(
741            1,
742            &ser(&OpenSessionRequest {
743                length_form: dvb_ci::length::LengthForm::Minimal,
744                resource: RESOURCE_MANAGER,
745            }),
746        )));
747        // module sends its profile → host: CamReady + profile_change +
748        // create_session for each module-provided resource (alloc nb 2,3,4).
749        s.handle(Event::Readable(&r_apdu(
750            1,
751            &ser(&Profile {
752                length_form: dvb_ci::length::LengthForm::Minimal,
753                resources: vec![APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, MMI],
754            }),
755        )));
756        pump_sbs(&mut s); // flush profile_change + the first create_session
757        // The module accepts each create_session → its session opens (+ on_open
758        // enq); each acceptance frees the link so the next create_session flushes.
759        for (nb, res) in [
760            (2u16, APPLICATION_INFORMATION),
761            (3, CONDITIONAL_ACCESS_SUPPORT),
762            (4, MMI),
763        ] {
764            s.handle(Event::Readable(&r_data(
765                1,
766                &ser(&CreateSessionResponse {
767                    length_form: dvb_ci::length::LengthForm::Minimal,
768                    status: SessionStatus::Ok,
769                    resource: res,
770                    session_nb: nb,
771                }),
772            )));
773            pump_sbs(&mut s);
774        }
775        // module advertises its CAIDs on the CA session
776        let ca_nb = s
777            .session
778            .sessions()
779            .into_iter()
780            .find(|&(_, r)| r == CONDITIONAL_ACCESS_SUPPORT)
781            .map(|(n, _)| n)
782            .expect("CA session open");
783        s.handle(Event::Readable(&r_apdu(
784            ca_nb,
785            &ser(&CaInfo {
786                length_form: dvb_ci::length::LengthForm::Minimal,
787                ca_system_ids: vec![0x0B00, 0x1800],
788            }),
789        )));
790        s
791    }
792
793    /// r10-W-20: a corrupt PMT on the raw `descramble` path must surface
794    /// as `Notification::Error` from the public `CiStack::handle` entry
795    /// point and send nothing — pre-fix `build_ca_pmt_bytes` reached
796    /// `CaPmtBuilt::to_bytes()`, so any serialization failure (dvb-si's
797    /// 12-bit reads clamp a *parseable* loop inside every ca_pmt field,
798    /// but a corrupted reassembly can still fail the re-parse/serialize
799    /// boundary) panicked the driver instead of reporting.
800    #[test]
801    fn descramble_of_a_corrupt_pmt_surfaces_an_error_not_a_panic() {
802        let mut s = stack_with_ca_session();
803        // Truncate a good PMT mid-ES-loop: `bytes_len < 3 +
804        // section_length` — the exact corrupt-reassembly shape.
805        let mut pmt = build_pmt();
806        pmt.truncate(pmt.len() - 8);
807        let actions = s.handle(Event::Host(HostRequest::Descramble(&pmt)));
808        assert!(
809            actions.iter().any(|a| matches!(
810                a,
811                Action::Notify(Notification::Error { detail })
812                    if detail.contains("invalid PMT")
813            )),
814            "expected an invalid-PMT Notification::Error, got {actions:?}"
815        );
816        assert!(
817            !actions.iter().any(|a| matches!(a, Action::Write(_))),
818            "a failed PMT must send nothing"
819        );
820    }
821
822    #[test]
823    fn descramble_sends_ok_descrambling_filtered() {
824        use dvb_ci::objects::ca_pmt::CaPmtCmdId;
825        use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
826        use dvb_ci::resource::CONDITIONAL_ACCESS_SUPPORT;
827
828        let mut s = stack_with_ca_session();
829        let ca_nb = s
830            .session
831            .sessions()
832            .into_iter()
833            .find(|&(_, r)| r == CONDITIONAL_ACCESS_SUPPORT)
834            .map(|(n, _)| n)
835            .unwrap();
836
837        // descramble() sends ca_pmt with cmd_id = ok_descrambling directly (no
838        // query first — a real CAM doesn't reply to a query; verified live).
839        let pmt = build_pmt();
840        let mut actions = s.handle(Event::Host(HostRequest::Descramble(&pmt)));
841        // Queued behind the in-flight link; the module's SB flushes it (one block
842        // per turn — #337).
843        actions.extend(pump_sbs(&mut s));
844        let c = first_ca_pmt(&actions).expect("ca_pmt sent");
845        assert_eq!(c.cmd_id, CaPmtCmdId::OkDescrambling);
846        // CA descriptors filtered to the CAM's advertised CAIDs.
847        assert_eq!(
848            c.program_ca_descriptors.as_slice(),
849            &[0x09, 0x04, 0x0B, 0x00, 0xE1, 0x00]
850        );
851
852        // The module's ca_pmt_reply is surfaced to the host (no follow-up SPDU).
853        let reply = s.handle(Event::Readable(&r_apdu(
854            ca_nb,
855            &ser(&CaPmtReply {
856                reserved_ca_enable: Default::default(),
857                reserved_version: Default::default(),
858                length_form: dvb_ci::length::LengthForm::Minimal,
859                program_number: 1,
860                version_number: 1,
861                current_next_indicator: true,
862                ca_enable: Some(CaEnable::Possible),
863                streams: vec![],
864            }),
865        )));
866        assert!(reply.iter().any(|a| matches!(
867            a,
868            Action::Notify(Notification::CaPmtReply {
869                descrambling_ok: true,
870                ..
871            })
872        )));
873    }
874
875    /// Whether any written frame carries the 3-byte APDU tag `want`.
876    fn wrote_apdu(actions: &[Action], want: [u8; 3]) -> bool {
877        actions
878            .iter()
879            .any(|a| matches!(a, Action::Write(w) if w.windows(3).any(|x| x == want)))
880    }
881
882    #[test]
883    fn mmi_menu_answer_sends_menu_answ() {
884        let mut s = stack_with_ca_session();
885        let mut acts = s.handle(Event::Host(HostRequest::MmiMenuAnswer(2)));
886        acts.extend(pump_sbs(&mut s));
887        // menu_answ APDU (9F 88 0B) reaches the wire.
888        assert!(wrote_apdu(&acts, [0x9F, 0x88, 0x0B]));
889    }
890
891    #[test]
892    fn mmi_enquiry_answer_sends_answ() {
893        let mut s = stack_with_ca_session();
894        let mut acts = s.handle(Event::Host(HostRequest::MmiEnquiryAnswer(b"1234")));
895        acts.extend(pump_sbs(&mut s));
896        // answ APDU (9F 88 08) reaches the wire.
897        assert!(wrote_apdu(&acts, [0x9F, 0x88, 0x08]));
898    }
899
900    /// Parse every `ca_pmt` (tag `9F 80 32`) found in the written frames,
901    /// returning each one's `cmd_id` + programme CA-descriptor bytes (owned).
902    fn all_ca_pmts(actions: &[Action]) -> Vec<CaPmtSummary> {
903        use broadcast_common::Parse;
904        use dvb_ci::objects::ca_pmt::CaPmt;
905        let tag = [0x9F, 0x80, 0x32];
906        let mut out = Vec::new();
907        for a in actions {
908            if let Action::Write(w) = a
909                && let Some(pos) = w.windows(3).position(|x| x == tag)
910                && let Ok(p) = CaPmt::parse(&w[pos..])
911            {
912                out.push(CaPmtSummary {
913                    list_management: p.list_management,
914                    cmd_id: p.cmd_id.expect("programme cmd_id present"),
915                    program_ca_descriptors: p.program_ca_descriptors.to_vec(),
916                });
917            }
918        }
919        out
920    }
921
922    /// The first `ca_pmt` in the written frames.
923    fn first_ca_pmt(actions: &[Action]) -> Option<CaPmtSummary> {
924        all_ca_pmts(actions).into_iter().next()
925    }
926
927    struct CaPmtSummary {
928        list_management: dvb_ci::objects::ca_pmt::CaPmtListManagement,
929        cmd_id: dvb_ci::objects::ca_pmt::CaPmtCmdId,
930        program_ca_descriptors: Vec<u8>,
931    }
932
933    #[test]
934    fn descramble_programs_emits_first_more_last() {
935        use dvb_ci::objects::ca_pmt::{CaPmtCmdId, CaPmtListManagement};
936
937        let mut s = stack_with_ca_session();
938        let pmt = build_pmt();
939        // Three programmes → first / more / last, all ok_descrambling.
940        let mut acts = s.handle(Event::Host(HostRequest::DescramblePrograms(&[
941            &pmt, &pmt, &pmt,
942        ])));
943        acts.extend(pump_sbs(&mut s));
944        let lms: Vec<_> = all_ca_pmts(&acts)
945            .iter()
946            .map(|c| c.list_management)
947            .collect();
948        assert_eq!(
949            lms,
950            vec![
951                CaPmtListManagement::First,
952                CaPmtListManagement::More,
953                CaPmtListManagement::Last,
954            ]
955        );
956        assert!(
957            all_ca_pmts(&acts)
958                .iter()
959                .all(|c| c.cmd_id == CaPmtCmdId::OkDescrambling)
960        );
961    }
962
963    #[test]
964    fn add_and_remove_program_use_add_update() {
965        use dvb_ci::objects::ca_pmt::{CaPmtCmdId, CaPmtListManagement};
966
967        let mut s = stack_with_ca_session();
968        let pmt = build_pmt();
969
970        let mut add = s.handle(Event::Host(HostRequest::AddProgram(&pmt)));
971        add.extend(pump_sbs(&mut s));
972        let a = first_ca_pmt(&add).expect("add ca_pmt");
973        assert_eq!(a.list_management, CaPmtListManagement::Add);
974        assert_eq!(a.cmd_id, CaPmtCmdId::OkDescrambling);
975
976        let mut rm = s.handle(Event::Host(HostRequest::RemoveProgram(&pmt)));
977        rm.extend(pump_sbs(&mut s));
978        let r = first_ca_pmt(&rm).expect("remove ca_pmt");
979        assert_eq!(r.list_management, CaPmtListManagement::Update);
980        assert_eq!(r.cmd_id, CaPmtCmdId::NotSelected);
981    }
982
983    /// A resource reached through several sessions must be ticked once per
984    /// tick, not once per session — otherwise a resource's own timer (the
985    /// `date_time` resend, say) runs N times as fast as it should (audit
986    /// a20-44). The session layer refuses the second session for one resource
987    /// through its open-request path, so the state is bound directly here.
988    #[test]
989    fn a_resource_is_ticked_once_however_many_sessions_reach_it() {
990        struct TickCounter(ResourceId);
991
992        impl Resource for TickCounter {
993            fn id(&self) -> ResourceId {
994                self.0
995            }
996            fn on_apdu(&mut self, _apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
997                Ok(ResourceOut::default())
998            }
999            fn tick(&mut self, _elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
1000                let mut out = ResourceOut::default();
1001                out.notify.push(Notification::CamReady);
1002                Ok(out)
1003            }
1004        }
1005
1006        let resource = ResourceId(0x0BAD_0001);
1007        let mut s = CiStack::new();
1008        s.register(Box::new(TickCounter(resource)));
1009        s.session.bind_for_test(10, resource);
1010        s.session.bind_for_test(11, resource);
1011
1012        let actions = s.handle(Event::Tick {
1013            elapsed: Duration::from_millis(10),
1014        });
1015        let ticks = actions
1016            .iter()
1017            .filter(|a| matches!(a, Action::Notify(Notification::CamReady)))
1018            .count();
1019        assert_eq!(
1020            ticks, 1,
1021            "the resource was ticked {ticks} times for two sessions"
1022        );
1023    }
1024}