use core::fmt;
use crate::crc::crc16;
use crate::record::Records;
use crate::{Check, Error, Result};
pub mod ci {
pub const RSP_LONG: u8 = 0x72;
pub const RSP_SHORT: u8 = 0x7A;
pub const RSP_NONE: u8 = 0x78;
pub const SND_UD: u8 = 0x51;
pub const CMD_SHORT: u8 = 0x5A;
pub const CMD_LONG: u8 = 0x5B;
pub const ERROR_SHORT: u8 = 0x6E;
pub const ERROR_LONG: u8 = 0x6F;
pub const ERROR_NONE: u8 = 0x70;
pub const ALARM_NONE: u8 = 0x71;
pub const ALARM_SHORT: u8 = 0x74;
pub const ALARM_LONG: u8 = 0x75;
pub const TPL_TO_DEVICE: u8 = 0x80;
pub const TPL_SHORT: u8 = 0x8A;
pub const TPL_LONG: u8 = 0x8B;
pub const ELL_SHORT: u8 = 0x8C;
pub const ELL_SHORT_SN: u8 = 0x8D;
pub const ELL_LONG: u8 = 0x8E;
pub const ELL_LONG_SN: u8 = 0x8F;
pub const AFL: u8 = 0x90;
pub const FORMAT_NONE: u8 = 0x69;
pub const FORMAT_SHORT: u8 = 0x6A;
pub const FORMAT_LONG: u8 = 0x6B;
pub const COMPACT_NONE: u8 = 0x79;
pub const COMPACT_SHORT: u8 = 0x7B;
pub const COMPACT_LONG: u8 = 0x73;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Manufacturer(pub u16);
impl Manufacturer {
pub const fn from_letters(l: [u8; 3]) -> Option<Self> {
let [a, b, c] = l;
if !a.is_ascii_uppercase() || !b.is_ascii_uppercase() || !c.is_ascii_uppercase() {
return None;
}
Some(Self((((a - 64) as u16) << 10) | (((b - 64) as u16) << 5) | ((c - 64) as u16)))
}
pub const fn letters(self) -> [u8; 3] {
let v = self.0;
[(((v >> 10) & 0x1F) as u8) + 64, (((v >> 5) & 0x1F) as u8) + 64, ((v & 0x1F) as u8) + 64]
}
}
impl fmt::Display for Manufacturer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for b in self.letters() {
write!(f, "{}", char::from(b))?;
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Medium(pub u8);
impl Medium {
pub const ELECTRICITY: Self = Self(0x02);
pub const GAS: Self = Self(0x03);
pub const HEAT: Self = Self(0x04);
pub const WARM_WATER: Self = Self(0x06);
pub const WATER: Self = Self(0x07);
pub const HEAT_COST_ALLOCATOR: Self = Self(0x08);
pub const COOLING: Self = Self(0x0A);
pub const HEAT_INLET: Self = Self(0x0C);
pub const HEAT_COOLING: Self = Self(0x0D);
pub const HOT_WATER: Self = Self(0x15);
pub const COLD_WATER: Self = Self(0x16);
pub const fn name(self) -> Option<&'static str> {
Some(match self.0 {
0x00 => "other",
0x01 => "oil",
0x02 => "electricity",
0x03 => "gas",
0x04 => "heat (outlet)",
0x05 => "steam",
0x06 => "warm water",
0x07 => "water",
0x08 => "heat cost allocator",
0x09 => "compressed air",
0x0A => "cooling (outlet)",
0x0B => "cooling (inlet)",
0x0C => "heat (inlet)",
0x0D => "heat / cooling",
0x0E => "bus / system",
0x0F => "unknown",
0x15 => "hot water",
0x16 => "cold water",
0x17 => "dual water",
0x18 => "pressure",
0x19 => "A/D converter",
0x1A => "smoke detector",
0x1B => "room sensor",
0x1C => "gas detector",
0x20 => "breaker (electricity)",
0x21 => "valve (gas or water)",
0x25 => "customer unit (display)",
0x28 => "waste water",
0x29 => "garbage",
0x31 => "communication controller",
0x32 => "unidirectional repeater",
0x33 => "bidirectional repeater",
0x36 => "radio converter (system side)",
0x37 => "radio converter (meter side)",
0x38 => "wired adapter",
_ => return None,
})
}
}
impl fmt::Display for Medium {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.name() {
Some(n) => f.write_str(n),
None => write!(f, "medium 0x{:02x}", self.0),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Address {
pub manufacturer: Manufacturer,
pub id: [u8; 4],
pub version: u8,
pub medium: Medium,
}
impl Address {
pub fn id_number(&self) -> Option<u32> {
crate::value::bcd_u32(self.id)
}
pub const fn to_bytes(self) -> [u8; 8] {
let [m0, m1] = self.manufacturer.0.to_le_bytes();
let [i0, i1, i2, i3] = self.id;
[m0, m1, i0, i1, i2, i3, self.version, self.medium.0]
}
pub const fn from_link_bytes(b: [u8; 8]) -> Self {
let [m0, m1, i0, i1, i2, i3, version, medium] = b;
Self {
manufacturer: Manufacturer(u16::from_le_bytes([m0, m1])),
id: [i0, i1, i2, i3],
version,
medium: Medium(medium),
}
}
}
impl fmt::Display for Address {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(n) = self.id_number() {
write!(f, "{} {n:08} {} v{}", self.manufacturer, self.medium, self.version)
} else {
let [a, b, c, d] = self.id;
write!(f, "{} {d:02X}{c:02X}{b:02X}{a:02X} {} v{}", self.manufacturer, self.medium, self.version)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SecurityMode {
pub mode: u8,
pub encrypted_blocks: u8,
}
impl SecurityMode {
pub const fn from_config(config: [u8; 2]) -> Self {
let [low, high] = config;
Self { mode: high & 0x1F, encrypted_blocks: low >> 4 }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShortHeader {
pub access_number: u8,
pub status: u8,
pub config: [u8; 2],
pub config_ext: Option<u16>,
pub counter: Option<u32>,
}
impl ShortHeader {
pub const fn security(&self) -> SecurityMode {
SecurityMode::from_config(self.config)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LongHeader {
pub address: Address,
pub short: ShortHeader,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Header {
None,
Short(ShortHeader),
Long(LongHeader),
}
impl Header {
pub const fn security(&self) -> SecurityMode {
match self {
Self::None => SecurityMode { mode: 0, encrypted_blocks: 0 },
Self::Short(s) => s.security(),
Self::Long(l) => l.short.security(),
}
}
pub const fn short(&self) -> Option<&ShortHeader> {
match self {
Self::None => None,
Self::Short(s) | Self::Long(LongHeader { short: s, .. }) => Some(s),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Ell {
pub cc: u8,
pub access_number: u8,
pub receiver: Option<Address>,
pub session: Option<u32>,
}
impl Ell {
pub const fn encrypted(&self) -> bool {
matches!(self.session, Some(sn) if sn >> 29 == 1)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Afl {
pub fcl: u16,
pub mcl: Option<u8>,
pub key_info: Option<u16>,
pub counter: Option<u32>,
pub length: Option<u16>,
mac: [u8; 16],
mac_len: u8,
}
impl Afl {
pub const fn more_fragments(&self) -> bool {
self.fcl & 0x4000 != 0
}
pub const fn fragment_id(&self) -> u8 {
self.fcl.to_le_bytes()[0]
}
pub(crate) const fn joined(first: &Self, last: &Self) -> Self {
Self {
fcl: (first.fcl & 0x3A00) | (last.fcl & 0x04FF),
mcl: first.mcl,
key_info: first.key_info,
counter: first.counter,
length: first.length,
mac: last.mac,
mac_len: last.mac_len,
}
}
pub fn mac(&self) -> &[u8] {
self.mac.get(..usize::from(self.mac_len)).unwrap_or(&[])
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Authenticity {
None,
Encrypted,
Authenticated {
counter: u32,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Security {
Mode5,
Mode7,
Mode10,
EllCtr,
Other(u8),
}
#[derive(Clone, Copy, Debug)]
pub struct Encrypted<'a> {
pub security: Security,
pub data: &'a [u8],
pub encrypted_len: usize,
pub meter: Option<Address>,
#[cfg_attr(not(feature = "oms"), allow(dead_code))]
pub(crate) ctx: Context,
}
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(not(feature = "oms"), allow(dead_code))]
pub(crate) struct Context {
pub(crate) iv: [u8; 16],
pub(crate) ci: u8,
pub(crate) header: [u8; 16],
pub(crate) header_len: u8,
pub(crate) ell: Option<Ell>,
pub(crate) afl: Option<Afl>,
pub(crate) tpl: Option<(u8, Header)>,
pub(crate) link: Option<Address>,
pub(crate) inside_ell: bool,
pub(crate) counter: Option<u32>,
pub(crate) tag: [u8; 16],
pub(crate) tag_len: u8,
}
#[derive(Clone, Debug)]
pub enum Body<'a> {
Records(Records<'a>),
Encrypted(Encrypted<'a>),
ApplicationError(&'a [u8]),
Alarm(&'a [u8]),
Empty,
Compact(crate::compact::Compact<'a>),
Format(crate::compact::Format<'a>),
Fragment(&'a [u8]),
}
#[derive(Clone, Debug)]
pub struct Application<'a> {
pub ell: Option<Ell>,
pub afl: Option<Afl>,
pub ci: u8,
pub header: Header,
pub authenticity: Authenticity,
pub body: Body<'a>,
meter: Option<Address>,
}
impl<'a> Application<'a> {
pub fn parse(ci: u8, data: &'a [u8]) -> Result<Self> {
Self::parse_with_link(ci, data, None)
}
pub fn parse_with_link(ci: u8, data: &'a [u8], link: Option<Address>) -> Result<Self> {
let ctx = Context { link, ..Context::default() };
parse_layers(ci, data, ctx, Stage::Ell)
}
pub(crate) fn reassembled(
data: &'a [u8],
afl: Afl,
ell: Option<Ell>,
link: Option<Address>,
decrypted: bool,
) -> Result<Self> {
let (&ci, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
let ctx = Context { link, ell, afl: Some(afl), inside_ell: decrypted, ..Context::default() };
let mut app = parse_layers(ci, rest, ctx, Stage::Tpl)?;
if decrypted && !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
app.authenticity = Authenticity::Encrypted;
}
Ok(app)
}
pub const fn meter(&self) -> Option<Address> {
self.meter
}
pub fn expand<'o, F: crate::compact::Formats + ?Sized>(
&self,
formats: &F,
out: &'o mut [u8],
) -> Result<Application<'o>> {
let Body::Compact(c) = &self.body else { return Err(Error::UnsupportedCi(self.ci)) };
let records = c.expand(formats, out)?;
Ok(Application {
ell: self.ell,
afl: self.afl,
ci: self.ci,
header: self.header,
authenticity: self.authenticity,
body: Body::Records(records),
meter: self.meter,
})
}
pub fn records(&self) -> Option<Records<'a>> {
match &self.body {
Body::Records(r) => Some(r.clone()),
_ => None,
}
}
}
#[cfg(feature = "oms")]
impl Encrypted<'_> {
pub fn decrypt<'o, K: crate::oms::Keys + ?Sized>(
&self,
keys: &K,
out: &'o mut [u8],
) -> Result<Application<'o>> {
use crate::oms;
let meter = self.meter.ok_or(Error::NoKey)?;
let key = keys.key(&meter).ok_or(Error::NoKey)?;
let buf = out.get_mut(..self.data.len()).ok_or(Error::OutputTooSmall)?;
buf.copy_from_slice(self.data);
let ctx = &self.ctx;
let authenticity = match self.security {
Security::EllCtr => {
oms::ctr_apply(key, &ctx.iv, buf);
let plain: &'o [u8] = buf;
let (crc, rest) = plain.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
if crc16(rest) != u16::from_le_bytes(*crc) {
return Err(Error::Verification(Check::PayloadCrc));
}
let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
let inner = Context { link: ctx.link, ell: ctx.ell, inside_ell: true, ..Context::default() };
let mut app = parse_layers(next, rest, inner, Stage::Afl)?;
if !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
app.authenticity = Authenticity::Encrypted;
}
return Ok(app);
}
Security::Mode5 => {
let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
oms::cbc_decrypt(key, &ctx.iv, enc)?;
Authenticity::Encrypted
}
Security::Mode7 => {
let afl = ctx.afl.ok_or(Error::Verification(Check::MissingCounter))?;
let counter = afl.counter.ok_or(Error::Verification(Check::MissingCounter))?;
let c = counter.to_le_bytes();
let mut authenticity = Authenticity::Encrypted;
if afl.mac().is_empty() && afl.mcl.and_then(mac_len).is_some() {
return Err(Error::Verification(Check::Mac));
}
if !afl.mac().is_empty() {
let kmac = oms::derive(key, 0x01, c, meter.id);
let ml = afl.length.map(u16::to_le_bytes);
let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
let tag = oms::cmac(
&kmac,
&[
&[afl.mcl.unwrap_or(0)],
&c,
ml.as_ref().map_or(&[][..], |m| &m[..]),
&[ctx.ci],
header,
self.data,
],
);
let mac = afl.mac();
if !oms::mac_matches(tag.get(..mac.len()).unwrap_or(&[]), mac) {
return Err(Error::Verification(Check::Mac));
}
authenticity = Authenticity::Authenticated { counter };
}
let kenc = oms::derive(key, 0x00, c, meter.id);
let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
oms::cbc_decrypt(&kenc, &[0; 16], enc)?;
authenticity
}
Security::Mode10 => return self.open_ccm(key, meter, buf),
Security::Other(mode) => return Err(Error::UnsupportedSecurity(mode)),
};
let plain: &'o [u8] = buf;
if matches!(ctx.ci, ci::COMPACT_SHORT | ci::COMPACT_LONG) {
return Err(Error::UnsupportedCi(ctx.ci));
}
if !plain.starts_with(&[0x2F, 0x2F]) {
return Err(Error::Verification(Check::Marker));
}
let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
Ok(Application {
ell: ctx.ell,
afl: ctx.afl,
ci,
header,
authenticity,
body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
meter: self.meter,
})
}
fn open_ccm<'o>(
&self,
key: &crate::oms::Key,
meter: Address,
buf: &'o mut [u8],
) -> Result<Application<'o>> {
use crate::oms;
let ctx = &self.ctx;
let counter = ctx.counter.ok_or(Error::Verification(Check::MissingCounter))?;
let kenc = oms::derive(key, 0x00, counter.to_le_bytes(), meter.id);
let [m0, m1, i0, i1, i2, i3, v, t] = meter.to_bytes();
let [c0, c1, c2, c3] = counter.to_be_bytes();
let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
let tail = self.data.get(self.encrypted_len..).unwrap_or(&[]);
let mut aad = [0u8; 1 + 16 + 256];
let aad_len = 1 + header.len() + tail.len();
if let Some((first, rest)) = aad.split_first_mut() {
*first = ctx.ci;
rest.get_mut(..header.len()).ok_or(Error::InvalidLength)?.copy_from_slice(header);
rest.get_mut(header.len()..header.len() + tail.len())
.ok_or(Error::InvalidLength)?
.copy_from_slice(tail);
}
let tag = ctx.tag.get(..usize::from(ctx.tag_len)).unwrap_or(&[]);
let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
oms::ccm_decrypt(&kenc, &nonce, aad.get(..aad_len).unwrap_or(&[]), enc, tag)?;
let plain: &'o [u8] = buf;
let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
Ok(Application {
ell: ctx.ell,
afl: ctx.afl,
ci,
header,
authenticity: Authenticity::Authenticated { counter },
body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
meter: self.meter,
})
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Stage {
Ell,
Afl,
Tpl,
}
fn address_id_first(b: [u8; 8]) -> Address {
let [i0, i1, i2, i3, m0, m1, version, medium] = b;
Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium])
}
#[allow(clippy::too_many_lines)]
fn parse_layers(ci: u8, data: &[u8], mut ctx: Context, stage: Stage) -> Result<Application<'_>> {
match ci {
ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN => {
if stage > Stage::Ell {
return Err(Error::UnexpectedLayer(ci));
}
let (&[cc, access], mut rest) = data.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
let mut ell = Ell { cc, access_number: access, receiver: None, session: None };
if matches!(ci, ci::ELL_LONG | ci::ELL_LONG_SN) {
let (a, r) = rest.split_first_chunk::<8>().ok_or(Error::UnexpectedEnd)?;
ell.receiver = Some(Address::from_link_bytes(*a));
rest = r;
}
if matches!(ci, ci::ELL_SHORT_SN | ci::ELL_LONG_SN) {
let (sn, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
let session = u32::from_le_bytes(*sn);
ell.session = Some(session);
ctx.ell = Some(ell);
if ell.encrypted() {
let mut iv = [0u8; 16];
if let Some(link) = ctx.link {
let [a, b, c, d, e, f, g, h] = link.to_bytes();
let [s0, s1, s2, s3] = *sn;
iv = [a, b, c, d, e, f, g, h, cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
}
ctx.iv = iv;
return Ok(Application {
ell: Some(ell),
afl: None,
ci,
header: Header::None,
authenticity: Authenticity::None,
meter: ctx.link,
body: Body::Encrypted(Encrypted {
security: Security::EllCtr,
data: r,
encrypted_len: r.len(),
meter: ctx.link,
ctx,
}),
});
}
let (crc, r) = r.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
if crc16(r) != u16::from_le_bytes(*crc) {
return Err(Error::Verification(Check::PayloadCrc));
}
rest = r;
}
ctx.ell = Some(ell);
let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
parse_layers(next, rest, ctx, Stage::Afl)
}
ci::AFL => {
if stage > Stage::Afl {
return Err(Error::UnexpectedLayer(ci));
}
let (&len, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
let afl_bytes = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
let rest = rest.get(usize::from(len)..).ok_or(Error::UnexpectedEnd)?;
let afl = parse_afl(afl_bytes)?;
ctx.afl = Some(afl);
if afl.fragment_id() != 0 {
return Ok(Application {
ell: ctx.ell,
afl: Some(afl),
ci,
header: Header::None,
authenticity: Authenticity::None,
body: Body::Fragment(rest),
meter: ctx.link,
});
}
let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
parse_layers(next, rest, ctx, Stage::Tpl)
}
_ => parse_tpl(ci, data, ctx),
}
}
pub(crate) const fn mac_len(mcl: u8) -> Option<usize> {
match mcl & 0x0F {
5 => Some(8),
6 => Some(12),
7 => Some(16),
_ => None,
}
}
fn parse_afl(b: &[u8]) -> Result<Afl> {
let (fcl, mut rest) = b.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
let fcl = u16::from_le_bytes(*fcl);
let mut afl =
Afl { fcl, mcl: None, key_info: None, counter: None, length: None, mac: [0; 16], mac_len: 0 };
if fcl & 0x2000 != 0 {
let (&mcl, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
afl.mcl = Some(mcl);
rest = r;
}
if fcl & 0x0200 != 0 {
let (ki, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
afl.key_info = Some(u16::from_le_bytes(*ki));
rest = r;
}
if fcl & 0x0800 != 0 {
let (c, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
afl.counter = Some(u32::from_le_bytes(*c));
rest = r;
}
if fcl & 0x0400 != 0 {
let n = match afl.mcl {
Some(mcl) => mac_len(mcl).ok_or(Error::InvalidLength)?,
None => rest.len().saturating_sub(if fcl & 0x1000 != 0 { 2 } else { 0 }),
};
if !matches!(n, 8 | 12 | 16) {
return Err(Error::InvalidLength);
}
let mac = rest.get(..n).ok_or(Error::UnexpectedEnd)?;
afl.mac.get_mut(..n).ok_or(Error::InvalidLength)?.copy_from_slice(mac);
afl.mac_len = u8::try_from(n).map_err(|_| Error::InvalidLength)?;
rest = rest.get(n..).unwrap_or(&[]);
}
if fcl & 0x1000 != 0 {
let (l, _) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
afl.length = Some(u16::from_le_bytes(*l));
}
Ok(afl)
}
#[derive(Clone, Copy)]
enum Kind {
Records,
Error,
Alarm,
Empty,
Compact,
Format,
}
#[allow(clippy::too_many_lines)] fn parse_tpl(ci: u8, data: &[u8], mut ctx: Context) -> Result<Application<'_>> {
let (len, kind) = match ci {
ci::RSP_LONG | ci::CMD_LONG => (12, Kind::Records),
ci::RSP_SHORT | ci::CMD_SHORT => (4, Kind::Records),
ci::RSP_NONE | ci::SND_UD => (0, Kind::Records),
ci::ERROR_LONG => (12, Kind::Error),
ci::ERROR_SHORT => (4, Kind::Error),
ci::ERROR_NONE => (0, Kind::Error),
ci::ALARM_LONG => (12, Kind::Alarm),
ci::ALARM_SHORT => (4, Kind::Alarm),
ci::ALARM_NONE => (0, Kind::Alarm),
ci::TPL_TO_DEVICE | ci::TPL_LONG => (12, Kind::Empty),
ci::TPL_SHORT => (4, Kind::Empty),
ci::COMPACT_NONE => (0, Kind::Compact),
ci::COMPACT_SHORT => (4, Kind::Compact),
ci::COMPACT_LONG => (12, Kind::Compact),
ci::FORMAT_NONE => (0, Kind::Format),
ci::FORMAT_SHORT => (4, Kind::Format),
ci::FORMAT_LONG => (12, Kind::Format),
ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN | ci::AFL => {
return Err(Error::UnexpectedLayer(ci));
}
other => return Err(Error::UnsupportedCi(other)),
};
let head = data.get(..len).ok_or(Error::UnexpectedEnd)?;
let mut rest = data.get(len..).ok_or(Error::UnexpectedEnd)?;
let header = match *head {
[i0, i1, i2, i3, m0, m1, version, medium, access, status, c0, c1] => Header::Long(LongHeader {
address: address_id_first([i0, i1, i2, i3, m0, m1, version, medium]),
short: ShortHeader {
access_number: access,
status,
config: [c0, c1],
config_ext: None,
counter: None,
},
}),
[access, status, c0, c1] => Header::Short(ShortHeader {
access_number: access,
status,
config: [c0, c1],
config_ext: None,
counter: None,
}),
_ => Header::None,
};
let security = header.security();
let mut header = header;
let mut header_len = len;
let mut ext = [0u8; 3];
let mut ext_len = 0usize;
if security.mode == 7 {
let (&cfe, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
rest = r;
ext[0] = cfe;
ext_len = 1;
if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
s.config_ext = Some(u16::from(cfe));
}
}
if security.mode == 10 {
let (cfe, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
let [e0, e1] = *cfe;
rest = r;
ext = [e0, e1, 0];
ext_len = 2;
let cfe = u16::from_le_bytes([e0, e1]);
if cfe & 0x0040 != 0 {
let (&kv, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
rest = r;
ext[2] = kv;
ext_len = 3;
}
let (mc, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
rest = r;
let counter = u32::from_le_bytes(*mc);
ctx.counter = Some(counter);
let tag_len = 4 + 4 * usize::from((cfe >> 8) & 0x03);
let split = rest.len().checked_sub(tag_len).ok_or(Error::UnexpectedEnd)?;
let (data, tag) = rest.split_at(split);
ctx.tag.get_mut(..tag_len).ok_or(Error::InvalidLength)?.copy_from_slice(tag);
ctx.tag_len = u8::try_from(tag_len).map_err(|_| Error::InvalidLength)?;
rest = data;
if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
s.config_ext = Some(cfe);
s.counter = Some(counter);
}
}
header_len += ext_len;
let meter = match header {
Header::Long(l) => Some(l.address),
_ => ctx.link,
};
let app = |body| Application {
ell: ctx.ell,
afl: ctx.afl,
ci,
header,
authenticity: Authenticity::None,
body,
meter,
};
if security.mode == 0 || (security.encrypted_blocks == 0 && matches!(security.mode, 5 | 7)) {
let body = match kind {
Kind::Records if ctx.inside_ell => Body::Records(Records::decrypted(rest, rest.len())),
Kind::Records => Body::Records(Records::new(rest)),
Kind::Error => Body::ApplicationError(rest),
Kind::Alarm => Body::Alarm(rest),
Kind::Empty => Body::Empty,
Kind::Compact => Body::Compact(crate::compact::Compact::parse(rest, ctx.inside_ell)?),
Kind::Format => {
let (&len, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
let body = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
let (sig, headers) = body.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
let format = crate::compact::Format::received(u16::from_le_bytes(*sig), headers)
.ok_or(Error::Verification(Check::FullFrameCrc))?;
Body::Format(format)
}
};
return Ok(app(body));
}
let encrypted_len = if security.mode == 10 {
match header.short().map_or(0, |s| s.config[0]) {
0xFF => rest.len(),
n => usize::from(n),
}
} else if security.encrypted_blocks == 0x0F || !matches!(security.mode, 5 | 7) {
rest.len()
} else {
usize::from(security.encrypted_blocks) * 16
};
if encrypted_len > rest.len() || (matches!(security.mode, 5 | 7) && encrypted_len % 16 != 0) {
return Err(Error::Verification(Check::Length));
}
let security = match security.mode {
5 => Security::Mode5,
7 => Security::Mode7,
10 => Security::Mode10,
other => Security::Other(other),
};
if let (Security::Mode5, Some(m), Some(s)) = (security, meter, header.short()) {
let [a, b, c, d, e, f, g, h] = m.to_bytes();
let x = s.access_number;
ctx.iv = [a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x];
}
ctx.ci = ci;
ctx.header.get_mut(..len).ok_or(Error::InvalidLength)?.copy_from_slice(head);
ctx.header
.get_mut(len..len + ext_len)
.ok_or(Error::InvalidLength)?
.copy_from_slice(ext.get(..ext_len).unwrap_or(&[]));
ctx.header_len = u8::try_from(header_len).map_err(|_| Error::InvalidLength)?;
ctx.tpl = Some((ci, header));
Ok(app(Body::Encrypted(Encrypted { security, data: rest, encrypted_len, meter, ctx })))
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use std::string::ToString;
#[test]
fn manufacturer_codes() {
assert_eq!(Manufacturer(0x4024).to_string(), "PAD");
let kam = Manufacturer::from_letters(*b"KAM").unwrap();
assert_eq!(kam.0, 0x2C2D);
assert_eq!(kam.to_string(), "KAM");
assert_eq!(Manufacturer::from_letters(*b"k1m"), None);
}
#[test]
fn security_mode_from_config() {
let s = SecurityMode::from_config([0x10, 0x05]);
assert_eq!(s, SecurityMode { mode: 5, encrypted_blocks: 1 });
let mut data = [0u8; 4 + 18];
data[..4].copy_from_slice(&[0x01, 0x00, 0x10, 0x05]);
let app = Application::parse(ci::RSP_SHORT, &data).unwrap();
let Body::Encrypted(e) = app.body else { panic!() };
assert_eq!((e.security, e.encrypted_len, e.data.len()), (Security::Mode5, 16, 18));
assert_eq!(
Application::parse(ci::RSP_SHORT, &data[..10]).unwrap_err(),
Error::Verification(Check::Length)
);
}
#[test]
fn layer_order_is_enforced() {
assert_eq!(Application::parse(0x7A, &[0, 0, 0, 0]).unwrap().authenticity, Authenticity::None);
assert_eq!(
Application::parse(0x90, &[0x02, 0x00, 0x00, 0x8C, 0, 0, 0x78]).unwrap_err(),
Error::UnexpectedLayer(0x8C)
);
assert_eq!(
Application::parse(0x8C, &[0x20, 0x01, 0x8C, 0, 0, 0x78]).unwrap_err(),
Error::UnexpectedLayer(0x8C)
);
assert_eq!(Application::parse(0x42, &[]).unwrap_err(), Error::UnsupportedCi(0x42));
}
}