1use core::fmt;
24
25use crate::crc::crc16;
26use crate::record::Records;
27use crate::{Check, Error, Result};
28
29pub mod ci {
31 pub const RSP_LONG: u8 = 0x72;
33 pub const RSP_SHORT: u8 = 0x7A;
35 pub const RSP_NONE: u8 = 0x78;
37 pub const SND_UD: u8 = 0x51;
39 pub const CMD_SHORT: u8 = 0x5A;
41 pub const CMD_LONG: u8 = 0x5B;
43 pub const ERROR_SHORT: u8 = 0x6E;
45 pub const ERROR_LONG: u8 = 0x6F;
47 pub const ERROR_NONE: u8 = 0x70;
49 pub const ALARM_NONE: u8 = 0x71;
51 pub const ALARM_SHORT: u8 = 0x74;
53 pub const ALARM_LONG: u8 = 0x75;
55 pub const TPL_TO_DEVICE: u8 = 0x80;
57 pub const TPL_SHORT: u8 = 0x8A;
59 pub const TPL_LONG: u8 = 0x8B;
61 pub const ELL_SHORT: u8 = 0x8C;
63 pub const ELL_SHORT_SN: u8 = 0x8D;
65 pub const ELL_LONG: u8 = 0x8E;
67 pub const ELL_LONG_SN: u8 = 0x8F;
69 pub const AFL: u8 = 0x90;
71 pub const FORMAT_NONE: u8 = 0x69;
73 pub const FORMAT_SHORT: u8 = 0x6A;
75 pub const FORMAT_LONG: u8 = 0x6B;
77 pub const COMPACT_NONE: u8 = 0x79;
79 pub const COMPACT_SHORT: u8 = 0x7B;
81 pub const COMPACT_LONG: u8 = 0x73;
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
87pub struct Manufacturer(pub u16);
88
89impl Manufacturer {
90 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117pub struct Medium(pub u8);
118
119impl Medium {
120 pub const ELECTRICITY: Self = Self(0x02);
122 pub const GAS: Self = Self(0x03);
124 pub const HEAT: Self = Self(0x04);
126 pub const WARM_WATER: Self = Self(0x06);
128 pub const WATER: Self = Self(0x07);
130 pub const HEAT_COST_ALLOCATOR: Self = Self(0x08);
132 pub const COOLING: Self = Self(0x0A);
134 pub const HEAT_INLET: Self = Self(0x0C);
136 pub const HEAT_COOLING: Self = Self(0x0D);
138 pub const HOT_WATER: Self = Self(0x15);
140 pub const COLD_WATER: Self = Self(0x16);
142
143 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
201pub struct Address {
202 pub manufacturer: Manufacturer,
204 pub id: [u8; 4],
206 pub version: u8,
208 pub medium: Medium,
210}
211
212impl Address {
213 pub fn id_number(&self) -> Option<u32> {
215 crate::value::bcd_u32(self.id)
216 }
217
218 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 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct SecurityMode {
253 pub mode: u8,
256 pub encrypted_blocks: u8,
258}
259
260impl SecurityMode {
261 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
270pub struct ShortHeader {
271 pub access_number: u8,
273 pub status: u8,
275 pub config: [u8; 2],
277 pub config_ext: Option<u16>,
280 pub counter: Option<u32>,
282}
283
284impl ShortHeader {
285 pub const fn security(&self) -> SecurityMode {
287 SecurityMode::from_config(self.config)
288 }
289}
290
291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293pub struct LongHeader {
294 pub address: Address,
296 pub short: ShortHeader,
298}
299
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
302pub enum Header {
303 None,
305 Short(ShortHeader),
307 Long(LongHeader),
309}
310
311impl Header {
312 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub struct Ell {
333 pub cc: u8,
335 pub access_number: u8,
337 pub receiver: Option<Address>,
339 pub session: Option<u32>,
341}
342
343impl Ell {
344 pub const fn encrypted(&self) -> bool {
346 matches!(self.session, Some(sn) if sn >> 29 == 1)
347 }
348}
349
350#[derive(Clone, Copy, Debug, PartialEq, Eq)]
357pub struct Afl {
358 pub fcl: u16,
361 pub mcl: Option<u8>,
363 pub key_info: Option<u16>,
365 pub counter: Option<u32>,
367 pub length: Option<u16>,
370 mac: [u8; 16],
371 mac_len: u8,
372}
373
374impl Afl {
375 pub const fn more_fragments(&self) -> bool {
377 self.fcl & 0x4000 != 0
378 }
379
380 pub const fn fragment_id(&self) -> u8 {
382 self.fcl.to_le_bytes()[0]
383 }
384
385 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 pub fn mac(&self) -> &[u8] {
401 self.mac.get(..usize::from(self.mac_len)).unwrap_or(&[])
402 }
403}
404
405#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum Authenticity {
409 None,
411 Encrypted,
418 Authenticated {
420 counter: u32,
423 },
424}
425
426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
428#[non_exhaustive]
429pub enum Security {
430 Mode5,
433 Mode7,
435 Mode10,
437 EllCtr,
439 Other(u8),
441}
442
443#[derive(Clone, Copy, Debug)]
445pub struct Encrypted<'a> {
446 pub security: Security,
448 pub data: &'a [u8],
450 pub encrypted_len: usize,
452 pub meter: Option<Address>,
454 #[cfg_attr(not(feature = "oms"), allow(dead_code))]
455 pub(crate) ctx: Context,
456}
457
458#[derive(Clone, Copy, Debug, Default)]
460#[cfg_attr(not(feature = "oms"), allow(dead_code))]
461pub(crate) struct Context {
462 pub(crate) iv: [u8; 16],
464 pub(crate) ci: u8,
466 pub(crate) header: [u8; 16],
469 pub(crate) header_len: u8,
470 pub(crate) ell: Option<Ell>,
472 pub(crate) afl: Option<Afl>,
473 pub(crate) tpl: Option<(u8, Header)>,
474 pub(crate) link: Option<Address>,
475 pub(crate) inside_ell: bool,
477 pub(crate) counter: Option<u32>,
479 pub(crate) tag: [u8; 16],
480 pub(crate) tag_len: u8,
481}
482
483#[derive(Clone, Debug)]
485pub enum Body<'a> {
486 Records(Records<'a>),
488 Encrypted(Encrypted<'a>),
490 ApplicationError(&'a [u8]),
493 Alarm(&'a [u8]),
495 Empty,
498 Compact(crate::compact::Compact<'a>),
501 Format(crate::compact::Format<'a>),
503 Fragment(&'a [u8]),
507}
508
509#[derive(Clone, Debug)]
511pub struct Application<'a> {
512 pub ell: Option<Ell>,
514 pub afl: Option<Afl>,
516 pub ci: u8,
518 pub header: Header,
520 pub authenticity: Authenticity,
522 pub body: Body<'a>,
524 meter: Option<Address>,
525}
526
527impl<'a> Application<'a> {
528 pub fn parse(ci: u8, data: &'a [u8]) -> Result<Self> {
532 Self::parse_with_link(ci, data, None)
533 }
534
535 pub fn parse_with_link(ci: u8, data: &'a [u8], link: Option<Address>) -> Result<Self> {
537 let ctx = Context { link, ..Context::default() };
538 parse_layers(ci, data, ctx, Stage::Ell)
539 }
540
541 pub(crate) fn reassembled(
544 data: &'a [u8],
545 afl: Afl,
546 ell: Option<Ell>,
547 link: Option<Address>,
548 decrypted: bool,
549 ) -> Result<Self> {
550 let (&ci, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
551 let ctx = Context { link, ell, afl: Some(afl), inside_ell: decrypted, ..Context::default() };
552 let mut app = parse_layers(ci, rest, ctx, Stage::Tpl)?;
553 if decrypted && !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
554 app.authenticity = Authenticity::Encrypted;
555 }
556 Ok(app)
557 }
558
559 pub const fn meter(&self) -> Option<Address> {
562 self.meter
563 }
564
565 pub fn expand<'o, F: crate::compact::Formats + ?Sized>(
570 &self,
571 formats: &F,
572 out: &'o mut [u8],
573 ) -> Result<Application<'o>> {
574 let Body::Compact(c) = &self.body else { return Err(Error::UnsupportedCi(self.ci)) };
575 let records = c.expand(formats, out)?;
576 Ok(Application {
577 ell: self.ell,
578 afl: self.afl,
579 ci: self.ci,
580 header: self.header,
581 authenticity: self.authenticity,
582 body: Body::Records(records),
583 meter: self.meter,
584 })
585 }
586
587 pub fn records(&self) -> Option<Records<'a>> {
589 match &self.body {
590 Body::Records(r) => Some(r.clone()),
591 _ => None,
592 }
593 }
594}
595
596#[cfg(feature = "oms")]
597impl Encrypted<'_> {
598 pub fn decrypt<'o, K: crate::oms::Keys + ?Sized>(
612 &self,
613 keys: &K,
614 out: &'o mut [u8],
615 ) -> Result<Application<'o>> {
616 use crate::oms;
617 let meter = self.meter.ok_or(Error::NoKey)?;
618 let key = keys.key(&meter).ok_or(Error::NoKey)?;
619 let buf = out.get_mut(..self.data.len()).ok_or(Error::OutputTooSmall)?;
620 buf.copy_from_slice(self.data);
621 let ctx = &self.ctx;
622 let authenticity = match self.security {
623 Security::EllCtr => {
624 oms::ctr_apply(key, &ctx.iv, buf);
625 let plain: &'o [u8] = buf;
626 let (crc, rest) = plain.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
627 if crc16(rest) != u16::from_le_bytes(*crc) {
628 return Err(Error::Verification(Check::PayloadCrc));
629 }
630 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
631 let inner = Context { link: ctx.link, ell: ctx.ell, inside_ell: true, ..Context::default() };
632 let mut app = parse_layers(next, rest, inner, Stage::Afl)?;
633 if !matches!(app.body, Body::Encrypted(_)) && app.authenticity == Authenticity::None {
634 app.authenticity = Authenticity::Encrypted;
635 }
636 return Ok(app);
637 }
638 Security::Mode5 => {
639 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
640 oms::cbc_decrypt(key, &ctx.iv, enc)?;
641 Authenticity::Encrypted
642 }
643 Security::Mode7 => {
644 let afl = ctx.afl.ok_or(Error::Verification(Check::MissingCounter))?;
645 let counter = afl.counter.ok_or(Error::Verification(Check::MissingCounter))?;
646 let c = counter.to_le_bytes();
647 let mut authenticity = Authenticity::Encrypted;
648 if afl.mac().is_empty() && afl.mcl.and_then(mac_len).is_some() {
650 return Err(Error::Verification(Check::Mac));
651 }
652 if !afl.mac().is_empty() {
653 let kmac = oms::derive(key, 0x01, c, meter.id);
656 let ml = afl.length.map(u16::to_le_bytes);
657 let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
658 let tag = oms::cmac(
659 &kmac,
660 &[
661 &[afl.mcl.unwrap_or(0)],
662 &c,
663 ml.as_ref().map_or(&[][..], |m| &m[..]),
664 &[ctx.ci],
665 header,
666 self.data,
667 ],
668 );
669 let mac = afl.mac();
670 if !oms::mac_matches(tag.get(..mac.len()).unwrap_or(&[]), mac) {
671 return Err(Error::Verification(Check::Mac));
672 }
673 authenticity = Authenticity::Authenticated { counter };
674 }
675 let kenc = oms::derive(key, 0x00, c, meter.id);
676 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
677 oms::cbc_decrypt(&kenc, &[0; 16], enc)?;
678 authenticity
679 }
680 Security::Mode10 => return self.open_ccm(key, meter, buf),
681 Security::Other(mode) => return Err(Error::UnsupportedSecurity(mode)),
682 };
683 let plain: &'o [u8] = buf;
684 if matches!(ctx.ci, ci::COMPACT_SHORT | ci::COMPACT_LONG) {
685 return Err(Error::UnsupportedCi(ctx.ci));
688 }
689 if !plain.starts_with(&[0x2F, 0x2F]) {
690 return Err(Error::Verification(Check::Marker));
691 }
692 let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
693 Ok(Application {
694 ell: ctx.ell,
695 afl: ctx.afl,
696 ci,
697 header,
698 authenticity,
699 body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
700 meter: self.meter,
701 })
702 }
703
704 fn open_ccm<'o>(
706 &self,
707 key: &crate::oms::Key,
708 meter: Address,
709 buf: &'o mut [u8],
710 ) -> Result<Application<'o>> {
711 use crate::oms;
712 let ctx = &self.ctx;
713 let counter = ctx.counter.ok_or(Error::Verification(Check::MissingCounter))?;
717 let kenc = oms::derive(key, 0x00, counter.to_le_bytes(), meter.id);
718 let [m0, m1, i0, i1, i2, i3, v, t] = meter.to_bytes();
719 let [c0, c1, c2, c3] = counter.to_be_bytes();
720 let nonce = [m0, m1, i0, i1, i2, i3, v, t, 0, c0, c1, c2, c3];
721 let header = ctx.header.get(..usize::from(ctx.header_len)).unwrap_or(&[]);
722 let tail = self.data.get(self.encrypted_len..).unwrap_or(&[]);
726 let mut aad = [0u8; 1 + 16 + 256];
727 let aad_len = 1 + header.len() + tail.len();
728 if let Some((first, rest)) = aad.split_first_mut() {
729 *first = ctx.ci;
730 rest.get_mut(..header.len()).ok_or(Error::InvalidLength)?.copy_from_slice(header);
731 rest.get_mut(header.len()..header.len() + tail.len())
732 .ok_or(Error::InvalidLength)?
733 .copy_from_slice(tail);
734 }
735 let tag = ctx.tag.get(..usize::from(ctx.tag_len)).unwrap_or(&[]);
736 let enc = buf.get_mut(..self.encrypted_len).ok_or(Error::UnexpectedEnd)?;
737 oms::ccm_decrypt(&kenc, &nonce, aad.get(..aad_len).unwrap_or(&[]), enc, tag)?;
738 let plain: &'o [u8] = buf;
739 let (ci, header) = ctx.tpl.unwrap_or((ctx.ci, Header::None));
740 Ok(Application {
741 ell: ctx.ell,
742 afl: ctx.afl,
743 ci,
744 header,
745 authenticity: Authenticity::Authenticated { counter },
746 body: Body::Records(Records::decrypted(plain, self.encrypted_len)),
747 meter: self.meter,
748 })
749 }
750}
751
752#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
754enum Stage {
755 Ell,
756 Afl,
757 Tpl,
758}
759
760fn address_id_first(b: [u8; 8]) -> Address {
761 let [i0, i1, i2, i3, m0, m1, version, medium] = b;
762 Address::from_link_bytes([m0, m1, i0, i1, i2, i3, version, medium])
763}
764
765#[allow(clippy::too_many_lines)]
766fn parse_layers(ci: u8, data: &[u8], mut ctx: Context, stage: Stage) -> Result<Application<'_>> {
767 match ci {
768 ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN => {
769 if stage > Stage::Ell {
770 return Err(Error::UnexpectedLayer(ci));
771 }
772 let (&[cc, access], mut rest) = data.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
773 let mut ell = Ell { cc, access_number: access, receiver: None, session: None };
774 if matches!(ci, ci::ELL_LONG | ci::ELL_LONG_SN) {
775 let (a, r) = rest.split_first_chunk::<8>().ok_or(Error::UnexpectedEnd)?;
776 ell.receiver = Some(Address::from_link_bytes(*a));
777 rest = r;
778 }
779 if matches!(ci, ci::ELL_SHORT_SN | ci::ELL_LONG_SN) {
780 let (sn, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
781 let session = u32::from_le_bytes(*sn);
782 ell.session = Some(session);
783 ctx.ell = Some(ell);
784 if ell.encrypted() {
785 let mut iv = [0u8; 16];
787 if let Some(link) = ctx.link {
788 let [a, b, c, d, e, f, g, h] = link.to_bytes();
789 let [s0, s1, s2, s3] = *sn;
790 iv = [a, b, c, d, e, f, g, h, cc & !0x12, s0, s1, s2, s3, 0, 0, 0];
791 }
792 ctx.iv = iv;
793 return Ok(Application {
794 ell: Some(ell),
795 afl: None,
796 ci,
797 header: Header::None,
798 authenticity: Authenticity::None,
799 meter: ctx.link,
800 body: Body::Encrypted(Encrypted {
801 security: Security::EllCtr,
802 data: r,
803 encrypted_len: r.len(),
804 meter: ctx.link,
805 ctx,
806 }),
807 });
808 }
809 let (crc, r) = r.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
811 if crc16(r) != u16::from_le_bytes(*crc) {
812 return Err(Error::Verification(Check::PayloadCrc));
813 }
814 rest = r;
815 }
816 ctx.ell = Some(ell);
817 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
818 parse_layers(next, rest, ctx, Stage::Afl)
819 }
820 ci::AFL => {
821 if stage > Stage::Afl {
822 return Err(Error::UnexpectedLayer(ci));
823 }
824 let (&len, rest) = data.split_first().ok_or(Error::UnexpectedEnd)?;
825 let afl_bytes = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
826 let rest = rest.get(usize::from(len)..).ok_or(Error::UnexpectedEnd)?;
827 let afl = parse_afl(afl_bytes)?;
828 ctx.afl = Some(afl);
829 if afl.fragment_id() != 0 {
830 return Ok(Application {
832 ell: ctx.ell,
833 afl: Some(afl),
834 ci,
835 header: Header::None,
836 authenticity: Authenticity::None,
837 body: Body::Fragment(rest),
838 meter: ctx.link,
839 });
840 }
841 let (&next, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
842 parse_layers(next, rest, ctx, Stage::Tpl)
843 }
844 _ => parse_tpl(ci, data, ctx),
845 }
846}
847
848pub(crate) const fn mac_len(mcl: u8) -> Option<usize> {
850 match mcl & 0x0F {
851 5 => Some(8),
852 6 => Some(12),
853 7 => Some(16),
854 _ => None,
855 }
856}
857
858fn parse_afl(b: &[u8]) -> Result<Afl> {
859 let (fcl, mut rest) = b.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
860 let fcl = u16::from_le_bytes(*fcl);
861 let mut afl =
862 Afl { fcl, mcl: None, key_info: None, counter: None, length: None, mac: [0; 16], mac_len: 0 };
863 if fcl & 0x2000 != 0 {
864 let (&mcl, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
865 afl.mcl = Some(mcl);
866 rest = r;
867 }
868 if fcl & 0x0200 != 0 {
869 let (ki, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
870 afl.key_info = Some(u16::from_le_bytes(*ki));
871 rest = r;
872 }
873 if fcl & 0x0800 != 0 {
874 let (c, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
875 afl.counter = Some(u32::from_le_bytes(*c));
876 rest = r;
877 }
878 if fcl & 0x0400 != 0 {
879 let n = match afl.mcl {
882 Some(mcl) => mac_len(mcl).ok_or(Error::InvalidLength)?,
883 None => rest.len().saturating_sub(if fcl & 0x1000 != 0 { 2 } else { 0 }),
884 };
885 if !matches!(n, 8 | 12 | 16) {
886 return Err(Error::InvalidLength);
887 }
888 let mac = rest.get(..n).ok_or(Error::UnexpectedEnd)?;
889 afl.mac.get_mut(..n).ok_or(Error::InvalidLength)?.copy_from_slice(mac);
890 afl.mac_len = u8::try_from(n).map_err(|_| Error::InvalidLength)?;
891 rest = rest.get(n..).unwrap_or(&[]);
892 }
893 if fcl & 0x1000 != 0 {
894 let (l, _) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
895 afl.length = Some(u16::from_le_bytes(*l));
896 }
897 Ok(afl)
898}
899
900#[derive(Clone, Copy)]
901enum Kind {
902 Records,
903 Error,
904 Alarm,
905 Empty,
906 Compact,
907 Format,
908}
909
910#[allow(clippy::too_many_lines)] fn parse_tpl(ci: u8, data: &[u8], mut ctx: Context) -> Result<Application<'_>> {
912 let (len, kind) = match ci {
914 ci::RSP_LONG | ci::CMD_LONG => (12, Kind::Records),
915 ci::RSP_SHORT | ci::CMD_SHORT => (4, Kind::Records),
916 ci::RSP_NONE | ci::SND_UD => (0, Kind::Records),
917 ci::ERROR_LONG => (12, Kind::Error),
918 ci::ERROR_SHORT => (4, Kind::Error),
919 ci::ERROR_NONE => (0, Kind::Error),
920 ci::ALARM_LONG => (12, Kind::Alarm),
921 ci::ALARM_SHORT => (4, Kind::Alarm),
922 ci::ALARM_NONE => (0, Kind::Alarm),
923 ci::TPL_TO_DEVICE | ci::TPL_LONG => (12, Kind::Empty),
924 ci::TPL_SHORT => (4, Kind::Empty),
925 ci::COMPACT_NONE => (0, Kind::Compact),
926 ci::COMPACT_SHORT => (4, Kind::Compact),
927 ci::COMPACT_LONG => (12, Kind::Compact),
928 ci::FORMAT_NONE => (0, Kind::Format),
929 ci::FORMAT_SHORT => (4, Kind::Format),
930 ci::FORMAT_LONG => (12, Kind::Format),
931 ci::ELL_SHORT | ci::ELL_SHORT_SN | ci::ELL_LONG | ci::ELL_LONG_SN | ci::AFL => {
932 return Err(Error::UnexpectedLayer(ci));
933 }
934 other => return Err(Error::UnsupportedCi(other)),
935 };
936 let head = data.get(..len).ok_or(Error::UnexpectedEnd)?;
937 let mut rest = data.get(len..).ok_or(Error::UnexpectedEnd)?;
938 let header = match *head {
939 [i0, i1, i2, i3, m0, m1, version, medium, access, status, c0, c1] => Header::Long(LongHeader {
940 address: address_id_first([i0, i1, i2, i3, m0, m1, version, medium]),
941 short: ShortHeader {
942 access_number: access,
943 status,
944 config: [c0, c1],
945 config_ext: None,
946 counter: None,
947 },
948 }),
949 [access, status, c0, c1] => Header::Short(ShortHeader {
950 access_number: access,
951 status,
952 config: [c0, c1],
953 config_ext: None,
954 counter: None,
955 }),
956 _ => Header::None,
957 };
958 let security = header.security();
959 let mut header = header;
960 let mut header_len = len;
961 let mut ext = [0u8; 3];
963 let mut ext_len = 0usize;
964 if security.mode == 7 {
965 let (&cfe, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
967 rest = r;
968 ext[0] = cfe;
969 ext_len = 1;
970 if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
971 s.config_ext = Some(u16::from(cfe));
972 }
973 }
974 if security.mode == 10 {
975 let (cfe, r) = rest.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
978 let [e0, e1] = *cfe;
979 rest = r;
980 ext = [e0, e1, 0];
981 ext_len = 2;
982 let cfe = u16::from_le_bytes([e0, e1]);
983 if cfe & 0x0040 != 0 {
984 let (&kv, r) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
985 rest = r;
986 ext[2] = kv;
987 ext_len = 3;
988 }
989 let (mc, r) = rest.split_first_chunk::<4>().ok_or(Error::UnexpectedEnd)?;
990 rest = r;
991 let counter = u32::from_le_bytes(*mc);
992 ctx.counter = Some(counter);
993 let tag_len = 4 + 4 * usize::from((cfe >> 8) & 0x03);
994 let split = rest.len().checked_sub(tag_len).ok_or(Error::UnexpectedEnd)?;
995 let (data, tag) = rest.split_at(split);
996 ctx.tag.get_mut(..tag_len).ok_or(Error::InvalidLength)?.copy_from_slice(tag);
997 ctx.tag_len = u8::try_from(tag_len).map_err(|_| Error::InvalidLength)?;
998 rest = data;
999 if let Header::Short(s) | Header::Long(LongHeader { short: s, .. }) = &mut header {
1000 s.config_ext = Some(cfe);
1001 s.counter = Some(counter);
1002 }
1003 }
1004 header_len += ext_len;
1005 let meter = match header {
1006 Header::Long(l) => Some(l.address),
1007 _ => ctx.link,
1008 };
1009 let app = |body| Application {
1010 ell: ctx.ell,
1011 afl: ctx.afl,
1012 ci,
1013 header,
1014 authenticity: Authenticity::None,
1015 body,
1016 meter,
1017 };
1018 if security.mode == 0 || (security.encrypted_blocks == 0 && matches!(security.mode, 5 | 7)) {
1023 let body = match kind {
1024 Kind::Records if ctx.inside_ell => Body::Records(Records::decrypted(rest, rest.len())),
1026 Kind::Records => Body::Records(Records::new(rest)),
1027 Kind::Error => Body::ApplicationError(rest),
1028 Kind::Alarm => Body::Alarm(rest),
1029 Kind::Empty => Body::Empty,
1030 Kind::Compact => Body::Compact(crate::compact::Compact::parse(rest, ctx.inside_ell)?),
1031 Kind::Format => {
1032 let (&len, rest) = rest.split_first().ok_or(Error::UnexpectedEnd)?;
1033 let body = rest.get(..usize::from(len)).ok_or(Error::UnexpectedEnd)?;
1034 let (sig, headers) = body.split_first_chunk::<2>().ok_or(Error::UnexpectedEnd)?;
1035 let format = crate::compact::Format::received(u16::from_le_bytes(*sig), headers)
1036 .ok_or(Error::Verification(Check::FullFrameCrc))?;
1037 Body::Format(format)
1038 }
1039 };
1040 return Ok(app(body));
1041 }
1042 let encrypted_len = if security.mode == 10 {
1043 match header.short().map_or(0, |s| s.config[0]) {
1045 0xFF => rest.len(),
1046 n => usize::from(n),
1047 }
1048 } else if security.encrypted_blocks == 0x0F || !matches!(security.mode, 5 | 7) {
1049 rest.len()
1051 } else {
1052 usize::from(security.encrypted_blocks) * 16
1053 };
1054 if encrypted_len > rest.len() || (matches!(security.mode, 5 | 7) && encrypted_len % 16 != 0) {
1055 return Err(Error::Verification(Check::Length));
1056 }
1057 let security = match security.mode {
1058 5 => Security::Mode5,
1059 7 => Security::Mode7,
1060 10 => Security::Mode10,
1061 other => Security::Other(other),
1062 };
1063 if let (Security::Mode5, Some(m), Some(s)) = (security, meter, header.short()) {
1064 let [a, b, c, d, e, f, g, h] = m.to_bytes();
1065 let x = s.access_number;
1066 ctx.iv = [a, b, c, d, e, f, g, h, x, x, x, x, x, x, x, x];
1067 }
1068 ctx.ci = ci;
1069 ctx.header.get_mut(..len).ok_or(Error::InvalidLength)?.copy_from_slice(head);
1070 ctx.header
1071 .get_mut(len..len + ext_len)
1072 .ok_or(Error::InvalidLength)?
1073 .copy_from_slice(ext.get(..ext_len).unwrap_or(&[]));
1074 ctx.header_len = u8::try_from(header_len).map_err(|_| Error::InvalidLength)?;
1075 ctx.tpl = Some((ci, header));
1076 Ok(app(Body::Encrypted(Encrypted { security, data: rest, encrypted_len, meter, ctx })))
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081 extern crate std;
1082 use super::*;
1083 use std::string::ToString;
1084
1085 #[test]
1086 fn manufacturer_codes() {
1087 assert_eq!(Manufacturer(0x4024).to_string(), "PAD");
1088 let kam = Manufacturer::from_letters(*b"KAM").unwrap();
1089 assert_eq!(kam.0, 0x2C2D);
1090 assert_eq!(kam.to_string(), "KAM");
1091 assert_eq!(Manufacturer::from_letters(*b"k1m"), None);
1092 }
1093
1094 #[test]
1095 fn security_mode_from_config() {
1096 let s = SecurityMode::from_config([0x10, 0x05]);
1098 assert_eq!(s, SecurityMode { mode: 5, encrypted_blocks: 1 });
1099 let mut data = [0u8; 4 + 18];
1100 data[..4].copy_from_slice(&[0x01, 0x00, 0x10, 0x05]);
1101 let app = Application::parse(ci::RSP_SHORT, &data).unwrap();
1102 let Body::Encrypted(e) = app.body else { panic!() };
1103 assert_eq!((e.security, e.encrypted_len, e.data.len()), (Security::Mode5, 16, 18));
1104 assert_eq!(
1106 Application::parse(ci::RSP_SHORT, &data[..10]).unwrap_err(),
1107 Error::Verification(Check::Length)
1108 );
1109 }
1110
1111 #[test]
1113 fn layer_order_is_enforced() {
1114 assert_eq!(Application::parse(0x7A, &[0, 0, 0, 0]).unwrap().authenticity, Authenticity::None);
1115 assert_eq!(
1117 Application::parse(0x90, &[0x02, 0x00, 0x00, 0x8C, 0, 0, 0x78]).unwrap_err(),
1118 Error::UnexpectedLayer(0x8C)
1119 );
1120 assert_eq!(
1121 Application::parse(0x8C, &[0x20, 0x01, 0x8C, 0, 0, 0x78]).unwrap_err(),
1122 Error::UnexpectedLayer(0x8C)
1123 );
1124 assert_eq!(Application::parse(0x42, &[]).unwrap_err(), Error::UnsupportedCi(0x42));
1125 }
1126}