Skip to main content

alpha2_host_core/
host_frames.rs

1//! Frames of the host protocol: an 8-byte preamble, a JSON header and binary attachments.
2//!
3//! The preamble holds the header's length and the attachments' total length, both little-endian
4//! `u32`, so a reader finds the next frame without parsing the header. The header's `attachments`
5//! lists each attachment's `type` and `bytes`, in order.
6
7use std::io::{self, BufRead, Read, Write};
8
9use serde_json::Value;
10
11/// What `serve` writes before its first frame, so a reader skips whatever reached the stream
12/// before the host owned it.
13pub const MAGIC: [u8; 8] = *b"\x89A2HOST\n";
14
15const PREAMBLE_BYTES: usize = 8;
16
17/// The most an attachment's `type` may hold.
18pub const MAX_ATTACHMENT_TYPE_BYTES: usize = 255;
19
20/// The largest frame a reader takes; a larger one is read through and dropped.
21#[derive(Clone, Copy, Debug)]
22pub struct FrameLimits {
23    /// Header bytes.
24    pub header_bytes: u32,
25    /// Attachment bytes, all together.
26    pub attachment_bytes: u32,
27}
28
29/// A frame as read: its header and its attachments' bytes, not yet split.
30#[derive(Debug, Default, PartialEq, Eq)]
31pub struct Frame {
32    /// The header's bytes, which should be one JSON object in UTF-8.
33    pub header: Vec<u8>,
34    /// Every attachment's bytes, in order.
35    pub attachments: Vec<u8>,
36}
37
38/// One attachment of a frame.
39#[derive(Clone, Debug, PartialEq, Eq)]
40pub struct Attachment {
41    /// A media type, such as `image/png`.
42    pub kind: String,
43    /// Its bytes.
44    pub bytes: Vec<u8>,
45}
46
47/// What [`read_frame`] found.
48#[derive(Debug, PartialEq, Eq)]
49pub enum ReadFrame {
50    /// A frame within the limits.
51    Frame(Frame),
52    /// A frame over a limit, skipped whole so the next one is read from its start.
53    TooLarge {
54        /// Its header's length.
55        header_bytes: u32,
56        /// Its attachments' length.
57        attachment_bytes: u32,
58    },
59    /// The stream ended, or ended inside a frame.
60    End,
61}
62
63/// Reads the next frame.
64///
65/// # Errors
66/// A read error other than the end of the stream.
67pub fn read_frame(input: &mut impl Read, limits: FrameLimits) -> io::Result<ReadFrame> {
68    let mut preamble = [0_u8; PREAMBLE_BYTES];
69    if !read_whole(input, &mut preamble)? {
70        return Ok(ReadFrame::End);
71    }
72    let header_bytes = u32::from_le_bytes([preamble[0], preamble[1], preamble[2], preamble[3]]);
73    let attachment_bytes = u32::from_le_bytes([preamble[4], preamble[5], preamble[6], preamble[7]]);
74    if header_bytes > limits.header_bytes || attachment_bytes > limits.attachment_bytes {
75        let skip = u64::from(header_bytes) + u64::from(attachment_bytes);
76        let skipped = io::copy(&mut input.take(skip), &mut io::sink())?;
77        if skipped < skip {
78            return Ok(ReadFrame::End);
79        }
80        return Ok(ReadFrame::TooLarge {
81            header_bytes,
82            attachment_bytes,
83        });
84    }
85    let mut header = vec![0_u8; header_bytes as usize];
86    let mut attachments = vec![0_u8; attachment_bytes as usize];
87    if !read_whole(input, &mut header)? || !read_whole(input, &mut attachments)? {
88        return Ok(ReadFrame::End);
89    }
90    Ok(ReadFrame::Frame(Frame {
91        header,
92        attachments,
93    }))
94}
95
96/// `false` when the stream ended first.
97fn read_whole(input: &mut impl Read, buffer: &mut [u8]) -> io::Result<bool> {
98    match input.read_exact(buffer) {
99        Ok(()) => Ok(true),
100        Err(error) if error.kind() == io::ErrorKind::UnexpectedEof => Ok(false),
101        Err(error) => Err(error),
102    }
103}
104
105/// One frame's bytes, preamble included, so it is written in one piece.
106///
107/// # Errors
108/// `InvalidInput` when the header or the attachments together exceed 4 GiB.
109pub fn frame_bytes(header: &[u8], attachments: &[&[u8]]) -> io::Result<Vec<u8>> {
110    let too_large = |what: &str| {
111        io::Error::new(
112            io::ErrorKind::InvalidInput,
113            format!("a frame's {what} is at most 4 GiB"),
114        )
115    };
116    let header_bytes = u32::try_from(header.len()).map_err(|_| too_large("header"))?;
117    let total = attachments
118        .iter()
119        .try_fold(0_u32, |total, attachment| {
120            u32::try_from(attachment.len())
121                .ok()
122                .and_then(|bytes| total.checked_add(bytes))
123        })
124        .ok_or_else(|| too_large("attachments"))?;
125    let mut frame = Vec::with_capacity(PREAMBLE_BYTES + header.len() + total as usize);
126    frame.extend_from_slice(&header_bytes.to_le_bytes());
127    frame.extend_from_slice(&total.to_le_bytes());
128    frame.extend_from_slice(header);
129    for attachment in attachments {
130        frame.extend_from_slice(attachment);
131    }
132    Ok(frame)
133}
134
135/// Writes one frame and flushes it.
136///
137/// # Errors
138/// A frame over 4 GiB, or the output's error.
139pub fn write_frame(
140    output: &mut impl Write,
141    header: &[u8],
142    attachments: &[&[u8]],
143) -> io::Result<()> {
144    output.write_all(&frame_bytes(header, attachments)?)?;
145    output.flush()
146}
147
148/// Splits `bytes` as the header's `attachments` list says.
149///
150/// # Errors
151/// A list that is not an array of `{type, bytes}`, an empty or overlong `type`, or lengths that do
152/// not add up to `bytes`.
153pub fn split_attachments(header: &Value, bytes: Vec<u8>) -> Result<Vec<Attachment>, String> {
154    let listed = match header.get("attachments") {
155        None | Some(Value::Null) => &[][..],
156        Some(Value::Array(listed)) => listed.as_slice(),
157        Some(_) => return Err("`attachments` is a list of {type, bytes}".to_owned()),
158    };
159    let mut declared = Vec::with_capacity(listed.len());
160    let mut total = 0_u64;
161    for (index, entry) in listed.iter().enumerate() {
162        let kind = entry
163            .get("type")
164            .and_then(Value::as_str)
165            .filter(|kind| !kind.is_empty() && kind.len() <= MAX_ATTACHMENT_TYPE_BYTES)
166            .ok_or_else(|| {
167                format!(
168                    "attachments[{index}].type is a media type of 1 to {MAX_ATTACHMENT_TYPE_BYTES} bytes"
169                )
170            })?;
171        let length = entry
172            .get("bytes")
173            .and_then(Value::as_u64)
174            .ok_or_else(|| format!("attachments[{index}].bytes is a byte count"))?;
175        total = total.saturating_add(length);
176        declared.push((kind.to_owned(), length));
177    }
178    if total != bytes.len() as u64 {
179        return Err(format!(
180            "the attachments list {total} bytes; the frame carries {}",
181            bytes.len()
182        ));
183    }
184    let mut rest = bytes;
185    let mut attachments = Vec::with_capacity(declared.len());
186    for (kind, length) in declared.into_iter().rev() {
187        let at = rest.len() - usize::try_from(length).unwrap_or(rest.len());
188        attachments.push(Attachment {
189            kind,
190            bytes: rest.split_off(at),
191        });
192    }
193    attachments.reverse();
194    Ok(attachments)
195}
196
197/// Reads up to and through [`MAGIC`] and returns what came before it; `None` when the stream ended
198/// or `limit` bytes passed first.
199///
200/// # Errors
201/// A read error other than the end of the stream.
202pub fn skip_to_magic(input: &mut impl BufRead, limit: usize) -> io::Result<Option<Vec<u8>>> {
203    let mut seen = Vec::new();
204    loop {
205        let available = match input.fill_buf() {
206            Ok(available) => available,
207            Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
208            Err(error) => return Err(error),
209        };
210        if available.is_empty() {
211            return Ok(None);
212        }
213        let byte = available[0];
214        input.consume(1);
215        seen.push(byte);
216        if seen.ends_with(&MAGIC) {
217            seen.truncate(seen.len() - MAGIC.len());
218            return Ok(Some(seen));
219        }
220        if seen.len() > limit.saturating_add(MAGIC.len()) {
221            return Ok(None);
222        }
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    const LIMITS: FrameLimits = FrameLimits {
231        header_bytes: 64,
232        attachment_bytes: 64,
233    };
234
235    #[test]
236    fn frames_round_trip_and_an_oversized_one_is_skipped_whole() {
237        let mut stream = Vec::new();
238        write_frame(&mut stream, br#"{"a":1}"#, &[]).expect("write");
239        write_frame(&mut stream, &[b'x'; 65], &[]).expect("write");
240        write_frame(&mut stream, br#"{"b":2}"#, &[b"12", b"345"]).expect("write");
241        let mut input = stream.as_slice();
242        assert_eq!(
243            read_frame(&mut input, LIMITS).expect("read"),
244            ReadFrame::Frame(Frame {
245                header: br#"{"a":1}"#.to_vec(),
246                attachments: Vec::new(),
247            })
248        );
249        assert_eq!(
250            read_frame(&mut input, LIMITS).expect("read"),
251            ReadFrame::TooLarge {
252                header_bytes: 65,
253                attachment_bytes: 0
254            }
255        );
256        assert_eq!(
257            read_frame(&mut input, LIMITS).expect("read"),
258            ReadFrame::Frame(Frame {
259                header: br#"{"b":2}"#.to_vec(),
260                attachments: b"12345".to_vec(),
261            })
262        );
263        assert_eq!(
264            read_frame(&mut input, LIMITS).expect("read"),
265            ReadFrame::End
266        );
267    }
268
269    #[test]
270    fn a_stream_that_ends_inside_a_frame_ends() {
271        let mut stream = Vec::new();
272        write_frame(&mut stream, br#"{"a":1}"#, &[b"abc"]).expect("write");
273        for cut in 1..stream.len() {
274            assert_eq!(
275                read_frame(&mut &stream[..cut], LIMITS).expect("read"),
276                ReadFrame::End,
277                "{cut}"
278            );
279        }
280    }
281
282    #[test]
283    fn attachments_split_by_the_header_list() {
284        let header = serde_json::json!({
285            "attachments": [{"type": "image/png", "bytes": 2}, {"type": "a/b", "bytes": 3}]
286        });
287        let split = split_attachments(&header, b"12345".to_vec()).expect("split");
288        assert_eq!(split.len(), 2);
289        assert_eq!(
290            (split[0].kind.as_str(), split[0].bytes.as_slice()),
291            ("image/png", &b"12"[..])
292        );
293        assert_eq!(
294            (split[1].kind.as_str(), split[1].bytes.as_slice()),
295            ("a/b", &b"345"[..])
296        );
297        assert_eq!(
298            split_attachments(&serde_json::json!({}), Vec::new()),
299            Ok(Vec::new())
300        );
301        for refused in [
302            serde_json::json!({"attachments": [{"type": "a/b", "bytes": 4}]}),
303            serde_json::json!({"attachments": [{"type": "", "bytes": 5}]}),
304            serde_json::json!({"attachments": [{"bytes": 5}]}),
305            serde_json::json!({"attachments": {"type": "a/b", "bytes": 5}}),
306            serde_json::json!({"attachments": [{"type": "a/b", "bytes": u64::MAX}, {"type": "a/b", "bytes": 6}]}),
307        ] {
308            assert!(
309                split_attachments(&refused, b"12345".to_vec()).is_err(),
310                "{refused}"
311            );
312        }
313        assert!(split_attachments(&serde_json::json!({}), b"1".to_vec()).is_err());
314    }
315
316    #[test]
317    fn the_magic_skips_what_came_before_it() {
318        let mut stream = b"running 1 test\n".to_vec();
319        stream.extend_from_slice(&MAGIC);
320        stream.extend_from_slice(b"rest");
321        let mut input = stream.as_slice();
322        assert_eq!(
323            skip_to_magic(&mut input, 1024).expect("read"),
324            Some(b"running 1 test\n".to_vec())
325        );
326        assert_eq!(input, b"rest");
327        assert_eq!(
328            skip_to_magic(&mut &b"no magic"[..], 1024).expect("read"),
329            None
330        );
331        assert_eq!(skip_to_magic(&mut &stream[..], 4).expect("read"), None);
332    }
333}