mbus_kit/fragment.rs
1//! AFL fragment reassembly (OMS Vol. 2 §6.2, §7.3; EN 13757-7 clause 6).
2//!
3//! A message too long for one frame is sent in fragments, each in its own frame with an
4//! AFL (CI `90`) in front. The fragment IDs count 1, 2, 3, …; *more fragments* is set
5//! on all but the last. The first fragment carries the message control, counter and
6//! length, and the transport layer starts in it; the last carries the MAC over the
7//! whole message. Fragments are requested one by one (`REQ_UD2` or `SND_UD`), never
8//! broadcast, so they arrive in order.
9//!
10//! ```text
11//! fragment 1: … 90 AFLL FCL(MF, ID 1) MCL MCR ML | 7A header …
12//! fragment 2: … 90 AFLL FCL(MF, ID 2) | … middle …
13//! fragment 3: … 90 AFLL FCL(ID 3) MAC | … end
14//! ```
15//!
16//! [`Reassembly`] copies the pieces into a buffer the caller owns, checks the order,
17//! the sender and the announced length, and parses the whole message, which then
18//! decrypts and authenticates like an unfragmented one. One `Reassembly` per meter.
19//!
20//! ```
21//! use mbus_kit::fragment::Reassembly;
22//! use mbus_kit::{Application, Body};
23//!
24//! // A 3-byte message (CI 78 and two record bytes) in two fragments.
25//! # let f1 = [0x90, 0x05, 0x01, 0x70, 0x40, 0x03, 0x00, 0x78, 0xAA];
26//! # let f2 = [0x90, 0x02, 0x02, 0x00, 0xBB];
27//! let mut buf = [0u8; 256];
28//! let mut message = Reassembly::new(&mut buf);
29//! assert!(message.push(&Application::parse(f1[0], &f1[1..])?)?.is_none()); // more to come
30//! let app = message.push(&Application::parse(f2[0], &f2[1..])?)?.expect("last fragment");
31//! assert!(matches!(app.body, Body::Records(_)));
32//! # Ok::<(), mbus_kit::Error>(())
33//! ```
34
35use crate::app::{Address, Afl, Application, Authenticity, Body, Ell};
36use crate::{Error, Result};
37
38/// Joins the fragments of one message into a caller buffer.
39#[derive(Debug)]
40pub struct Reassembly<'b> {
41 buf: &'b mut [u8],
42 len: usize,
43 /// The fragment ID expected next; 0 while no message is open.
44 next: u8,
45 first: Option<Afl>,
46 sender: Option<Address>,
47 ell: Option<Ell>,
48 decrypted: bool,
49}
50
51impl<'b> Reassembly<'b> {
52 /// Reassemble into `buf`. OMS limits a message to 16 KiB; size `buf` for the longest
53 /// message the meters send.
54 pub const fn new(buf: &'b mut [u8]) -> Self {
55 Self { buf, len: 0, next: 0, first: None, sender: None, ell: None, decrypted: false }
56 }
57
58 /// The fragment ID expected next, or `None` while no message is open (the next one
59 /// must be fragment 1).
60 pub const fn expected(&self) -> Option<u8> {
61 if self.next == 0 { None } else { Some(self.next) }
62 }
63
64 /// The bytes collected so far.
65 pub const fn len(&self) -> usize {
66 self.len
67 }
68
69 /// Whether nothing has been collected.
70 pub const fn is_empty(&self) -> bool {
71 self.len == 0
72 }
73
74 /// Drop a message in progress.
75 pub fn reset(&mut self) {
76 self.len = 0;
77 self.next = 0;
78 self.first = None;
79 self.sender = None;
80 self.ell = None;
81 self.decrypted = false;
82 }
83
84 /// Add a fragment. `Ok(None)` while more are expected; the whole message, parsed,
85 /// after the last one.
86 ///
87 /// Fragment 1 always starts a new message (a meter or gateway that starts over, OMS
88 /// Vol. 2 Annex L.4). Any other fragment must be the expected one from the same
89 /// meter: otherwise [`Error::UnexpectedFragment`] (missing, repeated, out of order,
90 /// or not a fragment at all: `found` 0) or [`Error::FragmentFromOtherMeter`], and the
91 /// message in progress is kept, so the caller can request the fragment again. A
92 /// message longer than the buffer is [`Error::OutputTooSmall`], one whose length
93 /// differs from the length announced in fragment 1 [`Error::InvalidLength`]; both
94 /// drop the message.
95 pub fn push(&mut self, fragment: &Application<'_>) -> Result<Option<Application<'_>>> {
96 let (Body::Fragment(data), Some(afl)) = (&fragment.body, fragment.afl) else {
97 return Err(Error::UnexpectedFragment { expected: self.next.max(1), found: 0 });
98 };
99 let id = afl.fragment_id();
100 if id == 1 {
101 self.reset();
102 if afl.length.is_some_and(|ml| usize::from(ml) > self.buf.len()) {
103 return Err(Error::OutputTooSmall);
104 }
105 self.first = Some(afl);
106 self.sender = fragment.meter();
107 self.ell = fragment.ell;
108 self.decrypted = fragment.authenticity == Authenticity::Encrypted;
109 } else if self.next == 0 || id != self.next {
110 return Err(Error::UnexpectedFragment { expected: self.next.max(1), found: id });
111 } else if fragment.meter() != self.sender {
112 return Err(Error::FragmentFromOtherMeter);
113 } else {
114 self.decrypted &= fragment.authenticity == Authenticity::Encrypted;
115 }
116 let Some(dst) = self.buf.get_mut(self.len..self.len + data.len()) else {
117 self.reset();
118 return Err(Error::OutputTooSmall);
119 };
120 dst.copy_from_slice(data);
121 self.len += data.len();
122 if afl.more_fragments() {
123 // The fragment ID never rolls over: 255 fragments at most.
124 let Some(next) = id.checked_add(1) else {
125 self.reset();
126 return Err(Error::UnexpectedFragment { expected: 0, found: id });
127 };
128 self.next = next;
129 return Ok(None);
130 }
131 let first = self.first.unwrap_or(afl);
132 let (len, ell, sender, decrypted) = (self.len, self.ell, self.sender, self.decrypted);
133 self.reset();
134 if first.length.is_some_and(|ml| usize::from(ml) != len) {
135 return Err(Error::InvalidLength);
136 }
137 // The last fragment's MAC has the length the first fragment's MCL announced.
138 if !afl.mac().is_empty() && first.mcl.and_then(crate::app::mac_len) != Some(afl.mac().len()) {
139 return Err(Error::InvalidLength);
140 }
141 let message = self.buf.get(..len).ok_or(Error::OutputTooSmall)?;
142 Application::reassembled(message, Afl::joined(&first, &afl), ell, sender, decrypted).map(Some)
143 }
144}