Skip to main content

spodes_rs/service/
gbt.rs

1//! General block transfer (IEC 62056-5-3, 7.3.13): a transport-independent
2//! mechanism that carries any (partial) xDLMS APDU in blocks.
3//!
4//! ```text
5//! E0 | block-control | block-number | block-number-ack | block-data
6//!      ^ LB|ST|window   ^ u16           ^ u16 (acked)      ^ A-XDR octet-string
7//! ```
8//!
9//! The block-control octet holds the last-block flag (bit 7), the streaming
10//! flag (bit 6) and the window size (bits 5..0).
11//!
12//! [`send`] and [`receive`] drive this codec over any
13//! [`crate::transport::DataLinkLayer`], transparently segmenting an oversized
14//! xDLMS APDU into blocks (and reassembling them on the other end) — an
15//! alternative to the service-specific WITH-DATABLOCK block transfer that
16//! also covers APDU types WITH-DATABLOCK does not, such as DataNotification
17//! and EventNotificationRequest.
18
19use super::{push_length, read_length, tag, ServiceError};
20use crate::transport::DataLinkLayer;
21use std::io;
22
23/// General-block-transfer APDU tag (`[224]`).
24pub const GENERAL_BLOCK_TRANSFER: u8 = 0xE0;
25
26const LAST_BLOCK: u8 = 0x80;
27const STREAMING: u8 = 0x40;
28const WINDOW_MASK: u8 = 0x3F;
29
30/// Octets reserved for the GBT header (tag, control, block numbers, and a
31/// worst-case long-form length) when budgeting a block's payload size from
32/// an overall frame-size limit.
33pub const HEADER_MAX: usize = 8;
34
35/// Default overall block size (including the header) used when a session
36/// enables GBT without specifying one explicitly.
37pub const DEFAULT_BLOCK_SIZE: usize = 64;
38
39/// A general-block-transfer APDU.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct GeneralBlockTransfer {
42    /// Whether this is the last block.
43    pub last_block: bool,
44    /// Whether streaming is in use.
45    pub streaming: bool,
46    /// Window size (0..63): the number of blocks that may be sent before an ack.
47    pub window: u8,
48    /// Number of this block.
49    pub block_number: u16,
50    /// Number of the last block acknowledged by the peer.
51    pub block_number_ack: u16,
52    /// This block's fragment of the embedded APDU.
53    pub block_data: Vec<u8>,
54}
55
56impl GeneralBlockTransfer {
57    /// Encodes the general-block-transfer APDU.
58    pub fn encode(&self) -> Vec<u8> {
59        let block_control = if self.last_block { LAST_BLOCK } else { 0 }
60            | if self.streaming { STREAMING } else { 0 }
61            | (self.window & WINDOW_MASK);
62        let mut buf = vec![GENERAL_BLOCK_TRANSFER, block_control];
63        buf.extend_from_slice(&self.block_number.to_be_bytes());
64        buf.extend_from_slice(&self.block_number_ack.to_be_bytes());
65        push_length(self.block_data.len(), &mut buf);
66        buf.extend_from_slice(&self.block_data);
67        buf
68    }
69
70    /// Decodes a general-block-transfer APDU.
71    pub fn decode(bytes: &[u8]) -> Result<GeneralBlockTransfer, ServiceError> {
72        if bytes.len() < 6 {
73            return Err(ServiceError::Truncated);
74        }
75        if bytes[0] != GENERAL_BLOCK_TRANSFER {
76            return Err(ServiceError::UnexpectedTag(bytes[0]));
77        }
78        let block_control = bytes[1];
79        let block_number = u16::from_be_bytes([bytes[2], bytes[3]]);
80        let block_number_ack = u16::from_be_bytes([bytes[4], bytes[5]]);
81        let (len, header) = read_length(&bytes[6..])?;
82        let start = 6 + header;
83        let block_data = bytes.get(start..start + len).ok_or(ServiceError::Truncated)?.to_vec();
84        Ok(GeneralBlockTransfer {
85            last_block: block_control & LAST_BLOCK != 0,
86            streaming: block_control & STREAMING != 0,
87            window: block_control & WINDOW_MASK,
88            block_number,
89            block_number_ack,
90            block_data,
91        })
92    }
93}
94
95/// Returns whether general block transfer applies to this APDU's service
96/// (IEC 62056-5-3 §9.3, Table): GET/SET/ACTION requests and responses, plus
97/// DataNotification and EventNotificationRequest.
98pub fn applies_to_apdu(apdu: &[u8]) -> bool {
99    matches!(
100        apdu.first(),
101        Some(&tag::GET_REQUEST)
102            | Some(&tag::GET_RESPONSE)
103            | Some(&tag::SET_REQUEST)
104            | Some(&tag::SET_RESPONSE)
105            | Some(&tag::ACTION_REQUEST)
106            | Some(&tag::ACTION_RESPONSE)
107            | Some(&tag::DATA_NOTIFICATION)
108            | Some(&tag::EVENT_NOTIFICATION_REQUEST)
109    )
110}
111
112/// Reads one frame from `link` and decodes it as a general-block-transfer
113/// APDU.
114fn read_block<L: DataLinkLayer>(link: &mut L) -> io::Result<GeneralBlockTransfer> {
115    let raw = link.receive_apdu()?;
116    Ok(GeneralBlockTransfer::decode(&raw)?)
117}
118
119/// Sends an ack-only general-block-transfer frame (no payload): confirms
120/// receipt up to `block_number_ack` and grants `window` further blocks.
121fn send_ack<L: DataLinkLayer>(link: &mut L, window: u8, block_number_ack: u16) -> io::Result<()> {
122    let ack = GeneralBlockTransfer {
123        last_block: true,
124        streaming: false,
125        window: window & WINDOW_MASK,
126        block_number: 1,
127        block_number_ack,
128        block_data: Vec::new(),
129    };
130    link.send_apdu(&ack.encode())
131}
132
133/// Segments `apdu` into general-block-transfer blocks of at most
134/// `block_payload_max` octets each and sends them over `link`. In confirmed
135/// mode (`window > 0`), waits for an ack-only GBT frame after each window of
136/// blocks and retransmits from the first block the peer has not acknowledged
137/// if it reports a gap; with `window == 0` (unconfirmed) or `streaming`, no
138/// ack is awaited until the caller separately reads a reply.
139///
140/// `block_payload_max` must be at least 1; a request that already fits
141/// within it is still sent as a single-block GBT APDU.
142pub fn send<L: DataLinkLayer>(
143    link: &mut L,
144    apdu: &[u8],
145    block_payload_max: usize,
146    window: u8,
147    streaming: bool,
148) -> io::Result<()> {
149    let block_payload_max = block_payload_max.max(1);
150    let win = window & WINDOW_MASK;
151    let mut offset = 0usize;
152    let mut block_number: u16 = 1;
153    let mut blocks_in_window: u8 = 0;
154
155    while offset < apdu.len() {
156        let chunk = (apdu.len() - offset).min(block_payload_max);
157        let last = offset + chunk >= apdu.len();
158
159        let block = GeneralBlockTransfer {
160            last_block: last,
161            streaming,
162            window: win,
163            block_number,
164            block_number_ack: 0,
165            block_data: apdu[offset..offset + chunk].to_vec(),
166        };
167        link.send_apdu(&block.encode())?;
168
169        offset += chunk;
170        block_number = block_number.wrapping_add(1);
171        blocks_in_window += 1;
172
173        // Confirmed mode: wait for an ack after each window (not after the
174        // last block, whose reply is the caller's concern).
175        if win > 0 && !last && blocks_in_window >= win {
176            let ack = read_block(link)?;
177            if !ack.block_data.is_empty() || !ack.last_block || ack.streaming {
178                return Err(io::Error::new(io::ErrorKind::InvalidData, "expected an ack-only GBT frame"));
179            }
180            // The peer reports a gap: retransmit from the first unconfirmed block.
181            if ack.block_number_ack.wrapping_add(1) < block_number {
182                block_number = ack.block_number_ack.wrapping_add(1);
183                offset = (block_number as usize - 1) * block_payload_max;
184                if offset >= apdu.len() {
185                    offset = 0;
186                    block_number = 1;
187                }
188            }
189            blocks_in_window = 0;
190        }
191    }
192    Ok(())
193}
194
195/// Reassembles a general-block-transfer sequence starting from `first`, the
196/// already-received first frame (typically the result of the caller's own
197/// `link.receive_apdu()` used to detect the [`GENERAL_BLOCK_TRANSFER`] tag),
198/// reading further blocks from `link` as needed. Handles out-of-order and
199/// duplicate blocks by requesting retransmission / acking-and-discarding.
200///
201/// In confirmed mode (peer window > 0), acks are sent at the same cadence
202/// the sender waits on — every `window` accepted blocks — so the two sides
203/// stay in lockstep; acking every block regardless of window size would
204/// desynchronize a sender that only checks for an ack once per window and
205/// trigger spurious retransmits.
206///
207/// Returns the reassembled plain (or still-ciphered, if the segmented APDU
208/// was ciphered) APDU bytes.
209pub fn receive<L: DataLinkLayer>(link: &mut L, first: &[u8]) -> io::Result<Vec<u8>> {
210    let mut block = GeneralBlockTransfer::decode(first)?;
211    let mut acc = Vec::new();
212    let mut expected_block: u16 = 1;
213    let mut peer_window: u8 = 0;
214    let mut blocks_since_ack: u8 = 0;
215
216    loop {
217        if block.block_number > expected_block {
218            // Gap: request retransmission from `expected_block`.
219            let gap = block.block_number - expected_block;
220            // The else branch only runs when gap <= WINDOW_MASK, so it always fits u8.
221            #[allow(clippy::cast_possible_truncation)]
222            let win = if gap > u16::from(WINDOW_MASK) { WINDOW_MASK } else { gap.max(1) as u8 };
223            send_ack(link, win, expected_block.saturating_sub(1))?;
224            block = read_block(link)?;
225            continue;
226        }
227        if block.block_number < expected_block {
228            // Duplicate or late block: ack (if a window is in use) and ignore.
229            let win = if block.window > 0 { block.window } else { peer_window };
230            if win > 0 {
231                send_ack(link, win, block.block_number)?;
232            }
233            block = read_block(link)?;
234            continue;
235        }
236        if block.window > 0 {
237            peer_window = block.window;
238        }
239        acc.extend_from_slice(&block.block_data);
240        if block.last_block {
241            return Ok(acc);
242        }
243        blocks_since_ack += 1;
244        if peer_window > 0 && blocks_since_ack >= peer_window {
245            send_ack(link, peer_window, expected_block)?;
246            blocks_since_ack = 0;
247        }
248        expected_block = expected_block.wrapping_add(1);
249        block = read_block(link)?;
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn general_block_transfer_round_trips() {
259        let gbt = GeneralBlockTransfer {
260            last_block: false,
261            streaming: false,
262            window: 1,
263            block_number: 1,
264            block_number_ack: 0,
265            block_data: vec![0xC0, 0x01, 0xC1, 0x00, 0x08],
266        };
267        let bytes = gbt.encode();
268        // E0 01 0001 0000 05 C001C10008.
269        assert_eq!(bytes, vec![0xE0, 0x01, 0x00, 0x01, 0x00, 0x00, 0x05, 0xC0, 0x01, 0xC1, 0x00, 0x08]);
270        assert_eq!(GeneralBlockTransfer::decode(&bytes).unwrap(), gbt);
271    }
272
273    #[test]
274    fn last_block_and_streaming_flags_round_trip() {
275        let gbt = GeneralBlockTransfer {
276            last_block: true,
277            streaming: true,
278            window: 5,
279            block_number: 3,
280            block_number_ack: 2,
281            block_data: vec![0xAA],
282        };
283        let bytes = gbt.encode();
284        assert_eq!(bytes[1], LAST_BLOCK | STREAMING | 5);
285        assert_eq!(GeneralBlockTransfer::decode(&bytes).unwrap(), gbt);
286    }
287
288    #[test]
289    fn decode_rejects_wrong_tag() {
290        assert_eq!(GeneralBlockTransfer::decode(&[0xC0, 0x00, 0, 0, 0, 0, 0]), Err(ServiceError::UnexpectedTag(0xC0)));
291    }
292
293    #[test]
294    fn applies_to_apdu_covers_the_documented_tags() {
295        for t in [
296            tag::GET_REQUEST,
297            tag::GET_RESPONSE,
298            tag::SET_REQUEST,
299            tag::SET_RESPONSE,
300            tag::ACTION_REQUEST,
301            tag::ACTION_RESPONSE,
302            tag::DATA_NOTIFICATION,
303            tag::EVENT_NOTIFICATION_REQUEST,
304        ] {
305            assert!(applies_to_apdu(&[t, 0x00]), "tag 0x{t:02X} should apply");
306        }
307        assert!(!applies_to_apdu(&[GENERAL_BLOCK_TRANSFER, 0x00]));
308        assert!(!applies_to_apdu(&[]));
309    }
310
311    // ------------------------------------------------------------------
312    // Transport-level send/receive, driven over a scripted DataLinkLayer.
313    // ------------------------------------------------------------------
314
315    use crate::transport::DataLinkLayer;
316    use std::collections::VecDeque;
317    use std::io;
318
319    /// A [`DataLinkLayer`] mock: `receive_apdu` returns pre-programmed frames
320    /// in order, `send_apdu` records what was sent.
321    #[derive(Default)]
322    struct ScriptedLink {
323        rx: VecDeque<Vec<u8>>,
324        tx: Vec<Vec<u8>>,
325    }
326
327    impl DataLinkLayer for ScriptedLink {
328        fn send_apdu(&mut self, apdu: &[u8]) -> io::Result<()> {
329            self.tx.push(apdu.to_vec());
330            Ok(())
331        }
332        fn receive_apdu(&mut self) -> io::Result<Vec<u8>> {
333            self.rx.pop_front().ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "script exhausted"))
334        }
335    }
336
337    #[test]
338    fn send_unconfirmed_segments_without_waiting_for_acks() {
339        let apdu = vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05];
340        let mut link = ScriptedLink::default();
341        // window = 0: no acks are read (an empty rx queue would panic if `send` tried to).
342        send(&mut link, &apdu, 4, 0, false).unwrap();
343
344        assert_eq!(link.tx.len(), 3); // 9 octets / 4-octet blocks = 3 blocks.
345        let b1 = GeneralBlockTransfer::decode(&link.tx[0]).unwrap();
346        assert_eq!(
347            b1,
348            GeneralBlockTransfer {
349                last_block: false,
350                streaming: false,
351                window: 0,
352                block_number: 1,
353                block_number_ack: 0,
354                block_data: apdu[0..4].to_vec(),
355            }
356        );
357        let b3 = GeneralBlockTransfer::decode(&link.tx[2]).unwrap();
358        assert!(b3.last_block);
359        assert_eq!(b3.block_data, apdu[8..9].to_vec());
360
361        // Reassembling the sent blocks recovers the original APDU.
362        let mut reassembled = Vec::new();
363        for raw in &link.tx {
364            reassembled.extend(GeneralBlockTransfer::decode(raw).unwrap().block_data);
365        }
366        assert_eq!(reassembled, apdu);
367    }
368
369    #[test]
370    fn send_confirmed_waits_for_ack_each_window() {
371        let apdu = vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05]; // 3 blocks of 3.
372        let mut link = ScriptedLink::default();
373        // window = 1: an ack is expected after block 1 and after block 2.
374        link.rx.push_back(
375            (GeneralBlockTransfer {
376                last_block: true,
377                streaming: false,
378                window: 1,
379                block_number: 1,
380                block_number_ack: 1,
381                block_data: Vec::new(),
382            })
383            .encode(),
384        );
385        link.rx.push_back(
386            (GeneralBlockTransfer {
387                last_block: true,
388                streaming: false,
389                window: 1,
390                block_number: 1,
391                block_number_ack: 2,
392                block_data: Vec::new(),
393            })
394            .encode(),
395        );
396
397        send(&mut link, &apdu, 3, 1, false).unwrap();
398        assert_eq!(link.tx.len(), 3);
399        assert!(link.rx.is_empty(), "both scripted acks must be consumed");
400    }
401
402    #[test]
403    fn send_retransmits_from_the_gap_reported_by_the_peer() {
404        let apdu = vec![0xC0, 0x01, 0xC1, 0x00, 0x01, 0x02]; // 3 blocks of 2.
405        let mut link = ScriptedLink::default();
406        // After block 1, the peer reports it never got anything (ack=0):
407        // retransmission must restart from block 1.
408        link.rx.push_back(
409            (GeneralBlockTransfer {
410                last_block: true,
411                streaming: false,
412                window: 1,
413                block_number: 1,
414                block_number_ack: 0,
415                block_data: Vec::new(),
416            })
417            .encode(),
418        );
419        // The retransmitted block 1 is acked properly this time.
420        link.rx.push_back(
421            (GeneralBlockTransfer {
422                last_block: true,
423                streaming: false,
424                window: 1,
425                block_number: 1,
426                block_number_ack: 1,
427                block_data: Vec::new(),
428            })
429            .encode(),
430        );
431        link.rx.push_back(
432            (GeneralBlockTransfer {
433                last_block: true,
434                streaming: false,
435                window: 1,
436                block_number: 1,
437                block_number_ack: 2,
438                block_data: Vec::new(),
439            })
440            .encode(),
441        );
442
443        send(&mut link, &apdu, 2, 1, false).unwrap();
444        // block 1 sent, retransmitted, block 2, block 3 = 4 sends.
445        assert_eq!(link.tx.len(), 4);
446        let numbers: Vec<u16> =
447            link.tx.iter().map(|raw| GeneralBlockTransfer::decode(raw).unwrap().block_number).collect();
448        assert_eq!(numbers, vec![1, 1, 2, 3]);
449    }
450
451    #[test]
452    fn send_rejects_a_reply_that_is_not_an_ack() {
453        let apdu = vec![0; 5];
454        let mut link = ScriptedLink::default();
455        // A frame carrying payload is not a valid ack.
456        link.rx.push_back(
457            (GeneralBlockTransfer {
458                last_block: true,
459                streaming: false,
460                window: 1,
461                block_number: 1,
462                block_number_ack: 1,
463                block_data: vec![0xAA],
464            })
465            .encode(),
466        );
467        let err = send(&mut link, &apdu, 2, 1, false).unwrap_err();
468        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
469    }
470
471    #[test]
472    fn receive_reassembles_a_single_block() {
473        let first = (GeneralBlockTransfer {
474            last_block: true,
475            streaming: false,
476            window: 0,
477            block_number: 1,
478            block_number_ack: 0,
479            block_data: vec![0xC0, 0x01],
480        })
481        .encode();
482        let mut link = ScriptedLink::default();
483        let apdu = receive(&mut link, &first).unwrap();
484        assert_eq!(apdu, vec![0xC0, 0x01]);
485        assert!(link.tx.is_empty(), "no window in use: no ack should be sent");
486    }
487
488    #[test]
489    fn receive_reassembles_multiple_blocks_and_acks_confirmed_ones() {
490        let first = (GeneralBlockTransfer {
491            last_block: false,
492            streaming: false,
493            window: 1,
494            block_number: 1,
495            block_number_ack: 0,
496            block_data: vec![0xC0, 0x01],
497        })
498        .encode();
499        let mut link = ScriptedLink::default();
500        link.rx.push_back(
501            (GeneralBlockTransfer {
502                last_block: true,
503                streaming: false,
504                window: 1,
505                block_number: 2,
506                block_number_ack: 0,
507                block_data: vec![0xC1, 0x00],
508            })
509            .encode(),
510        );
511
512        let apdu = receive(&mut link, &first).unwrap();
513        assert_eq!(apdu, vec![0xC0, 0x01, 0xC1, 0x00]);
514        // One ack sent, acknowledging block 1.
515        assert_eq!(link.tx.len(), 1);
516        let ack = GeneralBlockTransfer::decode(&link.tx[0]).unwrap();
517        assert_eq!(ack.block_number_ack, 1);
518        assert!(ack.block_data.is_empty());
519    }
520
521    #[test]
522    fn receive_requests_retransmission_on_a_gap_and_ignores_duplicates() {
523        // First frame received is block 2, but block 1 is expected: receive()
524        // must ask for a retransmit before it can make progress.
525        let first = (GeneralBlockTransfer {
526            last_block: true,
527            streaming: false,
528            window: 1,
529            block_number: 2,
530            block_number_ack: 0,
531            block_data: vec![0xC1, 0x00],
532        })
533        .encode();
534        let mut link = ScriptedLink::default();
535        // A duplicate of block 2 arrives before the real block 1 (should be
536        // acked and ignored), then block 1 arrives.
537        link.rx.push_back(
538            (GeneralBlockTransfer {
539                last_block: true,
540                streaming: false,
541                window: 1,
542                block_number: 2,
543                block_number_ack: 0,
544                block_data: vec![0xC1, 0x00],
545            })
546            .encode(),
547        );
548        link.rx.push_back(
549            (GeneralBlockTransfer {
550                last_block: false,
551                streaming: false,
552                window: 1,
553                block_number: 1,
554                block_number_ack: 0,
555                block_data: vec![0xC0, 0x01],
556            })
557            .encode(),
558        );
559        // Block 2 again, now expected — completes the transfer.
560        link.rx.push_back(
561            (GeneralBlockTransfer {
562                last_block: true,
563                streaming: false,
564                window: 1,
565                block_number: 2,
566                block_number_ack: 0,
567                block_data: vec![0xC1, 0x00],
568            })
569            .encode(),
570        );
571
572        let apdu = receive(&mut link, &first).unwrap();
573        assert_eq!(apdu, vec![0xC0, 0x01, 0xC1, 0x00]);
574        assert!(link.rx.is_empty());
575    }
576}