crates/edge/proto/src/frame.rs 11.3 KiB 390 lines Raw
1 //! The frame: an 8-byte header and one payload.2 //!3 //! ```text4 //!  0                   4        6        7        85 //!  +--------------------+--------+--------+--------+6 //!  | length (u32 LE)    | stream | type   | flags  |7 //!  +--------------------+--------+--------+--------+8 //! ```9 //!10 //! The length is the payload size and never includes the header. Its value is11 //! at most [`MAX_PAYLOAD`], so the largest frame is 16 MiB. That ceiling is the12 //! wire format and not a setting. A larger object travels as a descriptor.13 14 use std::fmt;15 use std::io::{self, Read, Write};16 17 /// The size of the header in bytes.18 pub const HEADER_LEN: usize = 8;19 20 /// The largest payload that one frame can carry.21 pub const MAX_PAYLOAD: usize = 0x00FF_FFFF;22 23 /// A frame type.24 ///25 /// Wire 2 assigns `0x01..=0x15` and `0x20..=0x27`. `0x40..=0x7f` is the26 /// extension range: a peer reads such a frame and ignores it. Every other value27 /// is a frame error.28 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]29 pub enum Kind {30     Hello,31     Welcome,32     Catalogue,33     Grant,34     Ready,35     Window,36     Ping,37     Pong,38     Bye,39     Fatal,40     Open,41     Accept,42     Event,43     Done,44     Reject,45     Cancel,46     CacheLookup,47     CacheLookupRes,48     CacheRelease,49     CacheReserve,50     CacheGrant,51     CacheCommit,52     CacheFlush,53     CacheFlushed,54     /// A type in `0x40..=0x7f`. The frame is read and then dropped.55     Extension(u8),56 }57 58 impl Kind {59     /// Every assigned kind, in wire order.60     pub const ALL: [Kind; 24] = [61         Kind::Hello,62         Kind::Welcome,63         Kind::Catalogue,64         Kind::Grant,65         Kind::Ready,66         Kind::Window,67         Kind::Ping,68         Kind::Pong,69         Kind::Bye,70         Kind::Fatal,71         Kind::Open,72         Kind::Accept,73         Kind::Event,74         Kind::Done,75         Kind::Reject,76         Kind::Cancel,77         Kind::CacheLookup,78         Kind::CacheLookupRes,79         Kind::CacheRelease,80         Kind::CacheReserve,81         Kind::CacheGrant,82         Kind::CacheCommit,83         Kind::CacheFlush,84         Kind::CacheFlushed,85     ];86 87     /// The byte that this kind carries on the wire.88     pub const fn as_u8(self) -> u8 {89         match self {90             Kind::Hello => 0x01,91             Kind::Welcome => 0x02,92             Kind::Catalogue => 0x03,93             Kind::Grant => 0x04,94             Kind::Ready => 0x05,95             Kind::Window => 0x06,96             Kind::Ping => 0x07,97             Kind::Pong => 0x08,98             Kind::Bye => 0x09,99             Kind::Fatal => 0x0a,100             Kind::Open => 0x10,101             Kind::Accept => 0x11,102             Kind::Event => 0x12,103             Kind::Done => 0x13,104             Kind::Reject => 0x14,105             Kind::Cancel => 0x15,106             Kind::CacheLookup => 0x20,107             Kind::CacheLookupRes => 0x21,108             Kind::CacheRelease => 0x22,109             Kind::CacheReserve => 0x23,110             Kind::CacheGrant => 0x24,111             Kind::CacheCommit => 0x25,112             Kind::CacheFlush => 0x26,113             Kind::CacheFlushed => 0x27,114             Kind::Extension(b) => b,115         }116     }117 118     /// Reads a byte as a kind.119     ///120     /// A value in the extension range gives `Ok(Kind::Extension(b))`. A value121     /// that wire 1 does not assign gives `Err(FrameError::Unknown(b))`.122     pub fn try_from_u8(byte: u8) -> Result<Kind, FrameError> {123         match byte {124             0x01 => Ok(Kind::Hello),125             0x02 => Ok(Kind::Welcome),126             0x03 => Ok(Kind::Catalogue),127             0x04 => Ok(Kind::Grant),128             0x05 => Ok(Kind::Ready),129             0x06 => Ok(Kind::Window),130             0x07 => Ok(Kind::Ping),131             0x08 => Ok(Kind::Pong),132             0x09 => Ok(Kind::Bye),133             0x0a => Ok(Kind::Fatal),134             0x10 => Ok(Kind::Open),135             0x11 => Ok(Kind::Accept),136             0x12 => Ok(Kind::Event),137             0x13 => Ok(Kind::Done),138             0x14 => Ok(Kind::Reject),139             0x15 => Ok(Kind::Cancel),140             0x20 => Ok(Kind::CacheLookup),141             0x21 => Ok(Kind::CacheLookupRes),142             0x22 => Ok(Kind::CacheRelease),143             0x23 => Ok(Kind::CacheReserve),144             0x24 => Ok(Kind::CacheGrant),145             0x25 => Ok(Kind::CacheCommit),146             0x26 => Ok(Kind::CacheFlush),147             0x27 => Ok(Kind::CacheFlushed),148             0x40..=0x7f => Ok(Kind::Extension(byte)),149             other => Err(FrameError::Unknown(other)),150         }151     }152 153     /// True for a kind in the extension range.154     pub const fn is_extension(self) -> bool {155         matches!(self, Kind::Extension(_))156     }157 158     /// True for a Wire 2 cache frame.159     pub const fn is_cache(self) -> bool {160         matches!(161             self,162             Kind::CacheLookup163                 | Kind::CacheLookupRes164                 | Kind::CacheRelease165                 | Kind::CacheReserve166                 | Kind::CacheGrant167                 | Kind::CacheCommit168                 | Kind::CacheFlush169                 | Kind::CacheFlushed170         )171     }172 }173 174 /// The 8 bytes at the front of every frame.175 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]176 pub struct Header {177     /// Payload bytes. Never includes the header. At most [`MAX_PAYLOAD`].178     pub length: u32,179     /// `0` is a session frame. Any other value is a job stream.180     pub stream: u16,181     pub kind: Kind,182     /// Must be `0` in wire 2.183     pub flags: u8,184 }185 186 impl Header {187     /// A header with no flags.188     pub const fn new(kind: Kind, stream: u16, length: u32) -> Header {189         Header {190             length,191             stream,192             kind,193             flags: 0,194         }195     }196 197     /// The eight bytes of this header.198     pub fn encode(self) -> [u8; HEADER_LEN] {199         let length = self.length.to_le_bytes();200         let stream = self.stream.to_le_bytes();201         [202             length[0],203             length[1],204             length[2],205             length[3],206             stream[0],207             stream[1],208             self.kind.as_u8(),209             self.flags,210         ]211     }212 213     /// Reads a header and checks it against wire 2.214     pub fn decode(bytes: [u8; HEADER_LEN]) -> Result<Header, FrameError> {215         let length = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);216         let stream = u16::from_le_bytes([bytes[4], bytes[5]]);217         let kind = Kind::try_from_u8(bytes[6])?;218         if bytes[7] != 0 {219             return Err(FrameError::Flags(bytes[7]));220         }221         if length as usize > MAX_PAYLOAD {222             return Err(FrameError::Length(length));223         }224         Ok(Header {225             length,226             stream,227             kind,228             flags: 0,229         })230     }231 }232 233 /// A header that wire 2 does not allow.234 #[derive(Clone, PartialEq, Eq, Debug)]235 pub enum FrameError {236     /// The type byte is not assigned and is not in the extension range.237     Unknown(u8),238     /// The flags byte is not zero.239     Flags(u8),240     /// The length is larger than [`MAX_PAYLOAD`].241     Length(u32),242     /// The reader ended in the middle of a frame.243     Truncated { want: usize, got: usize },244     /// The header length and the payload length disagree.245     Mismatch { header: u32, payload: usize },246 }247 248 impl fmt::Display for FrameError {249     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {250         match self {251             FrameError::Unknown(b) => write!(f, "unassigned frame type {b:#04x}"),252             FrameError::Flags(b) => write!(f, "flags must be zero in wire 2, got {b:#04x}"),253             FrameError::Length(n) => {254                 write!(f, "payload length {n} is above the ceiling {MAX_PAYLOAD}")255             }256             FrameError::Truncated { want, got } => {257                 write!(f, "frame truncated: wanted {want} bytes, got {got}")258             }259             FrameError::Mismatch { header, payload } => write!(260                 f,261                 "header says {header} payload bytes, payload holds {payload}"262             ),263         }264     }265 }266 267 impl std::error::Error for FrameError {}268 269 /// A frame that could not be read or written.270 #[derive(Debug)]271 pub enum Error {272     Io(io::Error),273     Frame(FrameError),274     /// The payload is larger than [`MAX_PAYLOAD`].275     TooLarge(usize),276     /// The frame carried more descriptors than one message can hold.277     TooManyDescriptors(usize),278     /// The kernel truncated the ancillary data, so the descriptor set is unknown.279     TruncatedDescriptors,280 }281 282 impl fmt::Display for Error {283     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {284         match self {285             Error::Io(e) => write!(f, "io: {e}"),286             Error::Frame(e) => write!(f, "frame: {e}"),287             Error::TooLarge(n) => {288                 write!(f, "payload of {n} bytes is larger than {MAX_PAYLOAD}")289             }290             Error::TooManyDescriptors(n) => {291                 write!(f, "frame carried {n} descriptors, above the kernel limit")292             }293             Error::TruncatedDescriptors => {294                 write!(295                     f,296                     "ancillary data was truncated, so no descriptor set is complete"297                 )298             }299         }300     }301 }302 303 impl std::error::Error for Error {}304 305 impl From<io::Error> for Error {306     fn from(e: io::Error) -> Error {307         Error::Io(e)308     }309 }310 311 impl From<FrameError> for Error {312     fn from(e: FrameError) -> Error {313         Error::Frame(e)314     }315 }316 317 /// One frame: a header and its payload.318 #[derive(Clone, PartialEq, Eq, Debug)]319 pub struct Frame {320     pub header: Header,321     pub payload: Vec<u8>,322 }323 324 /// Fills `buf` from `reader`, stopping early only when the reader is at its325 /// end. Returns how many bytes were filled.326 fn fill<R: Read>(reader: &mut R, buf: &mut [u8]) -> io::Result<usize> {327     let mut got = 0;328     while got < buf.len() {329         match reader.read(&mut buf[got..]) {330             Ok(0) => break,331             Ok(n) => got += n,332             Err(e) if e.kind() == io::ErrorKind::Interrupted => {}333             Err(e) => return Err(e),334         }335     }336     Ok(got)337 }338 339 /// Reads one frame.340 ///341 /// Returns `Ok(None)` when the reader is at a clean frame boundary and has no342 /// more bytes. A reader that ends after the first byte of a header is an error,343 /// not a clean end.344 pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Frame>, Error> {345     let mut head = [0u8; HEADER_LEN];346     let got = fill(reader, &mut head)?;347     if got == 0 {348         return Ok(None);349     }350     if got < HEADER_LEN {351         return Err(Error::Frame(FrameError::Truncated {352             want: HEADER_LEN,353             got,354         }));355     }356 357     // The header is checked in full before any payload is allocated.358     let header = Header::decode(head)?;359 360     let mut payload = vec![0u8; header.length as usize];361     let got = fill(reader, &mut payload)?;362     if got < payload.len() {363         return Err(Error::Frame(FrameError::Truncated {364             want: payload.len(),365             got,366         }));367     }368 369     Ok(Some(Frame { header, payload }))370 }371 372 /// Writes one frame.373 ///374 /// The header length must equal the payload length. A payload above375 /// [`MAX_PAYLOAD`] is `Error::TooLarge` and nothing is written.376 pub fn write_frame<W: Write>(writer: &mut W, header: Header, payload: &[u8]) -> Result<(), Error> {377     if payload.len() > MAX_PAYLOAD {378         return Err(Error::TooLarge(payload.len()));379     }380     if usize::try_from(header.length) != Ok(payload.len()) {381         return Err(Error::Frame(FrameError::Mismatch {382             header: header.length,383             payload: payload.len(),384         }));385     }386 387     writer.write_all(&header.encode())?;388     writer.write_all(payload)?;389     Ok(())390 }