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