Skip to main content

spodes_rs/transport/
hdlc.rs

1//! The HDLC-based data link layer (IEC 62056-46, ISO/IEC 13239 frame format
2//! type 3).
3//!
4//! This module provides a frame codec — [`HdlcFrame`], [`HdlcAddress`],
5//! [`Control`] and the [`fcs16`] check sequence — and, on top of a
6//! [`crate::transport::PhysicalTransport`], the [`crate::transport::hdlc::HdlcLayer`] data-link sub-layer. Because it only
7//! needs a byte channel, the same implementation works over a serial line and
8//! over TCP.
9//!
10//! A type-3 frame is laid out as:
11//!
12//! ```text
13//! 7E | format(2) | dest addr(1-4) | src addr(1-4) | control(1) | [HCS(2)] | [information] | FCS(2) | 7E
14//! ```
15//!
16//! The frame format field holds the type (0xA), a segmentation bit and an
17//! 11-bit frame length (the octet count between the flags). The HCS is present
18//! only when the frame carries an information field; the FCS is always present.
19//! Both check sequences are the CRC-16/X.25 defined by [`fcs16`].
20
21use std::io;
22use std::time::Duration;
23
24#[cfg(feature = "tracing")]
25use tracing::trace;
26
27use super::{DataLinkLayer, PhysicalTransport};
28
29/// HDLC opening/closing flag.
30pub const FLAG: u8 = 0x7E;
31
32/// Computes the HDLC frame/header check sequence (CRC-16/X.25): polynomial
33/// 0x1021 reflected (0x8408), initial value 0xFFFF, final one's complement.
34/// The result is transmitted low octet first.
35pub fn fcs16(data: &[u8]) -> u16 {
36    let mut fcs: u16 = 0xFFFF;
37    for &byte in data {
38        fcs ^= u16::from(byte);
39        for _ in 0..8 {
40            if fcs & 1 != 0 {
41                fcs = (fcs >> 1) ^ 0x8408;
42            } else {
43                fcs >>= 1;
44            }
45        }
46    }
47    !fcs
48}
49
50/// Errors that can occur while decoding an HDLC frame.
51#[derive(Debug, PartialEq, Eq)]
52pub enum HdlcError {
53    /// The buffer did not begin and end with the flag octet.
54    MissingFlag,
55    /// The frame is shorter than the minimum, or shorter than its length field.
56    Truncated,
57    /// The frame format type nibble was not 0xA (type 3).
58    InvalidFormatType,
59    /// The declared frame length did not match the actual length.
60    LengthMismatch,
61    /// An address field did not terminate within four octets.
62    AddressTooLong,
63    /// The header check sequence did not match.
64    BadHcs,
65    /// The frame check sequence did not match.
66    BadFcs,
67    /// The control field did not encode a known frame type.
68    UnknownControl(u8),
69}
70
71impl std::fmt::Display for HdlcError {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{self:?}")
74    }
75}
76
77impl std::error::Error for HdlcError {}
78
79impl From<HdlcError> for io::Error {
80    fn from(e: HdlcError) -> Self {
81        io::Error::new(io::ErrorKind::InvalidData, e)
82    }
83}
84
85/// An HDLC address (client or server), of 1, 2 or 4 octets. Each octet carries
86/// seven address bits and one extension bit (set on the final octet).
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub struct HdlcAddress {
89    /// The address value (up to 28 significant bits, seven per octet).
90    pub value: u32,
91    /// The address length in octets (1, 2 or 4).
92    pub length: u8,
93}
94
95impl HdlcAddress {
96    /// Creates an address with an explicit octet length (1, 2 or 4).
97    pub fn new(value: u32, length: u8) -> Self {
98        HdlcAddress { value, length }
99    }
100
101    /// Creates a single-octet address (typical for a client address).
102    pub fn one_byte(value: u8) -> Self {
103        HdlcAddress { value: u32::from(value), length: 1 }
104    }
105
106    fn encode(self, out: &mut Vec<u8>) {
107        for i in (0..self.length).rev() {
108            let group = ((self.value >> (7 * i)) & 0x7F) as u8;
109            let last = i == 0;
110            out.push((group << 1) | u8::from(last));
111        }
112    }
113
114    fn decode(bytes: &[u8], offset: usize) -> Result<(HdlcAddress, usize), HdlcError> {
115        let mut value = 0u32;
116        let mut consumed = 0usize;
117        loop {
118            let idx = offset + consumed;
119            let byte = *bytes.get(idx).ok_or(HdlcError::Truncated)?;
120            value = (value << 7) | u32::from(byte >> 1);
121            consumed += 1;
122            if byte & 1 == 1 {
123                break;
124            }
125            if consumed >= 4 {
126                return Err(HdlcError::AddressTooLong);
127            }
128        }
129        // consumed is 1..=4: the loop above returns AddressTooLong before it can grow further.
130        #[allow(clippy::cast_possible_truncation)]
131        let length = consumed as u8;
132        Ok((HdlcAddress { value, length }, consumed))
133    }
134}
135
136/// The HDLC control field.
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
138pub enum Control {
139    /// Set Normal Response Mode (connection establishment).
140    Snrm {
141        /// The poll bit.
142        poll: bool,
143    },
144    /// Unnumbered Acknowledge.
145    Ua {
146        /// The final bit.
147        final_bit: bool,
148    },
149    /// Disconnect.
150    Disc {
151        /// The poll bit.
152        poll: bool,
153    },
154    /// Disconnected Mode.
155    Dm {
156        /// The final bit.
157        final_bit: bool,
158    },
159    /// Frame Reject.
160    Frmr {
161        /// The final bit.
162        final_bit: bool,
163    },
164    /// Unnumbered Information.
165    Ui {
166        /// The poll bit.
167        poll: bool,
168    },
169    /// Information frame with send/receive sequence numbers.
170    Information {
171        /// The send sequence number N(S).
172        send_seq: u8,
173        /// The receive sequence number N(R).
174        recv_seq: u8,
175        /// The poll bit.
176        poll: bool,
177    },
178    /// Receive Ready (supervisory).
179    ReceiveReady {
180        /// The receive sequence number N(R).
181        recv_seq: u8,
182        /// The poll/final bit.
183        poll_final: bool,
184    },
185    /// Receive Not Ready (supervisory).
186    ReceiveNotReady {
187        /// The receive sequence number N(R).
188        recv_seq: u8,
189        /// The poll/final bit.
190        poll_final: bool,
191    },
192}
193
194impl Control {
195    fn encode(self) -> u8 {
196        let pf = |b: bool| if b { 0x10 } else { 0x00 };
197        match self {
198            Control::Snrm { poll } => 0x83 | pf(poll),
199            Control::Ua { final_bit } => 0x63 | pf(final_bit),
200            Control::Disc { poll } => 0x43 | pf(poll),
201            Control::Dm { final_bit } => 0x0F | pf(final_bit),
202            Control::Frmr { final_bit } => 0x87 | pf(final_bit),
203            Control::Ui { poll } => 0x03 | pf(poll),
204            Control::Information { send_seq, recv_seq, poll } => {
205                ((recv_seq & 0x07) << 5) | pf(poll) | ((send_seq & 0x07) << 1)
206            }
207            Control::ReceiveReady { recv_seq, poll_final } => ((recv_seq & 0x07) << 5) | pf(poll_final) | 0x01,
208            Control::ReceiveNotReady { recv_seq, poll_final } => ((recv_seq & 0x07) << 5) | pf(poll_final) | 0x05,
209        }
210    }
211
212    fn decode(byte: u8) -> Result<Control, HdlcError> {
213        let pf = byte & 0x10 != 0;
214        let recv_seq = (byte >> 5) & 0x07;
215        if byte & 0x01 == 0 {
216            // Information frame.
217            return Ok(Control::Information { send_seq: (byte >> 1) & 0x07, recv_seq, poll: pf });
218        }
219        if byte & 0x03 == 0x01 {
220            // Supervisory frame.
221            return match byte & 0x0F {
222                0x01 => Ok(Control::ReceiveReady { recv_seq, poll_final: pf }),
223                0x05 => Ok(Control::ReceiveNotReady { recv_seq, poll_final: pf }),
224                _ => Err(HdlcError::UnknownControl(byte)),
225            };
226        }
227        // Unnumbered frame: match with the P/F bit masked out.
228        match byte & !0x10 {
229            0x83 => Ok(Control::Snrm { poll: pf }),
230            0x63 => Ok(Control::Ua { final_bit: pf }),
231            0x43 => Ok(Control::Disc { poll: pf }),
232            0x0F => Ok(Control::Dm { final_bit: pf }),
233            0x87 => Ok(Control::Frmr { final_bit: pf }),
234            0x03 => Ok(Control::Ui { poll: pf }),
235            _ => Err(HdlcError::UnknownControl(byte)),
236        }
237    }
238}
239
240/// XID parameters negotiated during the SNRM/UA exchange (IEC 62056-46
241/// §6.4.4.4.3.2): the maximum information field length and window size each
242/// station uses in each direction.
243///
244/// Encoded on the wire as the SNRM/UA information field:
245/// `81 80 <group-len> 05 02 <max_info_tx:u16> 06 02 <max_info_rx:u16>
246/// 07 04 <window_tx:u32> 08 04 <window_rx:u32>` (big-endian values; the
247/// window fields are 4 octets on the wire though only small values, 1..7,
248/// are meaningful).
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250pub struct XidParams {
251    /// Maximum information field length this station will transmit.
252    pub max_info_tx: u16,
253    /// Maximum information field length this station will receive.
254    pub max_info_rx: u16,
255    /// Window size (1..7) this station uses when transmitting.
256    pub window_tx: u8,
257    /// Window size (1..7) this station uses when receiving.
258    pub window_rx: u8,
259}
260
261impl XidParams {
262    /// The client's default ceiling: 1280-octet info fields, window 1.
263    pub fn client_default() -> Self {
264        XidParams { max_info_tx: 1280, max_info_rx: 1280, window_tx: 1, window_rx: 1 }
265    }
266
267    /// The server's default ceiling: 512-octet info fields, window 1.
268    pub fn server_default() -> Self {
269        XidParams { max_info_tx: 512, max_info_rx: 512, window_tx: 1, window_rx: 1 }
270    }
271
272    fn encode(self) -> Vec<u8> {
273        let mut params = Vec::new();
274        params.push(0x05);
275        params.push(0x02);
276        params.extend_from_slice(&self.max_info_tx.to_be_bytes());
277        params.push(0x06);
278        params.push(0x02);
279        params.extend_from_slice(&self.max_info_rx.to_be_bytes());
280        params.push(0x07);
281        params.push(0x04);
282        params.extend_from_slice(&u32::from(self.window_tx).to_be_bytes());
283        params.push(0x08);
284        params.push(0x04);
285        params.extend_from_slice(&u32::from(self.window_rx).to_be_bytes());
286
287        // Fixed-shape encoding (4 TLV fields of known width): always 20 bytes.
288        #[allow(clippy::cast_possible_truncation)]
289        let mut out = vec![0x81, 0x80, params.len() as u8];
290        out.extend_from_slice(&params);
291        out
292    }
293
294    /// Decodes XID parameters from an SNRM/UA information field. Fields not
295    /// present (or a field whose value is 0, meaning "no opinion") are left
296    /// at 0 so [`Self::negotiate`] treats them as absent.
297    fn decode(data: &[u8]) -> XidParams {
298        let mut p = XidParams { max_info_tx: 0, max_info_rx: 0, window_tx: 0, window_rx: 0 };
299        // Skip the format ID (0x81), group ID (0x80) and group-length octets.
300        let mut idx = if data.len() >= 3 && data[0] == 0x81 && data[1] == 0x80 { 3 } else { 0 };
301        while idx + 2 <= data.len() {
302            let param_id = data[idx];
303            let param_len = data[idx + 1] as usize;
304            idx += 2;
305            let Some(value) = data.get(idx..idx + param_len) else { break };
306            match (param_id, value.len()) {
307                (0x05, 2) => p.max_info_tx = u16::from_be_bytes([value[0], value[1]]),
308                (0x06, 2) => p.max_info_rx = u16::from_be_bytes([value[0], value[1]]),
309                // Window sizes are conventionally 1..=7; a peer proposing an
310                // out-of-range value is clamped to u8::MAX rather than wrapped,
311                // so a bogus large value can't silently alias a small one.
312                (0x07, 4) => {
313                    p.window_tx =
314                        u8::try_from(u32::from_be_bytes([value[0], value[1], value[2], value[3]])).unwrap_or(u8::MAX);
315                }
316                (0x08, 4) => {
317                    p.window_rx =
318                        u8::try_from(u32::from_be_bytes([value[0], value[1], value[2], value[3]])).unwrap_or(u8::MAX);
319                }
320                _ => {}
321            }
322            idx += param_len;
323        }
324        p
325    }
326
327    /// Tightens `self` (this station's ceiling) against `peer`'s proposal: a
328    /// direction is only ever narrowed, and a zero value from the peer (no
329    /// opinion / absent) leaves that field unchanged.
330    fn negotiate(&mut self, peer: XidParams) {
331        if peer.max_info_tx > 0 && peer.max_info_tx < self.max_info_rx {
332            self.max_info_rx = peer.max_info_tx;
333        }
334        if peer.max_info_rx > 0 && peer.max_info_rx < self.max_info_tx {
335            self.max_info_tx = peer.max_info_rx;
336        }
337        if peer.window_tx > 0 && peer.window_tx < self.window_rx {
338            self.window_rx = peer.window_tx;
339        }
340        if peer.window_rx > 0 && peer.window_rx < self.window_tx {
341            self.window_tx = peer.window_rx;
342        }
343    }
344}
345
346/// A decoded HDLC frame.
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub struct HdlcFrame {
349    /// The destination address.
350    pub destination: HdlcAddress,
351    /// The source address.
352    pub source: HdlcAddress,
353    /// The control field.
354    pub control: Control,
355    /// The information field (may be empty for supervisory/unnumbered frames).
356    pub information: Vec<u8>,
357    /// The segmentation bit of the frame format field.
358    pub segmented: bool,
359}
360
361impl HdlcFrame {
362    /// Builds a frame without the segmentation bit set.
363    pub fn new(destination: HdlcAddress, source: HdlcAddress, control: Control, information: Vec<u8>) -> Self {
364        HdlcFrame { destination, source, control, information, segmented: false }
365    }
366
367    /// Encodes the frame, including the opening/closing flags, HCS and FCS.
368    pub fn encode(&self) -> Vec<u8> {
369        // Header: format field (filled in below) + addresses + control.
370        let mut header = Vec::new();
371        self.destination.encode(&mut header);
372        self.source.encode(&mut header);
373        header.push(self.control.encode());
374
375        let has_info = !self.information.is_empty();
376        // Frame length = format(2) + header + [HCS(2) + info] + FCS(2).
377        let length = 2 + header.len() + if has_info { 2 + self.information.len() } else { 0 } + 2;
378
379        let mut framed = Vec::with_capacity(length + 2);
380        let seg = if self.segmented { 0x08 } else { 0x00 };
381        // Both operands are masked to 3 and 8 bits respectively, so each always fits u8.
382        #[allow(clippy::cast_possible_truncation)]
383        let format_hi = 0xA0 | seg | ((length >> 8) & 0x07) as u8;
384        #[allow(clippy::cast_possible_truncation)]
385        let format_lo = (length & 0xFF) as u8;
386
387        // Everything the FCS is computed over (format .. end of info).
388        let mut checked = Vec::with_capacity(length - 2);
389        checked.push(format_hi);
390        checked.push(format_lo);
391        checked.extend_from_slice(&header);
392        if has_info {
393            let hcs = fcs16(&checked);
394            checked.extend_from_slice(&hcs.to_le_bytes());
395            checked.extend_from_slice(&self.information);
396        }
397        let fcs = fcs16(&checked);
398
399        framed.push(FLAG);
400        framed.extend_from_slice(&checked);
401        framed.extend_from_slice(&fcs.to_le_bytes());
402        framed.push(FLAG);
403        framed
404    }
405
406    /// Decodes a single frame that begins and ends with a flag octet.
407    pub fn decode(frame: &[u8]) -> Result<HdlcFrame, HdlcError> {
408        if frame.len() < 2 || frame[0] != FLAG || frame[frame.len() - 1] != FLAG {
409            return Err(HdlcError::MissingFlag);
410        }
411        let body = &frame[1..frame.len() - 1];
412        if body.len() < 5 {
413            return Err(HdlcError::Truncated);
414        }
415        if body[0] & 0xF0 != 0xA0 {
416            return Err(HdlcError::InvalidFormatType);
417        }
418        let segmented = body[0] & 0x08 != 0;
419        let length = (((body[0] & 0x07) as usize) << 8) | body[1] as usize;
420        if length != body.len() {
421            return Err(HdlcError::LengthMismatch);
422        }
423
424        let (destination, dlen) = HdlcAddress::decode(body, 2)?;
425        let (source, slen) = HdlcAddress::decode(body, 2 + dlen)?;
426        let control_idx = 2 + dlen + slen;
427        let control_byte = *body.get(control_idx).ok_or(HdlcError::Truncated)?;
428        let control = Control::decode(control_byte)?;
429
430        let header_len = control_idx + 1;
431        let remaining = body.len() - header_len;
432        // The trailing 2 octets are always the FCS.
433        if remaining < 2 {
434            return Err(HdlcError::Truncated);
435        }
436        let fcs_pos = body.len() - 2;
437        let expected_fcs = u16::from_le_bytes([body[fcs_pos], body[fcs_pos + 1]]);
438        if fcs16(&body[..fcs_pos]) != expected_fcs {
439            return Err(HdlcError::BadFcs);
440        }
441
442        let information = if remaining == 2 {
443            // No information field, hence no HCS.
444            Vec::new()
445        } else {
446            // HCS(2) directly after the header, then the information field.
447            let hcs = u16::from_le_bytes([body[header_len], body[header_len + 1]]);
448            if fcs16(&body[..header_len]) != hcs {
449                return Err(HdlcError::BadHcs);
450            }
451            body[header_len + 2..fcs_pos].to_vec()
452        };
453
454        Ok(HdlcFrame { destination, source, control, information, segmented })
455    }
456
457    /// Destination/source addresses when the control field is unknown but the
458    /// rest of the header (and FCS) is intact — used to reply with FRMR.
459    fn peek_addresses(frame: &[u8]) -> Result<(HdlcAddress, HdlcAddress), HdlcError> {
460        if frame.len() < 2 || frame[0] != FLAG || frame[frame.len() - 1] != FLAG {
461            return Err(HdlcError::MissingFlag);
462        }
463        let body = &frame[1..frame.len() - 1];
464        if body.len() < 5 || body[0] & 0xF0 != 0xA0 {
465            return Err(HdlcError::InvalidFormatType);
466        }
467        let length = (((body[0] & 0x07) as usize) << 8) | body[1] as usize;
468        if length != body.len() {
469            return Err(HdlcError::LengthMismatch);
470        }
471        let fcs_pos = body.len() - 2;
472        let expected_fcs = u16::from_le_bytes([body[fcs_pos], body[fcs_pos + 1]]);
473        if fcs16(&body[..fcs_pos]) != expected_fcs {
474            return Err(HdlcError::BadFcs);
475        }
476        let (destination, dlen) = HdlcAddress::decode(body, 2)?;
477        let (source, _) = HdlcAddress::decode(body, 2 + dlen)?;
478        Ok((destination, source))
479    }
480}
481
482/// The DLMS LLC header prepended to the information field of I/UI frames sent by
483/// the client (command).
484const LLC_COMMAND: [u8; 3] = [0xE6, 0xE6, 0x00];
485/// The DLMS LLC header for frames sent by the server (response).
486const LLC_RESPONSE: [u8; 3] = [0xE6, 0xE7, 0x00];
487
488/// The HDLC data-link sub-layer over a physical transport.
489///
490/// Sends APDUs as information frames (prefixed with the DLMS LLC header) and
491/// receives them, maintaining the send/receive sequence numbers. Connection
492/// management frames (SNRM/UA/DISC) are available through [`HdlcFrame`] directly.
493#[derive(Debug)]
494pub struct HdlcLayer<T: PhysicalTransport> {
495    transport: T,
496    /// Address of the peer this layer sends frames to.
497    peer: HdlcAddress,
498    /// This station's own address (used as the source address).
499    own: HdlcAddress,
500    is_client: bool,
501    send_seq: u8,
502    recv_seq: u8,
503    /// Whether the data link is in NRM (connected) as opposed to NDM.
504    connected: bool,
505    /// Maximum gap between two octets of the *same* frame (IEC 62056-46
506    /// "межсимвольный" timeout) before the read is aborted.
507    inter_octet_timeout: Duration,
508    /// Maximum time to wait for a *new* frame to start (IEC 62056-46
509    /// "межкадровый" / inactivity timeout); `None` waits indefinitely.
510    inactivity_timeout: Option<Duration>,
511    /// This station's configured XID ceiling, restored at the start of every
512    /// SNRM/UA negotiation.
513    xid_configured: XidParams,
514    /// The XID parameters actually negotiated with the peer (tightened from
515    /// `xid_configured` by the last SNRM/UA exchange).
516    xid: XidParams,
517}
518
519/// How many consecutive undecodable (bad FCS/HCS, malformed) frames are
520/// silently dropped before receive gives up (IEC 62056-46 §6.4.4.3: frames
521/// with an invalid check sequence are discarded without a response).
522const MAX_BAD_FRAMES: usize = 8;
523
524/// IEC 62056-46 / Blue Book inter-octet timeout limits, in milliseconds.
525const INTER_OCTET_MIN_MS: u16 = 20;
526const INTER_OCTET_MAX_MS: u16 = 6000;
527const INTER_OCTET_DEFAULT_MS: u16 = 25;
528
529/// IEC 62056-46 / Blue Book inactivity timeout limit, in seconds (0 disables it).
530const INACTIVITY_MAX_S: u16 = 120;
531
532impl<T: PhysicalTransport> HdlcLayer<T> {
533    /// Creates a client-side HDLC layer that talks to the server at `server`
534    /// address using the given `client` address.
535    pub fn new_client(transport: T, client: HdlcAddress, server: HdlcAddress) -> Self {
536        HdlcLayer {
537            transport,
538            peer: server,
539            own: client,
540            is_client: true,
541            send_seq: 0,
542            recv_seq: 0,
543            connected: false,
544            inter_octet_timeout: Duration::from_millis(u64::from(INTER_OCTET_DEFAULT_MS)),
545            inactivity_timeout: None,
546            xid_configured: XidParams::client_default(),
547            xid: XidParams::client_default(),
548        }
549    }
550
551    /// Creates a server-side HDLC layer.
552    pub fn new_server(transport: T, server: HdlcAddress, client: HdlcAddress) -> Self {
553        HdlcLayer {
554            transport,
555            peer: client,
556            own: server,
557            is_client: false,
558            send_seq: 0,
559            recv_seq: 0,
560            connected: false,
561            inter_octet_timeout: Duration::from_millis(u64::from(INTER_OCTET_DEFAULT_MS)),
562            inactivity_timeout: None,
563            xid_configured: XidParams::server_default(),
564            xid: XidParams::server_default(),
565        }
566    }
567
568    /// Sets the inter-octet timeout (IEC 62056-46 "межсимвольный"): the
569    /// maximum gap allowed between two octets of the same frame before the
570    /// read is aborted with a [`std::io::ErrorKind::TimedOut`] error.
571    /// Clamped to 20..=6000 ms per the standard; defaults to 25 ms.
572    ///
573    /// Has an effect only if the underlying [`PhysicalTransport`] honours
574    /// [`PhysicalTransport::set_read_timeout`].
575    pub fn set_inter_octet_timeout_ms(&mut self, ms: u16) {
576        self.inter_octet_timeout = Duration::from_millis(u64::from(ms.clamp(INTER_OCTET_MIN_MS, INTER_OCTET_MAX_MS)));
577    }
578
579    /// Sets the inactivity timeout (IEC 62056-46 "межкадровый"): the maximum
580    /// time to wait for a *new* frame to start before
581    /// [`Self::receive_apdu`]-driven reads abort with a
582    /// [`std::io::ErrorKind::TimedOut`] error and the link is considered
583    /// dropped (see [`Self::is_connected`]). Clamped to 0..=120 s; `0`
584    /// disables it (wait indefinitely), which is also the default.
585    ///
586    /// Has an effect only if the underlying [`PhysicalTransport`] honours
587    /// [`PhysicalTransport::set_read_timeout`].
588    pub fn set_inactivity_timeout_s(&mut self, seconds: u16) {
589        let seconds = seconds.min(INACTIVITY_MAX_S);
590        self.inactivity_timeout = if seconds == 0 { None } else { Some(Duration::from_secs(u64::from(seconds))) };
591    }
592
593    /// Sets this station's XID ceiling — the ceiling is what SNRM proposes
594    /// and what UA's negotiated values are tightened from — and immediately
595    /// resets the negotiated [`Self::xid`] to it. Call before [`Self::connect`]
596    /// (client) or before the next SNRM is received (server).
597    pub fn set_xid_ceiling(&mut self, xid: XidParams) {
598        self.xid_configured = xid;
599        self.xid = xid;
600    }
601
602    /// Returns the XID parameters actually negotiated with the peer (the
603    /// ceiling, tightened by the peer's counter-proposal in the last SNRM/UA
604    /// exchange). Before the first successful exchange this equals the
605    /// configured ceiling.
606    pub fn xid(&self) -> XidParams {
607        self.xid
608    }
609
610    /// Client: establishes the data link (NDM → NRM) with an SNRM/UA
611    /// exchange, negotiating XID parameters (IEC 62056-46 §6.4.4.4.3.2 —
612    /// see [`Self::set_xid_ceiling`] / [`Self::xid`]) and resetting both
613    /// sequence numbers (§6.4.4.2).
614    pub fn connect(&mut self) -> io::Result<()> {
615        self.xid = self.xid_configured;
616        let frame = HdlcFrame::new(self.peer, self.own, Control::Snrm { poll: true }, self.xid_configured.encode());
617        self.transport.send(&frame.encode())?;
618        let reply = self.read_decoded_frame()?;
619        match reply.control {
620            Control::Ua { .. } => {
621                if !reply.information.is_empty() {
622                    self.xid.negotiate(XidParams::decode(&reply.information));
623                }
624                self.send_seq = 0;
625                self.recv_seq = 0;
626                self.connected = true;
627                Ok(())
628            }
629            Control::Dm { .. } => Err(io::Error::new(io::ErrorKind::ConnectionRefused, "server answered DM to SNRM")),
630            other => Err(io::Error::new(io::ErrorKind::InvalidData, format!("unexpected reply to SNRM: {other:?}"))),
631        }
632    }
633
634    /// Client: releases the data link (NRM → NDM) with a DISC/UA exchange.
635    /// A DM answer also completes the release (the peer was already
636    /// disconnected).
637    pub fn disconnect(&mut self) -> io::Result<()> {
638        let frame = HdlcFrame::new(self.peer, self.own, Control::Disc { poll: true }, Vec::new());
639        self.transport.send(&frame.encode())?;
640        let reply = self.read_decoded_frame()?;
641        self.connected = false;
642        match reply.control {
643            Control::Ua { .. } | Control::Dm { .. } => Ok(()),
644            other => Err(io::Error::new(io::ErrorKind::InvalidData, format!("unexpected reply to DISC: {other:?}"))),
645        }
646    }
647
648    /// Returns whether the data link is connected (NRM).
649    pub fn is_connected(&self) -> bool {
650        self.connected
651    }
652
653    /// Reads frames until one decodes cleanly. Bad FCS/HCS frames are dropped
654    /// silently; an unknown control field in NRM is answered with FRMR (W)
655    /// (ISO 13239 / Yellow Book HDLC_COMMAND — C++ `OSP_ERR_UNSUPPORTED` path).
656    fn read_decoded_frame(&mut self) -> io::Result<HdlcFrame> {
657        for _ in 0..MAX_BAD_FRAMES {
658            let raw = self.read_frame()?;
659            match HdlcFrame::decode(&raw) {
660                Ok(frame) => return Ok(frame),
661                Err(HdlcError::UnknownControl(_)) if !self.is_client && self.connected => {
662                    if let Ok((destination, source)) = HdlcFrame::peek_addresses(&raw) {
663                        if destination.value == self.own.value {
664                            self.peer = source;
665                            self.send_unnumbered(Control::Frmr { final_bit: true })?;
666                        }
667                    }
668                }
669                Err(_) => {}
670            }
671        }
672        Err(io::Error::new(io::ErrorKind::InvalidData, "too many undecodable HDLC frames"))
673    }
674
675    /// Blocks until an RR/RNR acknowledges `expected_nr` (= next N(S) to send).
676    /// Partial acks with N(R) behind `expected_nr` are ignored; N(R) ahead of
677    /// V(S) yields FRMR (Z).
678    fn wait_for_rr(&mut self, expected_nr: u8) -> io::Result<()> {
679        loop {
680            let frame = self.read_decoded_frame()?;
681            if frame.destination.value != self.own.value {
682                continue;
683            }
684            match frame.control {
685                Control::ReceiveReady { recv_seq, .. } | Control::ReceiveNotReady { recv_seq, .. } => {
686                    self.peer = frame.source;
687                    if recv_seq == expected_nr {
688                        return Ok(());
689                    }
690                    // Distance from expected toward recv_seq in the forward
691                    // direction; values 1..=4 are treated as "ahead" (invalid).
692                    let ahead = (recv_seq.wrapping_sub(expected_nr)) & 0x07;
693                    if ahead != 0 && ahead <= 4 {
694                        self.send_unnumbered(Control::Frmr { final_bit: true })?;
695                        return Err(io::Error::new(io::ErrorKind::InvalidData, "HDLC RR N(R) ahead of V(S)"));
696                    }
697                }
698                Control::Disc { .. } => {
699                    self.peer = frame.source;
700                    self.connected = false;
701                    self.send_unnumbered(Control::Ua { final_bit: true })?;
702                    return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "peer released the data link"));
703                }
704                Control::Snrm { .. } => {
705                    self.peer = frame.source;
706                    self.xid = self.xid_configured;
707                    if !frame.information.is_empty() {
708                        self.xid.negotiate(XidParams::decode(&frame.information));
709                    }
710                    self.send_seq = 0;
711                    self.recv_seq = 0;
712                    self.connected = true;
713                    self.send_unnumbered_with_info(Control::Ua { final_bit: true }, self.xid.encode())?;
714                    return Err(io::Error::new(io::ErrorKind::ConnectionReset, "peer re-established the data link"));
715                }
716                _ => {}
717            }
718        }
719    }
720
721    /// Sends an unnumbered response frame (server side).
722    fn send_unnumbered(&mut self, control: Control) -> io::Result<()> {
723        self.send_unnumbered_with_info(control, Vec::new())
724    }
725
726    /// Sends an unnumbered frame carrying an information field (used for
727    /// UA's XID reply to SNRM).
728    fn send_unnumbered_with_info(&mut self, control: Control, information: Vec<u8>) -> io::Result<()> {
729        let frame = HdlcFrame::new(self.peer, self.own, control, information);
730        self.transport.send(&frame.encode())
731    }
732
733    /// Returns a mutable reference to the underlying transport.
734    pub fn transport_mut(&mut self) -> &mut T {
735        &mut self.transport
736    }
737
738    /// Consumes the layer and returns the underlying transport.
739    pub fn into_inner(self) -> T {
740        self.transport
741    }
742
743    fn llc(&self) -> [u8; 3] {
744        if self.is_client {
745            LLC_COMMAND
746        } else {
747            LLC_RESPONSE
748        }
749    }
750
751    /// Reads one complete frame (from an opening flag to a closing flag) from the
752    /// transport.
753    ///
754    /// Waits up to the configured inactivity timeout for the opening flag of
755    /// a *new* frame, then up to the (tighter) inter-octet timeout for every
756    /// subsequent octet of that same frame.
757    ///
758    /// An **inter-octet** timeout mid-frame discards the incomplete octets and
759    /// keeps waiting for the next frame (C++ `session_recv_frame` parity) —
760    /// it is not surfaced as an error. An **inactivity** timeout with an empty
761    /// buffer marks the link as NDM and returns
762    /// [`std::io::ErrorKind::TimedOut`].
763    ///
764    /// Both timeouts require the transport to honour
765    /// [`PhysicalTransport::set_read_timeout`]; a transport that doesn't
766    /// (the default) makes reads block indefinitely as before.
767    fn read_frame(&mut self) -> io::Result<Vec<u8>> {
768        loop {
769            // Skip to the opening flag, bounded by the inactivity timeout.
770            self.transport.set_read_timeout(self.inactivity_timeout)?;
771            let mut byte = [0u8; 1];
772            loop {
773                match read_exact(&mut self.transport, &mut byte) {
774                    Ok(()) => {}
775                    Err(e) if is_timeout(&e) => {
776                        self.connected = false;
777                        return Err(io::Error::new(
778                            io::ErrorKind::TimedOut,
779                            "HDLC inactivity timeout: no frame received",
780                        ));
781                    }
782                    Err(e) => return Err(e),
783                }
784                if byte[0] == FLAG {
785                    break;
786                }
787            }
788
789            // Frame started: subsequent octets use the inter-octet timeout.
790            self.transport.set_read_timeout(Some(self.inter_octet_timeout))?;
791            match self.read_frame_body() {
792                Ok(frame) => {
793                    let _ = self.transport.set_read_timeout(self.inactivity_timeout);
794                    return Ok(frame);
795                }
796                // Incomplete frame: drop it and wait for the next opening flag
797                // (C++ clears rx_pending and continues — not an error).
798                Err(e) if is_timeout(&e) => {
799                    #[cfg(feature = "tracing")]
800                    tracing::debug!(
801                        timeout_ms = self.inter_octet_timeout.as_millis() as u64,
802                        "HDLC inter-octet timeout, incomplete frame discarded"
803                    );
804                    let _ = self.transport.set_read_timeout(self.inactivity_timeout);
805                }
806                // Bad format / truncated mid-frame: resync like C++ buffer shift.
807                Err(e) if e.kind() == io::ErrorKind::InvalidData => {
808                    #[cfg(feature = "tracing")]
809                    tracing::debug!(error = %e, "HDLC invalid frame discarded, resync");
810                    let _ = self.transport.set_read_timeout(self.inactivity_timeout);
811                }
812                Err(e) => {
813                    let _ = self.transport.set_read_timeout(self.inactivity_timeout);
814                    return Err(e);
815                }
816            }
817        }
818    }
819
820    /// Reads the format field, payload and closing flag of a frame whose
821    /// opening flag octet has already been consumed.
822    fn read_frame_body(&mut self) -> io::Result<Vec<u8>> {
823        let mut format = [0u8; 2];
824        read_exact(&mut self.transport, &mut format).map_err(inter_octet_timeout)?;
825        if format[0] & 0xF0 != 0xA0 {
826            return Err(HdlcError::InvalidFormatType.into());
827        }
828        let length = (((format[0] & 0x07) as usize) << 8) | format[1] as usize;
829        if length < 4 {
830            return Err(HdlcError::Truncated.into());
831        }
832        // `length` counts the format field too; read the rest plus the closing flag.
833        let mut rest = vec![0u8; length - 2 + 1];
834        read_exact(&mut self.transport, &mut rest).map_err(inter_octet_timeout)?;
835        let mut frame = Vec::with_capacity(length + 2);
836        frame.push(FLAG);
837        frame.extend_from_slice(&format);
838        frame.extend_from_slice(&rest);
839        Ok(frame)
840    }
841}
842
843/// Whether `e` is a read timeout (from [`PhysicalTransport::set_read_timeout`]).
844fn is_timeout(e: &io::Error) -> bool {
845    matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)
846}
847
848/// Relabels a timeout mid-frame as an inter-octet timeout; other errors pass
849/// through unchanged.
850fn inter_octet_timeout(e: io::Error) -> io::Error {
851    if is_timeout(&e) {
852        io::Error::new(io::ErrorKind::TimedOut, "HDLC inter-octet timeout: frame aborted")
853    } else {
854        e
855    }
856}
857
858impl<T: PhysicalTransport> DataLinkLayer for HdlcLayer<T> {
859    /// Frames and sends `apdu`, splitting it into consecutive I-frames (the
860    /// format field's segmentation bit set on every frame but the last) when
861    /// the LLC-prefixed payload exceeds the negotiated `max_info_tx` (see
862    /// [`Self::xid`]) — the mirror of the segmented-frame reassembly already
863    /// performed by [`Self::receive_apdu`].
864    ///
865    /// With `window_tx == 1` the **server** waits for the peer's `RR` after
866    /// each non-final segment (etalon behaviour). Blasting every segment
867    /// back-to-back leaves the client's intermediate `RR`s (N(R) behind
868    /// `send_seq`) to be mis-classified as invalid N(R) → FRMR once
869    /// [`Self::receive_apdu`] resumes.
870    fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
871        if !self.is_client && !self.connected {
872            return Err(io::Error::new(io::ErrorKind::NotConnected, "HDLC link is in NDM"));
873        }
874        #[cfg(feature = "tracing")]
875        trace!(send_seq = self.send_seq, recv_seq = self.recv_seq, apdu_len = apdu.len(), "hdlc send");
876        let mut payload = Vec::with_capacity(3 + apdu.len());
877        payload.extend_from_slice(&self.llc());
878        payload.extend_from_slice(apdu);
879
880        // The LLC prefix makes `payload` at least 3 octets, so this always
881        // sends at least one frame.
882        let max_info = (self.xid.max_info_tx as usize).max(1);
883        let wait_rr = !self.is_client && self.xid.window_tx <= 1;
884        let mut offset = 0;
885        while offset < payload.len() {
886            let chunk = (payload.len() - offset).min(max_info);
887            let last = offset + chunk >= payload.len();
888            let control = Control::Information { send_seq: self.send_seq, recv_seq: self.recv_seq, poll: true };
889            let mut frame = HdlcFrame::new(self.peer, self.own, control, payload[offset..offset + chunk].to_vec());
890            frame.segmented = !last;
891            self.transport.send(&frame.encode())?;
892            self.send_seq = (self.send_seq + 1) & 0x07;
893            offset += chunk;
894            if !last && wait_rr {
895                self.wait_for_rr(self.send_seq)?;
896            }
897        }
898        Ok(())
899    }
900
901    fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
902        let mut information = Vec::new();
903        loop {
904            let frame = self.read_decoded_frame()?;
905            // Server: ignore frames not addressed to this station (C++ parity).
906            if !self.is_client && frame.destination.value != self.own.value {
907                continue;
908            }
909            match frame.control {
910                // ── NDM (server): only SNRM and DISC are meaningful. ──────
911                // Everything else (I, UI, RR/RNR, …) is ignored — Yellow Book
912                // HDLC_NDMOP / C++ openspodes connect-loop parity.
913                Control::Snrm { .. } if !self.is_client && !self.connected => {
914                    self.peer = frame.source;
915                    self.xid = self.xid_configured;
916                    if !frame.information.is_empty() {
917                        self.xid.negotiate(XidParams::decode(&frame.information));
918                    }
919                    self.send_seq = 0;
920                    self.recv_seq = 0;
921                    self.connected = true;
922                    self.send_unnumbered_with_info(Control::Ua { final_bit: true }, self.xid.encode())?;
923                }
924                Control::Disc { .. } if !self.is_client && !self.connected => {
925                    self.peer = frame.source;
926                    self.send_unnumbered(Control::Dm { final_bit: true })?;
927                }
928                _ if !self.is_client && !self.connected => {
929                    // NDM: silent drop (I / UI / RR / …).
930                }
931
932                // ── NRM (and client): information / UI deliver APDUs. ─────
933                Control::Information { send_seq, recv_seq, .. } => {
934                    if !self.is_client {
935                        self.peer = frame.source;
936                        let max_rx = usize::from(self.xid.max_info_rx.max(1));
937                        // Info longer than negotiated max_info_rx → FRMR (Y).
938                        if frame.information.len() > max_rx {
939                            self.send_unnumbered(Control::Frmr { final_bit: true })?;
940                            continue;
941                        }
942                        // N(R) ahead of V(S) → FRMR (Z). Behind/equal is OK
943                        // (equal = full ack; behind can appear if the peer's
944                        // cumulative ack lags a windowed burst).
945                        if recv_seq != self.send_seq {
946                            let ahead = (recv_seq.wrapping_sub(self.send_seq)) & 0x07;
947                            if ahead != 0 && ahead <= 4 {
948                                self.send_unnumbered(Control::Frmr { final_bit: true })?;
949                                continue;
950                            }
951                        }
952                        // Wrong N(S): RR with current N(R), do not advance.
953                        if send_seq != self.recv_seq {
954                            let rr = Control::ReceiveReady { recv_seq: self.recv_seq, poll_final: true };
955                            self.transport.send(&HdlcFrame::new(self.peer, self.own, rr, Vec::new()).encode())?;
956                            continue;
957                        }
958                    }
959                    self.recv_seq = (send_seq + 1) & 0x07;
960                    information.extend_from_slice(&frame.information);
961                    // A set segmentation bit means more I-frames follow; ask for
962                    // the next one with RR and keep reassembling (IEC 62056-46
963                    // §6.4.4.4).
964                    if frame.segmented {
965                        let rr = Control::ReceiveReady { recv_seq: self.recv_seq, poll_final: true };
966                        self.transport.send(&HdlcFrame::new(self.peer, self.own, rr, Vec::new()).encode())?;
967                        continue;
968                    }
969                    break;
970                }
971                Control::Ui { .. } => {
972                    information.extend_from_slice(&frame.information);
973                    break;
974                }
975                // Server in NRM: SNRM re-establishes (reset XID / seq / UA).
976                Control::Snrm { .. } if !self.is_client => {
977                    self.peer = frame.source;
978                    self.xid = self.xid_configured;
979                    if !frame.information.is_empty() {
980                        self.xid.negotiate(XidParams::decode(&frame.information));
981                    }
982                    self.send_seq = 0;
983                    self.recv_seq = 0;
984                    self.connected = true;
985                    self.send_unnumbered_with_info(Control::Ua { final_bit: true }, self.xid.encode())?;
986                }
987                // Server in NRM: DISC → UA → NDM.
988                Control::Disc { .. } if !self.is_client => {
989                    self.peer = frame.source;
990                    self.connected = false;
991                    self.send_unnumbered(Control::Ua { final_bit: true })?;
992                    return Err(io::Error::new(io::ErrorKind::ConnectionAborted, "peer released the data link"));
993                }
994                // RR/RNR: N(R) ahead of V(S) → FRMR (Z). N(R) behind is a
995                // late/partial ack (harmless after windowed send); equal is
996                // a full ack. Keep waiting either way.
997                Control::ReceiveReady { recv_seq, .. } | Control::ReceiveNotReady { recv_seq, .. } => {
998                    if !self.is_client && recv_seq != self.send_seq {
999                        let ahead = (recv_seq.wrapping_sub(self.send_seq)) & 0x07;
1000                        if ahead != 0 && ahead <= 4 {
1001                            self.peer = frame.source;
1002                            self.send_unnumbered(Control::Frmr { final_bit: true })?;
1003                        }
1004                    }
1005                }
1006                // Unknown / invalid in NRM → FRMR.
1007                _ => {
1008                    if !self.is_client {
1009                        self.peer = frame.source;
1010                        self.send_unnumbered(Control::Frmr { final_bit: true })?;
1011                    }
1012                }
1013            }
1014        }
1015        // Strip the 3-octet LLC header if present.
1016        let apdu =
1017            if information.len() >= 3 && information[0] == 0xE6 && (information[1] == 0xE6 || information[1] == 0xE7) {
1018                information[3..].to_vec()
1019            } else {
1020                information
1021            };
1022        #[cfg(feature = "tracing")]
1023        trace!(send_seq = self.send_seq, recv_seq = self.recv_seq, apdu_len = apdu.len(), "hdlc receive");
1024        Ok(apdu)
1025    }
1026
1027    fn client_sap(&self) -> Option<u8> {
1028        if !self.is_client && self.peer.length == 1 {
1029            // length == 1 means a single 7-bit address group, always < 128.
1030            #[allow(clippy::cast_possible_truncation)]
1031            let sap = self.peer.value as u8;
1032            Some(sap)
1033        } else {
1034            None
1035        }
1036    }
1037}
1038
1039/// Reads exactly `buf.len()` bytes from `transport`, looping over short reads.
1040fn read_exact<T: PhysicalTransport>(transport: &mut T, buf: &mut [u8]) -> io::Result<()> {
1041    let mut filled = 0;
1042    while filled < buf.len() {
1043        let n = transport.receive(&mut buf[filled..])?;
1044        if n == 0 {
1045            return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "transport closed"));
1046        }
1047        filled += n;
1048    }
1049    Ok(())
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054    use super::*;
1055    use crate::transport::MemoryTransport;
1056
1057    #[test]
1058    fn fcs_residue_is_the_good_fcs_constant() {
1059        // Recomputing the (complemented) FCS over `data || FCS_le` yields the
1060        // constant residue 0x0F47 — the one's complement of the classic 0xF0B8
1061        // "good FCS" magic value (this implementation complements the result).
1062        let data = [0xA0u8, 0x07, 0x03, 0x21, 0x93];
1063        let fcs = fcs16(&data);
1064        let mut with_fcs = data.to_vec();
1065        with_fcs.extend_from_slice(&fcs.to_le_bytes());
1066        assert_eq!(fcs16(&with_fcs), 0x0F47);
1067    }
1068
1069    #[test]
1070    fn address_round_trips_for_1_2_4_octets() {
1071        for (value, length) in [(0x10u32, 1u8), (0x3FFD, 2), (0x0102_0304 & 0x0FFF_FFFF, 4)] {
1072            let addr = HdlcAddress::new(value, length);
1073            let mut buf = Vec::new();
1074            addr.encode(&mut buf);
1075            assert_eq!(buf.len(), length as usize);
1076            let (decoded, consumed) = HdlcAddress::decode(&buf, 0).unwrap();
1077            assert_eq!(consumed, length as usize);
1078            assert_eq!(decoded, addr);
1079        }
1080    }
1081
1082    #[test]
1083    fn control_round_trips() {
1084        let controls = [
1085            Control::Snrm { poll: true },
1086            Control::Ua { final_bit: true },
1087            Control::Disc { poll: true },
1088            Control::Ui { poll: false },
1089            Control::Information { send_seq: 3, recv_seq: 5, poll: true },
1090            Control::ReceiveReady { recv_seq: 2, poll_final: false },
1091            Control::ReceiveNotReady { recv_seq: 7, poll_final: true },
1092        ];
1093        for c in controls {
1094            assert_eq!(Control::decode(c.encode()).unwrap(), c);
1095        }
1096    }
1097
1098    #[test]
1099    fn snrm_frame_round_trips() {
1100        let frame = HdlcFrame::new(
1101            HdlcAddress::one_byte(0x03),
1102            HdlcAddress::one_byte(0x10),
1103            Control::Snrm { poll: true },
1104            Vec::new(),
1105        );
1106        let encoded = frame.encode();
1107        assert_eq!(encoded[0], FLAG);
1108        assert_eq!(*encoded.last().unwrap(), FLAG);
1109        let decoded = HdlcFrame::decode(&encoded).unwrap();
1110        assert_eq!(decoded, frame);
1111    }
1112
1113    #[test]
1114    fn information_frame_round_trips_with_hcs() {
1115        let frame = HdlcFrame::new(
1116            HdlcAddress::one_byte(0x03),
1117            HdlcAddress::one_byte(0x10),
1118            Control::Information { send_seq: 0, recv_seq: 0, poll: true },
1119            vec![0xE6, 0xE6, 0x00, 0x60, 0x1D, 0xA1],
1120        );
1121        let encoded = frame.encode();
1122        let decoded = HdlcFrame::decode(&encoded).unwrap();
1123        assert_eq!(decoded, frame);
1124    }
1125
1126    #[test]
1127    fn decode_detects_fcs_corruption() {
1128        let frame = HdlcFrame::new(
1129            HdlcAddress::one_byte(0x03),
1130            HdlcAddress::one_byte(0x10),
1131            Control::Ua { final_bit: true },
1132            Vec::new(),
1133        );
1134        let mut encoded = frame.encode();
1135        let len = encoded.len();
1136        encoded[len - 2] ^= 0xFF; // corrupt the FCS
1137        assert_eq!(HdlcFrame::decode(&encoded), Err(HdlcError::BadFcs));
1138    }
1139
1140    #[test]
1141    fn layer_round_trips_apdu_over_transport() {
1142        let mut client =
1143            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1144        let apdu = vec![0x60, 0x1D, 0xA1, 0x09];
1145        client.send_apdu(&apdu).unwrap();
1146        // The loopback transport now holds the encoded frame; read it back.
1147        let received = client.receive_apdu().unwrap();
1148        assert_eq!(received, apdu);
1149    }
1150
1151    fn server_layer() -> HdlcLayer<MemoryTransport> {
1152        HdlcLayer::new_server(MemoryTransport::new(), HdlcAddress::one_byte(0x03), HdlcAddress::one_byte(0x10))
1153    }
1154
1155    fn client_frame(control: Control, information: Vec<u8>) -> Vec<u8> {
1156        HdlcFrame::new(HdlcAddress::one_byte(0x03), HdlcAddress::one_byte(0x10), control, information).encode()
1157    }
1158
1159    #[test]
1160    fn connect_performs_snrm_ua_exchange() {
1161        let mut client =
1162            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1163        // Pre-feed the server's UA so it is read back after our SNRM.
1164        let ua = HdlcFrame::new(
1165            HdlcAddress::one_byte(0x10),
1166            HdlcAddress::one_byte(0x03),
1167            Control::Ua { final_bit: true },
1168            Vec::new(),
1169        );
1170        client.transport_mut().feed(&ua.encode());
1171        client.connect().unwrap();
1172        assert!(client.is_connected());
1173    }
1174
1175    #[test]
1176    fn server_learns_client_address_from_snrm() {
1177        let mut server = server_layer();
1178        let snrm = HdlcFrame::new(
1179            HdlcAddress::one_byte(0x03),
1180            HdlcAddress::one_byte(0x61),
1181            Control::Snrm { poll: true },
1182            Vec::new(),
1183        )
1184        .encode();
1185        server.transport_mut().feed(&snrm);
1186        let info = Control::Information { send_seq: 0, recv_seq: 0, poll: true };
1187        server.transport_mut().feed(
1188            &HdlcFrame::new(
1189                HdlcAddress::one_byte(0x03),
1190                HdlcAddress::one_byte(0x61),
1191                info,
1192                vec![0xE6, 0xE6, 0x00, 0xC0, 0x01, 0xC1],
1193            )
1194            .encode(),
1195        );
1196        let _ = server.receive_apdu().unwrap();
1197        let ua_raw = server.read_frame().unwrap();
1198        let ua = HdlcFrame::decode(&ua_raw).unwrap();
1199        assert_eq!(ua.destination, HdlcAddress::one_byte(0x61));
1200    }
1201
1202    #[test]
1203    fn server_answers_snrm_with_ua_and_resets_sequences() {
1204        let mut server = server_layer();
1205        server.send_seq = 5;
1206        let info = Control::Information { send_seq: 0, recv_seq: 0, poll: true };
1207        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1208        server.transport_mut().feed(&client_frame(info, vec![0xC0, 0x01, 0xC1]));
1209        let apdu = server.receive_apdu().unwrap();
1210        assert_eq!(apdu, vec![0xC0, 0x01, 0xC1]);
1211        assert!(server.is_connected());
1212        assert_eq!(server.send_seq, 0);
1213        // The UA answer is queued in the transport after the consumed frames.
1214        let raw = server.read_frame().unwrap();
1215        let ua = HdlcFrame::decode(&raw).unwrap();
1216        assert!(matches!(ua.control, Control::Ua { .. }));
1217    }
1218
1219    #[test]
1220    fn server_answers_disc_in_ndm_with_dm() {
1221        let mut server = server_layer();
1222        // Default peer is 0x10; DISC comes from 0x21 — DM must target the source.
1223        let disc = HdlcFrame::new(
1224            HdlcAddress::one_byte(0x03),
1225            HdlcAddress::one_byte(0x21),
1226            Control::Disc { poll: true },
1227            Vec::new(),
1228        );
1229        let info = Control::Information { send_seq: 0, recv_seq: 0, poll: true };
1230        server.transport_mut().feed(&disc.encode());
1231        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1232        server.transport_mut().feed(&client_frame(info, vec![0xC0, 0x01, 0xC1]));
1233        let apdu = server.receive_apdu().unwrap();
1234        assert_eq!(apdu, vec![0xC0, 0x01, 0xC1]);
1235        let dm = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1236        assert!(matches!(dm.control, Control::Dm { .. }));
1237        assert_eq!(dm.destination, HdlcAddress::one_byte(0x21));
1238        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1239        assert!(matches!(ua.control, Control::Ua { .. }));
1240        assert!(server.is_connected());
1241    }
1242
1243    #[test]
1244    fn server_ignores_everything_but_snrm_and_disc_in_ndm() {
1245        let mut server = server_layer();
1246        assert!(!server.is_connected());
1247        // I / UI / RR while in NDM — must produce no wire reply.
1248        server.transport_mut().feed(&client_frame(
1249            Control::Information { send_seq: 0, recv_seq: 0, poll: true },
1250            vec![0xE6, 0xE6, 0x00, 0x60, 0x36],
1251        ));
1252        server.transport_mut().feed(&client_frame(Control::Ui { poll: true }, vec![0xAA]));
1253        server.transport_mut().feed(&client_frame(Control::ReceiveReady { recv_seq: 3, poll_final: true }, Vec::new()));
1254        // Then SNRM → UA → NRM and a normal I-frame.
1255        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1256        server.transport_mut().feed(&client_frame(
1257            Control::Information { send_seq: 0, recv_seq: 0, poll: true },
1258            vec![0xE6, 0xE6, 0x00, 0xC0, 0x01],
1259        ));
1260        let apdu = server.receive_apdu().unwrap();
1261        assert_eq!(apdu, vec![0xC0, 0x01]);
1262        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1263        assert!(matches!(ua.control, Control::Ua { .. }));
1264        // Only the UA for SNRM — nothing for the preceding NDM I/UI/RR.
1265        assert!(server.read_frame().is_err());
1266    }
1267
1268    #[test]
1269    fn server_answers_disc_in_nrm_with_ua_then_stays_in_ndm() {
1270        let mut server = server_layer();
1271        server.connected = true;
1272        server.peer = HdlcAddress::one_byte(0x21);
1273        server.transport_mut().feed(&client_frame(Control::Disc { poll: true }, Vec::new()));
1274        let err = server.receive_apdu().unwrap_err();
1275        assert_eq!(err.kind(), io::ErrorKind::ConnectionAborted);
1276        assert!(!server.is_connected());
1277        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1278        assert!(matches!(ua.control, Control::Ua { .. }));
1279    }
1280
1281    #[test]
1282    fn server_answers_unknown_control_with_frmr() {
1283        let mut server = server_layer();
1284        server.connected = true;
1285        server.peer = HdlcAddress::one_byte(0x21);
1286        // Control 0xFF is not a valid HDLC command.
1287        let mut unknown = HdlcFrame::new(
1288            HdlcAddress::one_byte(0x03),
1289            HdlcAddress::one_byte(0x21),
1290            Control::Disc { poll: true },
1291            Vec::new(),
1292        )
1293        .encode();
1294        // Patch control byte to 0xFF and recompute FCS over format..ctrl.
1295        unknown[5] = 0xFF;
1296        let fcs = super::fcs16(&unknown[1..6]);
1297        unknown[6] = fcs as u8;
1298        unknown[7] = (fcs >> 8) as u8;
1299
1300        let info = Control::Information { send_seq: 0, recv_seq: 0, poll: true };
1301        server.transport_mut().feed(&unknown);
1302        server.transport_mut().feed(&client_frame(info, vec![0xC0, 0x01]));
1303        let apdu = server.receive_apdu().unwrap();
1304        assert_eq!(apdu, vec![0xC0, 0x01]);
1305        let frmr = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1306        assert!(matches!(frmr.control, Control::Frmr { final_bit: true }));
1307        assert_eq!(frmr.destination, HdlcAddress::one_byte(0x21));
1308    }
1309
1310    #[test]
1311    fn server_rejects_oversized_i_frame_with_frmr() {
1312        let mut server = server_layer();
1313        server.connected = true;
1314        server.xid.max_info_rx = 16;
1315        let big = vec![0xAAu8; 64];
1316        let info = Control::Information { send_seq: 0, recv_seq: 0, poll: true };
1317        server.transport_mut().feed(&client_frame(info, big));
1318        server
1319            .transport_mut()
1320            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xC0, 0x01]));
1321        let apdu = server.receive_apdu().unwrap();
1322        assert_eq!(apdu, vec![0xC0, 0x01]);
1323        let frmr = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1324        assert!(matches!(frmr.control, Control::Frmr { .. }));
1325    }
1326
1327    #[test]
1328    fn server_answers_rr_with_bad_nr_with_frmr() {
1329        let mut server = server_layer();
1330        server.connected = true;
1331        server.send_seq = 0;
1332        let rr = Control::ReceiveReady { recv_seq: 1, poll_final: true };
1333        server.transport_mut().feed(&client_frame(rr, Vec::new()));
1334        server
1335            .transport_mut()
1336            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xBB]));
1337        let apdu = server.receive_apdu().unwrap();
1338        assert_eq!(apdu, vec![0xBB]);
1339        let frmr = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1340        assert!(matches!(frmr.control, Control::Frmr { .. }));
1341    }
1342
1343    #[test]
1344    fn server_answers_wrong_ns_with_rr() {
1345        let mut server = server_layer();
1346        server.connected = true;
1347        server.recv_seq = 0;
1348        // N(S)=1 while V(R)=0
1349        let info = Control::Information { send_seq: 1, recv_seq: 0, poll: true };
1350        server.transport_mut().feed(&client_frame(info, vec![0xE6, 0xE6, 0x00, 0x60]));
1351        server
1352            .transport_mut()
1353            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xC0]));
1354        let apdu = server.receive_apdu().unwrap();
1355        assert_eq!(apdu, vec![0xC0]);
1356        let rr = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1357        assert!(matches!(rr.control, Control::ReceiveReady { recv_seq: 0, poll_final: true }));
1358    }
1359
1360    // ------------------------------------------------------------------
1361    // State machine: NDM ↔ NRM via SNRM/UA and DISC/UA|DM.
1362    // ------------------------------------------------------------------
1363
1364    #[test]
1365    fn state_ndm_snrm_ua_nrm() {
1366        let mut server = server_layer();
1367        assert!(!server.is_connected(), "starts in NDM");
1368        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1369        server
1370            .transport_mut()
1371            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0x01]));
1372        assert_eq!(server.receive_apdu().unwrap(), vec![0x01]);
1373        assert!(server.is_connected(), "NDM --SNRM/UA--> NRM");
1374        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1375        assert!(matches!(ua.control, Control::Ua { final_bit: true }));
1376    }
1377
1378    #[test]
1379    fn state_nrm_disc_ua_ndm() {
1380        let mut server = server_layer();
1381        server.connected = true;
1382        server.transport_mut().feed(&client_frame(Control::Disc { poll: true }, Vec::new()));
1383        let err = server.receive_apdu().unwrap_err();
1384        assert_eq!(err.kind(), io::ErrorKind::ConnectionAborted);
1385        assert!(!server.is_connected(), "NRM --DISC/UA--> NDM");
1386        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1387        assert!(matches!(ua.control, Control::Ua { final_bit: true }));
1388    }
1389
1390    #[test]
1391    fn state_ndm_disc_dm_ndm() {
1392        let mut server = server_layer();
1393        assert!(!server.is_connected(), "starts in NDM");
1394        server.transport_mut().feed(&client_frame(Control::Disc { poll: true }, Vec::new()));
1395        // Unblock receive_apdu after DM handling with SNRM + I.
1396        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1397        server
1398            .transport_mut()
1399            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0x01]));
1400        let _ = server.receive_apdu().unwrap();
1401        let dm = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1402        assert!(matches!(dm.control, Control::Dm { final_bit: true }), "NDM --DISC/DM--> NDM");
1403        let ua = HdlcFrame::decode(&server.read_frame().unwrap()).unwrap();
1404        assert!(matches!(ua.control, Control::Ua { .. }));
1405        assert!(server.is_connected(), "SNRM after DM brings us to NRM");
1406    }
1407
1408    #[test]
1409    fn state_full_cycle_ndm_nrm_ndm_dm() {
1410        let mut server = server_layer();
1411        assert!(!server.is_connected());
1412
1413        // 1) NDM → SNRM → UA → NRM
1414        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1415        server
1416            .transport_mut()
1417            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xAA]));
1418        assert_eq!(server.receive_apdu().unwrap(), vec![0xAA]);
1419        assert!(server.is_connected());
1420        assert!(matches!(HdlcFrame::decode(&server.read_frame().unwrap()).unwrap().control, Control::Ua { .. }));
1421
1422        // 2) NRM → DISC → UA → NDM
1423        server.transport_mut().feed(&client_frame(Control::Disc { poll: true }, Vec::new()));
1424        assert_eq!(server.receive_apdu().unwrap_err().kind(), io::ErrorKind::ConnectionAborted);
1425        assert!(!server.is_connected());
1426        assert!(matches!(HdlcFrame::decode(&server.read_frame().unwrap()).unwrap().control, Control::Ua { .. }));
1427
1428        // 3) NDM → DISC → DM → NDM
1429        server.transport_mut().feed(&client_frame(Control::Disc { poll: true }, Vec::new()));
1430        server.transport_mut().feed(&client_frame(Control::Snrm { poll: true }, Vec::new()));
1431        server
1432            .transport_mut()
1433            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xBB]));
1434        assert_eq!(server.receive_apdu().unwrap(), vec![0xBB]);
1435        assert!(matches!(HdlcFrame::decode(&server.read_frame().unwrap()).unwrap().control, Control::Dm { .. }));
1436        assert!(matches!(HdlcFrame::decode(&server.read_frame().unwrap()).unwrap().control, Control::Ua { .. }));
1437        assert!(server.is_connected());
1438    }
1439
1440    #[test]
1441    fn segmented_information_is_reassembled() {
1442        let mut server = server_layer();
1443        server.connected = true;
1444        let mut first = HdlcFrame::new(
1445            HdlcAddress::one_byte(0x03),
1446            HdlcAddress::one_byte(0x10),
1447            Control::Information { send_seq: 0, recv_seq: 0, poll: true },
1448            vec![0xE6, 0xE6, 0x00, 0xC0, 0x01],
1449        );
1450        first.segmented = true;
1451        let second = HdlcFrame::new(
1452            HdlcAddress::one_byte(0x03),
1453            HdlcAddress::one_byte(0x10),
1454            Control::Information { send_seq: 1, recv_seq: 0, poll: true },
1455            vec![0xC1, 0x00, 0x01],
1456        );
1457        server.transport_mut().feed(&first.encode());
1458        server.transport_mut().feed(&second.encode());
1459        let apdu = server.receive_apdu().unwrap();
1460        assert_eq!(apdu, vec![0xC0, 0x01, 0xC1, 0x00, 0x01]);
1461    }
1462
1463    #[test]
1464    fn bad_fcs_frames_are_dropped_silently() {
1465        let mut server = server_layer();
1466        server.connected = true;
1467        let mut corrupted = client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xAA]);
1468        let len = corrupted.len();
1469        corrupted[len - 2] ^= 0xFF; // corrupt the FCS
1470        server.transport_mut().feed(&corrupted);
1471        server
1472            .transport_mut()
1473            .feed(&client_frame(Control::Information { send_seq: 1, recv_seq: 0, poll: true }, vec![0xBB]));
1474        // After bad frame, N(S)=1 is wrong for V(R)=0 → RR, so also feed correct N(S)=0.
1475        server
1476            .transport_mut()
1477            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xBB]));
1478        let apdu = server.receive_apdu().unwrap();
1479        assert_eq!(apdu, vec![0xBB]);
1480    }
1481
1482    // ------------------------------------------------------------------
1483    // Inter-octet / inactivity timeouts.
1484    // ------------------------------------------------------------------
1485
1486    #[test]
1487    fn inter_octet_timeout_ms_clamps_to_standard_range() {
1488        let mut layer =
1489            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1490        layer.set_inter_octet_timeout_ms(5); // below the 20 ms minimum
1491        assert_eq!(layer.inter_octet_timeout, Duration::from_millis(20));
1492        layer.set_inter_octet_timeout_ms(60_000); // above the 6000 ms maximum
1493        assert_eq!(layer.inter_octet_timeout, Duration::from_millis(6000));
1494        layer.set_inter_octet_timeout_ms(100);
1495        assert_eq!(layer.inter_octet_timeout, Duration::from_millis(100));
1496    }
1497
1498    #[test]
1499    fn inactivity_timeout_s_clamps_and_zero_disables() {
1500        let mut layer =
1501            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1502        assert_eq!(layer.inactivity_timeout, None, "disabled by default");
1503        layer.set_inactivity_timeout_s(200); // above the 120 s maximum
1504        assert_eq!(layer.inactivity_timeout, Some(Duration::from_secs(120)));
1505        layer.set_inactivity_timeout_s(30);
1506        assert_eq!(layer.inactivity_timeout, Some(Duration::from_secs(30)));
1507        layer.set_inactivity_timeout_s(0);
1508        assert_eq!(layer.inactivity_timeout, None, "0 disables it again");
1509    }
1510
1511    /// A [`PhysicalTransport`] mock that logs every requested read timeout
1512    /// and can simulate the peer going silent after a fixed number of
1513    /// delivered bytes (or immediately, if empty) by returning
1514    /// [`io::ErrorKind::TimedOut`] instead of blocking forever.
1515    #[derive(Default)]
1516    struct TimeoutTransport {
1517        data: std::collections::VecDeque<u8>,
1518        set_timeout_log: Vec<Option<Duration>>,
1519    }
1520
1521    impl PhysicalTransport for TimeoutTransport {
1522        fn send(&mut self, _data: &[u8]) -> io::Result<()> {
1523            Ok(())
1524        }
1525        fn receive(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1526            if self.data.is_empty() {
1527                // No more data will ever arrive: a real blocking transport
1528                // configured with a read timeout would time out here rather
1529                // than signal EOF.
1530                return Err(io::Error::new(io::ErrorKind::TimedOut, "simulated timeout"));
1531            }
1532            let mut n = 0;
1533            while n < buf.len() {
1534                match self.data.pop_front() {
1535                    Some(b) => {
1536                        buf[n] = b;
1537                        n += 1;
1538                    }
1539                    None => break,
1540                }
1541            }
1542            Ok(n)
1543        }
1544        fn set_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
1545            self.set_timeout_log.push(timeout);
1546            Ok(())
1547        }
1548    }
1549
1550    fn timeout_test_layer() -> HdlcLayer<TimeoutTransport> {
1551        let mut layer = HdlcLayer::new_client(
1552            TimeoutTransport::default(),
1553            HdlcAddress::one_byte(0x10),
1554            HdlcAddress::one_byte(0x03),
1555        );
1556        layer.set_inactivity_timeout_s(60);
1557        layer.set_inter_octet_timeout_ms(30);
1558        layer
1559    }
1560
1561    #[test]
1562    fn read_frame_switches_from_inactivity_to_inter_octet_timeout() {
1563        let mut layer = timeout_test_layer();
1564        let frame = HdlcFrame::new(
1565            HdlcAddress::one_byte(0x03),
1566            HdlcAddress::one_byte(0x10),
1567            Control::Ua { final_bit: true },
1568            Vec::new(),
1569        )
1570        .encode();
1571        layer.transport.data.extend(frame);
1572
1573        layer.read_frame().expect("full frame is available");
1574
1575        // Inactivity timeout while waiting for the flag, inter-octet timeout
1576        // for the rest of the frame, then inactivity restored for the next call.
1577        assert_eq!(
1578            layer.transport.set_timeout_log,
1579            vec![Some(Duration::from_secs(60)), Some(Duration::from_millis(30)), Some(Duration::from_secs(60))]
1580        );
1581    }
1582
1583    #[test]
1584    fn no_frame_at_all_times_out_as_inactivity_and_disconnects() {
1585        let mut layer = timeout_test_layer();
1586        layer.connected = true;
1587        let err = layer.read_frame().unwrap_err();
1588        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
1589        assert!(err.to_string().contains("inactivity"), "unexpected message: {err}");
1590        assert!(!layer.is_connected(), "inactivity timeout must drop the connected state");
1591    }
1592
1593    #[test]
1594    fn silence_mid_frame_discards_incomplete_then_inactivity_disconnects() {
1595        let mut layer = timeout_test_layer();
1596        layer.connected = true;
1597        // Only the opening flag and part of the format field arrive; the
1598        // peer then goes silent. Inter-octet discards the fragment (no error);
1599        // the next wait uses inactivity and disconnects to NDM.
1600        layer.transport.data.push_back(FLAG);
1601        layer.transport.data.push_back(0xA0);
1602
1603        let err = layer.read_frame().unwrap_err();
1604        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
1605        assert!(err.to_string().contains("inactivity"), "unexpected message: {err}");
1606        assert!(!layer.is_connected(), "inactivity after inter-octet discard drops to NDM");
1607        assert!(
1608            layer.transport.set_timeout_log.iter().any(|t| *t == Some(Duration::from_millis(30))),
1609            "inter-octet timeout must have been armed for the incomplete frame"
1610        );
1611    }
1612
1613    #[test]
1614    fn silence_mid_frame_then_next_complete_frame_is_accepted() {
1615        /// Delivers a partial frame, one inter-octet timeout, then a full UA.
1616        struct RecoverTransport {
1617            phase: u8,
1618            frame: Vec<u8>,
1619            set_timeout_log: Vec<Option<Duration>>,
1620        }
1621        impl PhysicalTransport for RecoverTransport {
1622            fn send(&mut self, _data: &[u8]) -> io::Result<()> {
1623                Ok(())
1624            }
1625            fn receive(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1626                match self.phase {
1627                    0 => {
1628                        // Opening flag only — starts the frame.
1629                        buf[0] = FLAG;
1630                        self.phase = 1;
1631                        Ok(1)
1632                    }
1633                    1 => {
1634                        // One format byte, then silence → inter-octet.
1635                        buf[0] = 0xA0;
1636                        self.phase = 2;
1637                        Ok(1)
1638                    }
1639                    2 => {
1640                        self.phase = 3;
1641                        Err(io::Error::new(io::ErrorKind::TimedOut, "inter-octet"))
1642                    }
1643                    _ => {
1644                        if self.frame.is_empty() {
1645                            return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "done"));
1646                        }
1647                        let n = buf.len().min(self.frame.len());
1648                        buf[..n].copy_from_slice(&self.frame[..n]);
1649                        self.frame.drain(..n);
1650                        Ok(n)
1651                    }
1652                }
1653            }
1654            fn set_read_timeout(&mut self, timeout: Option<Duration>) -> io::Result<()> {
1655                self.set_timeout_log.push(timeout);
1656                Ok(())
1657            }
1658        }
1659
1660        let frame = HdlcFrame::new(
1661            HdlcAddress::one_byte(0x03),
1662            HdlcAddress::one_byte(0x10),
1663            Control::Ua { final_bit: true },
1664            Vec::new(),
1665        )
1666        .encode();
1667        let mut layer = HdlcLayer::new_server(
1668            RecoverTransport { phase: 0, frame, set_timeout_log: Vec::new() },
1669            HdlcAddress::one_byte(0x03),
1670            HdlcAddress::one_byte(0x10),
1671        );
1672        layer.set_inactivity_timeout_s(60);
1673        layer.set_inter_octet_timeout_ms(30);
1674        layer.connected = true;
1675
1676        let raw = layer.read_frame().expect("next full frame after inter-octet discard");
1677        let decoded = HdlcFrame::decode(&raw).unwrap();
1678        assert!(matches!(decoded.control, Control::Ua { .. }));
1679        assert!(layer.is_connected(), "inter-octet discard must not drop to NDM");
1680    }
1681
1682    // ------------------------------------------------------------------
1683    // XID negotiation.
1684    // ------------------------------------------------------------------
1685
1686    #[test]
1687    fn xid_params_round_trip_through_wire_encoding() {
1688        let xid = XidParams { max_info_tx: 1280, max_info_rx: 512, window_tx: 3, window_rx: 1 };
1689        let encoded = xid.encode();
1690        assert_eq!(&encoded[..2], &[0x81, 0x80]);
1691        assert_eq!(XidParams::decode(&encoded), xid);
1692    }
1693
1694    #[test]
1695    fn xid_negotiate_tightens_to_the_smaller_value() {
1696        let mut mine = XidParams { max_info_tx: 1280, max_info_rx: 1280, window_tx: 3, window_rx: 3 };
1697        let peer = XidParams { max_info_tx: 200, max_info_rx: 400, window_tx: 1, window_rx: 2 };
1698        mine.negotiate(peer);
1699        // My rx is capped by the peer's tx, and vice-versa.
1700        assert_eq!(mine, XidParams { max_info_tx: 400, max_info_rx: 200, window_tx: 2, window_rx: 1 });
1701    }
1702
1703    #[test]
1704    fn xid_negotiate_ignores_zero_fields_from_peer() {
1705        let mut mine = XidParams::client_default();
1706        let peer = XidParams { max_info_tx: 0, max_info_rx: 0, window_tx: 0, window_rx: 0 };
1707        mine.negotiate(peer);
1708        assert_eq!(mine, XidParams::client_default(), "an all-zero (absent) proposal changes nothing");
1709    }
1710
1711    #[test]
1712    fn xid_decode_clamps_out_of_range_window_instead_of_wrapping() {
1713        // window_tx param (tag 0x07, len 4) carrying 300 — out of u8 range.
1714        let data = [0x81, 0x80, 0x06, 0x07, 0x04, 0x00, 0x00, 0x01, 0x2C];
1715        let p = XidParams::decode(&data);
1716        // 300 as u8 would wrap to 44; it must clamp to u8::MAX instead.
1717        assert_eq!(p.window_tx, u8::MAX);
1718    }
1719
1720    #[test]
1721    fn xid_negotiate_never_widens_the_ceiling() {
1722        let mut mine = XidParams { max_info_tx: 200, max_info_rx: 200, window_tx: 1, window_rx: 1 };
1723        let peer = XidParams { max_info_tx: 5000, max_info_rx: 5000, window_tx: 7, window_rx: 7 };
1724        mine.negotiate(peer);
1725        assert_eq!(mine, XidParams { max_info_tx: 200, max_info_rx: 200, window_tx: 1, window_rx: 1 });
1726    }
1727
1728    #[test]
1729    fn connect_sends_configured_xid_and_negotiates_the_ua_reply() {
1730        let mut client =
1731            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1732        let server_xid = XidParams { max_info_tx: 200, max_info_rx: 300, window_tx: 1, window_rx: 1 };
1733        let ua = HdlcFrame::new(
1734            HdlcAddress::one_byte(0x10),
1735            HdlcAddress::one_byte(0x03),
1736            Control::Ua { final_bit: true },
1737            server_xid.encode(),
1738        );
1739        client.transport_mut().feed(&ua.encode());
1740        client.connect().unwrap();
1741
1742        // Negotiated against the client's 1280/1280/1/1 default: tx capped
1743        // by the server's rx (300), rx capped by the server's tx (200).
1744        assert_eq!(client.xid(), XidParams { max_info_tx: 300, max_info_rx: 200, window_tx: 1, window_rx: 1 });
1745
1746        // The SNRM the client sent carried its configured (unnegotiated)
1747        // ceiling; nothing has consumed it yet since the UA was pre-fed.
1748        let mut raw = vec![0u8; 128];
1749        let n = client.transport_mut().receive(&mut raw).unwrap();
1750        let sent = HdlcFrame::decode(&raw[..n]).unwrap();
1751        assert!(matches!(sent.control, Control::Snrm { .. }));
1752        assert_eq!(XidParams::decode(&sent.information), XidParams::client_default());
1753    }
1754
1755    #[test]
1756    fn server_answers_snrm_with_negotiated_xid() {
1757        let mut server = server_layer();
1758        let client_xid = XidParams { max_info_tx: 128, max_info_rx: 128, window_tx: 1, window_rx: 1 };
1759        let snrm = client_frame(Control::Snrm { poll: true }, client_xid.encode());
1760        server.transport_mut().feed(&snrm);
1761        server
1762            .transport_mut()
1763            .feed(&client_frame(Control::Information { send_seq: 0, recv_seq: 0, poll: true }, vec![0xC0]));
1764
1765        server.receive_apdu().unwrap();
1766
1767        // Negotiated against the server's 512/512/1/1 default.
1768        assert_eq!(server.xid(), XidParams { max_info_tx: 128, max_info_rx: 128, window_tx: 1, window_rx: 1 });
1769    }
1770
1771    #[test]
1772    fn snrm_without_xid_info_leaves_the_configured_ceiling_untouched() {
1773        let mut client =
1774            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1775        let ua = HdlcFrame::new(
1776            HdlcAddress::one_byte(0x10),
1777            HdlcAddress::one_byte(0x03),
1778            Control::Ua { final_bit: true },
1779            Vec::new(), // no XID info field at all
1780        );
1781        client.transport_mut().feed(&ua.encode());
1782        client.connect().unwrap();
1783        assert_eq!(client.xid(), XidParams::client_default());
1784    }
1785
1786    // ------------------------------------------------------------------
1787    // Outbound I-frame segmentation.
1788    // ------------------------------------------------------------------
1789
1790    #[test]
1791    fn send_apdu_does_not_segment_when_it_fits_the_ceiling() {
1792        let mut client =
1793            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1794        client.send_apdu(&[0xC0, 0x01]).unwrap();
1795        assert_eq!(client.send_seq, 1, "a single small APDU is sent as exactly one frame");
1796    }
1797
1798    #[test]
1799    fn send_apdu_segments_when_it_exceeds_max_info_tx() {
1800        let mut client =
1801            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1802        client.set_xid_ceiling(XidParams { max_info_tx: 10, max_info_rx: 10, window_tx: 1, window_rx: 1 });
1803        let apdu: Vec<u8> = (0u8..25).collect();
1804        client.send_apdu(&apdu).unwrap();
1805        // LLC(3) + 25 = 28 octets, split into 10-octet blocks -> ceil(28/10) = 3 frames,
1806        // one N(S) slot consumed per frame.
1807        assert_eq!(client.send_seq, 3);
1808    }
1809
1810    #[test]
1811    fn send_apdu_segments_are_reassembled_correctly_by_a_peer() {
1812        let mut client =
1813            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1814        client.set_xid_ceiling(XidParams { max_info_tx: 10, max_info_rx: 10, window_tx: 1, window_rx: 1 });
1815        let apdu: Vec<u8> = (0u8..25).collect();
1816        client.send_apdu(&apdu).unwrap();
1817
1818        // Drain every byte the client produced and feed it into a fresh
1819        // server's transport, proving send_apdu's segmentation and
1820        // receive_apdu's reassembly are wire-compatible with each other.
1821        let mut buf = [0u8; 4096];
1822        let n = client.transport_mut().receive(&mut buf).unwrap();
1823
1824        let mut server = server_layer();
1825        server.connected = true;
1826        server.transport_mut().feed(&buf[..n]);
1827        let reassembled = server.receive_apdu().unwrap();
1828        assert_eq!(reassembled, apdu);
1829    }
1830
1831    #[test]
1832    fn send_apdu_respects_the_negotiated_ceiling_after_connect() {
1833        let mut client =
1834            HdlcLayer::new_client(MemoryTransport::new(), HdlcAddress::one_byte(0x10), HdlcAddress::one_byte(0x03));
1835        let tiny_ceiling = XidParams { max_info_tx: 8, max_info_rx: 8, window_tx: 1, window_rx: 1 };
1836        let ua = HdlcFrame::new(
1837            HdlcAddress::one_byte(0x10),
1838            HdlcAddress::one_byte(0x03),
1839            Control::Ua { final_bit: true },
1840            tiny_ceiling.encode(),
1841        );
1842        client.transport_mut().feed(&ua.encode());
1843        client.connect().unwrap();
1844        assert_eq!(client.xid().max_info_tx, 8);
1845
1846        let apdu = vec![0xAAu8; 20]; // LLC(3) + 20 = 23 octets -> ceil(23/8) = 3 frames.
1847        client.send_apdu(&apdu).unwrap();
1848        assert_eq!(client.send_seq, 3, "send_apdu must use the negotiated ceiling, not the configured default");
1849    }
1850}