Skip to main content

syncspin_core/
framing.rs

1//! Binary framing: message ids, fragmentation and reassembly.
2//!
3//! After the Noise handshake every application message is one Noise transport message. Its
4//! plaintext starts with a one-byte binary message id: `0` carries a UTF-8 JSON body, `1` is the
5//! fragmentation channel, and each role owns its own ids (for example `4` for player audio).
6//! [`MAX_PLAINTEXT_LEN`] bounds one plaintext, so a larger payload has to be split.
7//!
8//! Fragmentation keeps the byte layout of the published protocol:
9//!
10//! ```text
11//! first fragment   [1][flags with the first bit][original message id][data]
12//! later fragments  [1][flags][data]
13//! ```
14//!
15//! Bit 0 of the flags byte marks the last fragment, bit 1 the first one, and bits 2-7 must be
16//! zero. Only one fragmented message may be in flight per direction, so the receiver appends every
17//! fragment to one buffer and dispatches the result when the last flag arrives. [`Reassembler`]
18//! does that for a session reading frame by frame; [`reassemble_binary`] does it for a sequence
19//! already in hand. This module does no I/O.
20
21use anyhow::{bail, Context, Result};
22
23pub use crate::noise::MAX_PLAINTEXT_LEN;
24
25/// Binary message id of a JSON message body.
26pub const BINARY_MESSAGE_ID_JSON: u8 = 0;
27
28/// Binary message id of a fragment.
29///
30/// A sender must never use it as the id of a fragmented message.
31pub const BINARY_MESSAGE_ID_FRAGMENT: u8 = 1;
32
33/// Fragment flag marking the last fragment of a message.
34pub const FRAGMENT_FLAG_LAST: u8 = 0x01;
35
36/// Fragment flag marking the first fragment of a message.
37pub const FRAGMENT_FLAG_FIRST: u8 = 0x02;
38
39/// Fragment flag bits that are reserved and must be zero.
40pub const FRAGMENT_FLAGS_RESERVED: u8 = 0xfc;
41
42/// Largest reassembled message, bounding the buffer a peer can make the receiver allocate.
43///
44/// The protocol lets a receiver choose its own limit; a message beyond it is a protocol error.
45pub const MAX_REASSEMBLED_LEN: usize = 64 * 1024 * 1024;
46
47/// Header of a first fragment: message id, flags byte and original message id.
48const FIRST_FRAGMENT_HEADER_LEN: usize = 3;
49
50/// Header of a continuation fragment: message id and flags byte.
51const FRAGMENT_HEADER_LEN: usize = 2;
52
53/// One plaintext frame, classified by its leading message id.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Frame<'a> {
56    /// A JSON message body (message id [`BINARY_MESSAGE_ID_JSON`]).
57    Json(&'a str),
58    /// A binary message of the given id; `payload` is everything after the id byte.
59    Binary {
60        /// Binary message id.
61        id: u8,
62        /// Message body, without the id byte.
63        payload: &'a [u8],
64    },
65}
66
67/// Decodes one Noise transport plaintext into a [`Frame`].
68///
69/// The first byte of a plaintext is its binary message id: id [`BINARY_MESSAGE_ID_JSON`]
70/// introduces a UTF-8 JSON body and every other id introduces a binary body. Cleartext handshake
71/// messages do not travel through Noise, carry no id byte and are JSON text the caller parses
72/// directly; this function never sees them.
73///
74/// Fragment frames (id [`BINARY_MESSAGE_ID_FRAGMENT`]) are classified like any other binary
75/// message, with the payload starting at the flags byte. A session hands the plaintexts themselves
76/// to a [`Reassembler`], which needs the id byte of each fragment, and decodes only the message the
77/// reassembler completes.
78///
79/// # Errors
80/// Returns an error for an empty plaintext, which is always a protocol error, and for a JSON body
81/// that is not valid UTF-8.
82pub fn decode_frame(bytes: &[u8]) -> Result<Frame<'_>> {
83    let Some((&id, payload)) = bytes.split_first() else {
84        bail!("empty plaintext: every transport message carries a message id byte");
85    };
86    if id == BINARY_MESSAGE_ID_JSON {
87        let text = std::str::from_utf8(payload).context("JSON message body is not valid UTF-8")?;
88        return Ok(Frame::Json(text));
89    }
90    Ok(Frame::Binary { id, payload })
91}
92
93/// Encodes one binary message: the id byte followed by the payload.
94pub fn encode_binary(id: u8, payload: &[u8]) -> Vec<u8> {
95    let mut frame = Vec::with_capacity(1 + payload.len());
96    frame.push(id);
97    frame.extend_from_slice(payload);
98    frame
99}
100
101/// Splits a binary message into plaintext frames that each fit `max_plaintext`.
102///
103/// A message that fits returns exactly one frame, `[id][payload]`; a larger one returns the
104/// fragments of message id [`BINARY_MESSAGE_ID_FRAGMENT`], the first carrying the original id.
105/// Every fragment is at most `max_plaintext` bytes.
106///
107/// The payload is cut into equally sized chunks of `max_plaintext - 3` bytes, the capacity of a
108/// first fragment, so a continuation frame stays one byte below the limit.
109///
110/// # Panics
111/// Panics when `id` is [`BINARY_MESSAGE_ID_FRAGMENT`], or when `max_plaintext` is smaller than a
112/// first-fragment header plus one payload byte.
113pub fn split_binary(id: u8, payload: &[u8], max_plaintext: usize) -> Vec<Vec<u8>> {
114    assert!(
115        id != BINARY_MESSAGE_ID_FRAGMENT,
116        "message id 1 is reserved for fragmentation"
117    );
118    assert!(
119        max_plaintext > FIRST_FRAGMENT_HEADER_LEN,
120        "max_plaintext must leave room for a fragment header and at least one payload byte"
121    );
122
123    if payload.len() < max_plaintext {
124        return vec![encode_binary(id, payload)];
125    }
126
127    let chunk_len = max_plaintext - FIRST_FRAGMENT_HEADER_LEN;
128    let count = payload.len().div_ceil(chunk_len);
129    let mut frames = Vec::with_capacity(count);
130    for (index, data) in payload.chunks(chunk_len).enumerate() {
131        let first = index == 0;
132        let last = index + 1 == count;
133        let header_len = if first {
134            FIRST_FRAGMENT_HEADER_LEN
135        } else {
136            FRAGMENT_HEADER_LEN
137        };
138        let mut frame = Vec::with_capacity(header_len + data.len());
139        frame.push(BINARY_MESSAGE_ID_FRAGMENT);
140        frame.push(fragment_flags(first, last));
141        if first {
142            frame.push(id);
143        }
144        frame.extend_from_slice(data);
145        frames.push(frame);
146    }
147    frames
148}
149
150/// Incremental reassembler for one direction of a connection.
151///
152/// A session reads one frame at a time and owns a `Reassembler`; [`reassemble_binary`] is the same
153/// validation for a sequence that is already in hand. Both allow only one fragmented message in
154/// flight, as the protocol requires.
155#[derive(Debug)]
156pub struct Reassembler {
157    max_message_len: usize,
158    message: Option<InFlight>,
159}
160
161/// A fragmented message that is still being assembled.
162#[derive(Debug)]
163struct InFlight {
164    /// Original message id, carried by the first fragment.
165    message_id: u8,
166    /// Payload bytes collected so far.
167    body: Vec<u8>,
168}
169
170impl Reassembler {
171    /// Creates a reassembler that rejects a reassembled message longer than `max_message_len`.
172    ///
173    /// A session usually passes [`MAX_REASSEMBLED_LEN`], the bound a receiver may choose for
174    /// itself.
175    pub fn new(max_message_len: usize) -> Self {
176        Self {
177            max_message_len,
178            message: None,
179        }
180    }
181
182    /// Feeds one Noise transport plaintext.
183    ///
184    /// Returns `Some((id, payload))` when the frame completes a message: immediately for a plain
185    /// frame, and on the fragment that carries the last flag for a sequence. Every other fragment
186    /// returns `Ok(None)`.
187    ///
188    /// # Errors
189    /// Returns an error, and drops any message in flight, for the malformed sequences the protocol
190    /// defines: an empty frame, a plain frame while a fragmented message is in flight, a fragment
191    /// without its flags byte, reserved flag bits, a continuation fragment without a first
192    /// fragment, a second first fragment while one is in flight, a first fragment without its
193    /// original message id, an original id of [`BINARY_MESSAGE_ID_FRAGMENT`], and a message larger
194    /// than `max_message_len`.
195    ///
196    /// The framing carries no byte count and no sequence number, so a fragment lost from the middle
197    /// of a message cannot be detected here.
198    pub fn push(&mut self, frame: &[u8]) -> Result<Option<(u8, Vec<u8>)>> {
199        let outcome = self.push_frame(frame);
200        if outcome.is_err() {
201            self.message = None;
202        }
203        outcome
204    }
205
206    /// Validates one frame and advances the reassembly state.
207    fn push_frame(&mut self, frame: &[u8]) -> Result<Option<(u8, Vec<u8>)>> {
208        let Some((&id, body)) = frame.split_first() else {
209            bail!("empty frame");
210        };
211        if id != BINARY_MESSAGE_ID_FRAGMENT {
212            if self.message.is_some() {
213                bail!("non-fragment frame while a fragmented message is in flight");
214            }
215            return Ok(Some((id, body.to_vec())));
216        }
217
218        let Some((&flags, body)) = body.split_first() else {
219            bail!("fragment frame missing its flags byte");
220        };
221        if flags & FRAGMENT_FLAGS_RESERVED != 0 {
222            bail!("fragment flags 0x{flags:02x} set reserved bits");
223        }
224        let first = flags & FRAGMENT_FLAG_FIRST != 0;
225        let last = flags & FRAGMENT_FLAG_LAST != 0;
226
227        if first {
228            if self.message.is_some() {
229                bail!("first fragment while a fragmented message is in flight");
230            }
231            let Some((&message_id, data)) = body.split_first() else {
232                bail!("first fragment missing its original message id");
233            };
234            if message_id == BINARY_MESSAGE_ID_FRAGMENT {
235                bail!("first fragment carries the fragmentation id as its original message id");
236            }
237            if data.len() > self.max_message_len {
238                bail!("fragmented message exceeds {} bytes", self.max_message_len);
239            }
240            let mut message = InFlight {
241                message_id,
242                body: Vec::with_capacity(data.len()),
243            };
244            message.body.extend_from_slice(data);
245            if !last {
246                self.message = Some(message);
247                return Ok(None);
248            }
249            return Ok(Some((message_id, message.body)));
250        }
251
252        let Some(message) = self.message.as_mut() else {
253            bail!("continuation fragment without a first fragment");
254        };
255        if message.body.len() + body.len() > self.max_message_len {
256            bail!("fragmented message exceeds {} bytes", self.max_message_len);
257        }
258        message.body.extend_from_slice(body);
259        if !last {
260            return Ok(None);
261        }
262        let Some(InFlight { message_id, body }) = self.message.take() else {
263            bail!("continuation fragment without a first fragment");
264        };
265        Ok(Some((message_id, body)))
266    }
267}
268
269/// Reassembles a complete sequence of frames into the original message.
270///
271/// Accepts a single unfragmented frame, returning its id and body unchanged, as well as the
272/// fragment sequence [`split_binary`] produces. A session that reads frame by frame keeps a
273/// [`Reassembler`] instead; this is the batch form for a sequence that is already in hand.
274///
275/// The framing carries no byte count and no sequence number, so a fragment lost from the middle of
276/// a message cannot be detected here. What is detectable is rejected: a continuation before the
277/// first fragment, a first flag on a later fragment, data after the last fragment, a missing last
278/// fragment, reserved flag bits, an original id of [`BINARY_MESSAGE_ID_FRAGMENT`], and a message
279/// larger than [`MAX_REASSEMBLED_LEN`].
280///
281/// # Errors
282/// Returns an error when the frames are empty, cannot form exactly one well-formed message, or
283/// exceed [`MAX_REASSEMBLED_LEN`].
284pub fn reassemble_binary(frames: &[Vec<u8>]) -> Result<(u8, Vec<u8>)> {
285    if frames.is_empty() {
286        bail!("no frame to reassemble");
287    }
288    let mut reassembler = Reassembler::new(MAX_REASSEMBLED_LEN);
289    let mut message = None;
290    for (index, frame) in frames.iter().enumerate() {
291        let completed = reassembler
292            .push(frame)
293            .with_context(|| format!("frame {index}"))?;
294        if let Some(completed) = completed {
295            if message.is_some() {
296                bail!("frame {index}: more than one message in one sequence");
297            }
298            message = Some(completed);
299        }
300    }
301    let Some(message) = message else {
302        bail!("the last fragment is missing: no fragment carried the last flag");
303    };
304    Ok(message)
305}
306
307/// Largest encoded-audio payload that fits one frame without fragmentation.
308///
309/// An audio chunk spends one byte on its message id, eight on the timestamp and four on
310/// `send_ahead`, so the payload gets whatever `max_plaintext` has left. A value below that fixed
311/// header, which makes any chunk impossible, yields 0.
312pub fn max_audio_payload(max_plaintext: usize) -> usize {
313    max_plaintext.saturating_sub(crate::messages::AudioChunkHeader::LEN)
314}
315
316/// Builds the flags byte of one fragment.
317fn fragment_flags(first: bool, last: bool) -> u8 {
318    let mut flags = 0;
319    if first {
320        flags |= FRAGMENT_FLAG_FIRST;
321    }
322    if last {
323        flags |= FRAGMENT_FLAG_LAST;
324    }
325    flags
326}