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