Skip to main content

dtshim_core/
codec.rs

1//! The dtshim wire format.
2//!
3//! A frame is a four-byte big-endian payload length followed by that many
4//! bytes of a Postcard-encoded [`Message`]. This module owns the payload
5//! encoding and the size limit.
6
7use std::io;
8
9use crate::model::Message;
10
11pub const MAX_PAYLOAD_LEN: usize = 8 * 1024 * 1024;
12
13fn invalid_payload(error: postcard::Error) -> io::Error {
14    io::Error::new(io::ErrorKind::InvalidData, error)
15}
16
17/// Decodes the payload of one frame, without its length header.
18///
19/// # Errors
20///
21/// Returns [`io::ErrorKind::InvalidData`] if `payload` does not hold a
22/// Postcard-encoded [`Message`].
23pub fn decode_payload(payload: &[u8]) -> io::Result<Message> {
24    postcard::from_bytes(payload).map_err(invalid_payload)
25}
26
27/// Appends the Postcard encoding of `message` to `buffer` and returns it.
28///
29/// The length header is not written and [`MAX_PAYLOAD_LEN`] is not enforced:
30/// both belong to the framing layer.
31///
32/// # Errors
33///
34/// Returns [`io::ErrorKind::InvalidData`] if Postcard serialization fails.
35pub fn encode_payload(message: &Message, buffer: Vec<u8>) -> io::Result<Vec<u8>> {
36    postcard::to_extend(message, buffer).map_err(invalid_payload)
37}
38
39#[cfg(test)]
40mod tests {
41    use crate::model::Start;
42
43    use super::*;
44
45    // The expected bytes are worked out by hand from the Postcard specification.
46    // Both binaries build their frames from these payloads, so a change here is
47    // a change to the wire protocol.
48    #[test]
49    fn payloads_match_the_wire_contract() {
50        let contract: [(Message, &[u8]); 10] = [
51            (
52                Message::Start(Start {
53                    token: Some("secret".into()),
54                    command: "tool".into(),
55                    args: vec!["arg with spaces".into()],
56                    env: vec![("NAME".into(), "value".into())],
57                    cwd: "/work".into(),
58                }),
59                b"\x00\x01\x06secret\x04tool\x01\x0farg with spaces\x01\x04NAME\x05value\x05/work",
60            ),
61            (
62                Message::Start(Start {
63                    token: None,
64                    command: "tool".into(),
65                    args: vec![],
66                    env: vec![],
67                    cwd: "/".into(),
68                }),
69                b"\x00\x00\x04tool\x00\x00\x01/",
70            ),
71            (Message::Stdin(vec![0, 255, 128]), b"\x01\x03\x00\xff\x80"),
72            (Message::Stdin(vec![]), b"\x01\x00"),
73            (Message::Stdout(b"output".to_vec()), b"\x02\x06output"),
74            (Message::Stderr(b"error".to_vec()), b"\x03\x05error"),
75            (Message::Code(255), b"\x04\xfe\x03"),
76            (Message::Code(-1), b"\x04\x01"),
77            (Message::Signaled(15), b"\x05\x1e"),
78            (
79                Message::Failed("command failed".into()),
80                b"\x06\x0ecommand failed",
81            ),
82        ];
83
84        for (message, payload) in contract {
85            let encoded = encode_payload(&message, Vec::new()).unwrap();
86            assert_eq!(encoded, payload, "{message:?}");
87
88            let decoded = decode_payload(payload).unwrap();
89            assert_eq!(format!("{decoded:?}"), format!("{message:?}"));
90        }
91    }
92
93    #[test]
94    fn encoding_appends_to_the_given_buffer() {
95        let buffer = encode_payload(&Message::Code(7), vec![0xaa, 0xbb]).unwrap();
96        assert_eq!(buffer, [0xaa, 0xbb, 4, 14]);
97    }
98
99    #[test]
100    fn malformed_payloads_are_rejected() {
101        for payload in [&[][..], &[255][..], &[4][..], &[1, 3, 0][..]] {
102            let error = decode_payload(payload).unwrap_err();
103            assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{payload:?}");
104        }
105    }
106}