Skip to main content

dvb_ci_runtime/
resource.rs

1//! The resource layer — application-layer state machines (ETSI EN 50221 §8),
2//! one per resource, driven by the session layer's APDUs.
3//!
4//! Each resource implements [`Resource`]: it reacts to its session opening and
5//! to incoming APDUs, producing APDUs to send back, host [`Notification`]s, and
6//! requests to open further (module-provided) resources. This module ships the
7//! mandatory [`ResourceManager`]; application_information / conditional_access /
8//! date_time / mmi land as further `Resource` impls.
9
10use std::time::Duration;
11
12use broadcast_common::{Parse, Serialize};
13use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationInfoEnq};
14use dvb_ci::objects::ca_info::{CaInfo, CaInfoEnq};
15use dvb_ci::objects::ca_pmt_reply::{CaEnable, CaPmtReply};
16use dvb_ci::objects::date_time::{DateTime as CiDateTime, DateTimeEnq, UTC_TIME_LEN};
17use dvb_ci::objects::host_control::{AskRelease, ClearReplace, Replace, Tune};
18use dvb_ci::objects::mmi_display::{
19    DisplayControl, DisplayControlCmd, DisplayReply, DisplayReplyBody, DisplayReplyId, MmiMode,
20};
21use dvb_ci::objects::mmi_high::{Enq, List, Menu};
22use dvb_ci::objects::resource_manager::{Profile, ProfileChange, ProfileEnq};
23use dvb_ci::resource::{
24    APPLICATION_INFORMATION, CONDITIONAL_ACCESS_SUPPORT, DATE_TIME, HOST_CONTROL, MMI,
25    RESOURCE_MANAGER, ResourceId,
26};
27use dvb_ci::tag::{self, ApduTag};
28
29use crate::event::{HostControlEvent, MmiEvent, MmiMenu, Notification};
30
31/// Decode MMI `text_char` bytes to a `String` (lossy; full EN 300 468 Annex A
32/// decoding is the application's concern).
33fn text(chars: &[u8]) -> String {
34    String::from_utf8_lossy(chars).into_owned()
35}
36
37/// Project a parsed high-level [`Menu`] (also the body of a `list()`) onto the
38/// host-facing [`MmiMenu`] — the three header lines and the choice list kept
39/// distinct for display.
40fn to_menu(m: &Menu<'_>) -> MmiMenu {
41    MmiMenu {
42        title: text(m.title.text_chars),
43        subtitle: text(m.subtitle.text_chars),
44        bottom: text(m.bottom.text_chars),
45        choices: m.choices.iter().map(|c| text(c.text_chars)).collect(),
46    }
47}
48
49/// Serialize an APDU/SPDU object to owned bytes — the one helper the resource,
50/// session and stack layers share (audit r10-O-12: it was copied three times).
51///
52/// r10-W-20: `serialize_into` failing here used to be swallowed into a
53/// silently-empty `Vec` (and, in a later pass, turned into a panic) — either
54/// way the failure never reached the caller as a value it could act on. These
55/// layers react to APDUs that ultimately originate from the CAM/card, so a
56/// serialize error must propagate as `Err`, not corrupt the wire exchange or
57/// crash the driver.
58pub(crate) fn ser<S: Serialize<Error = dvb_ci::Error>>(s: &S) -> dvb_ci::Result<Vec<u8>> {
59    s.try_to_bytes()
60}
61
62/// The 3-byte `apdu_tag` at the start of an APDU, if present.
63pub(crate) fn peek_tag(apdu: &[u8]) -> Option<ApduTag> {
64    (apdu.len() >= 3).then(|| ApduTag::from_bytes(apdu[0], apdu[1], apdu[2]))
65}
66
67/// What a resource wants done after reacting to an input.
68#[derive(Debug, Default, Clone, PartialEq, Eq)]
69pub struct ResourceOut {
70    /// APDUs to send on this resource's session.
71    pub apdus: Vec<Vec<u8>>,
72    /// Host-facing notifications.
73    pub notify: Vec<Notification>,
74    /// Module-provided resources the host should now open (`create_session`).
75    pub open: Vec<ResourceId>,
76}
77
78/// An EN 50221 application-layer resource.
79pub trait Resource {
80    /// The resource this handler serves.
81    fn id(&self) -> ResourceId;
82    /// The session for this resource just opened.
83    fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
84        Ok(ResourceOut::default())
85    }
86    /// An APDU arrived on this resource's session.
87    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut>;
88    /// Logical time advanced (for resources with timers, e.g. date_time).
89    fn tick(&mut self, _elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
90        Ok(ResourceOut::default())
91    }
92    /// Reset this resource's internal state (r10-W-19): called on
93    /// [`HostRequest::Init`](crate::event::HostRequest::Init) and
94    /// [`HostRequest::Shutdown`](crate::event::HostRequest::Shutdown) so a
95    /// re-inserted CAM starts a fresh handshake against clean state rather
96    /// than one latched by whatever the previous module left behind (e.g. a
97    /// `ready` flag that never re-opens the `profile_change` gate on a
98    /// second `profile` exchange). The default no-op is only correct for a
99    /// resource that carries no state between calls.
100    fn reset(&mut self) {}
101}
102
103/// Resource Manager (§8.4.1) — host-provided. Drives the profile exchange and,
104/// once complete, reports [`Notification::CamReady`] and asks the host to open
105/// the module-provided resources it understands.
106#[derive(Debug)]
107pub struct ResourceManager {
108    host_resources: Vec<ResourceId>,
109    module_resources: Vec<ResourceId>,
110    module_profiled: bool,
111    ready: bool,
112}
113
114impl ResourceManager {
115    /// New RM advertising `host_resources` in its profile reply.
116    #[must_use]
117    pub fn new(host_resources: Vec<ResourceId>) -> Self {
118        Self {
119            host_resources,
120            module_resources: Vec::new(),
121            module_profiled: false,
122            ready: false,
123        }
124    }
125
126    /// Resources the module advertised (valid once the profile exchange ran).
127    #[must_use]
128    pub fn module_resources(&self) -> &[ResourceId] {
129        &self.module_resources
130    }
131}
132
133impl Resource for ResourceManager {
134    fn id(&self) -> ResourceId {
135        RESOURCE_MANAGER
136    }
137
138    fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
139        // Kick off the handshake: ask the module for its profile.
140        Ok(ResourceOut {
141            apdus: vec![ser(&ProfileEnq::default())?],
142            ..ResourceOut::default()
143        })
144    }
145
146    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
147        if apdu.len() < APDU_TAG_LEN {
148            return Err(dvb_ci::Error::InvalidLength("short APDU"));
149        }
150        let mut out = ResourceOut::default();
151        match peek_tag(apdu) {
152            // Module asks for the host's profile → reply with our resource list.
153            Some(t) if t == tag::PROFILE_ENQ => {
154                out.apdus.push(ser(&Profile {
155                    length_form: dvb_ci::length::LengthForm::Minimal,
156                    resources: self.host_resources.clone(),
157                })?);
158            }
159            // Module's profile → record its resources.
160            Some(t) if t == tag::PROFILE => {
161                // A CAM-originated APDU that fails to parse is a protocol error to
162                // surface, not to drop silently (audit #1092 interop).
163                let p = Profile::parse(apdu)?;
164                self.module_resources = p.resources;
165                self.module_profiled = true;
166            }
167            // Resource set changed → re-enquire.
168            Some(t) if t == tag::PROFILE_CHANGE => {
169                out.apdus.push(ser(&ProfileEnq::default())?);
170                self.module_profiled = false;
171                self.ready = false;
172            }
173            _ => {}
174        }
175        // Once we have the module's profile, the host sends `profile_change`
176        // (§8.4.1.1) — the gate the module waits on; until it arrives the module
177        // idles after its `profile` reply (#340 round 1).
178        //
179        // The host does NOT open application_information / conditional_access /
180        // mmi itself. Confirmed on hardware (#340, live AlphaCrypt): the module
181        // ignores a host `open_session_request` for them and rejects a
182        // `create_session` (`status=0xF0`). Those resources are **host-provided**
183        // — the host advertises them in its `profile` reply (see
184        // `CiStack::host_provided`), and the *module* opens sessions to them
185        // (module → host `open_session_request`), exactly as it does for
186        // resource_manager / date_time. The host just accepts. Each session's
187        // `on_open` then drives its enquiry (app_info_enq, ca_info_enq).
188        if self.module_profiled && !self.ready {
189            self.ready = true;
190            out.apdus.push(ser(&ProfileChange::default())?);
191            out.notify.push(Notification::CamReady);
192        }
193        Ok(out)
194    }
195
196    /// r10-W-19: without this, `ready`/`module_profiled` stay latched from a
197    /// prior handshake, so a second `profile` (e.g. after a hot-plug
198    /// re-insert routed through a fresh `Init`) never re-opens the
199    /// `profile_change`/`CamReady` gate — the module then idles forever
200    /// (`on_apdu`'s doc comment above).
201    fn reset(&mut self) {
202        self.module_resources.clear();
203        self.module_profiled = false;
204        self.ready = false;
205    }
206}
207
208/// Application Information (§8.4.2) — module-provided. On open, enquires the
209/// module's application info; surfaces it as [`Notification::ApplicationInfo`].
210#[derive(Debug, Default)]
211pub struct ApplicationInformation;
212
213impl Resource for ApplicationInformation {
214    fn id(&self) -> ResourceId {
215        APPLICATION_INFORMATION
216    }
217
218    fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
219        Ok(ResourceOut {
220            apdus: vec![ser(&ApplicationInfoEnq::default())?],
221            ..ResourceOut::default()
222        })
223    }
224
225    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
226        if apdu.len() < APDU_TAG_LEN {
227            return Err(dvb_ci::Error::InvalidLength("short APDU"));
228        }
229        let mut out = ResourceOut::default();
230        if peek_tag(apdu) == Some(tag::APPLICATION_INFO) {
231            let ai = ApplicationInfo::parse(apdu)?;
232            out.notify.push(Notification::ApplicationInfo {
233                application_type: ai.application_type.to_u8(),
234                manufacturer: ai.application_manufacturer,
235                code: ai.manufacturer_code,
236                menu: String::from_utf8_lossy(ai.menu_string).into_owned(),
237            });
238        }
239        Ok(out)
240    }
241    // No state carried between calls — the default `reset()` no-op applies.
242}
243
244/// Conditional Access Support (§8.4.3) — module-provided. On open, enquires the
245/// module's supported `CA_system_id`s ([`Notification::CaInfo`]); decodes
246/// `ca_pmt_reply` ([`Notification::CaPmtReply`]). The host sends `ca_pmt` via
247/// [`HostRequest::SendCaPmt`](crate::event::HostRequest::SendCaPmt).
248#[derive(Debug, Default)]
249pub struct ConditionalAccess;
250
251impl Resource for ConditionalAccess {
252    fn id(&self) -> ResourceId {
253        CONDITIONAL_ACCESS_SUPPORT
254    }
255
256    fn on_open(&mut self) -> dvb_ci::Result<ResourceOut> {
257        Ok(ResourceOut {
258            apdus: vec![ser(&CaInfoEnq::default())?],
259            ..ResourceOut::default()
260        })
261    }
262
263    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
264        if apdu.len() < APDU_TAG_LEN {
265            return Err(dvb_ci::Error::InvalidLength("short APDU"));
266        }
267        let mut out = ResourceOut::default();
268        match peek_tag(apdu) {
269            Some(t) if t == tag::CA_INFO => {
270                // A CAM-originated APDU that fails to parse is a protocol error to
271                // surface, not to drop silently (audit #1092 interop).
272                let ci = CaInfo::parse(apdu)?;
273                out.notify.push(Notification::CaInfo {
274                    ca_system_ids: ci.ca_system_ids,
275                });
276            }
277            Some(t) if t == tag::CA_PMT_REPLY => {
278                // A CAM-originated APDU that fails to parse is a protocol error to
279                // surface, not to drop silently (audit #1092 interop).
280                let r = CaPmtReply::parse(apdu)?;
281                // EN 50221 §8.4.3.5 Table 26: programme-level `CA_enable`.
282                // Plumb the object's own `Option<CaEnable>` straight
283                // through — `None` means the programme
284                // `CA_enable_flag` bit was clear (no programme-level
285                // status given), which is distinct from a genuine
286                // flag-set reserved code and must not be collapsed to a
287                // sentinel.
288                let descrambling_ok = matches!(
289                    r.ca_enable,
290                    Some(
291                        CaEnable::Possible
292                            | CaEnable::PossiblePurchaseDialogue
293                            | CaEnable::PossibleTechnicalDialogue
294                    )
295                );
296                out.notify.push(Notification::CaPmtReply {
297                    program_number: r.program_number,
298                    ca_enable: r.ca_enable,
299                    descrambling_ok,
300                });
301            }
302            _ => {}
303        }
304        Ok(out)
305    }
306    // No state carried between calls — the default `reset()` no-op applies.
307}
308
309const SECS_PER_DAY: u64 = 86_400;
310/// Modified Julian Date of the Unix epoch (1970-01-01).
311const MJD_UNIX_EPOCH: u64 = 40_587;
312
313fn bcd(v: u64) -> u8 {
314    (((v / 10) << 4) | (v % 10)) as u8
315}
316
317/// Encode a Unix timestamp as the 5-byte DVB `UTC_time` (MJD `[15:0]` + BCD
318/// HH:MM:SS), per EN 300 468 Annex C. `None` outside the 16-bit MJD range
319/// (before 1858-11-17, or from MJD 65536 = 2141-09-10 on), which the wire
320/// format cannot express.
321fn unix_to_mjd_bcd(unix_secs: u64) -> Option<[u8; UTC_TIME_LEN]> {
322    let mjd = u16::try_from(MJD_UNIX_EPOCH + unix_secs / SECS_PER_DAY).ok()?;
323    let sod = unix_secs % SECS_PER_DAY;
324    Some([
325        (mjd >> 8) as u8,
326        mjd as u8,
327        bcd(sod / 3600),
328        bcd((sod % 3600) / 60),
329        bcd(sod % 60),
330    ])
331}
332
333/// The host clock as a 5-byte DVB `UTC_time`, or `None` when the clock reads
334/// an instant that field cannot represent (a pre-1970 clock, or one past
335/// 2141-09-09).
336fn system_utc() -> Option<[u8; UTC_TIME_LEN]> {
337    let now = std::time::SystemTime::now();
338    now.duration_since(std::time::UNIX_EPOCH)
339        .ok()
340        .and_then(|d| unix_to_mjd_bcd(d.as_secs()))
341}
342
343/// Date-Time (§8.5.2) — host-provided. On `date_time_enq` replies with the
344/// current UTC; if the enquiry's `response_interval` is non-zero, re-sends every
345/// `response_interval` seconds (driven by [`tick`](Resource::tick)).
346pub struct DateTime {
347    clock: fn() -> Option<[u8; UTC_TIME_LEN]>,
348    interval: u8,
349    since: Duration,
350}
351
352impl Default for DateTime {
353    fn default() -> Self {
354        Self::new()
355    }
356}
357
358impl DateTime {
359    /// New handler using the system clock.
360    #[must_use]
361    pub fn new() -> Self {
362        Self {
363            clock: system_utc,
364            interval: 0,
365            since: Duration::ZERO,
366        }
367    }
368
369    /// New handler with an injected clock (for tests / a host-supplied source).
370    ///
371    /// The clock yields `None` for an instant the 5-byte `UTC_time` field
372    /// cannot represent (a pre-1970 clock, or one past 2141-09-09).
373    #[must_use]
374    pub fn with_clock(clock: fn() -> Option<[u8; UTC_TIME_LEN]>) -> Self {
375        Self {
376            clock,
377            interval: 0,
378            since: Duration::ZERO,
379        }
380    }
381
382    fn reply(&self) -> Option<dvb_ci::Result<Vec<u8>>> {
383        let utc_time = (self.clock)()?;
384        Some(ser(&CiDateTime {
385            length_form: dvb_ci::length::LengthForm::Minimal,
386            utc_time,
387            local_offset: None,
388        }))
389    }
390}
391
392impl Resource for DateTime {
393    fn id(&self) -> ResourceId {
394        DATE_TIME
395    }
396
397    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
398        if apdu.len() < APDU_TAG_LEN {
399            return Err(dvb_ci::Error::InvalidLength("short APDU"));
400        }
401        let mut out = ResourceOut::default();
402        if peek_tag(apdu) == Some(tag::DATE_TIME_ENQ) {
403            let enq = DateTimeEnq::parse(apdu)?;
404            self.interval = enq.response_interval;
405            self.since = Duration::ZERO;
406            match self.reply() {
407                Some(reply) => out.apdus.push(reply?),
408                None => out.notify.push(Notification::ClockUnrepresentable),
409            }
410        }
411        Ok(out)
412    }
413
414    fn tick(&mut self, elapsed: Duration) -> dvb_ci::Result<ResourceOut> {
415        let mut out = ResourceOut::default();
416        if self.interval > 0 {
417            self.since += elapsed;
418            if self.since >= Duration::from_secs(u64::from(self.interval)) {
419                self.since = Duration::ZERO;
420                match self.reply() {
421                    Some(reply) => out.apdus.push(reply?),
422                    None => out.notify.push(Notification::ClockUnrepresentable),
423                }
424            }
425        }
426        Ok(out)
427    }
428
429    /// r10-W-19: without this, a stale `interval`/`since` from a previous
430    /// module survives into the next connection, so the resend cadence
431    /// negotiated with the OLD CAM keeps firing (or a leftover partial
432    /// `since` fires early) before the new module ever sends its own
433    /// `date_time_enq`.
434    fn reset(&mut self) {
435        self.interval = 0;
436        self.since = Duration::ZERO;
437    }
438}
439
440/// MMI (§8.6) — module-provided. Surfaces the module's menus/enquiries and the
441/// close as [`Notification::Mmi`] events for the application to display, and
442/// answers the module's `display_control` mode negotiation. The host drives the
443/// dialog back through [`Driver::mmi_menu_answer`](crate::Driver::mmi_menu_answer)
444/// / [`mmi_enquiry_answer`](crate::Driver::mmi_enquiry_answer) /
445/// [`mmi_cancel`](crate::Driver::mmi_cancel) (sent by [`CiStack`](crate::CiStack)
446/// on the open MMI session).
447#[derive(Debug, Default)]
448pub struct Mmi {
449    chain: Option<MmiChain>,
450}
451
452/// Cap on a chained `menu`/`list` body (EN 50221 §8.3.2); a module that never
453/// sends the `_last` block cannot grow host memory past this.
454pub const MAX_MMI_CHAIN_LEN: usize = 0xFFFF;
455
456const APDU_TAG_LEN: usize = 3;
457
458#[derive(Debug)]
459struct MmiChain {
460    last: ApduTag,
461    body: Vec<u8>,
462}
463
464impl Mmi {
465    fn chain_more(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<()> {
466        let tail = apdu
467            .get(APDU_TAG_LEN..)
468            .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
469        let (len, hdr) = dvb_ci::length::decode(tail)?;
470        let start = APDU_TAG_LEN + hdr;
471        let data = apdu
472            .get(start..start + len)
473            .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
474        let mut chain = match self.chain.take() {
475            Some(c) if c.last == last => c,
476            _ => MmiChain {
477                last,
478                body: Vec::new(),
479            },
480        };
481        if chain.body.len() + data.len() > MAX_MMI_CHAIN_LEN {
482            return Err(dvb_ci::Error::LengthTooLarge(chain.body.len() + data.len()));
483        }
484        chain.body.extend_from_slice(data);
485        self.chain = Some(chain);
486        Ok(())
487    }
488
489    /// The complete `_last` APDU, with any chained `_more` bodies prepended to
490    /// its data field (EN 50221 §8.3.2: the receiver concatenates the data
491    /// fields once the last block arrives).
492    fn complete(&mut self, apdu: &[u8], last: ApduTag) -> dvb_ci::Result<Vec<u8>> {
493        let Some(chain) = self.chain.take().filter(|c| c.last == last) else {
494            return Ok(apdu.to_vec());
495        };
496        let tail = apdu
497            .get(APDU_TAG_LEN..)
498            .ok_or(dvb_ci::Error::InvalidLength("short APDU"))?;
499        let (len, hdr) = dvb_ci::length::decode(tail)?;
500        let start = APDU_TAG_LEN + hdr;
501        let data = apdu
502            .get(start..start + len)
503            .ok_or(dvb_ci::Error::LengthTooLarge(len))?;
504        let total = chain.body.len() + data.len();
505        let mut buf = vec![0u8; APDU_TAG_LEN + dvb_ci::length::encoded_len(total) + total];
506        buf[..APDU_TAG_LEN].copy_from_slice(&last.to_bytes());
507        let n = dvb_ci::length::encode_into(total, &mut buf[APDU_TAG_LEN..])?;
508        let body_at = APDU_TAG_LEN + n;
509        buf[body_at..body_at + chain.body.len()].copy_from_slice(&chain.body);
510        buf[body_at + chain.body.len()..].copy_from_slice(data);
511        Ok(buf)
512    }
513}
514
515impl Resource for Mmi {
516    fn id(&self) -> ResourceId {
517        MMI
518    }
519
520    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
521        if apdu.len() < APDU_TAG_LEN {
522            return Err(dvb_ci::Error::InvalidLength("short APDU"));
523        }
524        let mut out = ResourceOut::default();
525        match peek_tag(apdu) {
526            Some(t) if t == tag::ENQ => {
527                // A CAM-originated APDU that fails to parse is a protocol error to
528                // surface, not to drop silently (audit #1092 interop).
529                let e = Enq::parse(apdu)?;
530                out.notify.push(Notification::Mmi(MmiEvent::Enquiry {
531                    prompt: text(e.text_chars),
532                    blind: e.blind_answer,
533                    answer_len: e.answer_text_length,
534                }));
535            }
536            Some(t) if t == tag::MENU_MORE => self.chain_more(apdu, tag::MENU_LAST)?,
537            Some(t) if t == tag::LIST_MORE => self.chain_more(apdu, tag::LIST_LAST)?,
538            Some(t) if t == tag::MENU_LAST => {
539                // A CAM-originated APDU that fails to parse is a protocol error to
540                // surface, not to drop silently (audit #1092 interop).
541                let full = self.complete(apdu, tag::MENU_LAST)?;
542                let m = Menu::parse(&full)?;
543                out.notify
544                    .push(Notification::Mmi(MmiEvent::Menu(to_menu(&m))));
545            }
546            Some(t) if t == tag::LIST_LAST => {
547                // A CAM-originated APDU that fails to parse is a protocol error to
548                // surface, not to drop silently (audit #1092 interop).
549                let full = self.complete(apdu, tag::LIST_LAST)?;
550                let l = List::parse(&full)?;
551                out.notify
552                    .push(Notification::Mmi(MmiEvent::List(to_menu(&l.0))));
553            }
554            Some(t) if t == tag::CLOSE_MMI => {
555                dvb_ci::objects::mmi_close::CloseMmi::parse(apdu)?;
556                out.notify.push(Notification::Mmi(MmiEvent::Close));
557            }
558            // High-level MMI mode negotiation (§8.6.1): the module opens an MMI
559            // session and sends `display_control`. The host MUST answer
560            // `display_reply` or the module aborts the MMI — verified live: a
561            // real AlphaCrypt opens MMI after `ca_pmt` and, with no reply, closes
562            // the session and never descrambles (an Enigma2 box answers it).
563            Some(t) if t == tag::DISPLAY_CONTROL => {
564                // A CAM-originated APDU that fails to parse is a protocol error to
565                // surface, not to drop silently (audit #1092 interop).
566                let dc = DisplayControl::parse(apdu)?;
567                let reply = match dc.cmd {
568                    // Acknowledge the requested MMI mode (echo it back).
569                    DisplayControlCmd::SetMmiMode => DisplayReply {
570                        length_form: dvb_ci::length::LengthForm::Minimal,
571                        reply_id: DisplayReplyId::MmiModeAck,
572                        body: DisplayReplyBody::MmiModeAck(
573                            dc.mmi_mode.unwrap_or(MmiMode::HighLevel),
574                        ),
575                    },
576                    // We don't implement the character-table / graphics
577                    // queries; tell the module so per Table 35.
578                    _ => DisplayReply {
579                        length_form: dvb_ci::length::LengthForm::Minimal,
580                        reply_id: DisplayReplyId::UnknownDisplayControlCmd,
581                        body: DisplayReplyBody::None,
582                    },
583                };
584                out.apdus.push(ser(&reply)?);
585            }
586            _ => {}
587        }
588        Ok(out)
589    }
590    fn reset(&mut self) {
591        self.chain = None;
592    }
593}
594
595/// Host Control (§8.5.1) — host-provided. The module opens a host_control
596/// session and issues `tune` / `replace` / `clear_replace` / `ask_release`
597/// objects; this handler decodes each and surfaces it as
598/// [`Notification::HostControl`]. The host acts on the request out of band (it
599/// retunes / replaces PIDs itself) — the runtime does not re-tune, so there is
600/// no reply APDU.
601#[derive(Debug, Default)]
602pub struct HostControl;
603
604impl Resource for HostControl {
605    fn id(&self) -> ResourceId {
606        HOST_CONTROL
607    }
608
609    fn on_apdu(&mut self, apdu: &[u8]) -> dvb_ci::Result<ResourceOut> {
610        if apdu.len() < APDU_TAG_LEN {
611            return Err(dvb_ci::Error::InvalidLength("short APDU"));
612        }
613        let mut out = ResourceOut::default();
614        // A CAM-originated host-control APDU that fails to parse (e.g. a padded
615        // `tune`) is a protocol error: `?` surfaces it as `Notification::Error`
616        // through the stack instead of dropping it silently.
617        let event = match peek_tag(apdu) {
618            Some(t) if t == tag::TUNE => {
619                let t = Tune::parse(apdu)?;
620                Some(HostControlEvent::Tune {
621                    network_id: t.network_id,
622                    original_network_id: t.original_network_id,
623                    transport_stream_id: t.transport_stream_id,
624                    service_id: t.service_id,
625                })
626            }
627            Some(t) if t == tag::REPLACE => {
628                let r = Replace::parse(apdu)?;
629                Some(HostControlEvent::Replace {
630                    replacement_ref: r.replacement_ref,
631                    replaced_pid: r.replaced_pid,
632                    replacement_pid: r.replacement_pid,
633                })
634            }
635            Some(t) if t == tag::CLEAR_REPLACE => {
636                let c = ClearReplace::parse(apdu)?;
637                Some(HostControlEvent::ClearReplace {
638                    replacement_ref: c.replacement_ref,
639                })
640            }
641            Some(t) if t == tag::ASK_RELEASE => {
642                AskRelease::parse(apdu)?;
643                Some(HostControlEvent::AskRelease)
644            }
645            _ => None,
646        };
647        if let Some(event) = event {
648            out.notify.push(Notification::HostControl(event));
649        }
650        Ok(out)
651    }
652    // No state carried between calls — the default `reset()` no-op applies.
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658    use dvb_ci::objects::resource_manager::Profile;
659    use mpeg_ts::pid::Pid;
660
661    /// Local test helper: unwrap a serialize that must succeed for the
662    /// fixed/bounded values these tests construct.
663    fn s<S: Serialize<Error = dvb_ci::Error>>(v: &S) -> Vec<u8> {
664        ser(v).expect("test value must serialize")
665    }
666
667    #[test]
668    fn on_open_sends_profile_enq() {
669        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
670        let out = rm.on_open().unwrap();
671        assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
672    }
673
674    #[test]
675    fn module_profile_triggers_profile_change_and_camready() {
676        // #340: after the module's `profile`, the host fires CamReady and sends
677        // `profile_change` (the §8.4.1.1 gate) — and nothing else. It does NOT
678        // open application_information / conditional_access / mmi itself: those
679        // are host-provided resources the module opens sessions to (verified on
680        // a live AlphaCrypt, which rejects/ignores host-initiated opens).
681        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
682        rm.on_open().unwrap();
683        let empty_profile = s(&Profile {
684            length_form: dvb_ci::length::LengthForm::Minimal,
685            resources: vec![],
686        });
687        let o = rm.on_apdu(&empty_profile).unwrap();
688        assert!(o.notify.contains(&Notification::CamReady));
689        assert_eq!(o.apdus.len(), 1, "host sends profile_change");
690        assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE_CHANGE));
691        assert!(o.open.is_empty(), "host opens no sessions itself");
692    }
693
694    #[test]
695    fn answers_a_module_profile_enquiry_without_re_readying() {
696        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
697        rm.on_open().unwrap();
698        rm.on_apdu(&s(&Profile {
699            length_form: dvb_ci::length::LengthForm::Minimal,
700            resources: vec![APPLICATION_INFORMATION],
701        }))
702        .unwrap();
703        // A later module profile_enq → reply with our profile, no second CamReady.
704        let o = rm.on_apdu(&s(&ProfileEnq::default())).unwrap();
705        assert_eq!(o.apdus.len(), 1);
706        assert_eq!(peek_tag(&o.apdus[0]), Some(tag::PROFILE));
707        assert!(!o.notify.contains(&Notification::CamReady));
708    }
709
710    /// r10-W-19: `reset()` must clear every piece of the RM's latched state
711    /// (module resources, `module_profiled`, `ready`) so a fresh handshake
712    /// after a re-init behaves exactly like a brand-new `ResourceManager` —
713    /// in particular so `ready` does not stay latched and silently suppress
714    /// the next `CamReady`.
715    #[test]
716    fn resource_manager_reset_clears_latched_handshake_state() {
717        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
718        rm.on_open().unwrap();
719        let o = rm
720            .on_apdu(&s(&Profile {
721                length_form: dvb_ci::length::LengthForm::Minimal,
722                resources: vec![APPLICATION_INFORMATION],
723            }))
724            .unwrap();
725        assert!(o.notify.contains(&Notification::CamReady), "dirtied: ready");
726        assert!(
727            !rm.module_resources().is_empty(),
728            "dirtied: module_resources"
729        );
730
731        rm.reset();
732        assert!(
733            rm.module_resources().is_empty(),
734            "reset must clear module_resources"
735        );
736
737        // Pre-fix (no reset()), `ready` stayed latched `true` and this second
738        // profile exchange would NOT re-fire CamReady.
739        rm.on_open().unwrap();
740        let o2 = rm
741            .on_apdu(&s(&Profile {
742                length_form: dvb_ci::length::LengthForm::Minimal,
743                resources: vec![],
744            }))
745            .unwrap();
746        assert!(
747            o2.notify.contains(&Notification::CamReady),
748            "a fresh handshake after reset() must fire CamReady again"
749        );
750    }
751
752    #[test]
753    fn mmi_surfaces_enquiry_and_close() {
754        let mut h = Mmi::default();
755        // enquiry
756        let enq = s(&Enq {
757            reserved: Default::default(),
758            length_form: dvb_ci::length::LengthForm::Minimal,
759            blind_answer: true,
760            answer_text_length: 4,
761            text_chars: b"PIN?",
762        });
763        assert_eq!(
764            h.on_apdu(&enq).unwrap().notify,
765            vec![Notification::Mmi(MmiEvent::Enquiry {
766                prompt: "PIN?".to_string(),
767                blind: true,
768                answer_len: 4,
769            })]
770        );
771        // close_mmi (tag 9F 88 00) — surfaced as Close
772        let close = [0x9F, 0x88, 0x00, 0x01, 0x00];
773        assert_eq!(
774            h.on_apdu(&close).unwrap().notify,
775            vec![Notification::Mmi(MmiEvent::Close)]
776        );
777    }
778
779    #[test]
780    fn mmi_surfaces_structured_menu_and_list() {
781        use dvb_ci::objects::mmi_high::{List, Menu, Text};
782        let txt = |s: &'static [u8]| Text {
783            length_form: dvb_ci::length::LengthForm::Minimal,
784            more: false,
785            text_chars: s,
786        };
787        let mut h = Mmi::default();
788        // A `menu()` → MmiEvent::Menu with header lines and choices kept distinct.
789        let menu = s(&Menu {
790            length_form: dvb_ci::length::LengthForm::Minimal,
791            more: false,
792            choice_nb: 2,
793            title: txt(b"AlphaCrypt"),
794            subtitle: txt(b"Module Mainmenu"),
795            bottom: txt(b"Select item and press OK"),
796            choices: vec![txt(b"Smartcard"), txt(b"Quit")],
797        });
798        assert_eq!(
799            h.on_apdu(&menu).unwrap().notify,
800            vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
801                title: "AlphaCrypt".to_string(),
802                subtitle: "Module Mainmenu".to_string(),
803                bottom: "Select item and press OK".to_string(),
804                choices: vec!["Smartcard".to_string(), "Quit".to_string()],
805            }))]
806        );
807        // A `list()` (same body) → MmiEvent::List.
808        let list = s(&List(Menu {
809            length_form: dvb_ci::length::LengthForm::Minimal,
810            more: false,
811            choice_nb: 0xFF,
812            title: txt(b"Entitlements"),
813            subtitle: txt(b""),
814            bottom: txt(b""),
815            choices: vec![txt(b"ORF AUT")],
816        }));
817        assert_eq!(
818            h.on_apdu(&list).unwrap().notify,
819            vec![Notification::Mmi(MmiEvent::List(MmiMenu {
820                title: "Entitlements".to_string(),
821                subtitle: String::new(),
822                bottom: String::new(),
823                choices: vec!["ORF AUT".to_string()],
824            }))]
825        );
826    }
827
828    fn chained(more: ApduTag, last: ApduTag, whole_last_apdu: &[u8], split: usize) -> [Vec<u8>; 2] {
829        let (len, hdr) = dvb_ci::length::decode(&whole_last_apdu[3..]).unwrap();
830        let body = &whole_last_apdu[3 + hdr..3 + hdr + len];
831        let part = |t: ApduTag, b: &[u8]| {
832            let mut v = t.to_bytes().to_vec();
833            let mut l = [0u8; 3];
834            let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
835            v.extend_from_slice(&l[..n]);
836            v.extend_from_slice(b);
837            v
838        };
839        [part(more, &body[..split]), part(last, &body[split..])]
840    }
841
842    #[test]
843    fn mmi_reassembles_a_menu_chained_over_menu_more_and_menu_last() {
844        use dvb_ci::objects::mmi_high::{Menu, Text};
845        let txt = |s: &'static [u8]| Text {
846            length_form: dvb_ci::length::LengthForm::Minimal,
847            more: false,
848            text_chars: s,
849        };
850        let whole = s(&Menu {
851            length_form: dvb_ci::length::LengthForm::Minimal,
852            more: false,
853            choice_nb: 2,
854            title: txt(b"AlphaCrypt"),
855            subtitle: txt(b"Module Mainmenu"),
856            bottom: txt(b"Select item and press OK"),
857            choices: vec![txt(b"Smartcard"), txt(b"Quit")],
858        });
859        let [first, second] = chained(tag::MENU_MORE, tag::MENU_LAST, &whole, 20);
860        let mut h = Mmi::default();
861        assert!(h.on_apdu(&first).unwrap().notify.is_empty());
862        assert_eq!(
863            h.on_apdu(&second).unwrap().notify,
864            vec![Notification::Mmi(MmiEvent::Menu(MmiMenu {
865                title: "AlphaCrypt".to_string(),
866                subtitle: "Module Mainmenu".to_string(),
867                bottom: "Select item and press OK".to_string(),
868                choices: vec!["Smartcard".to_string(), "Quit".to_string()],
869            }))]
870        );
871    }
872
873    #[test]
874    fn mmi_reassembles_a_list_chained_over_list_more_and_list_last() {
875        use dvb_ci::objects::mmi_high::{List, Menu, Text};
876        let txt = |s: &'static [u8]| Text {
877            length_form: dvb_ci::length::LengthForm::Minimal,
878            more: false,
879            text_chars: s,
880        };
881        let whole = s(&List(Menu {
882            length_form: dvb_ci::length::LengthForm::Minimal,
883            more: false,
884            choice_nb: 2,
885            title: txt(b"Entitlements"),
886            subtitle: txt(b""),
887            bottom: txt(b""),
888            choices: vec![txt(b"ORF AUT"), txt(b"ZDF")],
889        }));
890        let [first, second] = chained(tag::LIST_MORE, tag::LIST_LAST, &whole, 9);
891        let mut h = Mmi::default();
892        assert!(h.on_apdu(&first).unwrap().notify.is_empty());
893        assert_eq!(
894            h.on_apdu(&second).unwrap().notify,
895            vec![Notification::Mmi(MmiEvent::List(MmiMenu {
896                title: "Entitlements".to_string(),
897                subtitle: String::new(),
898                bottom: String::new(),
899                choices: vec!["ORF AUT".to_string(), "ZDF".to_string()],
900            }))]
901        );
902    }
903
904    /// A module that keeps sending `menu_more` blocks past the chain cap must
905    /// be refused with the typed length error, not accumulate host memory
906    /// without bound (audit a20-55).
907    #[test]
908    fn mmi_chain_past_the_cap_is_refused_with_length_too_large() {
909        fn menu_more(data_len: usize) -> Vec<u8> {
910            let mut apdu = tag::MENU_MORE.to_bytes().to_vec();
911            let mut len = [0u8; 3];
912            let coded = dvb_ci::length::encode_into(data_len, &mut len).unwrap();
913            apdu.extend_from_slice(&len[..coded]);
914            apdu.extend(std::iter::repeat_n(0x00, data_len));
915            apdu
916        }
917
918        let mut h = Mmi::default();
919        assert!(
920            h.on_apdu(&menu_more(MAX_MMI_CHAIN_LEN))
921                .unwrap()
922                .notify
923                .is_empty(),
924            "a chain exactly at the cap is still accepted"
925        );
926        let err = h
927            .on_apdu(&menu_more(1))
928            .expect_err("one byte past the chain cap must be refused");
929        assert_eq!(err, dvb_ci::Error::LengthTooLarge(MAX_MMI_CHAIN_LEN + 1));
930    }
931
932    #[test]
933    fn mmi_discards_a_partial_chain_on_reset() {
934        let mut h = Mmi::default();
935        let first = [0x9F, 0x88, 0x0A, 0x01, 0x02];
936        assert!(h.on_apdu(&first).unwrap().notify.is_empty());
937        h.reset();
938        assert!(h.chain.is_none());
939    }
940
941    /// Chains belong to the `_last` tag their `_more` blocks anticipate: an
942    /// abandoned `menu_more` must not be prepended to an interleaved `list`.
943    #[test]
944    fn mmi_keeps_interleaved_chains_apart() {
945        use dvb_ci::objects::mmi_high::{List, Menu, Text};
946        let txt = |s: &'static [u8]| Text {
947            length_form: dvb_ci::length::LengthForm::Minimal,
948            more: false,
949            text_chars: s,
950        };
951        let part = |t: ApduTag, b: &[u8]| {
952            let mut v = t.to_bytes().to_vec();
953            let mut l = [0u8; 3];
954            let n = dvb_ci::length::encode_into(b.len(), &mut l).unwrap();
955            v.extend_from_slice(&l[..n]);
956            v.extend_from_slice(b);
957            v
958        };
959        let whole = s(&List(Menu {
960            length_form: dvb_ci::length::LengthForm::Minimal,
961            more: false,
962            choice_nb: 1,
963            title: txt(b"Entitlements"),
964            subtitle: txt(b""),
965            bottom: txt(b""),
966            choices: vec![txt(b"ORF AUT")],
967        }));
968        let (len, hdr) = dvb_ci::length::decode(&whole[3..]).unwrap();
969        let body = &whole[3 + hdr..3 + hdr + len];
970
971        let mut h = Mmi::default();
972        // A menu chunk that never gets its menu_last …
973        assert!(
974            h.on_apdu(&part(tag::MENU_MORE, &[0xFF, 0xFF]))
975                .unwrap()
976                .notify
977                .is_empty()
978        );
979        // … then a complete list body, then the list_last.
980        assert!(
981            h.on_apdu(&part(tag::LIST_MORE, body))
982                .unwrap()
983                .notify
984                .is_empty()
985        );
986        assert_eq!(
987            h.on_apdu(&part(tag::LIST_LAST, &[])).unwrap().notify,
988            vec![Notification::Mmi(MmiEvent::List(MmiMenu {
989                title: "Entitlements".to_string(),
990                subtitle: String::new(),
991                bottom: String::new(),
992                choices: vec!["ORF AUT".to_string()],
993            }))],
994            "the abandoned menu chunk must not be part of the list body"
995        );
996        assert!(h.chain.is_none());
997    }
998
999    #[test]
1000    fn mmi_answers_display_control_set_mmi_mode() {
1001        use dvb_ci::objects::mmi_display::{DisplayControl, DisplayControlCmd, MmiMode};
1002        let mut h = Mmi::default();
1003        let dc = s(&DisplayControl {
1004            length_form: dvb_ci::length::LengthForm::Minimal,
1005            cmd: DisplayControlCmd::SetMmiMode,
1006            mmi_mode: Some(MmiMode::HighLevel),
1007        });
1008        let out = h.on_apdu(&dc).unwrap();
1009        // mmi_mode_ack(high_level): 9F 88 02 02 01 01.
1010        assert_eq!(out.apdus, vec![vec![0x9F, 0x88, 0x02, 0x02, 0x01, 0x01]]);
1011        assert!(out.notify.is_empty());
1012    }
1013
1014    #[test]
1015    fn profile_change_re_enquires() {
1016        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
1017        let out = rm
1018            .on_apdu(&s(
1019                &dvb_ci::objects::resource_manager::ProfileChange::default(),
1020            ))
1021            .unwrap();
1022        assert_eq!(out.apdus, vec![s(&ProfileEnq::default())]);
1023    }
1024
1025    /// An APDU for some other resource must not be mistaken for a
1026    /// `profile_change`: that would re-enquire and clear the latched handshake,
1027    /// firing a second `CamReady` for a module that already completed it.
1028    #[test]
1029    fn resource_manager_does_not_treat_an_unrelated_apdu_as_profile_change() {
1030        use dvb_ci::objects::application_info::{ApplicationInfo, ApplicationType};
1031
1032        let mut rm = ResourceManager::new(vec![RESOURCE_MANAGER]);
1033        rm.on_open().unwrap();
1034        rm.on_apdu(&s(&Profile {
1035            length_form: dvb_ci::length::LengthForm::Minimal,
1036            resources: vec![APPLICATION_INFORMATION],
1037        }))
1038        .unwrap();
1039
1040        let unrelated = s(&ApplicationInfo {
1041            length_form: dvb_ci::length::LengthForm::Minimal,
1042            application_type: ApplicationType::ConditionalAccess,
1043            application_manufacturer: 0x1234,
1044            manufacturer_code: 0x5678,
1045            menu_string: b"Acme CAM",
1046        });
1047        assert_eq!(rm.on_apdu(&unrelated).unwrap(), ResourceOut::default());
1048        assert_eq!(rm.module_resources(), &[APPLICATION_INFORMATION]);
1049
1050        // The handshake is still complete: a further profile does not re-ready.
1051        let again = rm
1052            .on_apdu(&s(&Profile {
1053                length_form: dvb_ci::length::LengthForm::Minimal,
1054                resources: vec![],
1055            }))
1056            .unwrap();
1057        assert!(
1058            !again.notify.contains(&Notification::CamReady),
1059            "an unrelated APDU must not clear the ready/profile latch"
1060        );
1061    }
1062
1063    /// An unrelated APDU must not be parsed as a `ca_pmt_reply` (which would
1064    /// surface a spurious protocol error for a perfectly good frame).
1065    #[test]
1066    fn conditional_access_ignores_an_unrelated_apdu() {
1067        let mut h = ConditionalAccess;
1068        let profile = s(&Profile {
1069            length_form: dvb_ci::length::LengthForm::Minimal,
1070            resources: vec![],
1071        });
1072        assert_eq!(h.on_apdu(&profile).unwrap(), ResourceOut::default());
1073    }
1074
1075    /// An unrelated APDU must not be parsed as a `display_control` (that would
1076    /// answer the module with a nonsense `display_reply`).
1077    #[test]
1078    fn mmi_ignores_an_unrelated_apdu() {
1079        let mut h = Mmi::default();
1080        assert_eq!(
1081            h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1082            ResourceOut::default()
1083        );
1084        assert!(h.chain.is_none());
1085    }
1086
1087    /// An unrelated APDU must not be decoded as an `ask_release` event.
1088    #[test]
1089    fn host_control_ignores_an_unrelated_apdu() {
1090        let mut h = HostControl;
1091        assert_eq!(
1092            h.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1093            ResourceOut::default()
1094        );
1095    }
1096
1097    #[test]
1098    fn application_information_surfaces_notification() {
1099        use dvb_ci::objects::application_info::ApplicationType;
1100        let mut h = ApplicationInformation;
1101        assert_eq!(
1102            h.on_open().unwrap().apdus,
1103            vec![s(&ApplicationInfoEnq::default())]
1104        );
1105        let ai = s(&ApplicationInfo {
1106            length_form: dvb_ci::length::LengthForm::Minimal,
1107            application_type: ApplicationType::ConditionalAccess,
1108            application_manufacturer: 0x1234,
1109            manufacturer_code: 0x5678,
1110            menu_string: b"Acme CAM",
1111        });
1112        let out = h.on_apdu(&ai).unwrap();
1113        assert_eq!(
1114            out.notify,
1115            vec![Notification::ApplicationInfo {
1116                application_type: 0x01,
1117                manufacturer: 0x1234,
1118                code: 0x5678,
1119                menu: "Acme CAM".to_string(),
1120            }]
1121        );
1122    }
1123
1124    #[test]
1125    fn host_control_surfaces_tune_replace_clear_and_ask_release() {
1126        let mut h = HostControl;
1127        assert_eq!(h.id(), HOST_CONTROL);
1128
1129        // tune() → HostControlEvent::Tune with the four 16-bit identifiers.
1130        let tune = s(&Tune {
1131            length_form: dvb_ci::length::LengthForm::Minimal,
1132            network_id: 0x1122,
1133            original_network_id: 0x3344,
1134            transport_stream_id: 0x5566,
1135            service_id: 0x7788,
1136        });
1137        assert_eq!(
1138            h.on_apdu(&tune).unwrap().notify,
1139            vec![Notification::HostControl(HostControlEvent::Tune {
1140                network_id: 0x1122,
1141                original_network_id: 0x3344,
1142                transport_stream_id: 0x5566,
1143                service_id: 0x7788,
1144            })]
1145        );
1146
1147        // replace() → HostControlEvent::Replace with the 13-bit PIDs decoded.
1148        let replace = s(&Replace {
1149            length_form: dvb_ci::length::LengthForm::Minimal,
1150            replacement_ref: 0x07,
1151            replaced_pid: Pid::from_const(0x0123),
1152            replacement_pid: Pid::from_const(0x01FF),
1153            replaced_reserved: Default::default(),
1154            replacement_reserved: Default::default(),
1155        });
1156        assert_eq!(
1157            h.on_apdu(&replace).unwrap().notify,
1158            vec![Notification::HostControl(HostControlEvent::Replace {
1159                replacement_ref: 0x07,
1160                replaced_pid: Pid::from_const(0x0123),
1161                replacement_pid: Pid::from_const(0x01FF),
1162            })]
1163        );
1164
1165        // clear_replace() → HostControlEvent::ClearReplace.
1166        let clear = s(&ClearReplace {
1167            length_form: dvb_ci::length::LengthForm::Minimal,
1168            replacement_ref: 0x42,
1169        });
1170        assert_eq!(
1171            h.on_apdu(&clear).unwrap().notify,
1172            vec![Notification::HostControl(HostControlEvent::ClearReplace {
1173                replacement_ref: 0x42,
1174            })]
1175        );
1176
1177        // ask_release() → HostControlEvent::AskRelease (header-only).
1178        let ask = s(&AskRelease::default());
1179        assert_eq!(
1180            h.on_apdu(&ask).unwrap().notify,
1181            vec![Notification::HostControl(HostControlEvent::AskRelease)]
1182        );
1183
1184        // The host acts out of band: no reply APDU is produced.
1185        assert!(h.on_apdu(&tune).unwrap().apdus.is_empty());
1186    }
1187
1188    #[test]
1189    fn mjd_bcd_encoding_is_correct() {
1190        // Unix epoch 1970-01-01 00:00:00 → MJD 40587 (0x9E8B), 00:00:00.
1191        assert_eq!(unix_to_mjd_bcd(0), Some([0x9E, 0x8B, 0x00, 0x00, 0x00]));
1192        // 1970-01-02 13:45:09 → MJD 40588 (0x9E8C), BCD 13 45 09.
1193        let secs = SECS_PER_DAY + 13 * 3600 + 45 * 60 + 9;
1194        assert_eq!(unix_to_mjd_bcd(secs), Some([0x9E, 0x8C, 0x13, 0x45, 0x09]));
1195    }
1196
1197    #[test]
1198    fn mjd_beyond_its_sixteen_bits_is_refused_not_wrapped() {
1199        // 2_155_507_200 is 2038-04-22; any instant below MJD 65536 still fits
1200        // 16 bits and encodes normally.
1201        assert_eq!(
1202            unix_to_mjd_bcd(2_155_507_200 + 86_399),
1203            Some([0xFF, 0xFF, 0x23, 0x59, 0x59])
1204        );
1205        // From 2141-09-10 (MJD 65536) the old `as u16` wrapped the date back
1206        // to 1858-11-17 (MJD 0).
1207        assert_eq!(unix_to_mjd_bcd(5_417_971_200), None);
1208    }
1209
1210    #[test]
1211    fn date_time_reports_an_unrepresentable_clock_instead_of_a_wrong_date() {
1212        let mut h = DateTime::with_clock(|| None);
1213        let out = h
1214            .on_apdu(&s(&DateTimeEnq {
1215                length_form: dvb_ci::length::LengthForm::Minimal,
1216                response_interval: 0,
1217            }))
1218            .unwrap();
1219        assert!(out.apdus.is_empty());
1220        assert_eq!(out.notify, vec![Notification::ClockUnrepresentable]);
1221    }
1222
1223    #[test]
1224    fn system_clock_is_representable_today() {
1225        let now = std::time::SystemTime::now()
1226            .duration_since(std::time::UNIX_EPOCH)
1227            .unwrap_or_default()
1228            .as_secs();
1229        assert_eq!(system_utc(), unix_to_mjd_bcd(now));
1230        assert!(system_utc().is_some());
1231    }
1232
1233    #[test]
1234    fn date_time_replies_to_enq_and_resends_on_interval() {
1235        let fixed = || Some([0x9E, 0x7B, 0x00, 0x00, 0x00]);
1236        let mut h = DateTime::with_clock(fixed);
1237        // enquiry with a 5s response interval → immediate reply
1238        let enq = s(&DateTimeEnq {
1239            length_form: dvb_ci::length::LengthForm::Minimal,
1240            response_interval: 5,
1241        });
1242        let out = h.on_apdu(&enq).unwrap();
1243        assert_eq!(out.apdus.len(), 1);
1244        assert_eq!(peek_tag(&out.apdus[0]), Some(tag::DATE_TIME));
1245        // before the interval: no resend
1246        assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1247        // crossing the interval: resend
1248        assert_eq!(h.tick(Duration::from_secs(3)).unwrap().apdus.len(), 1);
1249    }
1250
1251    #[test]
1252    fn date_time_interval_zero_does_not_resend() {
1253        let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1254        h.on_apdu(&s(&DateTimeEnq {
1255            length_form: dvb_ci::length::LengthForm::Minimal,
1256            response_interval: 0,
1257        }))
1258        .unwrap();
1259        assert!(h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty());
1260    }
1261
1262    /// r10-W-19: `reset()` must clear the resend timer (`interval`/`since`)
1263    /// so a stale cadence negotiated with a PREVIOUS module does not keep
1264    /// firing (or fire early on a leftover partial `since`) before the new
1265    /// module ever sends its own `date_time_enq`.
1266    #[test]
1267    fn date_time_reset_clears_interval_and_resend_timer() {
1268        let mut h = DateTime::with_clock(|| Some([0u8; UTC_TIME_LEN]));
1269        h.on_apdu(&s(&DateTimeEnq {
1270            length_form: dvb_ci::length::LengthForm::Minimal,
1271            response_interval: 5,
1272        }))
1273        .unwrap();
1274        // Dirty: interval = 5, partway through the resend window.
1275        assert!(h.tick(Duration::from_secs(3)).unwrap().apdus.is_empty());
1276
1277        h.reset();
1278        // Pre-fix, the leftover `since` (3s) plus this tick would cross the
1279        // still-latched 5s interval and resend; post-reset, interval is 0 so
1280        // nothing fires no matter how much time passes.
1281        assert!(
1282            h.tick(Duration::from_secs(60)).unwrap().apdus.is_empty(),
1283            "reset must clear the resend cadence from the previous module"
1284        );
1285    }
1286
1287    #[test]
1288    fn conditional_access_surfaces_ca_info_and_pmt_reply() {
1289        let mut h = ConditionalAccess;
1290        assert_eq!(h.on_open().unwrap().apdus, vec![s(&CaInfoEnq::default())]);
1291        // ca_info -> CaInfo notification
1292        let ci = s(&CaInfo {
1293            length_form: dvb_ci::length::LengthForm::Minimal,
1294            ca_system_ids: vec![0x0B00, 0x1800],
1295        });
1296        assert_eq!(
1297            h.on_apdu(&ci).unwrap().notify,
1298            vec![Notification::CaInfo {
1299                ca_system_ids: vec![0x0B00, 0x1800],
1300            }]
1301        );
1302        // ca_pmt_reply (descrambling possible) -> CaPmtReply notification
1303        let reply = s(&CaPmtReply {
1304            reserved_ca_enable: Default::default(),
1305            reserved_version: Default::default(),
1306            length_form: dvb_ci::length::LengthForm::Minimal,
1307            program_number: 0x0042,
1308            version_number: 0,
1309            current_next_indicator: true,
1310            ca_enable: Some(CaEnable::Possible),
1311            streams: vec![],
1312        });
1313        assert_eq!(
1314            h.on_apdu(&reply).unwrap().notify,
1315            vec![Notification::CaPmtReply {
1316                program_number: 0x0042,
1317                ca_enable: Some(CaEnable::Possible),
1318                descrambling_ok: true,
1319            }]
1320        );
1321    }
1322
1323    #[test]
1324    fn conditional_access_ca_pmt_reply_flag_clear_surfaces_none() {
1325        let mut h = ConditionalAccess;
1326        h.on_open().unwrap();
1327        // Programme `CA_enable_flag` clear -> no programme-level status given.
1328        let reply = s(&CaPmtReply {
1329            reserved_ca_enable: Default::default(),
1330            reserved_version: Default::default(),
1331            length_form: dvb_ci::length::LengthForm::Minimal,
1332            program_number: 0x0007,
1333            version_number: 0,
1334            current_next_indicator: true,
1335            ca_enable: None,
1336            streams: vec![],
1337        });
1338        assert_eq!(
1339            h.on_apdu(&reply).unwrap().notify,
1340            vec![Notification::CaPmtReply {
1341                program_number: 0x0007,
1342                ca_enable: None,
1343                descrambling_ok: false,
1344            }]
1345        );
1346    }
1347
1348    #[test]
1349    fn short_apdu_returns_err() {
1350        for len in 0..3usize {
1351            let buf = vec![0u8; len];
1352            assert!(Mmi::default().on_apdu(&buf).is_err(), "Mmi len {len}");
1353            assert!(
1354                ResourceManager::new(vec![]).on_apdu(&buf).is_err(),
1355                "RM len {len}"
1356            );
1357            assert!(
1358                ApplicationInformation.on_apdu(&buf).is_err(),
1359                "AI len {len}"
1360            );
1361            assert!(ConditionalAccess.on_apdu(&buf).is_err(), "CA len {len}");
1362            assert!(DateTime::default().on_apdu(&buf).is_err(), "DT len {len}");
1363            assert!(HostControl.on_apdu(&buf).is_err(), "HC len {len}");
1364        }
1365    }
1366
1367    /// A bare 3-byte `apdu_tag` with no body is the shortest legal APDU: each
1368    /// resource must accept it (and, where the tag carries no body, answer or
1369    /// ignore it), not reject it as short.
1370    #[test]
1371    fn a_tag_only_apdu_is_accepted_by_every_resource() {
1372        let out = ResourceManager::new(vec![RESOURCE_MANAGER])
1373            .on_apdu(&tag::PROFILE_ENQ.to_bytes())
1374            .unwrap();
1375        assert_eq!(out.apdus.len(), 1, "profile_enq is answered");
1376        assert_eq!(peek_tag(&out.apdus[0]), Some(tag::PROFILE));
1377
1378        assert_eq!(
1379            ApplicationInformation
1380                .on_apdu(&tag::CA_INFO.to_bytes())
1381                .unwrap(),
1382            ResourceOut::default(),
1383            "an unrelated tag-only APDU is ignored, not an error"
1384        );
1385        assert_eq!(
1386            ConditionalAccess
1387                .on_apdu(&tag::APPLICATION_INFO.to_bytes())
1388                .unwrap(),
1389            ResourceOut::default()
1390        );
1391        assert_eq!(
1392            DateTime::default()
1393                .on_apdu(&tag::PROFILE_ENQ.to_bytes())
1394                .unwrap(),
1395            ResourceOut::default()
1396        );
1397        assert_eq!(
1398            Mmi::default().on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1399            ResourceOut::default()
1400        );
1401        assert_eq!(
1402            HostControl.on_apdu(&tag::CA_INFO.to_bytes()).unwrap(),
1403            ResourceOut::default()
1404        );
1405    }
1406}