synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-wire / src / transport.rs
| 1 | //! Stream transports for wire frames. |
| 2 | //! |
| 3 | //! Any reliable, ordered byte stream works (`UnixStream`, `TcpStream`, the shared-memory |
| 4 | //! [`crate::ring::RingStream`], an in-memory pipe). |
| 5 | //! The reader takes the 16-byte header first, checks the declared body length against its |
| 6 | //! cap, and only then allocates and reads exactly that many bytes, so a hostile peer cannot |
| 7 | //! make it allocate more than `max_frame_body` or consume bytes of the next frame. |
| 8 | //! Outgoing frames are queued and written with one `write_all` per [`FrameConn::flush`]. |
| 9 | |
| 10 | use crate::frame::{ |
| 11 | decode_body, decode_header, encode_frame_within, Frame, WireLimits, WireRefusal, |
| 12 | FRAME_HEADER_LEN, |
| 13 | }; |
| 14 | use std::io::{BufReader, ErrorKind, Read, Write}; |
| 15 | use synapse_core::{RefusalCode, SynapseError, SynapseResult}; |
| 16 | |
| 17 | /// An I/O error, except that a shared-memory ring refusal carried inside one keeps its own |
| 18 | /// code (`WireRingViolation`). |
| 19 | fn io(e: std::io::Error) -> SynapseError { |
| 20 | if let Some(r) = e |
| 21 | .get_ref() |
| 22 | .and_then(|inner| inner.downcast_ref::<crate::ring::RingRefusal>()) |
| 23 | { |
| 24 | return r.clone().into_error(); |
| 25 | } |
| 26 | SynapseError::new(RefusalCode::IoFailure, format!("wire transport: {e}")) |
| 27 | } |
| 28 | |
| 29 | /// Read one frame. `Ok(None)` is a clean end of stream at a frame boundary; an end of stream |
| 30 | /// inside a frame is `WireFrameMalformed` (truncated). |
| 31 | pub fn read_frame<R: Read>(r: &mut R, limits: &WireLimits) -> SynapseResult<Option<Frame>> { |
| 32 | let mut header = [0u8; FRAME_HEADER_LEN]; |
| 33 | let mut got = 0; |
| 34 | while got < FRAME_HEADER_LEN { |
| 35 | match r.read(&mut header[got..]) { |
| 36 | Ok(0) if got == 0 => return Ok(None), |
| 37 | Ok(0) => { |
| 38 | return Err(WireRefusal::Truncated { |
| 39 | at: got, |
| 40 | need: FRAME_HEADER_LEN - got, |
| 41 | } |
| 42 | .into_error()) |
| 43 | } |
| 44 | Ok(n) => got += n, |
| 45 | Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 46 | Err(e) => return Err(io(e)), |
| 47 | } |
| 48 | } |
| 49 | let h = decode_header(&header, limits).map_err(WireRefusal::into_error)?; |
| 50 | // Allocation is bounded by the cap checked in `decode_header`. |
| 51 | let mut body = vec![0u8; h.body_len as usize]; |
| 52 | let mut got = 0; |
| 53 | while got < body.len() { |
| 54 | match r.read(&mut body[got..]) { |
| 55 | Ok(0) => { |
| 56 | return Err(WireRefusal::Truncated { |
| 57 | at: FRAME_HEADER_LEN + got, |
| 58 | need: body.len() - got, |
| 59 | } |
| 60 | .into_error()) |
| 61 | } |
| 62 | Ok(n) => got += n, |
| 63 | Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 64 | Err(e) => return Err(io(e)), |
| 65 | } |
| 66 | } |
| 67 | decode_body(&h, &body, limits) |
| 68 | .map(Some) |
| 69 | .map_err(WireRefusal::into_error) |
| 70 | } |
| 71 | |
| 72 | /// A framed connection over one bidirectional stream, counting bytes in each direction. |
| 73 | pub struct FrameConn<S: Read + Write> { |
| 74 | stream: BufReader<S>, |
| 75 | out: Vec<u8>, |
| 76 | /// Limits applied to frames this side reads. |
| 77 | pub read_limits: WireLimits, |
| 78 | /// Limits the peer announced for frames it reads (applied when encoding). |
| 79 | pub peer_limits: WireLimits, |
| 80 | pub bytes_sent: u64, |
| 81 | pub bytes_received: u64, |
| 82 | pub frames_sent: u64, |
| 83 | pub frames_received: u64, |
| 84 | } |
| 85 | |
| 86 | impl<S: Read + Write> FrameConn<S> { |
| 87 | pub fn new(stream: S, read_limits: WireLimits) -> Self { |
| 88 | Self { |
| 89 | stream: BufReader::with_capacity(64 * 1024, stream), |
| 90 | out: Vec::with_capacity(64 * 1024), |
| 91 | read_limits, |
| 92 | peer_limits: read_limits, |
| 93 | bytes_sent: 0, |
| 94 | bytes_received: 0, |
| 95 | frames_sent: 0, |
| 96 | frames_received: 0, |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | /// Queue one frame for the next [`Self::flush`]. Refused (and nothing queued) if it |
| 101 | /// exceeds the peer's announced `max_frame_body`. |
| 102 | pub fn queue(&mut self, frame: &Frame) -> SynapseResult<()> { |
| 103 | let bytes = encode_frame_within(frame, &self.peer_limits)?; |
| 104 | self.out.extend_from_slice(&bytes); |
| 105 | self.frames_sent += 1; |
| 106 | Ok(()) |
| 107 | } |
| 108 | |
| 109 | /// Write every queued frame. |
| 110 | pub fn flush(&mut self) -> SynapseResult<()> { |
| 111 | if self.out.is_empty() { |
| 112 | return Ok(()); |
| 113 | } |
| 114 | let s = self.stream.get_mut(); |
| 115 | s.write_all(&self.out).map_err(io)?; |
| 116 | s.flush().map_err(io)?; |
| 117 | self.bytes_sent += self.out.len() as u64; |
| 118 | self.out.clear(); |
| 119 | Ok(()) |
| 120 | } |
| 121 | |
| 122 | /// Queue and flush one frame. |
| 123 | pub fn send(&mut self, frame: &Frame) -> SynapseResult<()> { |
| 124 | self.queue(frame)?; |
| 125 | self.flush() |
| 126 | } |
| 127 | |
| 128 | /// Read the next frame (`None` at a clean end of stream). |
| 129 | pub fn recv(&mut self) -> SynapseResult<Option<Frame>> { |
| 130 | let mut counted = CountingRead { |
| 131 | inner: &mut self.stream, |
| 132 | n: 0, |
| 133 | }; |
| 134 | let frame = read_frame(&mut counted, &self.read_limits); |
| 135 | self.bytes_received += counted.n; |
| 136 | if let Ok(Some(_)) = &frame { |
| 137 | self.frames_received += 1; |
| 138 | } |
| 139 | frame |
| 140 | } |
| 141 | |
| 142 | pub fn get_ref(&self) -> &S { |
| 143 | self.stream.get_ref() |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | struct CountingRead<'a, R: Read> { |
| 148 | inner: &'a mut R, |
| 149 | n: u64, |
| 150 | } |
| 151 | |
| 152 | impl<R: Read> Read for CountingRead<'_, R> { |
| 153 | fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> { |
| 154 | let n = self.inner.read(buf)?; |
| 155 | self.n += n as u64; |
| 156 | Ok(n) |
| 157 | } |
| 158 | } |