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