Skip to main content

dvb_ci_runtime/
session.rs

1//! SPDU session layer — a sans-IO mechanism over the transport layer
2//! (ETSI EN 50221 §7.2).
3//!
4//! Multiplexes logical sessions (one per resource in use) over the transport
5//! connection: allocates/tracks `session_nb`s, answers `open_session_request`
6//! for resources the host advertises, opens `create_session` on demand, and
7//! routes `session_number`+APDU to/from the resource bound to a session. It is
8//! mechanism only — *which* resources the host provides is the caller's policy,
9//! supplied as the `provides` predicate to [`SessionLayer::on_spdu`].
10
11use std::collections::BTreeMap;
12
13use crate::resource::ser;
14use broadcast_common::Parse;
15use dvb_ci::resource::ResourceId;
16use dvb_ci::spdu::{
17    CloseSessionRequest, CloseSessionResponse, CreateSessionResponse, OpenSessionRequest,
18    OpenSessionResponse, SessionNumber, SessionStatus, tags,
19};
20
21/// Most sessions this layer keeps open at once.
22///
23/// One CI slot's resources are a handful — the host advertises six, plus
24/// whatever the module opens — and nothing here needs anywhere near the 65 535
25/// representable `session_nb`s. Unbounded, a module repeating
26/// `open_session_request` for one resource grew the table to that size and had
27/// its resource handler ticked once per duplicate, running (for example) the
28/// `date_time` resend timer N times as fast (audit a20-44). A request past
29/// this bound, and a request for a resource that already has an open session,
30/// are answered `session_status = resource_busy` (EN 50221 Table 7).
31const MAX_SESSIONS: usize = 32;
32
33/// What the session layer wants done after handling one SPDU.
34#[derive(Debug, Default, Clone, PartialEq, Eq)]
35pub struct SessionOut {
36    /// SPDUs to hand down to the transport layer (each becomes a `T_Data_Last`).
37    pub spdus: Vec<Vec<u8>>,
38    /// `(session_nb, apdu_bytes)` to pass up to the resource layer.
39    pub apdus: Vec<(u16, Vec<u8>)>,
40    /// Sessions newly opened (`session_nb`, bound resource).
41    pub opened: Vec<(u16, ResourceId)>,
42    /// `session_nb`s that closed.
43    pub closed: Vec<u16>,
44}
45
46/// The session table + `session_nb` allocator.
47#[derive(Debug, Default)]
48pub struct SessionLayer {
49    sessions: BTreeMap<u16, ResourceId>,
50    next: u16,
51}
52
53impl SessionLayer {
54    /// New, empty session layer.
55    #[must_use]
56    pub fn new() -> Self {
57        Self {
58            sessions: BTreeMap::new(),
59            next: 1, // session_nb 0 is reserved
60        }
61    }
62
63    /// Resource bound to `session_nb`, if open.
64    #[must_use]
65    pub fn resource_of(&self, session_nb: u16) -> Option<ResourceId> {
66        self.sessions.get(&session_nb).copied()
67    }
68
69    /// The lowest open `session_nb` bound to `resource`, if any.
70    ///
71    /// Walks only the open sessions (a handful per slot), where the caller
72    /// used to probe every one of the 65 535 representable numbers through
73    /// [`resource_of`](Self::resource_of) (audit r10-O-9).
74    #[must_use]
75    pub fn session_for(&self, resource: ResourceId) -> Option<u16> {
76        self.sessions
77            .iter()
78            .find(|&(_, &r)| r == resource)
79            .map(|(&n, _)| n)
80    }
81
82    /// All open `(session_nb, resource)` pairs, ascending by `session_nb`.
83    #[must_use]
84    pub fn sessions(&self) -> Vec<(u16, ResourceId)> {
85        self.sessions.iter().map(|(&n, &r)| (n, r)).collect()
86    }
87
88    /// Number of open sessions.
89    #[must_use]
90    pub fn len(&self) -> usize {
91        self.sessions.len()
92    }
93
94    /// Whether there are no open sessions.
95    #[must_use]
96    pub fn is_empty(&self) -> bool {
97        self.sessions.is_empty()
98    }
99
100    /// r10-W-18: probe past any `session_nb` still in `self.sessions` —
101    /// `next` wraps around after 65535 allocations (a long-running slot with
102    /// enough session churn, e.g. repeated MMI dialogues, can reach this),
103    /// and without the probe a wrapped-around number could alias a session
104    /// that is still open, silently corrupting its `resource_of` mapping.
105    fn alloc(&mut self) -> Option<u16> {
106        let start = self.next;
107        loop {
108            let nb = self.next;
109            self.next = self.next.checked_add(1).filter(|&n| n != 0).unwrap_or(1);
110            if !self.sessions.contains_key(&nb) {
111                return Some(nb);
112            }
113            // Every one of the 65535 representable numbers is in use. Callers
114            // hold `MAX_SESSIONS`, so this is unreachable in practice; report
115            // the exhaustion instead of aliasing a live session.
116            if self.next == start {
117                return None;
118            }
119        }
120    }
121
122    /// Bind `session_nb` to `resource` directly, bypassing the open-request
123    /// policy — a test needs the several-sessions-for-one-resource state that
124    /// policy now refuses, to show the resource layer still ticks it once.
125    #[cfg(test)]
126    pub(crate) fn bind_for_test(&mut self, session_nb: u16, resource: ResourceId) {
127        self.sessions.insert(session_nb, resource);
128    }
129
130    /// Whether `resource` already has an open session.
131    fn resource_is_open(&self, resource: ResourceId) -> bool {
132        self.sessions.values().any(|&r| r == resource)
133    }
134
135    /// Open a session to a **module-provided** resource (host-initiated):
136    /// returns the `open_session_request` SPDU to send. Sessions are opened the
137    /// same way in both directions (§8.4.1) — the host sends
138    /// `open_session_request`, and the module (the resource provider) assigns the
139    /// `session_nb` in its `open_session_response`. (`create_session`/0x93 is a
140    /// resource-manager-internal primitive; a real CAM rejects it with
141    /// `status=0xF0` — verified live against an AlphaCrypt.) The session is
142    /// recorded once the module's `open_session_response(ok)` arrives.
143    pub fn create_session(&mut self, resource: ResourceId) -> dvb_ci::Result<Vec<u8>> {
144        ser(&OpenSessionRequest {
145            length_form: dvb_ci::length::LengthForm::Minimal,
146            resource,
147        })
148    }
149
150    /// Wrap an APDU for sending on `session_nb` (`session_number` + body).
151    pub fn send_apdu(&self, session_nb: u16, apdu: &[u8]) -> dvb_ci::Result<Vec<u8>> {
152        let mut v = ser(&SessionNumber {
153            length_form: dvb_ci::length::LengthForm::Minimal,
154            session_nb,
155        })?;
156        v.extend_from_slice(apdu);
157        Ok(v)
158    }
159
160    /// Begin closing `session_nb`: returns the `close_session_request` SPDU.
161    pub fn close(&mut self, session_nb: u16) -> dvb_ci::Result<Vec<u8>> {
162        self.sessions.remove(&session_nb);
163        ser(&CloseSessionRequest {
164            length_form: dvb_ci::length::LengthForm::Minimal,
165            session_nb,
166        })
167    }
168
169    /// Bind a module-chosen `session_nb` to `resource` (from
170    /// `open_session_response`/`create_session_response`), returning
171    /// whether the binding is now in effect.
172    ///
173    /// r10-W-18: `session_nb` is the MODULE's own choice, not ours — a
174    /// misbehaving (or hostile) module reusing a number already bound to a
175    /// DIFFERENT resource would otherwise silently alias that resource's
176    /// session, misrouting its APDUs from then on. `0` is also rejected: it
177    /// is the reserved value `alloc` never hands out. Re-asserting the SAME
178    /// resource on an already-open `session_nb` is treated as an idempotent
179    /// success, not a collision (a module may legitimately repeat its own
180    /// prior response).
181    fn try_bind_module_chosen(&mut self, session_nb: u16, resource: ResourceId) -> bool {
182        if session_nb == 0 {
183            return false;
184        }
185        match self.sessions.get(&session_nb) {
186            Some(&existing) => existing == resource,
187            None => {
188                if self.resource_is_open(resource) || self.sessions.len() >= MAX_SESSIONS {
189                    return false;
190                }
191                self.sessions.insert(session_nb, resource);
192                true
193            }
194        }
195    }
196
197    /// Handle one inbound SPDU. `provides` answers "does the host provide this
198    /// resource?" for an incoming `open_session_request`.
199    pub fn on_spdu(
200        &mut self,
201        spdu: &[u8],
202        provides: impl Fn(ResourceId) -> bool,
203    ) -> dvb_ci::Result<SessionOut> {
204        let mut out = SessionOut::default();
205        match spdu.first().copied() {
206            // Module wants a host-provided resource.
207            Some(tags::OPEN_SESSION_REQUEST) => {
208                // A malformed CAM SPDU is surfaced (`?` -> Notification::Error),
209                // never dropped silently.
210                let req = OpenSessionRequest::parse(spdu)?;
211                let granted = provides(req.resource)
212                    && !self.resource_is_open(req.resource)
213                    && self.sessions.len() < MAX_SESSIONS;
214                let session_nb = if granted { self.alloc() } else { None };
215                let Some(session_nb) = session_nb else {
216                    out.spdus.push(ser(&OpenSessionResponse {
217                        length_form: dvb_ci::length::LengthForm::Minimal,
218                        status: if provides(req.resource) {
219                            SessionStatus::ResourceBusy
220                        } else {
221                            SessionStatus::ResourceNonExistent
222                        },
223                        resource: req.resource,
224                        session_nb: 0,
225                    })?);
226                    return Ok(out);
227                };
228                self.sessions.insert(session_nb, req.resource);
229                out.spdus.push(ser(&OpenSessionResponse {
230                    length_form: dvb_ci::length::LengthForm::Minimal,
231                    status: SessionStatus::Ok,
232                    resource: req.resource,
233                    session_nb,
234                })?);
235                out.opened.push((session_nb, req.resource));
236            }
237            // Module's reply to our open_session_request (host opened a
238            // module-provided resource); the module assigns the session_nb.
239            // r10-W-18: the assignment is not trusted blindly — see
240            // `try_bind_module_chosen`.
241            Some(tags::OPEN_SESSION_RESPONSE) => {
242                let resp = OpenSessionResponse::parse(spdu)?;
243                if resp.status == SessionStatus::Ok {
244                    out.opened.extend(
245                        self.try_bind_module_chosen(resp.session_nb, resp.resource)
246                            .then_some((resp.session_nb, resp.resource)),
247                    );
248                }
249            }
250            // (Legacy) module's reply to a create_session, if any module uses it.
251            Some(tags::CREATE_SESSION_RESPONSE) => {
252                let resp = CreateSessionResponse::parse(spdu)?;
253                if resp.status == SessionStatus::Ok {
254                    out.opened.extend(
255                        self.try_bind_module_chosen(resp.session_nb, resp.resource)
256                            .then_some((resp.session_nb, resp.resource)),
257                    );
258                }
259            }
260            // Peer closes a session.
261            Some(tags::CLOSE_SESSION_REQUEST) => {
262                let req = CloseSessionRequest::parse(spdu)?;
263                let known = self.sessions.remove(&req.session_nb).is_some();
264                out.spdus.push(ser(&CloseSessionResponse {
265                    length_form: dvb_ci::length::LengthForm::Minimal,
266                    status: if known {
267                        SessionStatus::Ok
268                    } else {
269                        SessionStatus::ResourceNonExistent
270                    },
271                    session_nb: req.session_nb,
272                })?);
273                if known {
274                    out.closed.push(req.session_nb);
275                }
276            }
277            // Ack of a close we initiated.
278            Some(tags::CLOSE_SESSION_RESPONSE) => {
279                let resp = CloseSessionResponse::parse(spdu)?;
280                self.sessions.remove(&resp.session_nb);
281                out.closed.push(resp.session_nb);
282            }
283            // Data: session_number(nb) + APDU body.
284            Some(tags::SESSION_NUMBER) => {
285                let sn = SessionNumber::parse(spdu)?;
286                // The header is `sn.header_len()` long: 4 bytes when the
287                // `length_field` is minimally coded, longer for a CAM that
288                // codes it in a long form (`90 82 00 02 ..`).
289                let header_len = sn.header_len();
290                if spdu.len() > header_len {
291                    out.apdus.push((sn.session_nb, spdu[header_len..].to_vec()));
292                }
293            }
294            _ => {}
295        }
296        Ok(out)
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303    use dvb_ci::resource::{APPLICATION_INFORMATION, RESOURCE_MANAGER};
304
305    fn provides_rm(r: ResourceId) -> bool {
306        r == RESOURCE_MANAGER
307    }
308
309    #[test]
310    fn session_for_returns_the_lowest_open_session_of_a_resource() {
311        let mut s = SessionLayer::new();
312        assert_eq!(s.session_for(RESOURCE_MANAGER), None);
313        let rm_req = ser(&OpenSessionRequest {
314            length_form: dvb_ci::length::LengthForm::Minimal,
315            resource: RESOURCE_MANAGER,
316        })
317        .unwrap();
318        let ai_req = ser(&OpenSessionRequest {
319            length_form: dvb_ci::length::LengthForm::Minimal,
320            resource: APPLICATION_INFORMATION,
321        })
322        .unwrap();
323        let all = |_: ResourceId| true;
324        let rm = s.on_spdu(&rm_req, all).unwrap().opened[0].0;
325        let ai = s.on_spdu(&ai_req, all).unwrap().opened[0].0;
326        assert_ne!(rm, ai);
327        assert_eq!(s.session_for(RESOURCE_MANAGER), Some(rm));
328        assert_eq!(s.session_for(APPLICATION_INFORMATION), Some(ai));
329        // Closing the session removes it from the lookup.
330        s.close(rm).unwrap();
331        assert_eq!(s.session_for(RESOURCE_MANAGER), None);
332    }
333
334    #[test]
335    fn open_request_for_provided_resource_grants_and_tracks() {
336        let mut s = SessionLayer::new();
337        let req = ser(&OpenSessionRequest {
338            length_form: dvb_ci::length::LengthForm::Minimal,
339            resource: RESOURCE_MANAGER,
340        })
341        .unwrap();
342        let out = s.on_spdu(&req, provides_rm).unwrap();
343        assert_eq!(out.opened.len(), 1);
344        let (nb, res) = out.opened[0];
345        assert_eq!(res, RESOURCE_MANAGER);
346        assert_eq!(s.resource_of(nb), Some(RESOURCE_MANAGER));
347        // reply is an open_session_response with status ok
348        let resp = OpenSessionResponse::parse(&out.spdus[0]).unwrap();
349        assert_eq!(resp.status, SessionStatus::Ok);
350        assert_eq!(resp.session_nb, nb);
351    }
352
353    /// A module repeating `open_session_request` for one resource must not
354    /// grow the session table (audit a20-44): the resource already has its
355    /// session, so the repeat is refused `resource_busy` and nothing new is
356    /// opened.
357    #[test]
358    fn repeated_open_session_request_for_one_resource_is_refused_as_busy() {
359        let mut s = SessionLayer::new();
360        let req = ser(&OpenSessionRequest {
361            length_form: dvb_ci::length::LengthForm::Minimal,
362            resource: RESOURCE_MANAGER,
363        })
364        .unwrap();
365        let first = s.on_spdu(&req, provides_rm).unwrap();
366        assert_eq!(first.opened.len(), 1);
367
368        for _ in 0..16 {
369            let out = s.on_spdu(&req, provides_rm).unwrap();
370            assert!(
371                out.opened.is_empty(),
372                "a duplicate open_session_request must not open another session"
373            );
374            let resp = OpenSessionResponse::parse(&out.spdus[0]).unwrap();
375            assert_eq!(resp.status, SessionStatus::ResourceBusy);
376        }
377        assert_eq!(s.len(), 1, "the table must still hold exactly one session");
378    }
379
380    /// The table is bounded: past `MAX_SESSIONS` distinct resources every
381    /// further request is refused `resource_busy` instead of being granted a
382    /// 65 535th session (audit a20-44).
383    #[test]
384    fn session_table_is_capped_at_max_sessions() {
385        let mut s = SessionLayer::new();
386        let open = |resource: ResourceId| {
387            ser(&OpenSessionRequest {
388                length_form: dvb_ci::length::LengthForm::Minimal,
389                resource,
390            })
391            .unwrap()
392        };
393
394        for resource in 0..MAX_SESSIONS as u32 {
395            let out = s
396                .on_spdu(&open(ResourceId(0x0100_0000 + resource)), |_| true)
397                .unwrap();
398            assert_eq!(out.opened.len(), 1, "session {resource} must be granted");
399        }
400        assert_eq!(s.len(), MAX_SESSIONS);
401
402        let out = s
403            .on_spdu(&open(ResourceId(0x0100_0000 + MAX_SESSIONS as u32)), |_| {
404                true
405            })
406            .unwrap();
407        assert!(
408            out.opened.is_empty(),
409            "the cap must refuse the next session"
410        );
411        let resp = OpenSessionResponse::parse(&out.spdus[0]).unwrap();
412        assert_eq!(resp.status, SessionStatus::ResourceBusy);
413        assert_eq!(s.len(), MAX_SESSIONS);
414    }
415
416    /// #2946: the cap also holds on the module-chosen bind path — the one a
417    /// CAM drives by sending `open_session_response`s of its own.
418    #[test]
419    fn module_chosen_sessions_are_capped_at_max_sessions() {
420        let response = |session_nb: u16, resource: u32, status: SessionStatus| {
421            ser(&OpenSessionResponse {
422                length_form: dvb_ci::length::LengthForm::Minimal,
423                status,
424                resource: ResourceId(0x0100_0000 + resource),
425                session_nb,
426            })
427            .unwrap()
428        };
429
430        let mut s = SessionLayer::new();
431        for i in 0..MAX_SESSIONS as u16 {
432            let out = s
433                .on_spdu(&response(i + 1, u32::from(i), SessionStatus::Ok), |_| true)
434                .unwrap();
435            assert_eq!(
436                out.opened,
437                vec![(i + 1, ResourceId(0x0100_0000 + u32::from(i)))]
438            );
439        }
440        assert_eq!(s.len(), MAX_SESSIONS);
441
442        let out = s
443            .on_spdu(&response(100, 0x0000_00FF, SessionStatus::Ok), |_| true)
444            .unwrap();
445        assert!(
446            out.opened.is_empty(),
447            "the cap must refuse a further module-chosen session"
448        );
449        assert_eq!(s.len(), MAX_SESSIONS);
450
451        let out = s
452            .on_spdu(&response(101, 0, SessionStatus::Ok), |_| true)
453            .unwrap();
454        assert!(
455            out.opened.is_empty(),
456            "a second session for an already-open resource is refused"
457        );
458        assert_eq!(s.resource_of(101), None);
459        assert_eq!(s.len(), MAX_SESSIONS);
460    }
461
462    /// #2946: only an `ok` status binds a module-chosen session.
463    #[test]
464    fn a_non_ok_open_session_response_never_binds() {
465        let mut s = SessionLayer::new();
466        let resp = ser(&OpenSessionResponse {
467            length_form: dvb_ci::length::LengthForm::Minimal,
468            status: SessionStatus::ResourceBusy,
469            resource: ResourceId(0x0004_1001),
470            session_nb: 7,
471        })
472        .unwrap();
473        let out = s.on_spdu(&resp, |_| true).unwrap();
474        assert!(out.opened.is_empty());
475        assert_eq!(s.resource_of(7), None);
476        assert!(s.is_empty());
477    }
478
479    /// #2946: the host-initiated open request is the tag-`0x91` SPDU with the
480    /// resource identifier, hand-derived from ETSI EN 50221 §7.2.6.1.
481    #[test]
482    fn create_session_emits_the_open_session_request_spdu() {
483        let mut s = SessionLayer::new();
484        assert_eq!(
485            s.create_session(ResourceId(0x0004_1001)).unwrap(),
486            vec![0x91, 0x04, 0x00, 0x04, 0x10, 0x01]
487        );
488    }
489
490    /// #2946: a module acknowledging a close the host initiated removes the
491    /// session and reports it closed.
492    #[test]
493    fn a_close_session_response_removes_the_session() {
494        let mut s = SessionLayer::new();
495        for i in 0..5u32 {
496            let req = ser(&OpenSessionRequest {
497                length_form: dvb_ci::length::LengthForm::Minimal,
498                resource: ResourceId(0x0100_0000 + i),
499            })
500            .unwrap();
501            let out = s.on_spdu(&req, |_| true).unwrap();
502            assert_eq!(out.opened[0].0, u16::try_from(i).unwrap() + 1);
503        }
504        assert_eq!(s.len(), 5);
505
506        let resp = ser(&CloseSessionResponse {
507            length_form: dvb_ci::length::LengthForm::Minimal,
508            status: SessionStatus::Ok,
509            session_nb: 5,
510        })
511        .unwrap();
512        let out = s.on_spdu(&resp, |_| false).unwrap();
513        assert_eq!(out.closed, vec![5]);
514        assert_eq!(s.resource_of(5), None);
515        assert_eq!(s.len(), 4);
516    }
517
518    /// #2946: a `session_number` SPDU carries an APDU only when a body follows
519    /// the header.
520    #[test]
521    fn a_session_number_spdu_without_a_body_yields_no_apdu() {
522        let mut s = SessionLayer::new();
523        let header_only = ser(&SessionNumber {
524            length_form: dvb_ci::length::LengthForm::Minimal,
525            session_nb: 3,
526        })
527        .unwrap();
528        assert_eq!(header_only.len(), 4);
529        assert!(s.on_spdu(&header_only, |_| false).unwrap().apdus.is_empty());
530
531        let mut with_body = header_only;
532        with_body.push(0xAA);
533        assert_eq!(
534            s.on_spdu(&with_body, |_| false).unwrap().apdus,
535            vec![(3, vec![0xAA])]
536        );
537    }
538
539    #[test]
540    fn open_request_for_absent_resource_denied() {
541        let mut s = SessionLayer::new();
542        let req = ser(&OpenSessionRequest {
543            length_form: dvb_ci::length::LengthForm::Minimal,
544            resource: APPLICATION_INFORMATION,
545        })
546        .unwrap();
547        let out = s.on_spdu(&req, provides_rm).unwrap();
548        assert!(out.opened.is_empty());
549        let resp = OpenSessionResponse::parse(&out.spdus[0]).unwrap();
550        assert_eq!(resp.status, SessionStatus::ResourceNonExistent);
551        assert!(s.is_empty());
552    }
553
554    #[test]
555    fn create_session_tracked_on_ok_response() {
556        let mut s = SessionLayer::new();
557        let _spdu = s.create_session(APPLICATION_INFORMATION).unwrap();
558        // module replies ok for session 1
559        let resp = ser(&CreateSessionResponse {
560            length_form: dvb_ci::length::LengthForm::Minimal,
561            status: SessionStatus::Ok,
562            resource: APPLICATION_INFORMATION,
563            session_nb: 1,
564        })
565        .unwrap();
566        let out = s.on_spdu(&resp, |_| false).unwrap();
567        assert_eq!(out.opened, vec![(1, APPLICATION_INFORMATION)]);
568        assert_eq!(s.resource_of(1), Some(APPLICATION_INFORMATION));
569    }
570
571    /// r10-W-18: a module-chosen `session_nb` that already maps to a
572    /// DIFFERENT resource must be rejected, not silently overwritten —
573    /// otherwise a misbehaving module aliases an existing session and its
574    /// APDUs are misrouted from then on.
575    #[test]
576    fn module_chosen_session_nb_colliding_with_a_different_resource_is_rejected() {
577        let mut s = SessionLayer::new();
578        // Session 1 is already RESOURCE_MANAGER (opened via the ordinary path).
579        let open = ser(&OpenSessionRequest {
580            length_form: dvb_ci::length::LengthForm::Minimal,
581            resource: RESOURCE_MANAGER,
582        })
583        .unwrap();
584        let opened = s.on_spdu(&open, provides_rm).unwrap().opened;
585        let nb = opened[0].0;
586        assert_eq!(s.resource_of(nb), Some(RESOURCE_MANAGER));
587
588        // The module now claims that SAME session_nb for a totally
589        // different resource via create_session_response.
590        let colliding = ser(&CreateSessionResponse {
591            length_form: dvb_ci::length::LengthForm::Minimal,
592            status: SessionStatus::Ok,
593            resource: APPLICATION_INFORMATION,
594            session_nb: nb,
595        })
596        .unwrap();
597        let out = s.on_spdu(&colliding, |_| false).unwrap();
598        assert!(
599            out.opened.is_empty(),
600            "a colliding module-chosen session_nb must not be reported as opened"
601        );
602        assert_eq!(
603            s.resource_of(nb),
604            Some(RESOURCE_MANAGER),
605            "the original binding must survive the collision attempt"
606        );
607    }
608
609    /// r10-W-18: `session_nb = 0` is reserved (`alloc` never hands it out)
610    /// and must never be accepted as a module-chosen binding.
611    #[test]
612    fn module_chosen_session_nb_zero_is_rejected() {
613        let mut s = SessionLayer::new();
614        let resp = ser(&OpenSessionResponse {
615            length_form: dvb_ci::length::LengthForm::Minimal,
616            status: SessionStatus::Ok,
617            resource: APPLICATION_INFORMATION,
618            session_nb: 0,
619        })
620        .unwrap();
621        let out = s.on_spdu(&resp, |_| false).unwrap();
622        assert!(out.opened.is_empty());
623        assert_eq!(s.resource_of(0), None);
624    }
625
626    /// r10-W-18: `alloc` must skip any `session_nb` still open, even across
627    /// the 65535 wraparound — otherwise a long-running slot with enough
628    /// session churn eventually reissues a number that aliases a session
629    /// that never closed.
630    #[test]
631    fn alloc_probes_past_a_still_open_session_across_wraparound() {
632        let mut s = SessionLayer::new();
633        // Force the allocator right up to the wraparound boundary.
634        s.next = 65535;
635        let first = s.alloc().expect("65535 is free");
636        assert_eq!(first, 65535);
637        s.sessions.insert(first, APPLICATION_INFORMATION);
638        // Next candidate would be `65535 -> checked_add overflows -> 1`.
639        // Occupy 1 directly (as if it were opened earlier and never closed).
640        s.sessions.insert(1, RESOURCE_MANAGER);
641        let second = s.alloc().expect("65535 and 1 are the only sessions open");
642        assert_ne!(
643            second, 1,
644            "alloc must not hand out a session_nb that is still open"
645        );
646        assert_eq!(s.resource_of(1), Some(RESOURCE_MANAGER), "untouched");
647    }
648
649    #[test]
650    fn session_number_routes_apdu_up() {
651        let mut s = SessionLayer::new();
652        let apdu = [0x9F, 0x80, 0x21, 0x00];
653        let mut spdu = ser(&SessionNumber {
654            length_form: dvb_ci::length::LengthForm::Minimal,
655            session_nb: 7,
656        })
657        .unwrap();
658        spdu.extend_from_slice(&apdu);
659        let out = s.on_spdu(&spdu, |_| false).unwrap();
660        assert_eq!(out.apdus, vec![(7, apdu.to_vec())]);
661    }
662
663    #[test]
664    fn close_request_acks_and_removes() {
665        let mut s = SessionLayer::new();
666        // open one first
667        let req = ser(&OpenSessionRequest {
668            length_form: dvb_ci::length::LengthForm::Minimal,
669            resource: RESOURCE_MANAGER,
670        })
671        .unwrap();
672        let nb = s.on_spdu(&req, provides_rm).unwrap().opened[0].0;
673        // peer closes it
674        let close = ser(&CloseSessionRequest {
675            length_form: dvb_ci::length::LengthForm::Minimal,
676            session_nb: nb,
677        })
678        .unwrap();
679        let out = s.on_spdu(&close, |_| false).unwrap();
680        assert_eq!(out.closed, vec![nb]);
681        assert!(s.is_empty());
682        // reply is a close_session_response
683        assert_eq!(out.spdus[0][0], tags::CLOSE_SESSION_RESPONSE);
684    }
685
686    #[test]
687    fn send_apdu_prefixes_session_number() {
688        let s = SessionLayer::new();
689        let wire = s.send_apdu(3, &[0xAA, 0xBB]).unwrap();
690        let sn = SessionNumber::parse(&wire).unwrap();
691        assert_eq!(sn.session_nb, 3);
692        assert_eq!(&wire[SessionNumber::HEADER_LEN..], &[0xAA, 0xBB]);
693    }
694
695    /// r10-W-4: a CAM may code the `session_number` `length_field` in a long
696    /// form (`90 82 00 02 ..`, the `82 00 NN` shape captured on hardware in
697    /// #337 at the TPDU layer). The APDU body then starts after the longer
698    /// header; slicing at the fixed 4-byte `HEADER_LEN` handed the APDU layer
699    /// two stray session bytes.
700    #[test]
701    fn session_number_in_a_long_length_form_still_yields_the_apdu() {
702        let mut s = SessionLayer::new();
703        let wire = [0x90, 0x82, 0x00, 0x02, 0x00, 0x03, 0xAA, 0xBB];
704        let out = s.on_spdu(&wire, |_| false).unwrap();
705        assert_eq!(out.apdus, vec![(3, vec![0xAA, 0xBB])]);
706    }
707
708    #[test]
709    fn closing_an_unallocated_session_is_answered_not_allocated() {
710        let mut s = SessionLayer::new();
711        let req = ser(&CloseSessionRequest {
712            length_form: dvb_ci::length::LengthForm::Minimal,
713            session_nb: 77,
714        })
715        .unwrap();
716        let out = s.on_spdu(&req, |_| true).unwrap();
717        let resp = CloseSessionResponse::parse(&out.spdus[0]).unwrap();
718        assert_eq!(resp.status, SessionStatus::ResourceNonExistent);
719        assert!(out.closed.is_empty(), "no session was closed");
720    }
721}