dtshim-core 0.10.0

Wire protocol shared by the dtshim client and the dtshimd host daemon (internal)
Documentation
//! The dtshim wire format.
//!
//! A frame is a four-byte big-endian payload length followed by that many
//! bytes of a Postcard-encoded [`Message`]. This module owns the payload
//! encoding and the size limit.

use std::io;

use crate::model::Message;

pub const MAX_PAYLOAD_LEN: usize = 8 * 1024 * 1024;

fn invalid_payload(error: postcard::Error) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, error)
}

/// Decodes the payload of one frame, without its length header.
///
/// # Errors
///
/// Returns [`io::ErrorKind::InvalidData`] if `payload` does not hold a
/// Postcard-encoded [`Message`].
pub fn decode_payload(payload: &[u8]) -> io::Result<Message> {
    postcard::from_bytes(payload).map_err(invalid_payload)
}

/// Appends the Postcard encoding of `message` to `buffer` and returns it.
///
/// The length header is not written and [`MAX_PAYLOAD_LEN`] is not enforced:
/// both belong to the framing layer.
///
/// # Errors
///
/// Returns [`io::ErrorKind::InvalidData`] if Postcard serialization fails.
pub fn encode_payload(message: &Message, buffer: Vec<u8>) -> io::Result<Vec<u8>> {
    postcard::to_extend(message, buffer).map_err(invalid_payload)
}

#[cfg(test)]
mod tests {
    use crate::model::Start;

    use super::*;

    // The expected bytes are worked out by hand from the Postcard specification.
    // Both binaries build their frames from these payloads, so a change here is
    // a change to the wire protocol.
    #[test]
    fn payloads_match_the_wire_contract() {
        let contract: [(Message, &[u8]); 10] = [
            (
                Message::Start(Start {
                    token: Some("secret".into()),
                    command: "tool".into(),
                    args: vec!["arg with spaces".into()],
                    env: vec![("NAME".into(), "value".into())],
                    cwd: "/work".into(),
                }),
                b"\x00\x01\x06secret\x04tool\x01\x0farg with spaces\x01\x04NAME\x05value\x05/work",
            ),
            (
                Message::Start(Start {
                    token: None,
                    command: "tool".into(),
                    args: vec![],
                    env: vec![],
                    cwd: "/".into(),
                }),
                b"\x00\x00\x04tool\x00\x00\x01/",
            ),
            (Message::Stdin(vec![0, 255, 128]), b"\x01\x03\x00\xff\x80"),
            (Message::Stdin(vec![]), b"\x01\x00"),
            (Message::Stdout(b"output".to_vec()), b"\x02\x06output"),
            (Message::Stderr(b"error".to_vec()), b"\x03\x05error"),
            (Message::Code(255), b"\x04\xfe\x03"),
            (Message::Code(-1), b"\x04\x01"),
            (Message::Signaled(15), b"\x05\x1e"),
            (
                Message::Failed("command failed".into()),
                b"\x06\x0ecommand failed",
            ),
        ];

        for (message, payload) in contract {
            let encoded = encode_payload(&message, Vec::new()).unwrap();
            assert_eq!(encoded, payload, "{message:?}");

            let decoded = decode_payload(payload).unwrap();
            assert_eq!(format!("{decoded:?}"), format!("{message:?}"));
        }
    }

    #[test]
    fn encoding_appends_to_the_given_buffer() {
        let buffer = encode_payload(&Message::Code(7), vec![0xaa, 0xbb]).unwrap();
        assert_eq!(buffer, [0xaa, 0xbb, 4, 14]);
    }

    #[test]
    fn malformed_payloads_are_rejected() {
        for payload in [&[][..], &[255][..], &[4][..], &[1, 3, 0][..]] {
            let error = decode_payload(payload).unwrap_err();
            assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{payload:?}");
        }
    }
}