Skip to main content

mbus_kit/
app.rs

1//! The layers above the link layer: ELL, AFL and TPL (EN 13757-3, EN 13757-7,
2//! OMS Vol. 2), and the data records they carry.
3//!
4//! ```text
5//! [ELL 8C–8F]  [AFL 90]  TPL (CI + header)  records
6//! ```
7//!
8//! | CI | Layer | Header |
9//! |---|---|---|
10//! | `8C`, `8E` | extended link layer: CC, access number (`8E`: + receiver address) | |
11//! | `8D`, `8F` | the same + session number and payload CRC; **AES-CTR** encrypted | |
12//! | `90` | authentication and fragmentation layer: message counter, **CMAC** | |
13//! | `72`, `5B`, `6F`, `75`, `8B`, `80` | transport layer | long (12 bytes) |
14//! | `7A`, `5A`, `6E`, `74`, `8A` | transport layer | short (4 bytes) |
15//! | `78`, `51`, `70`, `71` | transport layer | none |
16//!
17//! [`Application::parse`] reads every layer without a key and stops at the first
18//! encrypted one: [`Body::Encrypted`] then says how it is encrypted, and (feature `oms`)
19//! [`Encrypted::decrypt`] opens it. [`Application::authenticity`] says what, if
20//! anything, was cryptographically verified: radio data is not evidence until it is
21//! (constitution V).
22
23use core::fmt;
24
25use crate::crc::crc16;
26use crate::record::Records;
27use crate::{Check, Error, Result};
28
29/// CI values.
30pub mod ci {
31    /// Response with variable data structure, long header.
32    pub const RSP_LONG: u8 = 0x72;
33    /// Response with variable data structure, short header.
34    pub const RSP_SHORT: u8 = 0x7A;
35    /// Response with variable data structure, no header.
36    pub const RSP_NONE: u8 = 0x78;
37    /// Data send (master to slave), no header.
38    pub const SND_UD: u8 = 0x51;
39    /// Command to a device, short header (OMS).
40    pub const CMD_SHORT: u8 = 0x5A;
41    /// Command to a device, long header (OMS).
42    pub const CMD_LONG: u8 = 0x5B;
43    /// Application error, short header.
44    pub const ERROR_SHORT: u8 = 0x6E;
45    /// Application error, long header.
46    pub const ERROR_LONG: u8 = 0x6F;
47    /// Application error, no header.
48    pub const ERROR_NONE: u8 = 0x70;
49    /// Alarm, no header.
50    pub const ALARM_NONE: u8 = 0x71;
51    /// Alarm, short header.
52    pub const ALARM_SHORT: u8 = 0x74;
53    /// Alarm, long header.
54    pub const ALARM_LONG: u8 = 0x75;
55    /// Transport layer to a device, long header, no application data.
56    pub const TPL_TO_DEVICE: u8 = 0x80;
57    /// Transport layer from a device, short header, no application data.
58    pub const TPL_SHORT: u8 = 0x8A;
59    /// Transport layer from a device, long header, no application data.
60    pub const TPL_LONG: u8 = 0x8B;
61    /// Extended link layer: CC, access number.
62    pub const ELL_SHORT: u8 = 0x8C;
63    /// Extended link layer with session number and payload CRC (AES-CTR).
64    pub const ELL_SHORT_SN: u8 = 0x8D;
65    /// Extended link layer with receiver address.
66    pub const ELL_LONG: u8 = 0x8E;
67    /// Extended link layer with receiver address, session number and payload CRC.
68    pub const ELL_LONG_SN: u8 = 0x8F;
69    /// Authentication and fragmentation layer.
70    pub const AFL: u8 = 0x90;
71    /// Format frame (the record layout of compact frames), no header.
72    pub const FORMAT_NONE: u8 = 0x69;
73    /// Format frame, short header.
74    pub const FORMAT_SHORT: u8 = 0x6A;
75    /// Format frame, long header.
76    pub const FORMAT_LONG: u8 = 0x6B;
77    /// Compact frame, no header.
78    pub const COMPACT_NONE: u8 = 0x79;
79    /// Compact frame, short header.
80    pub const COMPACT_SHORT: u8 = 0x7B;
81    /// Compact frame, long header.
82    pub const COMPACT_LONG: u8 = 0x73;
83}
84
85/// A manufacturer code: three letters packed into 15 bits (the FLAG association ID).
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
87pub struct Manufacturer(pub u16);
88
89impl Manufacturer {
90    /// The code for three upper-case letters, e.g. `b"KAM"`.
91    pub const fn from_letters(l: [u8; 3]) -> Option<Self> {
92        let [a, b, c] = l;
93        if !a.is_ascii_uppercase() || !b.is_ascii_uppercase() || !c.is_ascii_uppercase() {
94            return None;
95        }
96        Some(Self((((a - 64) as u16) << 10) | (((b - 64) as u16) << 5) | ((c - 64) as u16)))
97    }
98
99    /// The three letters.
100    pub const fn letters(self) -> [u8; 3] {
101        let v = self.0;
102        [(((v >> 10) & 0x1F) as u8) + 64, (((v >> 5) & 0x1F) as u8) + 64, ((v & 0x1F) as u8) + 64]
103    }
104}
105
106impl fmt::Display for Manufacturer {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        for b in self.letters() {
109            write!(f, "{}", char::from(b))?;
110        }
111        Ok(())
112    }
113}
114
115/// The medium (device type) a meter measures.
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub struct Medium(pub u8);
118
119impl Medium {
120    /// Electricity.
121    pub const ELECTRICITY: Self = Self(0x02);
122    /// Gas.
123    pub const GAS: Self = Self(0x03);
124    /// Heat, measured at the outlet.
125    pub const HEAT: Self = Self(0x04);
126    /// Warm water (30–90 °C).
127    pub const WARM_WATER: Self = Self(0x06);
128    /// Water.
129    pub const WATER: Self = Self(0x07);
130    /// Heat cost allocator.
131    pub const HEAT_COST_ALLOCATOR: Self = Self(0x08);
132    /// Cooling load, measured at the outlet.
133    pub const COOLING: Self = Self(0x0A);
134    /// Heat, measured at the inlet.
135    pub const HEAT_INLET: Self = Self(0x0C);
136    /// Combined heat and cooling.
137    pub const HEAT_COOLING: Self = Self(0x0D);
138    /// Hot water (≥ 90 °C).
139    pub const HOT_WATER: Self = Self(0x15);
140    /// Cold water.
141    pub const COLD_WATER: Self = Self(0x16);
142
143    /// A short English name, if this crate knows the code.
144    pub const fn name(self) -> Option<&'static str> {
145        Some(match self.0 {
146            0x00 => "other",
147            0x01 => "oil",
148            0x02 => "electricity",
149            0x03 => "gas",
150            0x04 => "heat (outlet)",
151            0x05 => "steam",
152            0x06 => "warm water",
153            0x07 => "water",
154            0x08 => "heat cost allocator",
155            0x09 => "compressed air",
156            0x0A => "cooling (outlet)",
157            0x0B => "cooling (inlet)",
158            0x0C => "heat (inlet)",
159            0x0D => "heat / cooling",
160            0x0E => "bus / system",
161            0x0F => "unknown",
162            0x15 => "hot water",
163            0x16 => "cold water",
164            0x17 => "dual water",
165            0x18 => "pressure",
166            0x19 => "A/D converter",
167            0x1A => "smoke detector",
168            0x1B => "room sensor",
169            0x1C => "gas detector",
170            0x20 => "breaker (electricity)",
171            0x21 => "valve (gas or water)",
172            0x25 => "customer unit (display)",
173            0x28 => "waste water",
174            0x29 => "garbage",
175            0x31 => "communication controller",
176            0x32 => "unidirectional repeater",
177            0x33 => "bidirectional repeater",
178            0x36 => "radio converter (system side)",
179            0x37 => "radio converter (meter side)",
180            0x38 => "wired adapter",
181            _ => return None,
182        })
183    }
184}
185
186impl fmt::Display for Medium {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        match self.name() {
189            Some(n) => f.write_str(n),
190            None => write!(f, "medium 0x{:02x}", self.0),
191        }
192    }
193}
194
195/// A meter's address: manufacturer, identification number, version and device type.
196///
197/// The same eight bytes appear in the wireless link layer and in a long header (where
198/// they name the meter behind a repeater or a gateway). They select the key and form
199/// part of the OMS initialisation vector.
200#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
201pub struct Address {
202    /// Manufacturer (FLAG association code).
203    pub manufacturer: Manufacturer,
204    /// Identification number, 8 BCD digits, as transmitted (LSB first).
205    pub id: [u8; 4],
206    /// Version / generation.
207    pub version: u8,
208    /// Device type (medium).
209    pub medium: Medium,
210}
211
212impl Address {
213    /// The identification number as printed on the meter, if it is valid BCD.
214    pub fn id_number(&self) -> Option<u32> {
215        crate::value::bcd_u32(self.id)
216    }
217
218    /// The address in link-layer order: manufacturer (LE), ID, version, medium.
219    pub const fn to_bytes(self) -> [u8; 8] {
220        let [m0, m1] = self.manufacturer.0.to_le_bytes();
221        let [i0, i1, i2, i3] = self.id;
222        [m0, m1, i0, i1, i2, i3, self.version, self.medium.0]
223    }
224
225    /// Parse link-layer order (manufacturer first).
226    pub const fn from_link_bytes(b: [u8; 8]) -> Self {
227        let [m0, m1, i0, i1, i2, i3, version, medium] = b;
228        Self {
229            manufacturer: Manufacturer(u16::from_le_bytes([m0, m1])),
230            id: [i0, i1, i2, i3],
231            version,
232            medium: Medium(medium),
233        }
234    }
235}
236
237impl fmt::Display for Address {
238    /// `KAM 12345678 water v27`; the raw ID in hex if it is not valid BCD.
239    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240        if let Some(n) = self.id_number() {
241            write!(f, "{} {n:08} {} v{}", self.manufacturer, self.medium, self.version)
242        } else {
243            let [a, b, c, d] = self.id;
244            write!(f, "{} {d:02X}{c:02X}{b:02X}{a:02X} {} v{}", self.manufacturer, self.medium, self.version)
245        }
246    }
247}
248
249/// The security mode from a transport header's configuration field (OMS Vol. 2
250/// §7.2.4, Tables 19 and 20).
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct SecurityMode {
253    /// The mode: 0 = none, 5 = AES-128-CBC with a static key, 7 = AES-128-CBC with a
254    /// derived key and CMAC, others as defined in EN 13757-7.
255    pub mode: u8,
256    /// The number of encrypted 16-byte blocks; 0 = none, 15 = everything to the end.
257    pub encrypted_blocks: u8,
258}
259
260impl SecurityMode {
261    /// Read the mode from the 2-byte configuration field (as transmitted, LSB first).
262    pub const fn from_config(config: [u8; 2]) -> Self {
263        let [low, high] = config;
264        Self { mode: high & 0x1F, encrypted_blocks: low >> 4 }
265    }
266}
267
268/// The short header: access number, status and configuration.
269#[derive(Clone, Copy, Debug, PartialEq, Eq)]
270pub struct ShortHeader {
271    /// Access number, incremented by the meter per telegram.
272    pub access_number: u8,
273    /// Status byte (application errors, battery low, …).
274    pub status: u8,
275    /// Configuration field, as transmitted.
276    pub config: [u8; 2],
277    /// The configuration field extension: mode 7 one byte (KDF, key id), mode 10 two
278    /// bytes (content index, tag size, KDF, key id), as a little-endian value.
279    pub config_ext: Option<u16>,
280    /// Mode 10: the message counter in the transport layer. Strictly increasing per meter.
281    pub counter: Option<u32>,
282}
283
284impl ShortHeader {
285    /// The security mode the configuration field announces.
286    pub const fn security(&self) -> SecurityMode {
287        SecurityMode::from_config(self.config)
288    }
289}
290
291/// The long header: the meter's address plus the short header.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct LongHeader {
294    /// The meter (ID first on the wire here, unlike the link layer).
295    pub address: Address,
296    /// Access number, status and configuration.
297    pub short: ShortHeader,
298}
299
300/// The transport-layer header.
301#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub enum Header {
303    /// No header.
304    None,
305    /// Short header.
306    Short(ShortHeader),
307    /// Long header.
308    Long(LongHeader),
309}
310
311impl Header {
312    /// The security mode, or mode 0 when there is no header.
313    pub const fn security(&self) -> SecurityMode {
314        match self {
315            Self::None => SecurityMode { mode: 0, encrypted_blocks: 0 },
316            Self::Short(s) => s.security(),
317            Self::Long(l) => l.short.security(),
318        }
319    }
320
321    /// The short part (access number, status, configuration), if there is a header.
322    pub const fn short(&self) -> Option<&ShortHeader> {
323        match self {
324            Self::None => None,
325            Self::Short(s) | Self::Long(LongHeader { short: s, .. }) => Some(s),
326        }
327    }
328}
329
330/// The extended link layer (CI `8C`–`8F`).
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub struct Ell {
333    /// Communication control (bidirectional, response delay, synchronous, hop, …).
334    pub cc: u8,
335    /// The link layer's access number (the TPL's is used for the mode-5 IV).
336    pub access_number: u8,
337    /// `8E`/`8F`: the receiver's address.
338    pub receiver: Option<Address>,
339    /// `8D`/`8F`: the session number (encryption in bits 31–29, time, session counter).
340    pub session: Option<u32>,
341}
342
343impl Ell {
344    /// Whether the session number announces AES-128-CTR encryption (ENC = 1).
345    pub const fn encrypted(&self) -> bool {
346        matches!(self.session, Some(sn) if sn >> 29 == 1)
347    }
348}
349
350/// The authentication and fragmentation layer (CI `90`, OMS Vol. 2 §6, EN 13757-7).
351///
352/// Its MAC is verified only for security mode 7 (by [`Encrypted::decrypt`]); an AFL MAC in
353/// front of a plaintext or mode-5 transport layer is parsed, not checked. A fragment
354/// (fragment ID not 0) has [`Body::Fragment`]; join the fragments with
355/// [`Reassembly`](crate::fragment::Reassembly).
356#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Afl {
358    /// Fragmentation control: bit 14 more fragments, 13–9 which fields are present,
359    /// 7–0 fragment ID.
360    pub fcl: u16,
361    /// Message control: authentication type in bits 3–0.
362    pub mcl: Option<u8>,
363    /// Key information.
364    pub key_info: Option<u16>,
365    /// Message counter: strictly increasing per meter; compare it to detect replays.
366    pub counter: Option<u32>,
367    /// Message length: the bytes of the whole message from the TPL CI on (first fragment
368    /// of a fragmented message only).
369    pub length: Option<u16>,
370    mac: [u8; 16],
371    mac_len: u8,
372}
373
374impl Afl {
375    /// More fragments follow this one.
376    pub const fn more_fragments(&self) -> bool {
377        self.fcl & 0x4000 != 0
378    }
379
380    /// The fragment ID: 0 for an unfragmented message, 1, 2, … for the fragments of one.
381    pub const fn fragment_id(&self) -> u8 {
382        self.fcl.to_le_bytes()[0]
383    }
384
385    /// The AFL of a reassembled message: message control, key information, counter and
386    /// length from the first fragment, the MAC from the last (OMS Vol. 2 §6.2).
387    pub(crate) const fn joined(first: &Self, last: &Self) -> Self {
388        Self {
389            fcl: (first.fcl & 0x3A00) | (last.fcl & 0x04FF),
390            mcl: first.mcl,
391            key_info: first.key_info,
392            counter: first.counter,
393            length: first.length,
394            mac: last.mac,
395            mac_len: last.mac_len,
396        }
397    }
398
399    /// The message authentication code, as received (empty if absent).
400    pub fn mac(&self) -> &[u8] {
401        self.mac.get(..usize::from(self.mac_len)).unwrap_or(&[])
402    }
403}
404
405/// What was cryptographically verified about a telegram. Only
406/// [`Authenticity::Authenticated`] makes a radio reading evidence.
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum Authenticity {
409    /// Nothing: plaintext, or still encrypted. Anyone in radio range can send this.
410    None,
411    /// Decrypted with the meter's key (mode 5, ELL, or mode 7 without a MAC):
412    /// **confidential, but not integrity-protected.** These modes are malleable: without
413    /// the key, an attacker can change bits of the plaintext through the IV inputs in the
414    /// header (mode 5) or the CTR ciphertext with a fixed-up CRC (ELL), and `2F 2F` and the
415    /// payload CRC still pass. And anyone holding the key, often shared by a fleet, can
416    /// send anything. Not evidence of a reading.
417    Encrypted,
418    /// The mode-7 AFL CMAC or the mode-10 CCM tag was verified with the key derived for
419    /// this message. It covers the transport layer from its CI on (records, tail) and the
420    /// counter, and binds the meter's identification number (through the key
421    /// derivation). **Mode 7 does not cover the link layer's manufacturer, version or
422    /// device type**, nor the ELL and the AFL's other fields: compare
423    /// [`Application::meter`] with your key table before you attribute the reading. Mode
424    /// 10's nonce binds all eight address bytes.
425    Authenticated {
426        /// The message counter the MAC covers. Reject a counter not greater than the
427        /// last one accepted from this meter: the library keeps no state.
428        counter: u32,
429    },
430}
431
432/// How an encrypted layer is protected.
433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434#[non_exhaustive]
435pub enum Security {
436    /// TPL mode 5: AES-128-CBC with a static key and an IV from address and access
437    /// number.
438    Mode5,
439    /// TPL mode 7: AES-128-CBC with a per-message key derived from the AFL counter.
440    Mode7,
441    /// TPL mode 10: AES-128-CCM with a per-message key; the tag authenticates.
442    Mode10,
443    /// ELL: AES-128-CTR (CI `8D`/`8F`).
444    EllCtr,
445    /// Any other TPL security mode (not decrypted by this crate).
446    Other(u8),
447}
448
449/// An encrypted layer and everything needed to open it.
450#[derive(Clone, Copy, Debug)]
451pub struct Encrypted<'a> {
452    /// How it is protected.
453    pub security: Security,
454    /// The encrypted bytes, and any plain bytes after them.
455    pub data: &'a [u8],
456    /// How many leading bytes of `data` are encrypted.
457    pub encrypted_len: usize,
458    /// The meter whose key opens it, if known.
459    pub meter: Option<Address>,
460    #[cfg_attr(not(feature = "oms"), allow(dead_code))]
461    pub(crate) ctx: Context,
462}
463
464/// What decryption needs from the layers around the ciphertext.
465#[derive(Clone, Copy, Debug, Default)]
466#[cfg_attr(not(feature = "oms"), allow(dead_code))]
467pub(crate) struct Context {
468    /// IV for mode 5 and the ELL; zero for mode 7.
469    pub(crate) iv: [u8; 16],
470    /// The TPL CI (part of the MAC input).
471    pub(crate) ci: u8,
472    /// The TPL header bytes after the CI (MAC input, CCM associated data): at most 12 +
473    /// CFE (2) + key version (1).
474    pub(crate) header: [u8; 16],
475    pub(crate) header_len: u8,
476    /// The layers parsed so far, copied into the decrypted result.
477    pub(crate) ell: Option<Ell>,
478    pub(crate) afl: Option<Afl>,
479    pub(crate) tpl: Option<(u8, Header)>,
480    pub(crate) link: Option<Address>,
481    /// Parsing the plaintext of a decrypted ELL.
482    pub(crate) inside_ell: bool,
483    /// Mode 10: TPL message counter and tag.
484    pub(crate) counter: Option<u32>,
485    pub(crate) tag: [u8; 16],
486    pub(crate) tag_len: u8,
487}
488
489/// The payload after the transport header.
490#[derive(Clone, Debug)]
491pub enum Body<'a> {
492    /// Data records.
493    Records(Records<'a>),
494    /// An encrypted layer; open it with [`Encrypted::decrypt`] (feature `oms`).
495    Encrypted(Encrypted<'a>),
496    /// An application error (CI `6E`–`70`): the error code bytes (OMS Vol. 2 Table 40:
497    /// `01` CI error, `03` too many records, `08` busy, …).
498    ApplicationError(&'a [u8]),
499    /// An alarm (CI `71`, `74`, `75`): the alarm status bytes.
500    Alarm(&'a [u8]),
501    /// A transport layer without application data (CI `80`, `8A`, `8B`): an ACK, an
502    /// access demand or a request.
503    Empty,
504    /// A compact frame (CI `79`, `7B`, `73`): values only; expand it with the layout of
505    /// an earlier full frame ([`Compact::expand`](crate::compact::Compact::expand)).
506    Compact(crate::compact::Compact<'a>),
507    /// A format frame (CI `69`, `6A`, `6B`): a record layout for compact frames.
508    Format(crate::compact::Format<'a>),
509    /// One fragment of a longer message (AFL fragment ID not 0): the bytes after the AFL,
510    /// a piece of the transport layer. Join them with
511    /// [`Reassembly`](crate::fragment::Reassembly).
512    Fragment(&'a [u8]),
513}
514
515/// A parsed telegram above the link layer.
516#[derive(Clone, Debug)]
517pub struct Application<'a> {
518    /// The extended link layer, if present.
519    pub ell: Option<Ell>,
520    /// The authentication and fragmentation layer, if present.
521    pub afl: Option<Afl>,
522    /// The transport layer's CI, or the ELL's while the ELL is still encrypted.
523    pub ci: u8,
524    /// The transport header.
525    pub header: Header,
526    /// What was cryptographically verified.
527    pub authenticity: Authenticity,
528    /// The payload.
529    pub body: Body<'a>,
530    meter: Option<Address>,
531}
532
533impl<'a> Application<'a> {
534    /// Parse the bytes after a CI field: a wired telegram, or a wireless one when the
535    /// link-layer address does not matter (it is needed for a mode-5 short header and
536    /// the ELL: use [`Application::parse_with_link`]).
537    pub fn parse(ci: u8, data: &'a [u8]) -> Result<Self> {
538        Self::parse_with_link(ci, data, None)
539    }
540
541    /// Parse the bytes after a CI field of a wireless telegram from `link`.
542    pub fn parse_with_link(ci: u8, data: &'a [u8], link: Option<Address>) -> Result<Self> {
543        let ctx = Context { link, ..Context::default() };
544        parse_layers(ci, data, ctx, Stage::Ell)
545    }
546
547    /// Parse a message reassembled from fragments: `data` from the TPL CI on, with the
548    /// AFL joined from the first and last fragment.
549    pub(crate) fn reassembled(
550        data: &'a [u8],
551        afl: Afl,
552        ell: Option<Ell>,
553        link: Option<Address>,
554        decrypted: bool,
555    ) -> Result<Self> {
556        let (&ci, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
557        let ctx = Context { link, ell, afl: Some(afl), inside_ell: decrypted, ..Context::default() };
558        let mut app = parse_layers(ci, rest, ctx, Stage::Tpl)?;
559        if decrypted && !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
560            app.authenticity = Authenticity::Encrypted;
561        }
562        Ok(app)
563    }
564
565    /// The meter: the long header's address if there is one (a meter behind a radio
566    /// adapter or gateway), the link layer's otherwise. In mode 7 only its
567    /// identification number is authenticated ([`Authenticity::Authenticated`]).
568    pub const fn meter(&self) -> Option<Address> {
569        self.meter
570    }
571
572    /// A compact frame expanded with a layout from `formats` into `out`, as an
573    /// application with the same meter, header and authenticity and the full records
574    /// ([`Compact::expand`](crate::compact::Compact::expand)); any other body is
575    /// [`Error::UnsupportedCi`].
576    pub fn expand<'o, F: crate::compact::Formats + ?Sized>(
577        &self,
578        formats: &F,
579        out: &'o mut [u8],
580    ) -> Result<Application<'o>> {
581        let Body::Compact(c) = &self.body else { return Err(Error::UnsupportedCi(self.ci)) };
582        let records = c.expand(formats, out)?;
583        Ok(Application {
584            ell: self.ell,
585            afl: self.afl,
586            ci: self.ci,
587            header: self.header,
588            authenticity: self.authenticity,
589            body: Body::Records(records),
590            meter: self.meter,
591        })
592    }
593
594    /// The records, if the body is plain records.
595    pub fn records(&self) -> Option<Records<'a>> {
596        match &self.body {
597            Body::Records(r) => Some(r.clone()),
598            _ => None,
599        }
600    }
601}
602
603#[cfg(feature = "oms")]
604impl Encrypted<'_> {
605    /// Decrypt (and, for mode 7 with an AFL MAC and mode 10, authenticate) this layer into `out`,
606    /// and parse what is inside.
607    ///
608    /// | Security | Key | Verified by | Authenticity |
609    /// |---|---|---|---|
610    /// | mode 5 | the meter's | `2F 2F` | [`Authenticity::Encrypted`] |
611    /// | mode 7 | derived from the meter's and the AFL counter | AFL CMAC, then `2F 2F` | [`Authenticity::Authenticated`] (without a MAC: `Encrypted`) |
612    /// | mode 10 | derived from the meter's and the TPL counter | CCM tag | [`Authenticity::Authenticated`] |
613    /// | ELL | the meter's | payload CRC | `Encrypted`; the inner layers may add more |
614    ///
615    /// `out` needs `self.data.len()` bytes. On any failed check the result is an error
616    /// naming the check ([`Check`]), never partial records and never key material. A
617    /// transport layer that is not data records (alarm, error, compact) is
618    /// [`Error::UnsupportedCi`]. An ELL may contain a TPL that is itself encrypted: the
619    /// result's body is then [`Body::Encrypted`] again ([`wireless::open`](crate::wireless::open)
620    /// opens both).
621    pub fn decrypt<'o, K: crate::oms::Keys + ?Sized>(
622        &self,
623        keys: &K,
624        out: &'o mut [u8],
625    ) -> Result<Application<'o>> {
626        use crate::oms;
627        // Modes 5, 7 and 10 decrypt into data records only. An encrypted alarm, error,
628        // empty, format or compact transport layer has no public vector (for compact
629        // frames: whether 2F 2F is inside the full-frame CRC): refused, never misread as
630        // records. ELL-encrypted compact frames, the common case, work.
631        if self.security != Security::EllCtr && !matches!(tpl_layout(self.ctx.ci), Ok((_, Kind::Records))) {
632            return Err(Error::UnsupportedCi(self.ctx.ci));
633        }
634        let meter = self.meter.ok_or(Error::NoKey)?;
635        let key = keys.key(&meter).ok_or(Error::NoKey)?;
636        let buf = out.get_mut(..self.data.len()).ok_or(Error::OutputTooSmall)?;
637        buf.copy_from_slice(self.data);
638        let ctx = &self.ctx;
639        let authenticity = match self.security {
640            Security::EllCtr => {
641                oms::ctr_apply(key, &ctx.iv, buf);
642                let plain: &'o [u8] = buf;
643                let (crc, rest) = plain.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
644                if crc16(rest) != u16::from_le_bytes(*crc) {
645                    return Err(Error::Verification(Check::PayloadCrc));
646                }
647                let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
648                let inner = Context { link: ctx.link, ell: ctx.ell, inside_ell: true, ..Context::default() };
649                let mut app = parse_layers(next, rest, inner, Stage::Afl)?;
650                if !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
651                    app.authenticity = Authenticity::Encrypted;
652                }
653                return Ok(app);
654            }
655            Security::Mode5 => {
656                let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
657                oms::cbc_decrypt(key, &ctx.iv, enc)?;
658                Authenticity::Encrypted
659            }
660            Security::Mode7 => {
661                let afl = ctx.afl.ok_or(Error::Verification(Check::MissingCounter))?;
662                let counter = afl.counter.ok_or(Error::Verification(Check::MissingCounter))?;
663                let c = counter.to_le_bytes();
664                let mut authenticity = Authenticity::Encrypted;
665                // The message control announces a MAC (AT 5–7) that is not there: stripped.
666                if afl.mac().is_empty() && afl.mcl.and_then(mac_len).is_some() {
667                    return Err(Error::Verification(Check::Mac));
668                }
669                if !afl.mac().is_empty() {
670                    // Whether ML is in the MAC input must not hang on the FCL alone, which
671                    // the MAC does not cover: the MCL's ML-present bit (MLMP, 6) has to agree.
672                    if afl.mcl.map(|m| m & 0x40 != 0) != Some(afl.length.is_some()) {
673                        return Err(Error::Verification(Check::Mac));
674                    }
675                    // OMS Vol. 2 §9.3.3: CMAC(Kmac, MCL ‖ MCR ‖ [ML] ‖ TPL CI … end), verified
676                    // over the ciphertext before decrypting.
677                    let kmac = oms::derive(key, 0x01, c, meter.id);
678                    let ml = afl.length.map(u16::to_le_bytes);
679                    let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
680                    let tag = oms::cmac(
681                        &kmac,
682                        &[
683                            &[afl.mcl.unwrap_or(0)],
684                            &c,
685                            ml.as_ref().map_or(&[][..], |m| &m[..]),
686                            &[ctx.ci],
687                            header,
688                            self.data,
689                        ],
690                    );
691                    let mac = afl.mac();
692                    if !oms::mac_matches(tag.get(..mac.len()).unwrap_or(&[]), mac) {
693                        return Err(Error::Verification(Check::Mac));
694                    }
695                    authenticity = Authenticity::Authenticated { counter };
696                }
697                let kenc = oms::derive(key, 0x00, c, meter.id);
698                let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
699                oms::cbc_decrypt(&kenc, &[0; 16], enc)?;
700                authenticity
701            }
702            Security::Mode10 => return self.open_ccm(key, meter, buf),
703            Security::Other(mode) => return Err(Error::UnsupportedSecurity(mode)),
704        };
705        let plain: &'o [u8] = buf;
706        // The bytes after the ciphertext: covered by the MAC, by a decrypted ELL around
707        // this layer, or by nothing.
708        let tail = match authenticity {
709            Authenticity::Authenticated { .. } => authenticity,
710            _ if ctx.inside_ell => Authenticity::Encrypted,
711            _ => Authenticity::None,
712        };
713        if !plain.starts_with(&[0x2F, 0x2F]) {
714            return Err(Error::Verification(Check::Marker));
715        }
716        let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
717        Ok(Application {
718            ell: ctx.ell,
719            afl: ctx.afl,
720            ci,
721            header,
722            authenticity,
723            body: Body::Records(Records::protected(plain, self.encrypted_len, authenticity, tail)),
724            meter: self.meter,
725        })
726    }
727
728    /// Mode 10: verify the CCM tag and decrypt (OMS Vol. 2 §9.3.7).
729    fn open_ccm<'o>(
730        &self,
731        key: &crate::oms::Key,
732        meter: Address,
733        buf: &'o mut [u8],
734    ) -> Result<Application<'o>> {
735        use crate::oms;
736        let ctx = &self.ctx;
737        // OMS Vol. 2 §9.3.7: Kenc from the TPL counter; nonce M ‖ A ‖ 00 ‖ counter
738        // (big-endian); associated data CI ‖ TPL header ‖ CFE ‖ [key version] ‖ the
739        // unencrypted tail, if any.
740        let counter = ctx.counter.ok_or(Error::Verification(Check::MissingCounter))?;
741        let kenc = oms::derive(key, 0x00, counter.to_le_bytes(), meter.id);
742        let [m0, m1, i0, i1, i2, i3, v, t] = meter.to_bytes();
743        let [c0, c1, c2, c3] = counter.to_be_bytes();
744        let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
745        let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
746        // Bytes after the encrypted part are authenticated as associated data, or the
747        // telegram is refused: a tail outside the tag would let anyone append records to
748        // an "authenticated" message (EN 13757-7 itself is not public).
749        let tail = self.data.get(self.encrypted_len..).unwrap_or(&[]);
750        let mut aad = [0u8; 1 + 16 + 256];
751        let aad_len = 1 + header.len() + tail.len();
752        if let Some((first, rest)) = aad.split_first_mut() {
753            *first = ctx.ci;
754            rest.get_mut(..header.len()).ok_or(Error::InvalidLength)?.copy_from_slice(header);
755            rest.get_mut(header.len()..header.len() + tail.len())
756                .ok_or(Error::InvalidLength)?
757                .copy_from_slice(tail);
758        }
759        let tag = ctx.tag.get(..usize::from(ctx.tag_len)).unwrap_or(&[]);
760        let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
761        oms::ccm_decrypt(&kenc, &nonce, aad.get(..aad_len).unwrap_or(&[]), enc, tag)?;
762        let plain: &'o [u8] = buf;
763        let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
764        Ok(Application {
765            ell: ctx.ell,
766            afl: ctx.afl,
767            ci,
768            header,
769            authenticity: Authenticity::Authenticated { counter },
770            body: Body::Records(Records::protected(
771                plain,
772                self.encrypted_len,
773                Authenticity::Authenticated { counter },
774                Authenticity::Authenticated { counter },
775            )),
776            meter: self.meter,
777        })
778    }
779}
780
781/// Which layers may still come: each at most once, in this order.
782#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
783enum Stage {
784    Ell,
785    Afl,
786    Tpl,
787}
788
789fn address_id_first(b: [u8; 8]) -> Address {
790    let [i0, i1, i2, i3, m0, m1, version, medium] = b;
791    Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium])
792}
793
794#[allow(clippy::too_many_lines)]
795fn parse_layers(ci: u8, data: &[u8], mut ctx: Context, stage: Stage) -> Result<Application<'_>> {
796    match ci {
797        ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN => {
798            if stage > Stage::Ell {
799                return Err(Error::UnexpectedLayer(ci));
800            }
801            let (&[cc, access], mut rest) = data.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
802            let mut ell = Ell { cc, access_number: access, receiver: None, session: None };
803            if matches!(ci, ci::ELL_LONG | ci::ELL_LONG_SN) {
804                let (a, r) = rest.split_first_chunk::<8>().ok_or(Error::UnexpectedEnd)?;
805                ell.receiver = Some(Address::from_link_bytes(*a));
806                rest = r;
807            }
808            if matches!(ci, ci::ELL_SHORT_SN | ci::ELL_LONG_SN) {
809                let (sn, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
810                let session = u32::from_le_bytes(*sn);
811                ell.session = Some(session);
812                ctx.ell = Some(ell);
813                if ell.encrypted() {
814                    // IV: M ‖ A of the transmitter ‖ CC without H and R ‖ SN ‖ FN 0 ‖ BC 0.
815                    let mut iv = [0u8; 16];
816                    if let Some(link) = ctx.link {
817                        let [a, b, c, d, e, f, g, h] = link.to_bytes();
818                        let [s0, s1, s2, s3] = *sn;
819                        iv = [a, b, c, d, e, f, g, h, cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
820                    }
821                    ctx.iv = iv;
822                    return Ok(Application {
823                        ell: Some(ell),
824                        afl: None,
825                        ci,
826                        header: Header::None,
827                        authenticity: Authenticity::None,
828                        meter: ctx.link,
829                        body: Body::Encrypted(Encrypted {
830                            security: Security::EllCtr,
831                            data: r,
832                            encrypted_len: r.len(),
833                            meter: ctx.link,
834                            ctx,
835                        }),
836                    });
837                }
838                // Not encrypted: the payload CRC is plain and covers the rest.
839                let (crc, r) = r.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
840                if crc16(r) != u16::from_le_bytes(*crc) {
841                    return Err(Error::Verification(Check::PayloadCrc));
842                }
843                rest = r;
844            }
845            ctx.ell = Some(ell);
846            let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
847            parse_layers(next, rest, ctx, Stage::Afl)
848        }
849        ci::AFL => {
850            if stage > Stage::Afl {
851                return Err(Error::UnexpectedLayer(ci));
852            }
853            let (&len, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
854            let afl_bytes = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
855            let rest = rest.get(usize::from(len)..).ok_or(Error::UnexpectedEnd)?;
856            let afl = parse_afl(afl_bytes)?;
857            ctx.afl = Some(afl);
858            if afl.fragment_id() != 0 {
859                // OMS Vol. 2 §7.3: only the first fragment carries the TPL, cut anywhere.
860                return Ok(Application {
861                    ell: ctx.ell,
862                    afl: Some(afl),
863                    ci,
864                    header: Header::None,
865                    authenticity: Authenticity::None,
866                    body: Body::Fragment(rest),
867                    meter: ctx.link,
868                });
869            }
870            let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
871            parse_layers(next, rest, ctx, Stage::Tpl)
872        }
873        _ => parse_tpl(ci, data, ctx),
874    }
875}
876
877/// AT 5, 6, 7: AES-CMAC truncated to 8, 12, 16 bytes (OMS Vol. 2 §6.2.1).
878pub(crate) const fn mac_len(mcl: u8) -> Option<usize> {
879    match mcl & 0x0F {
880        5 => Some(8),
881        6 => Some(12),
882        7 => Some(16),
883        _ => None,
884    }
885}
886
887fn parse_afl(b: &[u8]) -> Result<Afl> {
888    let (fcl, mut rest) = b.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
889    let fcl = u16::from_le_bytes(*fcl);
890    let mut afl =
891        Afl { fcl, mcl: None, key_info: None, counter: None, length: None, mac: [0; 16], mac_len: 0 };
892    if fcl & 0x2000 != 0 {
893        let (&mcl, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
894        afl.mcl = Some(mcl);
895        rest = r;
896    }
897    if fcl & 0x0200 != 0 {
898        let (ki, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
899        afl.key_info = Some(u16::from_le_bytes(*ki));
900        rest = r;
901    }
902    if fcl & 0x0800 != 0 {
903        let (c, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
904        afl.counter = Some(u32::from_le_bytes(*c));
905        rest = r;
906    }
907    if fcl & 0x0400 != 0 {
908        // With MCL: its authentication type sets the length. Without (the last fragment of
909        // a message, OMS Vol. 2 §6.2.4): the MAC fills the AFL up to the ML field.
910        let n = match afl.mcl {
911            Some(mcl) => mac_len(mcl).ok_or(Error::InvalidLength)?,
912            None => rest.len().saturating_sub(if fcl & 0x1000 != 0 { 2 } else { 0 }),
913        };
914        if !matches!(n, 8 | 12 | 16) {
915            return Err(Error::InvalidLength);
916        }
917        let mac = rest.get(..n).ok_or(Error::UnexpectedEnd)?;
918        afl.mac.get_mut(..n).ok_or(Error::InvalidLength)?.copy_from_slice(mac);
919        afl.mac_len = u8::try_from(n).map_err(|_| Error::InvalidLength)?;
920        rest = rest.get(n..).unwrap_or(&[]);
921    }
922    if fcl & 0x1000 != 0 {
923        let (l, _) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
924        afl.length = Some(u16::from_le_bytes(*l));
925    }
926    Ok(afl)
927}
928
929#[derive(Clone, Copy)]
930enum Kind {
931    Records,
932    Error,
933    Alarm,
934    Empty,
935    Compact,
936    Format,
937}
938
939/// A transport layer's header length and what follows it, from its CI.
940fn tpl_layout(ci: u8) -> Result<(usize, Kind)> {
941    Ok(match ci {
942        ci::RSP_LONG | ci::CMD_LONG => (12, Kind::Records),
943        ci::RSP_SHORT | ci::CMD_SHORT => (4, Kind::Records),
944        ci::RSP_NONE | ci::SND_UD => (0, Kind::Records),
945        ci::ERROR_LONG => (12, Kind::Error),
946        ci::ERROR_SHORT => (4, Kind::Error),
947        ci::ERROR_NONE => (0, Kind::Error),
948        ci::ALARM_LONG => (12, Kind::Alarm),
949        ci::ALARM_SHORT => (4, Kind::Alarm),
950        ci::ALARM_NONE => (0, Kind::Alarm),
951        ci::TPL_TO_DEVICE | ci::TPL_LONG => (12, Kind::Empty),
952        ci::TPL_SHORT => (4, Kind::Empty),
953        ci::COMPACT_NONE => (0, Kind::Compact),
954        ci::COMPACT_SHORT => (4, Kind::Compact),
955        ci::COMPACT_LONG => (12, Kind::Compact),
956        ci::FORMAT_NONE => (0, Kind::Format),
957        ci::FORMAT_SHORT => (4, Kind::Format),
958        ci::FORMAT_LONG => (12, Kind::Format),
959        ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN | ci::AFL => {
960            return Err(Error::UnexpectedLayer(ci));
961        }
962        other => return Err(Error::UnsupportedCi(other)),
963    })
964}
965
966#[allow(clippy::too_many_lines)] // one table-driven pass over the transport header
967fn parse_tpl(ci: u8, data: &[u8], mut ctx: Context) -> Result<Application<'_>> {
968    let (len, kind) = tpl_layout(ci)?;
969    let head = data.get(..len).ok_or(Error::UnexpectedEnd)?;
970    let mut rest = data.get(len..).ok_or(Error::UnexpectedEnd)?;
971    let header = match *head {
972        [i0, i1, i2, i3, m0, m1, version, medium, access, status, c0, c1] => Header::Long(LongHeader {
973            address: address_id_first([i0, i1, i2, i3, m0, m1, version, medium]),
974            short: ShortHeader {
975                access_number: access,
976                status,
977                config: [c0, c1],
978                config_ext: None,
979                counter: None,
980            },
981        }),
982        [access, status, c0, c1] => Header::Short(ShortHeader {
983            access_number: access,
984            status,
985            config: [c0, c1],
986            config_ext: None,
987            counter: None,
988        }),
989        _ => Header::None,
990    };
991    let security = header.security();
992    let mut header = header;
993    let mut header_len = len;
994    // Bytes after the fixed header that belong to it: the CFE, a key version.
995    let mut ext = [0u8; 3];
996    let mut ext_len = 0usize;
997    if security.mode == 7 {
998        // Mode 7 has a configuration field extension byte (OMS Vol. 2 Table 21).
999        let (&cfe, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1000        rest = r;
1001        ext[0] = cfe;
1002        ext_len = 1;
1003        if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1004            s.config_ext = Some(u16::from(cfe));
1005        }
1006    }
1007    if security.mode == 10 {
1008        // Mode 10: CFE (2 bytes), key version if CFE bit 6, message counter (4) (OMS Vol. 2
1009        // §7.2.4.5); the tag is the end of the message.
1010        let (cfe, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1011        let [e0, e1] = *cfe;
1012        rest = r;
1013        ext = [e0, e1, 0];
1014        ext_len = 2;
1015        let cfe = u16::from_le_bytes([e0, e1]);
1016        if cfe & 0x0040 != 0 {
1017            let (&kv, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1018            rest = r;
1019            ext[2] = kv;
1020            ext_len = 3;
1021        }
1022        let (mc, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
1023        rest = r;
1024        let counter = u32::from_le_bytes(*mc);
1025        ctx.counter = Some(counter);
1026        let tag_len = 4 + 4 * usize::from((cfe >> 8) & 0x03);
1027        let split = rest.len().checked_sub(tag_len).ok_or(Error::UnexpectedEnd)?;
1028        let (data, tag) = rest.split_at(split);
1029        ctx.tag.get_mut(..tag_len).ok_or(Error::InvalidLength)?.copy_from_slice(tag);
1030        ctx.tag_len = u8::try_from(tag_len).map_err(|_| Error::InvalidLength)?;
1031        rest = data;
1032        if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1033            s.config_ext = Some(cfe);
1034            s.counter = Some(counter);
1035        }
1036    }
1037    header_len += ext_len;
1038    let meter = match header {
1039        Header::Long(l) => Some(l.address),
1040        _ => ctx.link,
1041    };
1042    let app = |body| Application {
1043        ell: ctx.ell,
1044        afl: ctx.afl,
1045        ci,
1046        header,
1047        authenticity: Authenticity::None,
1048        body,
1049        meter,
1050    };
1051    // Mode 10 is always opened: with nothing encrypted the tag still authenticates.
1052    // Only modes 5 and 7 count 16-byte blocks in NNNN (0 = plaintext). Mode 10 is always
1053    // opened (with nothing encrypted the tag still authenticates); any other mode (13: TLS)
1054    // has its own layout and stays encrypted.
1055    if security.mode == 0 || (security.encrypted_blocks == 0 && matches!(security.mode, 5 | 7)) {
1056        let body = match kind {
1057            // Behind a decrypted ELL every byte came out of the ciphertext.
1058            Kind::Records if ctx.inside_ell => Body::Records(Records::protected(
1059                rest,
1060                rest.len(),
1061                Authenticity::Encrypted,
1062                Authenticity::Encrypted,
1063            )),
1064            Kind::Records => Body::Records(Records::new(rest)),
1065            Kind::Error => Body::ApplicationError(rest),
1066            Kind::Alarm => Body::Alarm(rest),
1067            Kind::Empty => Body::Empty,
1068            Kind::Compact => Body::Compact(crate::compact::Compact::parse(rest, ctx.inside_ell)?),
1069            Kind::Format => {
1070                let (&len, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1071                let body = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
1072                let (sig, headers) = body.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1073                let format = crate::compact::Format::received(u16::from_le_bytes(*sig), headers)
1074                    .ok_or(Error::Verification(Check::FullFrameCrc))?;
1075                Body::Format(format)
1076            }
1077        };
1078        return Ok(app(body));
1079    }
1080    let encrypted_len = if security.mode == 10 {
1081        // Mode 10 counts encrypted bytes in the whole low byte; FF means everything.
1082        match header.short().map_or(0, |s| s.config[0]) {
1083            0xFF => rest.len(),
1084            n => usize::from(n),
1085        }
1086    } else if security.encrypted_blocks == 0x0F || !matches!(security.mode, 5 | 7) {
1087        // 15 blocks means "to the end"; other modes: the whole rest is opaque.
1088        rest.len()
1089    } else {
1090        usize::from(security.encrypted_blocks) * 16
1091    };
1092    if encrypted_len > rest.len() || (matches!(security.mode, 5 | 7) && encrypted_len % 16 != 0) {
1093        return Err(Error::Verification(Check::Length));
1094    }
1095    let security = match security.mode {
1096        5 => Security::Mode5,
1097        7 => Security::Mode7,
1098        10 => Security::Mode10,
1099        other => Security::Other(other),
1100    };
1101    if let (Security::Mode5, Some(m), Some(s)) = (security, meter, header.short()) {
1102        let [a, b, c, d, e, f, g, h] = m.to_bytes();
1103        let x = s.access_number;
1104        ctx.iv = [a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x];
1105    }
1106    ctx.ci = ci;
1107    ctx.header.get_mut(..len).ok_or(Error::InvalidLength)?.copy_from_slice(head);
1108    ctx.header
1109        .get_mut(len..len + ext_len)
1110        .ok_or(Error::InvalidLength)?
1111        .copy_from_slice(ext.get(..ext_len).unwrap_or(&[]));
1112    ctx.header_len = u8::try_from(header_len).map_err(|_| Error::InvalidLength)?;
1113    ctx.tpl = Some((ci, header));
1114    Ok(app(Body::Encrypted(Encrypted { security, data: rest, encrypted_len, meter, ctx })))
1115}
1116
1117#[cfg(test)]
1118mod tests {
1119    extern crate std;
1120    use super::*;
1121    use std::string::ToString;
1122
1123    #[test]
1124    fn manufacturer_codes() {
1125        assert_eq!(Manufacturer(0x4024).to_string(), "PAD");
1126        let kam = Manufacturer::from_letters(*b"KAM").unwrap();
1127        assert_eq!(kam.0, 0x2C2D);
1128        assert_eq!(kam.to_string(), "KAM");
1129        assert_eq!(Manufacturer::from_letters(*b"k1m"), None);
1130    }
1131
1132    #[test]
1133    fn security_mode_from_config() {
1134        // OMS mode 5 with 1 encrypted block: configuration 0x0510, sent as 10 05.
1135        let s = SecurityMode::from_config([0x10, 0x05]);
1136        assert_eq!(s, SecurityMode { mode: 5, encrypted_blocks: 1 });
1137        let mut data = [0u8; 4 + 18];
1138        data[..4].copy_from_slice(&[0x01, 0x00, 0x10, 0x05]);
1139        let app = Application::parse(ci::RSP_SHORT, &data).unwrap();
1140        let Body::Encrypted(e) = app.body else { panic!() };
1141        assert_eq!((e.security, e.encrypted_len, e.data.len()), (Security::Mode5, 16, 18));
1142        // More blocks announced than present.
1143        assert_eq!(
1144            Application::parse(ci::RSP_SHORT, &data[..10]).unwrap_err(),
1145            Error::Verification(Check::Length)
1146        );
1147    }
1148
1149    // 002-oms-security/SR-004: each layer once, in order.
1150    #[test]
1151    fn layer_order_is_enforced() {
1152        assert_eq!(Application::parse(0x7A, &[0, 0, 0, 0]).unwrap().authenticity, Authenticity::None);
1153        // AFL after the TPL is not a TPL.
1154        assert_eq!(
1155            Application::parse(0x90, &[0x02, 0x00, 0x00, 0x8C, 0, 0, 0x78]).unwrap_err(),
1156            Error::UnexpectedLayer(0x8C)
1157        );
1158        assert_eq!(
1159            Application::parse(0x8C, &[0x20, 0x01, 0x8C, 0, 0, 0x78]).unwrap_err(),
1160            Error::UnexpectedLayer(0x8C)
1161        );
1162        assert_eq!(Application::parse(0x42, &[]).unwrap_err(), Error::UnsupportedCi(0x42));
1163    }
1164
1165    #[cfg(feature = "oms")]
1166    fn meter() -> Address {
1167        Address {
1168            manufacturer: Manufacturer(0x1593),
1169            id: [0x78, 0x56, 0x34, 0x12],
1170            version: 0x33,
1171            medium: Medium::GAS,
1172        }
1173    }
1174
1175    /// A mode-7 transport layer behind an AFL with MAC and ML (FCL `3C00`), its MAC
1176    /// computed with ML in the input, and message control `mcl`.
1177    #[cfg(feature = "oms")]
1178    fn mode_7_with_ml(mcl: u8, key: &crate::oms::Key) -> std::vec::Vec<u8> {
1179        use crate::oms;
1180        let counter = 7u32.to_le_bytes();
1181        let ml = 22u16.to_le_bytes(); // TPL CI … end: 1 + 5 + 16
1182        let mut plain = [0x2F; 16];
1183        plain[2..5].copy_from_slice(&[0x01, 0x13, 0x05]);
1184        oms::cbc_encrypt(&oms::derive(key, 0, counter, meter().id), &[0; 16], &mut plain).unwrap();
1185        let tpl = [&[ci::RSP_SHORT, 1, 0, 0x10, 0x07, 0x10][..], &plain].concat();
1186        let tag = oms::cmac(&oms::derive(key, 1, counter, meter().id), &[&[mcl], &counter, &ml, &tpl]);
1187        [&[17, 0x00, 0x3C, mcl][..], &counter, &tag[..8], &ml, &tpl].concat()
1188    }
1189
1190    #[cfg(feature = "oms")]
1191    #[test]
1192    fn ml_in_the_mac_input_needs_the_mcl_to_say_so() {
1193        // Independent review 2026-11-30: the FCL (outside the MAC) alone decided whether ML
1194        // was part of the MAC input. MCL 65 announces ML (MLMP); MCL 25 does not.
1195        let key = crate::oms::Key::new([0x42; 16]);
1196        let mut out = [0u8; 64];
1197        for (mcl, ok) in [(0x65, true), (0x25, false)] {
1198            let data = mode_7_with_ml(mcl, &key);
1199            let app = Application::parse_with_link(ci::AFL, &data, Some(meter())).unwrap();
1200            let Body::Encrypted(e) = &app.body else { panic!() };
1201            let r = e.decrypt(&key, &mut out);
1202            if ok {
1203                assert_eq!(r.unwrap().authenticity, Authenticity::Authenticated { counter: 7 });
1204            } else {
1205                assert_eq!(r.unwrap_err(), Error::Verification(Check::Mac));
1206            }
1207        }
1208    }
1209
1210    #[cfg(feature = "oms")]
1211    #[test]
1212    fn decryption_yields_records_only_for_a_records_ci() {
1213        // Independent review 2026-11-30: an encrypted alarm (CI 74) decrypted into
1214        // invented records. Correctly encrypted, it is refused by its CI.
1215        use crate::oms;
1216        let key = oms::Key::new([0x42; 16]);
1217        let mut plain = [0x2F; 16];
1218        plain[2..5].copy_from_slice(&[0x01, 0x13, 0x05]);
1219        let [a, b, c, d, e, f, g, h] = meter().to_bytes();
1220        oms::cbc_encrypt(&key, &[a, b, c, d, e, f, g, h, 1, 1, 1, 1, 1, 1, 1, 1], &mut plain).unwrap();
1221        let mut out = [0u8; 64];
1222        for (ci, ok) in [
1223            (ci::RSP_SHORT, true),
1224            (ci::ALARM_SHORT, false),
1225            (ci::ERROR_SHORT, false),
1226            (ci::TPL_SHORT, false),
1227        ] {
1228            let data = [&[1, 0, 0x10, 0x05][..], &plain].concat();
1229            let app = Application::parse_with_link(ci, &data, Some(meter())).unwrap();
1230            let Body::Encrypted(enc) = &app.body else { panic!("{ci:02X}") };
1231            match enc.decrypt(&key, &mut out) {
1232                Ok(inner) => assert!(ok && inner.records().is_some(), "{ci:02X}"),
1233                Err(err) => assert!(!ok && err == Error::UnsupportedCi(ci), "{ci:02X}: {err:?}"),
1234            }
1235        }
1236    }
1237}