Skip to main content

dlms_cosem_kit/transport/
hdlc.rs

1//! HDLC — the data link layer of the three-layer connection-oriented profile.
2//!
3//! This is what an optical probe, an RS-485 bus and a great many GPRS meters speak.
4//! Frame format type 3: an eleven-bit length, addresses of one, two or four bytes, a
5//! header check sequence when there is an information field, and a frame check sequence
6//! over everything.
7//!
8//! The decoder is built to resynchronise. A serial link delivers noise, half frames and
9//! echoes of what was just transmitted, so [`Framer`] scans for a flag, validates, and
10//! on failure discards to the next flag rather than giving up on the link.
11
12use crate::codec::{Encode, Error, ErrorKind, Reader, Result, Writer};
13
14/// The flag byte that opens and closes every frame.
15pub const FLAG: u8 = 0x7E;
16
17/// The LLC header a client sends before an APDU.
18pub const LLC_REQUEST: [u8; 3] = [0xE6, 0xE6, 0x00];
19/// The LLC header a server sends before an APDU.
20pub const LLC_RESPONSE: [u8; 3] = [0xE6, 0xE7, 0x00];
21
22/// The frame check sequence: CRC-16/X-25, as PPP and HDLC define it.
23///
24/// Reflected polynomial `0x8408` (that is, `x^16 + x^12 + x^5 + 1`), initial value
25/// `0xFFFF`, final complement, transmitted least significant byte first.
26#[must_use]
27pub fn fcs16(data: &[u8]) -> u16 {
28    let mut fcs: u16 = 0xFFFF;
29    for b in data {
30        fcs ^= u16::from(*b);
31        for _ in 0..8 {
32            fcs = if fcs & 1 != 0 { (fcs >> 1) ^ 0x8408 } else { fcs >> 1 };
33        }
34    }
35    !fcs
36}
37
38/// An HDLC address: one, two or four bytes, each byte carrying seven bits and the last
39/// one marked by its low bit.
40///
41/// The upper half is the logical device and the lower half the physical device, which
42/// is how one physical meter hosts several logical ones on the same link.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Address {
45    /// One byte: a client SAP, or a server whose logical and physical device are one.
46    Single(u8),
47    /// Two bytes: an upper and a lower address of seven bits each.
48    Double {
49        /// Logical device.
50        upper: u8,
51        /// Physical device.
52        lower: u8,
53    },
54    /// Four bytes: an upper and a lower address of fourteen bits each.
55    Quad {
56        /// Logical device.
57        upper: u16,
58        /// Physical device.
59        lower: u16,
60    },
61}
62
63impl Address {
64    /// The management logical device, address 1.
65    pub const MANAGEMENT_LOGICAL_DEVICE: Self = Self::Single(1);
66
67    /// A client SAP. 0x10 is the public client, 0x20 a meter reader, 0x30 management.
68    #[must_use]
69    pub const fn client(sap: u8) -> Self {
70        Self::Single(sap)
71    }
72
73    /// A server address with a logical and a physical device.
74    ///
75    /// The four-byte form is chosen when either half needs more than seven bits, which
76    /// is what a physical address like 0x3FFF ("any") requires.
77    #[must_use]
78    pub const fn server(logical: u16, physical: u16) -> Self {
79        if logical <= 0x7F && physical <= 0x7F {
80            Self::Double { upper: logical as u8, lower: physical as u8 }
81        } else {
82            Self::Quad { upper: logical, lower: physical }
83        }
84    }
85
86    /// How many bytes this address occupies.
87    #[must_use]
88    pub const fn len(self) -> usize {
89        match self {
90            Self::Single(_) => 1,
91            Self::Double { .. } => 2,
92            Self::Quad { .. } => 4,
93        }
94    }
95
96    /// Always false; an address has at least one byte. Present because clippy asks for
97    /// it next to `len`.
98    #[must_use]
99    pub const fn is_empty(self) -> bool {
100        false
101    }
102
103    fn encode(self, w: &mut dyn Writer) -> Result<()> {
104        match self {
105            Self::Single(v) => w.write_u8((v << 1) | 1),
106            Self::Double { upper, lower } => w.write_bytes(&[upper << 1, (lower << 1) | 1]),
107            Self::Quad { upper, lower } => w.write_bytes(&[
108                ((upper >> 7) as u8) << 1,
109                ((upper & 0x7F) as u8) << 1,
110                ((lower >> 7) as u8) << 1,
111                (((lower & 0x7F) as u8) << 1) | 1,
112            ]),
113        }
114    }
115
116    /// Read an address, stopping at the byte whose low bit is set.
117    fn decode(r: &mut Reader<'_>) -> Result<Self> {
118        let mut parts = [0u8; 4];
119        let mut n = 0;
120        loop {
121            if n == 4 {
122                return Err(r.err(ErrorKind::InvalidValue));
123            }
124            let b = r.u8()?;
125            parts[n] = b >> 1;
126            n += 1;
127            if b & 1 != 0 {
128                break;
129            }
130        }
131        Ok(match n {
132            1 => Self::Single(parts[0]),
133            2 => Self::Double { upper: parts[0], lower: parts[1] },
134            4 => Self::Quad {
135                upper: (u16::from(parts[0]) << 7) | u16::from(parts[1]),
136                lower: (u16::from(parts[2]) << 7) | u16::from(parts[3]),
137            },
138            // Three bytes is not a defined address length.
139            _ => return Err(r.err(ErrorKind::InvalidValue)),
140        })
141    }
142}
143
144/// The control field: which kind of frame, and its sequence numbers.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub enum Control {
147    /// Information frame, carrying an APDU fragment.
148    I {
149        /// Send sequence number, 0–7.
150        ns: u8,
151        /// Receive sequence number, 0–7.
152        nr: u8,
153        /// Poll or final bit.
154        pf: bool,
155    },
156    /// Receive ready: acknowledges up to `nr` and invites the next frame.
157    Rr {
158        /// Receive sequence number.
159        nr: u8,
160        /// Poll or final bit.
161        pf: bool,
162    },
163    /// Receive not ready: acknowledges, but asks the peer to pause.
164    Rnr {
165        /// Receive sequence number.
166        nr: u8,
167        /// Poll or final bit.
168        pf: bool,
169    },
170    /// Set normal response mode: opens the link and negotiates parameters.
171    Snrm,
172    /// Unnumbered acknowledge: the answer to SNRM or DISC.
173    Ua,
174    /// Disconnect.
175    Disc,
176    /// Disconnected mode: the peer is not connected.
177    Dm,
178    /// Frame reject.
179    Frmr,
180    /// Unnumbered information, used by the discovery services.
181    Ui,
182}
183
184impl Control {
185    /// The control byte.
186    #[must_use]
187    pub const fn as_u8(self) -> u8 {
188        match self {
189            Self::I { ns, nr, pf } => ((nr & 7) << 5) | ((pf as u8) << 4) | ((ns & 7) << 1),
190            Self::Rr { nr, pf } => ((nr & 7) << 5) | ((pf as u8) << 4) | 0x01,
191            Self::Rnr { nr, pf } => ((nr & 7) << 5) | ((pf as u8) << 4) | 0x05,
192            Self::Snrm => 0x93,
193            Self::Ua => 0x73,
194            Self::Disc => 0x53,
195            Self::Dm => 0x1F,
196            Self::Frmr => 0x97,
197            Self::Ui => 0x13,
198        }
199    }
200
201    /// Classify a control byte.
202    #[must_use]
203    pub const fn from_u8(v: u8) -> Self {
204        if v & 1 == 0 {
205            return Self::I { ns: (v >> 1) & 7, nr: (v >> 5) & 7, pf: v & 0x10 != 0 };
206        }
207        // Unnumbered frames are identified with the poll/final bit masked out.
208        match v & !0x10 {
209            0x83 => Self::Snrm,
210            0x63 => Self::Ua,
211            0x43 => Self::Disc,
212            0x0F => Self::Dm,
213            0x87 => Self::Frmr,
214            0x03 => Self::Ui,
215            _ => match v & 0x0F {
216                0x01 => Self::Rr { nr: (v >> 5) & 7, pf: v & 0x10 != 0 },
217                0x05 => Self::Rnr { nr: (v >> 5) & 7, pf: v & 0x10 != 0 },
218                _ => Self::Frmr,
219            },
220        }
221    }
222
223    /// True when this frame carries no information field.
224    #[must_use]
225    pub const fn is_supervisory(self) -> bool {
226        matches!(self, Self::Rr { .. } | Self::Rnr { .. })
227    }
228}
229
230/// A decoded HDLC frame, borrowing its information field.
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub struct Frame<'a> {
233    /// True when the APDU continues in the next frame.
234    pub segmented: bool,
235    /// Who the frame is for.
236    pub destination: Address,
237    /// Who sent it.
238    pub source: Address,
239    /// Which kind of frame.
240    pub control: Control,
241    /// The information field, empty for a supervisory or bare unnumbered frame.
242    pub information: &'a [u8],
243}
244
245impl Frame<'_> {
246    /// A frame with no information field.
247    #[must_use]
248    pub const fn control_only(destination: Address, source: Address, control: Control) -> Self {
249        Self { segmented: false, destination, source, control, information: &[] }
250    }
251
252    /// The total encoded length, flags included.
253    #[must_use]
254    pub fn encoded_len(&self) -> usize {
255        let body = 2 + self.destination.len() + self.source.len() + 1;
256        let info = if self.information.is_empty() { 0 } else { 2 + self.information.len() };
257        1 + body + info + 2 + 1
258    }
259}
260
261impl Encode for Frame<'_> {
262    fn encode(&self, w: &mut dyn Writer) -> Result<()> {
263        let header_len = 2 + self.destination.len() + self.source.len() + 1;
264        let hcs_len = usize::from(!self.information.is_empty()) * 2;
265        // The length in the format field spans everything between the flags.
266        let frame_len = header_len + hcs_len + self.information.len() + 2;
267        if frame_len > 0x7FF {
268            return Err(Error::new(ErrorKind::InvalidLength, 0));
269        }
270
271        let mut header = [0u8; 12];
272        let mut hw = crate::codec::SliceWriter::new(&mut header);
273        let format = 0xA000 | (u16::from(self.segmented) << 11) | (frame_len as u16);
274        hw.write_u16(format)?;
275        self.destination.encode(&mut hw)?;
276        self.source.encode(&mut hw)?;
277        hw.write_u8(self.control.as_u8())?;
278        let header_bytes_len = hw.written();
279        let header = &header[..header_bytes_len];
280
281        w.write_u8(FLAG)?;
282        w.write_bytes(header)?;
283        if !self.information.is_empty() {
284            w.write_bytes(&fcs16(header).to_le_bytes())?;
285            w.write_bytes(self.information)?;
286        }
287        // The frame check sequence covers the header, the HCS and the information.
288        let mut fcs = 0xFFFFu16;
289        fcs = crc_update(fcs, header);
290        if !self.information.is_empty() {
291            fcs = crc_update(fcs, &fcs16(header).to_le_bytes());
292            fcs = crc_update(fcs, self.information);
293        }
294        w.write_bytes(&(!fcs).to_le_bytes())?;
295        w.write_u8(FLAG)
296    }
297}
298
299fn crc_update(mut fcs: u16, data: &[u8]) -> u16 {
300    for b in data {
301        fcs ^= u16::from(*b);
302        for _ in 0..8 {
303            fcs = if fcs & 1 != 0 { (fcs >> 1) ^ 0x8408 } else { fcs >> 1 };
304        }
305    }
306    fcs
307}
308
309/// The shortest HDLC frame that can exist: the two format bytes, a one-byte destination,
310/// a one-byte source, the control byte and the frame check sequence. Anything shorter
311/// describes a frame with nowhere to put its own checksum.
312const MIN_FRAME_LEN: usize = 2 + 1 + 1 + 1 + 2;
313
314/// Decode one frame from `bytes`, which must start at the opening flag.
315///
316/// # Errors
317/// [`ErrorKind::BadChecksum`] when the header or frame check sequence does not match,
318/// [`ErrorKind::Truncated`] when the frame is not all there yet.
319pub fn decode_frame(bytes: &[u8]) -> Result<(Frame<'_>, usize)> {
320    let mut r = Reader::new(bytes);
321    if r.u8()? != FLAG {
322        return Err(r.err_back(ErrorKind::InvalidValue, 1));
323    }
324    let format = r.u16()?;
325    if format & 0xF000 != 0xA000 {
326        return Err(r.err_back(ErrorKind::InvalidValue, 2));
327    }
328    let segmented = format & 0x0800 != 0;
329    let frame_len = usize::from(format & 0x07FF);
330    if frame_len < MIN_FRAME_LEN {
331        return Err(r.err_back(ErrorKind::InvalidLength, 2));
332    }
333    // The whole frame is the opening flag, `frame_len` bytes, and the closing flag.
334    let total = 1 + frame_len + 1;
335    if bytes.len() < total {
336        return Err(Error::new(ErrorKind::Truncated { needed: total - bytes.len() }, bytes.len()));
337    }
338    if bytes[total - 1] != FLAG {
339        return Err(Error::new(ErrorKind::InvalidValue, total - 1));
340    }
341
342    // Everything from here on is read out of the frame itself, never out of whatever
343    // else the caller happened to have buffered behind it. The addresses are
344    // variable-length and attacker-controlled, so a header that claims more bytes than
345    // the frame holds must fail as a short read rather than reach past the closing flag.
346    let frame = &bytes[..total];
347    let mut r = Reader::new(frame);
348    r.skip(3)?;
349    let destination = Address::decode(&mut r)?;
350    let source = Address::decode(&mut r)?;
351    let control = Control::from_u8(r.u8()?);
352    let header_end = r.offset();
353
354    // The frame check sequence occupies the last two bytes before the closing flag.
355    let fcs_at = total - 3;
356    // A header that runs into or past the frame check sequence describes a frame that
357    // cannot exist: there is nowhere for the checksum to be.
358    if header_end > fcs_at {
359        return Err(Error::new(ErrorKind::InvalidLength, header_end));
360    }
361    let header = &frame[1..header_end];
362    let fcs = u16::from_le_bytes([frame[fcs_at], frame[fcs_at + 1]]);
363    if fcs != fcs16(&frame[1..fcs_at]) {
364        return Err(Error::new(ErrorKind::BadChecksum, fcs_at));
365    }
366
367    let information = if header_end == fcs_at {
368        &[][..]
369    } else {
370        // An information field needs its own two-byte header check sequence in front of
371        // it, so there must be room for both.
372        if header_end + 2 > fcs_at {
373            return Err(Error::new(ErrorKind::InvalidLength, header_end));
374        }
375        let hcs = u16::from_le_bytes([frame[header_end], frame[header_end + 1]]);
376        if hcs != fcs16(header) {
377            return Err(Error::new(ErrorKind::BadChecksum, header_end));
378        }
379        &frame[header_end + 2..fcs_at]
380    };
381
382    Ok((Frame { segmented, destination, source, control, information }, total))
383}
384
385/// What a [`Framer`] found.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387pub enum Found<'a> {
388    /// A complete, checksum-valid frame.
389    Frame {
390        /// The frame.
391        frame: Frame<'a>,
392        /// How many bytes of the input it used, including anything discarded before it.
393        consumed: usize,
394    },
395    /// No complete frame yet.
396    Incomplete {
397        /// How many leading bytes are certainly not part of any frame and may be
398        /// dropped.
399        ///
400        /// This is what keeps a receive buffer bounded on a noisy link: without it, a
401        /// caller that keeps everything until a frame arrives grows without limit while
402        /// a broken transmitter chatters.
403        discard: usize,
404    },
405}
406
407/// A resynchronising frame finder over a byte stream.
408///
409/// Feed it whatever arrives. It returns complete, checksum-valid frames and discards
410/// everything else — line noise, the echo of the frame just sent on a half-duplex bus,
411/// a partial frame from before the link came up.
412///
413/// The scan does not stop at the first flag that *might* begin a frame. A noise byte
414/// that happens to look like a length field would otherwise make the finder wait
415/// forever for a frame that was never sent, while the real frame sat in the buffer
416/// behind it. So every flag position is tried, a complete frame wins over an incomplete
417/// candidate, and only when nothing completes does the finder report how much it is
418/// still waiting on.
419#[derive(Debug, Default, Clone, Copy)]
420pub struct Framer {
421    discarded: usize,
422}
423
424impl Framer {
425    /// A new finder.
426    #[must_use]
427    pub const fn new() -> Self {
428        Self { discarded: 0 }
429    }
430
431    /// How many bytes have been thrown away. A rising count is the symptom of a
432    /// mis-wired or noisy link, and is worth reporting.
433    #[must_use]
434    pub const fn discarded(&self) -> usize {
435        self.discarded
436    }
437
438    /// Find the next frame in `buf`.
439    ///
440    /// # Errors
441    /// Never, currently: a malformed candidate is discarded rather than reported, which
442    /// is what a link layer facing noise has to do. The signature keeps the `Result` so
443    /// a future policy — refusing after too many discards, say — does not break callers.
444    pub fn next_frame<'b>(&mut self, buf: &'b [u8]) -> Result<Found<'b>> {
445        let mut first_incomplete: Option<usize> = None;
446        let mut start = 0usize;
447
448        while start < buf.len() {
449            let Some(rel) = buf[start..].iter().position(|b| *b == FLAG) else {
450                break;
451            };
452            let from = start + rel;
453            match decode_frame(&buf[from..]) {
454                Ok((frame, used)) => {
455                    self.discarded += from;
456                    return Ok(Found::Frame { frame, consumed: from + used });
457                }
458                Err(e) => {
459                    if e.is_truncated() && first_incomplete.is_none() {
460                        first_incomplete = Some(from);
461                    }
462                    // This flag did not begin a frame. It may have been the *closing*
463                    // flag of one, so the search resumes after it.
464                    start = from + 1;
465                }
466            }
467        }
468
469        // Everything before the earliest candidate that might still complete is noise.
470        let discard = first_incomplete.unwrap_or(buf.len());
471        self.discarded += discard;
472        Ok(Found::Incomplete { discard })
473    }
474}
475
476/// Splits one LLC service data unit across as many information frames as it takes.
477///
478/// The information field is 128 bytes until SNRM negotiates otherwise, so an APDU of any
479/// substance needs several frames: every one but the last sets the segmentation bit, and
480/// the receiver concatenates the information fields.
481///
482/// Not the same mechanism as application-layer block transfer, and they compose. Block
483/// transfer cuts a **value** into APDUs the PDU size can hold; this cuts each **APDU**
484/// into frames the information field can hold. A meter with a 1024-byte PDU size on a
485/// 128-byte link uses both at once.
486///
487/// The unit split is the whole LSDU — LLC header and APDU — because that is what the
488/// link layer carries, so the header rides in the first segment only.
489///
490/// ```
491/// use dlms_cosem_kit::transport::hdlc::{Address, Segmenter, LLC_REQUEST};
492///
493/// let apdu = [0xC0u8; 300];
494/// let mut lsdu = [0u8; 3 + 300];
495/// lsdu[..3].copy_from_slice(&LLC_REQUEST);
496/// lsdu[3..].copy_from_slice(&apdu);
497///
498/// let mut segmenter = Segmenter::new(&lsdu, 128)?;
499/// let mut frame = [0u8; 256];
500/// let mut frames = 0;
501/// while let Some(n) = segmenter.next_frame(
502///     Address::server(1, 17), Address::client(0x10), 0, 0, &mut frame)?
503/// {
504///     assert!(n <= 128 + 16, "each frame fits the link");
505///     frames += 1;
506/// }
507/// assert_eq!(frames, 3, "303 bytes at 128 per frame");
508/// # Ok::<(), dlms_cosem_kit::Error>(())
509/// ```
510#[derive(Debug, Clone, Copy)]
511pub struct Segmenter<'a> {
512    lsdu: &'a [u8],
513    sent: usize,
514    max_info: usize,
515}
516
517impl<'a> Segmenter<'a> {
518    /// Split `lsdu` into information fields of at most `max_info` bytes.
519    ///
520    /// # Errors
521    /// [`ErrorKind::InvalidLength`] when `max_info` is zero, which would never finish.
522    pub fn new(lsdu: &'a [u8], max_info: u16) -> Result<Self> {
523        if max_info == 0 {
524            return Err(Error::new(ErrorKind::InvalidLength, 0));
525        }
526        Ok(Self { lsdu, sent: 0, max_info: usize::from(max_info) })
527    }
528
529    /// True when every segment has been produced.
530    #[must_use]
531    pub const fn is_done(&self) -> bool {
532        self.sent >= self.lsdu.len()
533    }
534
535    /// How many bytes are still to go out.
536    #[must_use]
537    pub const fn remaining(&self) -> usize {
538        self.lsdu.len().saturating_sub(self.sent)
539    }
540
541    /// Encode the next frame into `out`, or `None` when there are none left.
542    ///
543    /// `ns` and `nr` are the link's sequence numbers; the caller owns flow control and
544    /// advances them, because a station that is also acknowledging the peer's frames
545    /// knows things this type does not.
546    ///
547    /// # Errors
548    /// When `out` is too small for the frame.
549    pub fn next_frame(
550        &mut self,
551        destination: Address,
552        source: Address,
553        ns: u8,
554        nr: u8,
555        out: &mut [u8],
556    ) -> Result<Option<usize>> {
557        if self.is_done() {
558            return Ok(None);
559        }
560        let end = self.sent.saturating_add(self.max_info).min(self.lsdu.len());
561        let information = self.lsdu.get(self.sent..end).ok_or(Error::new(ErrorKind::InvalidLength, 0))?;
562        let segmented = end < self.lsdu.len();
563        let frame = Frame {
564            segmented,
565            destination,
566            source,
567            // The poll/final bit closes the transmission, so it belongs on the last
568            // segment: a station that sets it on every one invites the peer to answer
569            // in the middle of an APDU.
570            control: Control::I { ns, nr, pf: !segmented },
571            information,
572        };
573        let mut w = crate::codec::SliceWriter::new(out);
574        frame.encode(&mut w)?;
575        self.sent = end;
576        Ok(Some(w.written()))
577    }
578}
579
580/// Reassembles an LLC service data unit from segmented information frames.
581///
582/// The buffer is the caller's, as everywhere else: the largest APDU a link must carry
583/// is a property of the deployment, and a reassembler that allocated one would be the
584/// crate deciding it.
585///
586/// Frames are required to arrive with consecutive send-sequence numbers. That is not
587/// bookkeeping — a lost or duplicated segment concatenated in the wrong place produces
588/// a byte string that often still decodes, into an APDU that is simply wrong.
589#[derive(Debug)]
590pub struct Reassembler<'a> {
591    buf: &'a mut [u8],
592    len: usize,
593    /// The send-sequence number the next segment must carry, once one has arrived.
594    expect_ns: Option<u8>,
595    complete: bool,
596}
597
598/// Where a [`Reassembler`] is, without the buffer it fills.
599///
600/// A reassembler borrows its storage, so a driver that owns the storage cannot keep the
601/// reassembler between reads. It keeps this instead and resumes with
602/// [`Reassembler::resume`] over the same buffer.
603#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
604pub struct ReassemblyState {
605    len: usize,
606    expect_ns: Option<u8>,
607    complete: bool,
608}
609
610impl<'a> Reassembler<'a> {
611    /// A reassembler filling `buf`.
612    #[must_use]
613    pub fn new(buf: &'a mut [u8]) -> Self {
614        Self { buf, len: 0, expect_ns: None, complete: false }
615    }
616
617    /// Continue a unit over `buf` — the same buffer the saved [`ReassemblyState`] came from.
618    #[must_use]
619    pub fn resume(buf: &'a mut [u8], state: ReassemblyState) -> Self {
620        let len = state.len.min(buf.len());
621        Self { buf, len, expect_ns: state.expect_ns, complete: state.complete }
622    }
623
624    /// Where this reassembler is, to resume later.
625    #[must_use]
626    pub const fn state(&self) -> ReassemblyState {
627        ReassemblyState { len: self.len, expect_ns: self.expect_ns, complete: self.complete }
628    }
629
630    /// Feed one frame. Returns true when a complete LSDU is available.
631    ///
632    /// Frames that carry no information — supervisory and unnumbered ones — are ignored
633    /// rather than refused, so a caller can hand over everything the framer finds.
634    ///
635    /// # Errors
636    /// [`ErrorKind::UnexpectedMessage`] when a segment arrives out of sequence;
637    /// [`ErrorKind::BufferTooSmall`] when the reassembled unit does not fit.
638    pub fn push(&mut self, frame: &Frame<'_>) -> Result<bool> {
639        let Control::I { ns, .. } = frame.control else {
640            return Ok(false);
641        };
642        if self.complete {
643            // The previous unit was never taken; starting a new one over the top of it
644            // would silently discard it.
645            self.reset();
646        }
647        if let Some(expected) = self.expect_ns {
648            if ns != expected {
649                return Err(Error::new(ErrorKind::UnexpectedMessage, self.len));
650            }
651        }
652        let end = self.len.saturating_add(frame.information.len());
653        let capacity = self.buf.len();
654        let at = self.len;
655        let slot = self
656            .buf
657            .get_mut(at..end)
658            .ok_or(Error::new(ErrorKind::BufferTooSmall { needed: end.saturating_sub(capacity) }, at))?;
659        slot.copy_from_slice(frame.information);
660        self.len = end;
661        self.expect_ns = Some((ns + 1) % 8);
662        self.complete = !frame.segmented;
663        Ok(self.complete)
664    }
665
666    /// The reassembled unit — the LLC header and the APDU behind it.
667    ///
668    /// Empty until [`Reassembler::push`] has returned true.
669    #[must_use]
670    pub fn lsdu(&self) -> &[u8] {
671        if self.complete { self.buf.get(..self.len).unwrap_or(&[]) } else { &[] }
672    }
673
674    /// How many bytes have been gathered, complete or not.
675    #[must_use]
676    pub const fn len(&self) -> usize {
677        self.len
678    }
679
680    /// True before any information has been gathered.
681    #[must_use]
682    pub const fn is_empty(&self) -> bool {
683        self.len == 0
684    }
685
686    /// Discard everything, ready for the next unit.
687    pub const fn reset(&mut self) {
688        self.len = 0;
689        self.expect_ns = None;
690        self.complete = false;
691    }
692}
693
694/// Which end of the link a [`Connection`] is.
695///
696/// HDLC as DLMS uses it is not symmetric: the client is the *primary* station and the
697/// only one that may open the link or poll, and the server answers. A connection that did
698/// not know which it was would let a meter send an SNRM, which no meter does.
699#[derive(Debug, Clone, Copy, PartialEq, Eq)]
700pub enum Role {
701    /// The primary station: opens the link, polls, and sets the poll bit.
702    Client,
703    /// The secondary station: answers, and sets the final bit.
704    Server,
705}
706
707/// Where the link is.
708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
709pub enum LinkState {
710    /// No link. An information frame here is refused.
711    Disconnected,
712    /// An SNRM has gone out and the UA has not come back.
713    Connecting,
714    /// Normal response mode: information frames may flow.
715    Connected,
716    /// A DISC has gone out.
717    Disconnecting,
718}
719
720/// What a received frame means for the caller.
721///
722/// Every variant is something to *do*, which is the point: a caller loops on frames and
723/// branches on this, and there is nothing else it has to know about HDLC's rules.
724#[derive(Debug, Clone, Copy, PartialEq, Eq)]
725pub enum Event {
726    /// Nothing to do; keep reading.
727    Idle,
728    /// The link came up. [`Connection::parameters`] are what both ends agreed.
729    Connected,
730    /// The link went down, because the peer asked or refused.
731    Disconnected,
732    /// A complete service data unit is in the reassembler.
733    Lsdu,
734    /// Answer with what [`Connection::acknowledge`] builds — a UA confirming the peer's
735    /// SNRM or DISC.
736    AcknowledgeRequired,
737    /// The peer has stopped short of a complete unit and is waiting to be asked for the
738    /// rest: send what [`Connection::poll`] builds.
739    PollRequired,
740}
741
742/// One HDLC link, with its sequence numbers.
743///
744/// [`Framer`], [`Segmenter`] and [`Reassembler`] are the pieces; this is the machine that
745/// drives them, and it exists because the pieces alone leave the caller holding the two
746/// things that are easy to get wrong: **the SNRM/UA handshake**, whose answer carries the
747/// parameters every later frame is sized by, and **the send and receive sequence
748/// numbers**, which are modulo eight, advance on different events for each role, and
749/// produce a link that half works when they drift.
750///
751/// What it deliberately does **not** do is recover from loss. Retransmission needs a
752/// timer, and there is no clock in this crate ([`crate::transport`]); a frame out of
753/// sequence is reported by name so the caller can reset the link, rather than being
754/// silently accepted into the wrong place in a service data unit. Naming that limit is
755/// worth more than a retry loop that cannot time out.
756///
757/// ```
758/// use dlms_cosem_kit::transport::hdlc::{Address, Connection, Event, Parameters, Role};
759///
760/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
761/// let client_addr = Address::client(0x10);
762/// let server_addr = Address::server(1, 17);
763/// let mut client = Connection::new(Role::Client, client_addr, server_addr, Parameters::default());
764/// let mut server = Connection::new(Role::Server, server_addr, client_addr, Parameters::default());
765///
766/// let mut buf = [0u8; 128];
767/// let mut storage = [0u8; 512];
768/// let mut into = dlms_cosem_kit::transport::hdlc::Reassembler::new(&mut storage);
769///
770/// // The client opens the link and the server confirms it.
771/// let n = client.connect(&mut buf)?;
772/// let (frame, _) = dlms_cosem_kit::transport::hdlc::decode_frame(&buf[..n])?;
773/// assert_eq!(server.handle(&frame, &mut into)?, Event::AcknowledgeRequired);
774///
775/// let mut reply = [0u8; 128];
776/// let n = server.acknowledge(&mut reply)?;
777/// let (frame, _) = dlms_cosem_kit::transport::hdlc::decode_frame(&reply[..n])?;
778/// assert_eq!(client.handle(&frame, &mut into)?, Event::Connected);
779/// # Ok(())
780/// # }
781/// ```
782#[derive(Debug, Clone, Copy)]
783pub struct Connection {
784    role: Role,
785    local: Address,
786    peer: Address,
787    state: LinkState,
788    /// The sequence number the next information frame this station sends will carry.
789    ns: u8,
790    /// The sequence number this station next expects from the peer.
791    nr: u8,
792    proposed: Parameters,
793    negotiated: Parameters,
794    /// What the pending [`Connection::acknowledge`] is answering.
795    acknowledging: Option<Control>,
796}
797
798impl Connection {
799    /// A link between `local` and `peer`, proposing `proposed` when it opens.
800    ///
801    /// Until SNRM and UA have been exchanged the link runs on
802    /// [`Parameters::default`] — 128-byte information fields and a window of one — which
803    /// is what the standard says a station must assume, and what an optical probe often
804    /// stays on.
805    #[must_use]
806    pub const fn new(role: Role, local: Address, peer: Address, proposed: Parameters) -> Self {
807        Self {
808            role,
809            local,
810            peer,
811            state: LinkState::Disconnected,
812            ns: 0,
813            nr: 0,
814            proposed,
815            negotiated: Parameters::DEFAULT,
816            acknowledging: None,
817        }
818    }
819
820    /// Where the link is.
821    #[must_use]
822    pub const fn state(&self) -> LinkState {
823        self.state
824    }
825
826    /// What both ends agreed, or the defaults before they have.
827    #[must_use]
828    pub const fn parameters(&self) -> Parameters {
829        self.negotiated
830    }
831
832    /// True when information frames may flow.
833    #[must_use]
834    pub const fn is_connected(&self) -> bool {
835        matches!(self.state, LinkState::Connected)
836    }
837
838    /// Build the SNRM that opens the link.
839    ///
840    /// # Errors
841    /// [`ErrorKind::UnexpectedMessage`] on a server, which never opens a link, or when
842    /// one is already open; [`ErrorKind::BufferTooSmall`] when `out` is too small.
843    pub fn connect(&mut self, out: &mut [u8]) -> Result<usize> {
844        if self.role != Role::Client || self.state == LinkState::Connected {
845            return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
846        }
847        let mut info = [0u8; 32];
848        let mut iw = crate::codec::SliceWriter::new(&mut info);
849        self.proposed.encode(&mut iw)?;
850        let n = iw.written();
851        let frame = Frame {
852            segmented: false,
853            destination: self.peer,
854            source: self.local,
855            control: Control::Snrm,
856            information: info.get(..n).unwrap_or(&[]),
857        };
858        let mut w = crate::codec::SliceWriter::new(out);
859        frame.encode(&mut w)?;
860        self.state = LinkState::Connecting;
861        Ok(w.written())
862    }
863
864    /// Build the DISC that closes the link.
865    ///
866    /// # Errors
867    /// When `out` is too small.
868    pub fn disconnect(&mut self, out: &mut [u8]) -> Result<usize> {
869        let frame = Frame::control_only(self.peer, self.local, Control::Disc);
870        let mut w = crate::codec::SliceWriter::new(out);
871        frame.encode(&mut w)?;
872        self.state = LinkState::Disconnecting;
873        Ok(w.written())
874    }
875
876    /// Build the UA that [`Event::AcknowledgeRequired`] asked for.
877    ///
878    /// Answering an SNRM it carries the negotiated parameters, which is how the peer
879    /// learns what it may actually send; answering a DISC it carries nothing.
880    ///
881    /// # Errors
882    /// [`ErrorKind::UnexpectedMessage`] when nothing is waiting to be acknowledged.
883    pub fn acknowledge(&mut self, out: &mut [u8]) -> Result<usize> {
884        let pending = self.acknowledging.take().ok_or(Error::new(ErrorKind::UnexpectedMessage, 0))?;
885        let mut info = [0u8; 32];
886        let mut n = 0;
887        if pending == Control::Snrm {
888            let mut iw = crate::codec::SliceWriter::new(&mut info);
889            self.negotiated.encode(&mut iw)?;
890            n = iw.written();
891        }
892        let frame = Frame {
893            segmented: false,
894            destination: self.peer,
895            source: self.local,
896            control: Control::Ua,
897            information: info.get(..n).unwrap_or(&[]),
898        };
899        let mut w = crate::codec::SliceWriter::new(out);
900        frame.encode(&mut w)?;
901        Ok(w.written())
902    }
903
904    /// Build the receive-ready frame that [`Event::PollRequired`] asked for.
905    ///
906    /// It carries this station's receive sequence number, which is what tells the peer
907    /// where to continue, and the poll bit, which is what gives it permission to.
908    ///
909    /// # Errors
910    /// When `out` is too small.
911    pub fn poll(&mut self, out: &mut [u8]) -> Result<usize> {
912        let frame = Frame::control_only(self.peer, self.local, Control::Rr { nr: self.nr, pf: true });
913        let mut w = crate::codec::SliceWriter::new(out);
914        frame.encode(&mut w)?;
915        Ok(w.written())
916    }
917
918    /// Split a service data unit — the LLC header and the APDU behind it — into frames
919    /// this link can carry.
920    ///
921    /// # Errors
922    /// [`ErrorKind::UnexpectedMessage`] when the link is not open.
923    pub fn segmenter<'d>(&self, lsdu: &'d [u8]) -> Result<Segmenter<'d>> {
924        if self.state != LinkState::Connected {
925            return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
926        }
927        Segmenter::new(lsdu, self.negotiated.max_info_tx)
928    }
929
930    /// Emit the next frame of a unit, advancing the send sequence number.
931    ///
932    /// This is the reason the segmenter is driven through the connection rather than
933    /// used directly: `ns` advances once per information frame, modulo eight, and a
934    /// caller keeping it by hand is a caller whose link works until the ninth frame.
935    ///
936    /// # Errors
937    /// When the link is not open, or `out` is too small.
938    pub fn next_frame(&mut self, segmenter: &mut Segmenter<'_>, out: &mut [u8]) -> Result<Option<usize>> {
939        if self.state != LinkState::Connected {
940            return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
941        }
942        let n = segmenter.next_frame(self.peer, self.local, self.ns, self.nr, out)?;
943        if n.is_some() {
944            self.ns = (self.ns + 1) % 8;
945        }
946        Ok(n)
947    }
948
949    /// Take one received frame and say what it means.
950    ///
951    /// Frames carrying information are pushed into `into`; supervisory and unnumbered
952    /// frames are handled here.
953    ///
954    /// # Errors
955    /// [`ErrorKind::UnexpectedMessage`] for a frame that is not addressed to this
956    /// station, or whose send sequence number is neither the expected one nor a repeat
957    /// of the last accepted one — recovering from *that* needs a timer this crate does
958    /// not have, so it is named rather than guessed at.
959    pub fn handle(&mut self, frame: &Frame<'_>, into: &mut Reassembler<'_>) -> Result<Event> {
960        // A frame for somebody else on a shared bus is not this link's business. RS-485
961        // segments carry several meters, and accepting one addressed elsewhere mixes two
962        // conversations into one reassembly buffer.
963        if frame.destination != self.local {
964            return Ok(Event::Idle);
965        }
966        match frame.control {
967            Control::Snrm => {
968                if self.role != Role::Server {
969                    return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
970                }
971                let peer = Parameters::decode(frame.information)?;
972                self.negotiated = self.proposed.negotiate(peer);
973                self.reset_sequence();
974                self.state = LinkState::Connected;
975                self.acknowledging = Some(Control::Snrm);
976                into.reset();
977                Ok(Event::AcknowledgeRequired)
978            }
979            Control::Ua => {
980                if self.state == LinkState::Connecting {
981                    // The UA carries the parameters the peer actually agreed to, and
982                    // every later frame is sized by them.
983                    let peer = Parameters::decode(frame.information)?;
984                    self.negotiated = self.proposed.negotiate(peer);
985                    self.reset_sequence();
986                    self.state = LinkState::Connected;
987                    into.reset();
988                    return Ok(Event::Connected);
989                }
990                // Otherwise it answers our DISC.
991                self.state = LinkState::Disconnected;
992                Ok(Event::Disconnected)
993            }
994            Control::Disc => {
995                self.state = LinkState::Disconnected;
996                self.acknowledging = Some(Control::Disc);
997                Ok(Event::AcknowledgeRequired)
998            }
999            // The peer is not connected, or rejected the frame. Either way the link is
1000            // not usable and pretending otherwise wastes a round trip per frame.
1001            Control::Dm | Control::Frmr => {
1002                self.state = LinkState::Disconnected;
1003                Ok(Event::Disconnected)
1004            }
1005            Control::I { ns, .. } => {
1006                if self.state != LinkState::Connected {
1007                    return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1008                }
1009                // A repeat of the frame just accepted is a retransmission of something
1010                // already held: ignoring it is right, and concatenating it again is the
1011                // bug that produces an APDU with a duplicated middle.
1012                if ns == (self.nr + 7) % 8 {
1013                    return Ok(Event::Idle);
1014                }
1015                if ns != self.nr {
1016                    return Err(Error::new(ErrorKind::UnexpectedMessage, 0));
1017                }
1018                self.nr = (self.nr + 1) % 8;
1019                if into.push(frame)? {
1020                    return Ok(Event::Lsdu);
1021                }
1022                // The unit is not finished. If the peer has given up the line — the
1023                // poll/final bit closes a transmission — it is waiting to be asked for
1024                // the rest.
1025                let handed_over = match frame.control {
1026                    Control::I { pf, .. } => pf,
1027                    _ => false,
1028                };
1029                Ok(if handed_over { Event::PollRequired } else { Event::Idle })
1030            }
1031            Control::Rr { .. } | Control::Rnr { .. } | Control::Ui => Ok(Event::Idle),
1032        }
1033    }
1034
1035    /// Forget the link, ready for a new one on the same wire.
1036    pub const fn reset(&mut self) {
1037        self.state = LinkState::Disconnected;
1038        self.negotiated = Parameters::DEFAULT;
1039        self.acknowledging = None;
1040        self.reset_sequence();
1041    }
1042
1043    /// SNRM and UA reset both counters at both ends. A station that carried them over
1044    /// answers the first frame of a new link with the sequence number of the last frame
1045    /// of the old one.
1046    const fn reset_sequence(&mut self) {
1047        self.ns = 0;
1048        self.nr = 0;
1049    }
1050}
1051
1052/// The link parameters SNRM proposes and UA confirms.
1053#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1054pub struct Parameters {
1055    /// The largest information field this side will send.
1056    pub max_info_tx: u16,
1057    /// The largest information field this side will accept.
1058    pub max_info_rx: u16,
1059    /// How many frames this side will send before an acknowledgement.
1060    pub window_tx: u32,
1061    /// How many frames this side will accept before acknowledging.
1062    pub window_rx: u32,
1063}
1064
1065impl Default for Parameters {
1066    fn default() -> Self {
1067        Self::DEFAULT
1068    }
1069}
1070
1071impl Parameters {
1072    /// The values a station must assume when the peer negotiates nothing: 128-byte
1073    /// information fields and a window of one.
1074    ///
1075    /// Not a guess and not a minimum — it is what the standard says both ends run on
1076    /// until SNRM and UA say otherwise, and what a great many optical probes never leave.
1077    pub const DEFAULT: Self = Self { max_info_tx: 128, max_info_rx: 128, window_tx: 1, window_rx: 1 };
1078
1079    /// Encode as the SNRM/UA information field.
1080    pub fn encode(&self, w: &mut dyn Writer) -> Result<()> {
1081        let mut body = [0u8; 32];
1082        let mut bw = crate::codec::SliceWriter::new(&mut body);
1083        write_param(&mut bw, 5, u32::from(self.max_info_tx))?;
1084        write_param(&mut bw, 6, u32::from(self.max_info_rx))?;
1085        write_param(&mut bw, 7, self.window_tx)?;
1086        write_param(&mut bw, 8, self.window_rx)?;
1087        let n = bw.written();
1088        w.write_bytes(&[0x81, 0x80, n as u8])?;
1089        w.write_bytes(&body[..n])
1090    }
1091
1092    /// Decode an SNRM/UA information field, keeping the default for anything absent.
1093    pub fn decode(bytes: &[u8]) -> Result<Self> {
1094        let mut out = Self::default();
1095        if bytes.is_empty() {
1096            return Ok(out);
1097        }
1098        let mut r = Reader::new(bytes);
1099        if r.u8()? != 0x81 || r.u8()? != 0x80 {
1100            return Err(r.err_back(ErrorKind::InvalidValue, 2));
1101        }
1102        let len = usize::from(r.u8()?);
1103        let mut inner = Reader::with_base(r.take(len)?, 3);
1104        while !inner.is_empty() {
1105            let id = inner.u8()?;
1106            let vlen = usize::from(inner.u8()?);
1107            let raw = inner.take(vlen)?;
1108            let mut v: u32 = 0;
1109            for b in raw {
1110                v = (v << 8) | u32::from(*b);
1111            }
1112            match id {
1113                5 => out.max_info_tx = u16::try_from(v).unwrap_or(u16::MAX),
1114                6 => out.max_info_rx = u16::try_from(v).unwrap_or(u16::MAX),
1115                7 => out.window_tx = v,
1116                8 => out.window_rx = v,
1117                _ => {}
1118            }
1119        }
1120        Ok(out)
1121    }
1122
1123    /// What both sides can do: each side's send limit capped by the other's receive
1124    /// limit.
1125    #[must_use]
1126    pub const fn negotiate(self, peer: Self) -> Self {
1127        Self {
1128            max_info_tx: if self.max_info_tx < peer.max_info_rx {
1129                self.max_info_tx
1130            } else {
1131                peer.max_info_rx
1132            },
1133            max_info_rx: if self.max_info_rx < peer.max_info_tx {
1134                self.max_info_rx
1135            } else {
1136                peer.max_info_tx
1137            },
1138            window_tx: if self.window_tx < peer.window_rx { self.window_tx } else { peer.window_rx },
1139            window_rx: if self.window_rx < peer.window_tx { self.window_rx } else { peer.window_tx },
1140        }
1141    }
1142}
1143
1144fn write_param(w: &mut dyn Writer, id: u8, value: u32) -> Result<()> {
1145    let be = value.to_be_bytes();
1146    let first = be.iter().position(|b| *b != 0).unwrap_or(3);
1147    let n = 4 - first;
1148    w.write_bytes(&[id, n as u8])?;
1149    w.write_bytes(&be[first..])
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154    use super::*;
1155    use crate::codec::SliceWriter;
1156
1157    /// The X-25 / PPP check value for "123456789", which is what every published FCS-16
1158    /// description uses as its own test.
1159    #[test]
1160    fn fcs16_matches_the_published_check_value() {
1161        assert_eq!(fcs16(b"123456789"), 0x906E);
1162    }
1163
1164    #[test]
1165    fn addresses_round_trip_in_every_width() {
1166        for a in [
1167            Address::Single(0x10),
1168            Address::Double { upper: 1, lower: 0x11 },
1169            Address::Quad { upper: 1, lower: 0x3FFF },
1170        ] {
1171            let mut buf = [0u8; 8];
1172            let mut w = SliceWriter::new(&mut buf);
1173            a.encode(&mut w).unwrap();
1174            let n = w.written();
1175            assert_eq!(n, a.len());
1176            assert_eq!(buf[n - 1] & 1, 1, "the last byte marks the end");
1177            assert_eq!(Address::decode(&mut Reader::new(&buf[..n])).unwrap(), a);
1178        }
1179    }
1180
1181    #[test]
1182    fn a_client_address_is_the_sap_shifted_and_marked() {
1183        let mut buf = [0u8; 4];
1184        let mut w = SliceWriter::new(&mut buf);
1185        Address::client(0x10).encode(&mut w).unwrap();
1186        assert_eq!(w.as_slice(), [0x21]);
1187    }
1188
1189    #[test]
1190    fn a_wide_physical_address_forces_the_four_byte_form() {
1191        assert_eq!(Address::server(1, 0x3FFF).len(), 4);
1192        assert_eq!(Address::server(1, 17).len(), 2);
1193    }
1194
1195    #[test]
1196    fn control_bytes_round_trip() {
1197        for c in [
1198            Control::Snrm,
1199            Control::Ua,
1200            Control::Disc,
1201            Control::Dm,
1202            Control::Ui,
1203            Control::I { ns: 3, nr: 5, pf: true },
1204            Control::Rr { nr: 2, pf: false },
1205            Control::Rnr { nr: 7, pf: true },
1206        ] {
1207            assert_eq!(Control::from_u8(c.as_u8()), c, "{c:?} -> {:#04x}", c.as_u8());
1208        }
1209        assert_eq!(Control::Snrm.as_u8(), 0x93);
1210        assert_eq!(Control::Ua.as_u8(), 0x73);
1211        assert_eq!(Control::Disc.as_u8(), 0x53);
1212    }
1213
1214    #[test]
1215    fn a_frame_with_information_carries_both_check_sequences() {
1216        let frame = Frame {
1217            segmented: false,
1218            destination: Address::server(1, 17),
1219            source: Address::client(0x10),
1220            control: Control::I { ns: 0, nr: 0, pf: true },
1221            information: &[0xE6, 0xE6, 0x00, 0xC0, 0x01, 0x81],
1222        };
1223        let mut buf = [0u8; 64];
1224        let mut w = SliceWriter::new(&mut buf);
1225        frame.encode(&mut w).unwrap();
1226        let bytes = w.as_slice();
1227        assert_eq!(bytes[0], FLAG);
1228        assert_eq!(*bytes.last().unwrap(), FLAG);
1229        assert_eq!(bytes.len(), frame.encoded_len());
1230        let (back, used) = decode_frame(bytes).unwrap();
1231        assert_eq!(used, bytes.len());
1232        assert_eq!(back, frame);
1233    }
1234
1235    #[test]
1236    fn a_supervisory_frame_has_no_header_check_sequence() {
1237        let frame = Frame::control_only(
1238            Address::server(1, 17),
1239            Address::client(0x10),
1240            Control::Rr { nr: 1, pf: true },
1241        );
1242        let mut buf = [0u8; 32];
1243        let mut w = SliceWriter::new(&mut buf);
1244        frame.encode(&mut w).unwrap();
1245        let (back, _) = decode_frame(w.as_slice()).unwrap();
1246        assert_eq!(back, frame);
1247        assert_eq!(back.information, &[] as &[u8]);
1248    }
1249
1250    #[test]
1251    fn a_flipped_bit_is_caught_by_the_frame_check_sequence() {
1252        let frame = Frame {
1253            segmented: false,
1254            destination: Address::client(0x10),
1255            source: Address::server(1, 17),
1256            control: Control::I { ns: 0, nr: 1, pf: true },
1257            information: &[1, 2, 3, 4],
1258        };
1259        let mut buf = [0u8; 64];
1260        let mut w = SliceWriter::new(&mut buf);
1261        frame.encode(&mut w).unwrap();
1262        let n = w.written();
1263        for i in 1..n - 1 {
1264            let mut corrupt = buf;
1265            corrupt[i] ^= 0x01;
1266            if corrupt[i] == FLAG || buf[i] == FLAG {
1267                continue;
1268            }
1269            assert!(decode_frame(&corrupt[..n]).is_err(), "a flipped bit at {i} was not caught");
1270        }
1271    }
1272
1273    #[test]
1274    fn the_framer_resynchronises_past_noise() {
1275        let frame = Frame {
1276            segmented: false,
1277            destination: Address::client(0x10),
1278            source: Address::server(1, 17),
1279            control: Control::Ua,
1280            information: &[0x81, 0x80, 0x06, 0x05, 0x01, 0x80, 0x06, 0x01, 0x80],
1281        };
1282        let mut buf = [0u8; 64];
1283        let mut w = SliceWriter::new(&mut buf);
1284        frame.encode(&mut w).unwrap();
1285        let good = w.as_slice().to_vec();
1286
1287        let mut stream = alloc::vec::Vec::new();
1288        stream.extend_from_slice(&[0xAA, 0x7E, 0x55, 0x00]); // noise, including a flag
1289        stream.extend_from_slice(&good);
1290
1291        let mut framer = Framer::new();
1292        let Found::Frame { frame: back, consumed } = framer.next_frame(&stream).unwrap() else {
1293            panic!("the frame behind the noise was not found");
1294        };
1295        assert_eq!(back, frame);
1296        assert_eq!(consumed, stream.len());
1297        assert!(framer.discarded() >= 4, "the noise was counted");
1298    }
1299
1300    #[test]
1301    fn the_framer_waits_rather_than_failing_on_a_partial_frame() {
1302        let frame = Frame::control_only(Address::client(0x10), Address::server(1, 17), Control::Ua);
1303        let mut buf = [0u8; 32];
1304        let mut w = SliceWriter::new(&mut buf);
1305        frame.encode(&mut w).unwrap();
1306        let n = w.written();
1307        let mut framer = Framer::new();
1308        for split in 1..n {
1309            assert!(
1310                matches!(framer.next_frame(&buf[..split]).unwrap(), Found::Incomplete { discard: 0 }),
1311                "a frame cut at {split} must be waited for, not rejected or discarded"
1312            );
1313        }
1314        assert!(matches!(framer.next_frame(&buf[..n]).unwrap(), Found::Frame { .. }));
1315    }
1316
1317    /// Split, frame, find, reassemble — and get the same bytes back.
1318    #[test]
1319    fn a_long_apdu_survives_segmentation_and_reassembly() {
1320        let lsdu: alloc::vec::Vec<u8> = (0..1000u32).map(|i| (i % 251) as u8).collect();
1321        for max_info in [1u16, 2, 31, 32, 33, 128, 999, 1000, 1001] {
1322            let mut stream = alloc::vec::Vec::new();
1323            let mut segmenter = Segmenter::new(&lsdu, max_info).unwrap();
1324            let mut ns = 0u8;
1325            let mut frames = 0;
1326            let mut buf = [0u8; 1100];
1327            while let Some(n) =
1328                segmenter.next_frame(Address::server(1, 17), Address::client(0x10), ns, 0, &mut buf).unwrap()
1329            {
1330                stream.extend_from_slice(&buf[..n]);
1331                ns = (ns + 1) % 8;
1332                frames += 1;
1333            }
1334            let expected_frames = lsdu.len().div_ceil(usize::from(max_info));
1335            assert_eq!(frames, expected_frames, "at {max_info} bytes a frame");
1336
1337            let mut storage = [0u8; 1100];
1338            let mut assembled = Reassembler::new(&mut storage);
1339            let mut framer = Framer::new();
1340            let mut offset = 0;
1341            let mut done = false;
1342            while let Ok(Found::Frame { frame, consumed }) = framer.next_frame(&stream[offset..]) {
1343                assert!(
1344                    frame.information.len() <= usize::from(max_info),
1345                    "a segment overran the negotiated information field"
1346                );
1347                done = assembled.push(&frame).unwrap();
1348                offset += consumed;
1349                if done {
1350                    break;
1351                }
1352            }
1353            assert!(done, "the last segment must clear the segmentation bit");
1354            assert_eq!(assembled.lsdu(), &lsdu[..], "at {max_info} bytes a frame");
1355        }
1356    }
1357
1358    /// The poll/final bit closes a transmission, so it goes on the last segment only.
1359    /// Setting it on every one invites the peer to answer in the middle of an APDU.
1360    #[test]
1361    fn only_the_last_segment_is_final() {
1362        let lsdu = [0xAAu8; 300];
1363        let mut segmenter = Segmenter::new(&lsdu, 128).unwrap();
1364        let mut buf = [0u8; 256];
1365        let mut flags = alloc::vec::Vec::new();
1366        while let Some(n) =
1367            segmenter.next_frame(Address::server(1, 17), Address::client(0x10), 0, 0, &mut buf).unwrap()
1368        {
1369            let (frame, _) = decode_frame(&buf[..n]).unwrap();
1370            let Control::I { pf, .. } = frame.control else { panic!("not an information frame") };
1371            flags.push((frame.segmented, pf));
1372        }
1373        assert_eq!(flags, [(true, false), (true, false), (false, true)]);
1374    }
1375
1376    #[test]
1377    fn a_segment_out_of_sequence_is_refused_rather_than_concatenated() {
1378        let mut storage = [0u8; 64];
1379        let mut assembled = Reassembler::new(&mut storage);
1380        let seg = |ns, segmented, info| Frame {
1381            segmented,
1382            destination: Address::client(0x10),
1383            source: Address::server(1, 17),
1384            control: Control::I { ns, nr: 0, pf: !segmented },
1385            information: info,
1386        };
1387        assert!(!assembled.push(&seg(0, true, &[1, 2])).unwrap());
1388        // A repeat of the frame just taken, and a gap, are both refused.
1389        assert_eq!(assembled.push(&seg(0, true, &[1, 2])).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1390        assert_eq!(assembled.push(&seg(3, true, &[9])).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1391        assert!(assembled.push(&seg(1, false, &[3])).unwrap());
1392        assert_eq!(assembled.lsdu(), [1, 2, 3]);
1393    }
1394
1395    #[test]
1396    fn the_sequence_number_wraps_at_eight() {
1397        let mut storage = [0u8; 64];
1398        let mut assembled = Reassembler::new(&mut storage);
1399        for ns in 0..8u8 {
1400            let last = ns == 7;
1401            let frame = Frame {
1402                segmented: !last,
1403                destination: Address::client(0x10),
1404                source: Address::server(1, 17),
1405                control: Control::I { ns, nr: 0, pf: last },
1406                information: &[ns],
1407            };
1408            assert_eq!(assembled.push(&frame).unwrap(), last);
1409        }
1410        assert_eq!(assembled.lsdu(), [0, 1, 2, 3, 4, 5, 6, 7]);
1411    }
1412
1413    #[test]
1414    fn frames_that_carry_nothing_are_ignored_not_refused() {
1415        // A caller should be able to hand over everything the framer finds.
1416        let mut storage = [0u8; 32];
1417        let mut assembled = Reassembler::new(&mut storage);
1418        let rr = Frame::control_only(
1419            Address::client(0x10),
1420            Address::server(1, 17),
1421            Control::Rr { nr: 1, pf: true },
1422        );
1423        assert!(!assembled.push(&rr).unwrap());
1424        assert!(assembled.is_empty());
1425    }
1426
1427    #[test]
1428    fn a_unit_too_large_for_the_buffer_is_refused_before_it_overruns() {
1429        let mut storage = [0u8; 4];
1430        let mut assembled = Reassembler::new(&mut storage);
1431        let frame = Frame {
1432            segmented: true,
1433            destination: Address::client(0x10),
1434            source: Address::server(1, 17),
1435            control: Control::I { ns: 0, nr: 0, pf: false },
1436            information: &[0; 8],
1437        };
1438        assert!(matches!(assembled.push(&frame).unwrap_err().kind, ErrorKind::BufferTooSmall { .. }));
1439    }
1440
1441    #[test]
1442    fn an_information_field_of_zero_would_never_finish() {
1443        assert_eq!(Segmenter::new(&[1, 2, 3], 0).unwrap_err().kind, ErrorKind::InvalidLength);
1444    }
1445
1446    /// A whole link, both ends in one process: open it, carry a unit that needs several
1447    /// frames, and close it — with neither side keeping a sequence number by hand.
1448    #[test]
1449    fn a_link_opens_carries_a_long_unit_and_closes() {
1450        let client_addr = Address::client(0x10);
1451        let server_addr = Address::server(1, 17);
1452        let proposed = Parameters { max_info_tx: 64, max_info_rx: 64, window_tx: 1, window_rx: 1 };
1453        let mut client = Connection::new(Role::Client, client_addr, server_addr, proposed);
1454        let mut server = Connection::new(Role::Server, server_addr, client_addr, Parameters::default());
1455
1456        let mut a = [0u8; 256];
1457        let mut b = [0u8; 256];
1458        let mut client_storage = [0u8; 1024];
1459        let mut server_storage = [0u8; 1024];
1460        let mut to_server = Reassembler::new(&mut server_storage);
1461        let mut to_client = Reassembler::new(&mut client_storage);
1462
1463        // SNRM / UA.
1464        let n = client.connect(&mut a).unwrap();
1465        let (f, _) = decode_frame(&a[..n]).unwrap();
1466        assert_eq!(server.handle(&f, &mut to_server).unwrap(), Event::AcknowledgeRequired);
1467        let m = server.acknowledge(&mut b).unwrap();
1468        let (f, _) = decode_frame(&b[..m]).unwrap();
1469        assert_eq!(client.handle(&f, &mut to_client).unwrap(), Event::Connected);
1470        assert!(client.is_connected() && server.is_connected());
1471        // Each side sends at most what the other will receive.
1472        assert_eq!(client.parameters().max_info_tx, 64);
1473        assert_eq!(server.parameters().max_info_tx, 64, "capped by what the client proposed to receive");
1474
1475        // A unit several frames long, from client to server.
1476        let lsdu: alloc::vec::Vec<u8> = (0..200u32).map(|i| (i % 251) as u8).collect();
1477        let mut segmenter = client.segmenter(&lsdu).unwrap();
1478        let mut sequence_numbers = alloc::vec::Vec::new();
1479        let mut event = Event::Idle;
1480        while let Some(n) = client.next_frame(&mut segmenter, &mut a).unwrap() {
1481            let (f, _) = decode_frame(&a[..n]).unwrap();
1482            let Control::I { ns, .. } = f.control else { panic!("an information frame") };
1483            sequence_numbers.push(ns);
1484            event = server.handle(&f, &mut to_server).unwrap();
1485        }
1486        assert_eq!(sequence_numbers, [0, 1, 2, 3], "the connection counted, not the caller");
1487        assert_eq!(event, Event::Lsdu);
1488        assert_eq!(to_server.lsdu(), &lsdu[..]);
1489
1490        // And back, with the roles reversed.
1491        let reply: alloc::vec::Vec<u8> = (0..150u32).map(|i| (i % 97) as u8).collect();
1492        let mut segmenter = server.segmenter(&reply).unwrap();
1493        let mut event = Event::Idle;
1494        while let Some(m) = server.next_frame(&mut segmenter, &mut b).unwrap() {
1495            let (f, _) = decode_frame(&b[..m]).unwrap();
1496            event = client.handle(&f, &mut to_client).unwrap();
1497        }
1498        assert_eq!(event, Event::Lsdu);
1499        assert_eq!(to_client.lsdu(), &reply[..]);
1500
1501        // DISC / UA.
1502        let n = client.disconnect(&mut a).unwrap();
1503        let (f, _) = decode_frame(&a[..n]).unwrap();
1504        assert_eq!(server.handle(&f, &mut to_server).unwrap(), Event::AcknowledgeRequired);
1505        let m = server.acknowledge(&mut b).unwrap();
1506        let (f, _) = decode_frame(&b[..m]).unwrap();
1507        assert_eq!(client.handle(&f, &mut to_client).unwrap(), Event::Disconnected);
1508        assert!(!client.is_connected() && !server.is_connected());
1509    }
1510
1511    /// The counters are modulo eight, so a link that carries more than eight frames is
1512    /// where a hand-kept sequence number goes wrong — and it goes wrong by *working*
1513    /// for the first eight.
1514    #[test]
1515    fn the_sequence_numbers_wrap_at_eight_and_keep_working() {
1516        let client_addr = Address::client(0x10);
1517        let server_addr = Address::server(1, 17);
1518        let mut client = Connection::new(Role::Client, client_addr, server_addr, Parameters::default());
1519        let mut server = Connection::new(Role::Server, server_addr, client_addr, Parameters::default());
1520        let mut a = [0u8; 256];
1521        let mut b = [0u8; 256];
1522        let mut storage = [0u8; 4096];
1523        let mut into = Reassembler::new(&mut storage);
1524        let mut scratch = [0u8; 64];
1525        let mut ignored = Reassembler::new(&mut scratch);
1526
1527        let n = client.connect(&mut a).unwrap();
1528        let (f, _) = decode_frame(&a[..n]).unwrap();
1529        server.handle(&f, &mut into).unwrap();
1530        let m = server.acknowledge(&mut b).unwrap();
1531        let (f, _) = decode_frame(&b[..m]).unwrap();
1532        client.handle(&f, &mut ignored).unwrap();
1533
1534        // Twenty frames' worth: two and a half turns of the modulo-eight counter.
1535        let lsdu = [0xABu8; 20 * 128];
1536        let mut segmenter = client.segmenter(&lsdu).unwrap();
1537        let mut seen = alloc::vec::Vec::new();
1538        let mut event = Event::Idle;
1539        while let Some(n) = client.next_frame(&mut segmenter, &mut a).unwrap() {
1540            let (f, _) = decode_frame(&a[..n]).unwrap();
1541            let Control::I { ns, .. } = f.control else { panic!() };
1542            seen.push(ns);
1543            event = server.handle(&f, &mut into).unwrap();
1544        }
1545        assert_eq!(seen.len(), 20);
1546        assert_eq!(&seen[..10], &[0, 1, 2, 3, 4, 5, 6, 7, 0, 1], "and it wrapped");
1547        assert_eq!(event, Event::Lsdu);
1548        assert_eq!(into.lsdu().len(), lsdu.len());
1549    }
1550
1551    /// A frame addressed to another station on the same bus belongs to another
1552    /// conversation. Accepting it mixes two of them into one reassembly buffer.
1553    #[test]
1554    fn a_frame_for_another_station_is_ignored_rather_than_reassembled() {
1555        let mut server = Connection::new(
1556            Role::Server,
1557            Address::server(1, 17),
1558            Address::client(0x10),
1559            Parameters::default(),
1560        );
1561        let mut storage = [0u8; 64];
1562        let mut into = Reassembler::new(&mut storage);
1563        let elsewhere = Frame {
1564            segmented: false,
1565            destination: Address::server(1, 99),
1566            source: Address::client(0x10),
1567            control: Control::I { ns: 0, nr: 0, pf: true },
1568            information: &[1, 2, 3],
1569        };
1570        assert_eq!(server.handle(&elsewhere, &mut into).unwrap(), Event::Idle);
1571        assert!(into.is_empty(), "nothing of another station's conversation was kept");
1572    }
1573
1574    /// A retransmission of the frame just accepted is ignored; a gap is named. Recovering
1575    /// from the gap needs a timer, which is the caller's, so the link says so rather than
1576    /// concatenating the fragment into the wrong place.
1577    #[test]
1578    fn a_repeat_is_ignored_and_a_gap_is_named() {
1579        let client_addr = Address::client(0x10);
1580        let server_addr = Address::server(1, 17);
1581        let mut client = Connection::new(Role::Client, client_addr, server_addr, Parameters::default());
1582        let mut server = Connection::new(Role::Server, server_addr, client_addr, Parameters::default());
1583        let mut a = [0u8; 256];
1584        let mut b = [0u8; 256];
1585        let mut storage = [0u8; 256];
1586        let mut into = Reassembler::new(&mut storage);
1587        let mut scratch = [0u8; 64];
1588        let mut ignored = Reassembler::new(&mut scratch);
1589
1590        let n = client.connect(&mut a).unwrap();
1591        let (f, _) = decode_frame(&a[..n]).unwrap();
1592        server.handle(&f, &mut into).unwrap();
1593        let m = server.acknowledge(&mut b).unwrap();
1594        let (f, _) = decode_frame(&b[..m]).unwrap();
1595        client.handle(&f, &mut ignored).unwrap();
1596
1597        let lsdu = [0xAAu8; 200];
1598        let mut segmenter = client.segmenter(&lsdu).unwrap();
1599        let n = client.next_frame(&mut segmenter, &mut a).unwrap().unwrap();
1600        let (first, _) = decode_frame(&a[..n]).unwrap();
1601        assert_eq!(server.handle(&first, &mut into).unwrap(), Event::Idle);
1602        let held = into.len();
1603        // The same frame again.
1604        assert_eq!(server.handle(&first, &mut into).unwrap(), Event::Idle);
1605        assert_eq!(into.len(), held, "a retransmission must not be concatenated twice");
1606
1607        // And a frame from two places further on.
1608        let jumped = Frame {
1609            segmented: true,
1610            destination: server_addr,
1611            source: client_addr,
1612            control: Control::I { ns: 5, nr: 0, pf: false },
1613            information: &[9, 9],
1614        };
1615        assert_eq!(server.handle(&jumped, &mut into).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1616    }
1617
1618    /// A server never opens a link, and nothing may flow before one is open.
1619    #[test]
1620    fn the_roles_are_not_interchangeable() {
1621        let mut server = Connection::new(
1622            Role::Server,
1623            Address::server(1, 17),
1624            Address::client(0x10),
1625            Parameters::default(),
1626        );
1627        let mut out = [0u8; 64];
1628        assert_eq!(server.connect(&mut out).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1629        assert_eq!(server.segmenter(&[1, 2, 3]).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1630        assert_eq!(server.acknowledge(&mut out).unwrap_err().kind, ErrorKind::UnexpectedMessage);
1631    }
1632
1633    #[test]
1634    fn snrm_parameters_round_trip_and_negotiate_downwards() {
1635        let p = Parameters { max_info_tx: 512, max_info_rx: 1024, window_tx: 3, window_rx: 5 };
1636        let mut buf = [0u8; 64];
1637        let mut w = SliceWriter::new(&mut buf);
1638        p.encode(&mut w).unwrap();
1639        assert_eq!(Parameters::decode(w.as_slice()).unwrap(), p);
1640
1641        let peer = Parameters { max_info_tx: 256, max_info_rx: 128, window_tx: 1, window_rx: 1 };
1642        let n = p.negotiate(peer);
1643        assert_eq!(n.max_info_tx, 128, "capped by what the peer will receive");
1644        assert_eq!(n.max_info_rx, 256);
1645        assert_eq!(n.window_tx, 1);
1646    }
1647
1648    #[test]
1649    fn an_empty_information_field_means_the_defaults() {
1650        assert_eq!(Parameters::decode(&[]).unwrap(), Parameters::default());
1651    }
1652
1653    #[test]
1654    fn a_false_candidate_does_not_hide_the_frame_behind_it() {
1655        // A noise byte that looks like the start of a long frame, then a real one. A
1656        // finder that stopped at the first plausible flag would wait for a frame that
1657        // was never sent while the real one sat behind it.
1658        let frame = Frame::control_only(Address::client(0x10), Address::server(1, 17), Control::Ua);
1659        let mut buf = [0u8; 32];
1660        let mut w = SliceWriter::new(&mut buf);
1661        frame.encode(&mut w).unwrap();
1662        let good = w.as_slice();
1663
1664        let mut stream = alloc::vec::Vec::new();
1665        stream.extend_from_slice(&[0x7E, 0xA0, 0x7E]); // claims a 126-byte frame
1666        stream.extend_from_slice(good);
1667
1668        let mut framer = Framer::new();
1669        let Found::Frame { frame: back, consumed } = framer.next_frame(&stream).unwrap() else {
1670            panic!("the real frame was not found behind a false candidate");
1671        };
1672        assert_eq!(back, frame);
1673        assert_eq!(consumed, stream.len());
1674    }
1675
1676    #[test]
1677    fn a_buffer_of_pure_noise_is_entirely_discardable() {
1678        let mut framer = Framer::new();
1679        let noise = [0xAAu8, 0xBB, 0xCC, 0xDD];
1680        assert_eq!(
1681            framer.next_frame(&noise).unwrap(),
1682            Found::Incomplete { discard: 4 },
1683            "with no flag at all, every byte can go"
1684        );
1685        assert_eq!(framer.discarded(), 4);
1686    }
1687
1688    #[test]
1689    fn noise_before_a_partial_frame_is_discardable_and_the_partial_is_kept() {
1690        let frame = Frame::control_only(Address::client(0x10), Address::server(1, 17), Control::Ua);
1691        let mut buf = [0u8; 32];
1692        let mut w = SliceWriter::new(&mut buf);
1693        frame.encode(&mut w).unwrap();
1694        let n = w.written();
1695
1696        let mut stream = alloc::vec::Vec::new();
1697        stream.extend_from_slice(&[0x11, 0x22, 0x33]);
1698        stream.extend_from_slice(&buf[..n - 2]); // cut short
1699
1700        let mut framer = Framer::new();
1701        assert_eq!(
1702            framer.next_frame(&stream).unwrap(),
1703            Found::Incomplete { discard: 3 },
1704            "the leading noise goes, the partial frame stays"
1705        );
1706    }
1707}