Skip to main content

weirdnet_agent/remote/
codec.rs

1//! Length-prefixed framing for byte streams: a big-endian `u32` length, then the message.
2
3use super::RemoteError;
4
5/// Largest message accepted (32 MiB): a long conversation with a few full-HD images fits, a
6/// runaway one does not. Peers before 0.5 accept 8 MiB.
7pub const MAX_FRAME: usize = 32 << 20;
8
9/// One framed message, ready to write.
10pub fn encode_frame(message: &[u8]) -> Result<Vec<u8>, RemoteError> {
11    if message.len() > MAX_FRAME {
12        return Err(RemoteError::protocol(format!("message of {} bytes is over the {MAX_FRAME}-byte limit", message.len())));
13    }
14    let mut out = Vec::with_capacity(4 + message.len());
15    out.extend_from_slice(&(message.len() as u32).to_be_bytes());
16    out.extend_from_slice(message);
17    Ok(out)
18}
19
20/// Collects bytes as they are read and hands out whole messages.
21#[derive(Debug, Default)]
22pub struct FrameDecoder {
23    buf: Vec<u8>,
24}
25
26impl FrameDecoder {
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    pub fn push(&mut self, bytes: &[u8]) {
32        self.buf.extend_from_slice(bytes);
33    }
34
35    /// The next whole message, if one has arrived.
36    pub fn next_frame(&mut self) -> Result<Option<Vec<u8>>, RemoteError> {
37        if self.buf.len() < 4 {
38            return Ok(None);
39        }
40        let len = u32::from_be_bytes([self.buf[0], self.buf[1], self.buf[2], self.buf[3]]) as usize;
41        if len > MAX_FRAME {
42            return Err(RemoteError::protocol(format!("incoming message of {len} bytes is over the {MAX_FRAME}-byte limit")));
43        }
44        if self.buf.len() < 4 + len {
45            return Ok(None);
46        }
47        let msg = self.buf[4..4 + len].to_vec();
48        self.buf.drain(..4 + len);
49        Ok(Some(msg))
50    }
51
52    /// Bytes held that are not a whole message yet.
53    pub fn pending(&self) -> usize {
54        self.buf.len()
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn frames_survive_any_split() {
64        let mut wire = encode_frame(b"hello").unwrap();
65        wire.extend(encode_frame(b"").unwrap());
66        wire.extend(encode_frame("wörld".as_bytes()).unwrap());
67        for split in 0..wire.len() {
68            let mut d = FrameDecoder::new();
69            let mut got = Vec::new();
70            for chunk in [&wire[..split], &wire[split..]] {
71                d.push(chunk);
72                while let Some(m) = d.next_frame().unwrap() {
73                    got.push(m);
74                }
75            }
76            assert_eq!(got, [b"hello".to_vec(), Vec::new(), "wörld".as_bytes().to_vec()], "split at {split}");
77            assert_eq!(d.pending(), 0);
78        }
79    }
80
81    #[test]
82    fn oversized_frames_are_refused_both_ways() {
83        assert!(encode_frame(&vec![0; MAX_FRAME + 1]).is_err());
84        let mut d = FrameDecoder::new();
85        d.push(&((MAX_FRAME as u32) + 1).to_be_bytes());
86        assert!(matches!(d.next_frame(), Err(RemoteError::Protocol { .. })));
87    }
88}