lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

wire.rs (8214B)


      1 //! Fixed-memory admission of decrypted ingress before WebSocket decoding.
      2 
      3 use radroots_transport::host::websocket::Admission;
      4 use std::io;
      5 use std::pin::Pin;
      6 use std::sync::Arc;
      7 use std::task::{Context, Poll};
      8 use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
      9 
     10 const MAX_UPGRADE_BYTES: usize = 16 * 1024;
     11 const READ_CHUNK_BYTES: usize = 4096;
     12 
     13 /// Counts HTTP response and frame overhead conservatively in the same raw-byte
     14 /// allowance as payloads. No message or payload is retained by this layer.
     15 pub(crate) struct MeteredIo<S> {
     16     inner: S,
     17     ingress: Arc<dyn Admission>,
     18     parser: WireParser,
     19     failed: bool,
     20 }
     21 
     22 impl<S> MeteredIo<S> {
     23     pub(crate) fn new(inner: S, ingress: Arc<dyn Admission>, max_message_bytes: usize) -> Self {
     24         Self {
     25             inner,
     26             ingress,
     27             parser: WireParser::new(max_message_bytes),
     28             failed: false,
     29         }
     30     }
     31 
     32     fn admitted(&self, context: &Context<'_>) -> io::Result<()> {
     33         if self.failed || !self.ingress.admitted_read(context) {
     34             Err(denied())
     35         } else {
     36             Ok(())
     37         }
     38     }
     39 }
     40 
     41 impl<S: AsyncRead + Unpin> AsyncRead for MeteredIo<S> {
     42     fn poll_read(
     43         self: Pin<&mut Self>,
     44         context: &mut Context<'_>,
     45         output: &mut ReadBuf<'_>,
     46     ) -> Poll<io::Result<()>> {
     47         let this = self.get_mut();
     48         if let Err(error) = this.admitted(context) {
     49             return Poll::Ready(Err(error));
     50         }
     51         if output.remaining() == 0 {
     52             return Poll::Ready(Ok(()));
     53         }
     54         let mut scratch = [0; READ_CHUNK_BYTES];
     55         let length = output.remaining().min(scratch.len());
     56         let mut input = ReadBuf::new(&mut scratch[..length]);
     57         match Pin::new(&mut this.inner).poll_read(context, &mut input) {
     58             Poll::Pending => Poll::Pending,
     59             Poll::Ready(Err(error)) => {
     60                 this.failed = true;
     61                 Poll::Ready(Err(error))
     62             }
     63             Poll::Ready(Ok(())) => {
     64                 let bytes = input.filled();
     65                 let result = if !this.ingress.charge(bytes.len(), 0, 0) {
     66                     Err(denied())
     67                 } else if bytes.is_empty() {
     68                     this.parser.eof()
     69                 } else {
     70                     this.parser
     71                         .consume(bytes, |data| this.ingress.charge(0, 1, usize::from(data)))
     72                 };
     73                 if let Err(error) = result {
     74                     this.failed = true;
     75                     return Poll::Ready(Err(error));
     76                 }
     77                 // Cancellation may race a ready read. Revalidate before any
     78                 // plaintext becomes visible to the WebSocket implementation.
     79                 if let Err(error) = this.admitted(context) {
     80                     this.failed = true;
     81                     return Poll::Ready(Err(error));
     82                 }
     83                 output.put_slice(bytes);
     84                 Poll::Ready(Ok(()))
     85             }
     86         }
     87     }
     88 }
     89 
     90 impl<S: AsyncWrite + Unpin> AsyncWrite for MeteredIo<S> {
     91     fn poll_write(
     92         self: Pin<&mut Self>,
     93         context: &mut Context<'_>,
     94         bytes: &[u8],
     95     ) -> Poll<io::Result<usize>> {
     96         let this = self.get_mut();
     97         if this.failed || !this.ingress.admitted_write(context) {
     98             return Poll::Ready(Err(denied()));
     99         }
    100         Pin::new(&mut this.inner).poll_write(context, bytes)
    101     }
    102 
    103     fn poll_flush(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
    104         let this = self.get_mut();
    105         if this.failed || !this.ingress.admitted_write(context) {
    106             return Poll::Ready(Err(denied()));
    107         }
    108         Pin::new(&mut this.inner).poll_flush(context)
    109     }
    110 
    111     fn poll_shutdown(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<io::Result<()>> {
    112         // Closing the underlying transport remains possible after revocation.
    113         Pin::new(&mut self.get_mut().inner).poll_shutdown(context)
    114     }
    115 }
    116 
    117 #[derive(Default)]
    118 struct WireParser {
    119     max_message_bytes: usize,
    120     upgrade_bytes: usize,
    121     delimiter: u32,
    122     upgraded: bool,
    123     header: [u8; 10],
    124     header_len: usize,
    125     header_needed: usize,
    126     payload_remaining: usize,
    127 }
    128 
    129 impl WireParser {
    130     fn new(max_message_bytes: usize) -> Self {
    131         Self {
    132             max_message_bytes,
    133             ..Self::default()
    134         }
    135     }
    136 
    137     fn consume(
    138         &mut self,
    139         mut bytes: &[u8],
    140         mut admit_frame: impl FnMut(bool) -> bool,
    141     ) -> io::Result<()> {
    142         while let Some((&byte, rest)) = bytes.split_first() {
    143             if !self.upgraded {
    144                 self.upgrade_bytes += 1;
    145                 if self.upgrade_bytes > MAX_UPGRADE_BYTES {
    146                     return Err(invalid("WebSocket upgrade response exceeds its limit"));
    147                 }
    148                 self.delimiter = (self.delimiter << 8) | u32::from(byte);
    149                 self.upgraded = self.delimiter == u32::from_be_bytes(*b"\r\n\r\n");
    150                 bytes = rest;
    151             } else if self.payload_remaining != 0 {
    152                 let consumed = self.payload_remaining.min(bytes.len());
    153                 self.payload_remaining -= consumed;
    154                 bytes = &bytes[consumed..];
    155             } else {
    156                 if self.header_len == 0 {
    157                     let opcode = byte & 0x0f;
    158                     if !admit_frame(matches!(opcode, 1 | 2)) {
    159                         return Err(denied());
    160                     }
    161                     if byte & 0x70 != 0 || !matches!(opcode, 0 | 1 | 2 | 8 | 9 | 10) {
    162                         return Err(invalid("unsupported WebSocket frame flags or opcode"));
    163                     }
    164                     if opcode >= 8 && byte & 0x80 == 0 {
    165                         return Err(invalid("fragmented WebSocket control frame"));
    166                     }
    167                     self.header_needed = 2;
    168                 }
    169                 self.header[self.header_len] = byte;
    170                 self.header_len += 1;
    171                 bytes = rest;
    172                 if self.header_len == 2 {
    173                     if byte & 0x80 != 0 {
    174                         return Err(invalid("masked server WebSocket frame"));
    175                     }
    176                     self.header_needed = match byte {
    177                         126 => 4,
    178                         127 => 10,
    179                         _ => 2,
    180                     };
    181                 }
    182                 if self.header_len == self.header_needed {
    183                     self.payload_remaining = self.payload_length()?;
    184                     self.header_len = 0;
    185                 }
    186             }
    187         }
    188         Ok(())
    189     }
    190 
    191     fn payload_length(&self) -> io::Result<usize> {
    192         let (length, minimum) = match self.header[1] {
    193             126 => (
    194                 u64::from(u16::from_be_bytes([self.header[2], self.header[3]])),
    195                 126,
    196             ),
    197             127 => {
    198                 let mut extended = [0; 8];
    199                 extended.copy_from_slice(&self.header[2..10]);
    200                 (u64::from_be_bytes(extended), 65536)
    201             }
    202             length => (u64::from(length), 0),
    203         };
    204         if length < minimum || length > self.max_message_bytes as u64 {
    205             return Err(invalid(
    206                 "WebSocket frame length is noncanonical or exceeds its limit",
    207             ));
    208         }
    209         if self.header[0] & 0x0f >= 8 && length > 125 {
    210             return Err(invalid("WebSocket control frame exceeds its limit"));
    211         }
    212         usize::try_from(length).map_err(|_| invalid("WebSocket frame length cannot be represented"))
    213     }
    214 
    215     fn eof(&self) -> io::Result<()> {
    216         if !self.upgraded || self.header_len != 0 || self.payload_remaining != 0 {
    217             Err(io::Error::new(
    218                 io::ErrorKind::UnexpectedEof,
    219                 "truncated WebSocket ingress",
    220             ))
    221         } else {
    222             Ok(())
    223         }
    224     }
    225 }
    226 
    227 fn invalid(message: &'static str) -> io::Error {
    228     io::Error::new(io::ErrorKind::InvalidData, message)
    229 }
    230 
    231 fn denied() -> io::Error {
    232     io::Error::new(
    233         io::ErrorKind::ConnectionAborted,
    234         "relay ingress budget or generation revoked",
    235     )
    236 }
    237 
    238 #[cfg(test)]
    239 #[path = "wire_tests.rs"]
    240 mod tests;