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