| 1 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 2 |
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 3 |
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 4 |
// option. This file may not be copied, modified, or distributed |
| 5 |
// except according to those terms. |
| 6 |
|
| 7 |
#![allow( |
| 8 |
clippy::module_name_repetitions, |
| 9 |
reason = "<https://github.com/mozilla/neqo/issues/2284#issuecomment-2782711813>" |
| 10 |
)] |
| 11 |
use std::{cmp::min, fmt::Debug}; |
| 12 |
|
| 13 |
use neqo_common::{ |
| 14 |
hex_with_len, qtrace, Decoder, IncrementalDecoderBuffer, IncrementalDecoderIgnore, |
| 15 |
IncrementalDecoderUint, |
| 16 |
}; |
| 17 |
use neqo_transport::{Connection, StreamId}; |
| 18 |
|
| 19 |
use super::hframe::HFrameType; |
| 20 |
use crate::{Error, RecvStream, Res}; |
| 21 |
|
| 22 |
const MAX_READ_SIZE: usize = 2048; // Given a practical MTU of 1500 bytes, this seems reasonable. |
| 23 |
|
| 24 |
pub trait FrameDecoder<T> { |
| 25 |
fn is_known_type(frame_type: HFrameType) -> bool; |
| 26 |
|
| 27 |
/// # Errors |
| 28 |
/// |
| 29 |
/// Returns `HttpFrameUnexpected` if frames is not allowed, i.e. is a `H3_RESERVED_FRAME_TYPES`. |
| 30 |
fn frame_type_allowed(_frame_type: HFrameType) -> Res<()> { |
| 31 |
Ok(()) |
| 32 |
} |
| 33 |
|
| 34 |
/// # Errors |
| 35 |
/// |
| 36 |
/// If a frame cannot be properly decoded. |
| 37 |
fn decode(frame_type: HFrameType, frame_len: u64, data: Option<&[u8]>) -> Res<Option<T>>; |
| 38 |
} |
| 39 |
|
| 40 |
pub trait StreamReader { |
| 41 |
/// # Errors |
| 42 |
/// |
| 43 |
/// An error may happen while reading a stream, e.g. early close, protocol error, etc. |
| 44 |
/// Return an error if the stream was closed on the transport layer, but that information is not |
| 45 |
/// yet consumed on the http/3 layer. |
| 46 |
fn read_data(&mut self, buf: &mut [u8]) -> Res<(usize, bool)>; |
| 47 |
} |
| 48 |
|
| 49 |
pub struct StreamReaderConnectionWrapper<'a> { |
| 50 |
conn: &'a mut Connection, |
| 51 |
stream_id: StreamId, |
| 52 |
} |
| 53 |
|
| 54 |
impl<'a> StreamReaderConnectionWrapper<'a> { |
| 55 |
pub fn new(conn: &'a mut Connection, stream_id: StreamId) -> Self { |
| 56 |
Self { conn, stream_id } |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
impl StreamReader for StreamReaderConnectionWrapper<'_> { |
| 61 |
/// # Errors |
| 62 |
/// |
| 63 |
/// An error may happen while reading a stream, e.g. early close, protocol error, etc. |
| 64 |
fn read_data(&mut self, buf: &mut [u8]) -> Res<(usize, bool)> { |
| 65 |
let res = self.conn.stream_recv(self.stream_id, buf)?; |
| 66 |
Ok(res) |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
pub struct StreamReaderRecvStreamWrapper<'a> { |
| 71 |
recv_stream: &'a mut Box<dyn RecvStream>, |
| 72 |
conn: &'a mut Connection, |
| 73 |
} |
| 74 |
|
| 75 |
impl<'a> StreamReaderRecvStreamWrapper<'a> { |
| 76 |
pub fn new(conn: &'a mut Connection, recv_stream: &'a mut Box<dyn RecvStream>) -> Self { |
| 77 |
Self { recv_stream, conn } |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
impl StreamReader for StreamReaderRecvStreamWrapper<'_> { |
| 82 |
/// # Errors |
| 83 |
/// |
| 84 |
/// An error may happen while reading a stream, e.g. early close, protocol error, etc. |
| 85 |
fn read_data(&mut self, buf: &mut [u8]) -> Res<(usize, bool)> { |
| 86 |
self.recv_stream.read_data(self.conn, buf) |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
#[derive(Clone, Debug)] |
| 91 |
enum FrameReaderState { |
| 92 |
GetType { decoder: IncrementalDecoderUint }, |
| 93 |
GetLength { decoder: IncrementalDecoderUint }, |
| 94 |
GetData { decoder: IncrementalDecoderBuffer }, |
| 95 |
UnknownFrameDischargeData { decoder: IncrementalDecoderIgnore }, |
| 96 |
} |
| 97 |
|
| 98 |
#[derive(Debug)] |
| 99 |
pub struct FrameReader { |
| 100 |
state: FrameReaderState, |
| 101 |
frame_type: HFrameType, |
| 102 |
frame_len: u64, |
| 103 |
buffer: [u8; MAX_READ_SIZE], |
| 104 |
} |
| 105 |
|
| 106 |
impl Default for FrameReader { |
| 107 |
fn default() -> Self { |
| 108 |
Self::new() |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
impl FrameReader { |
| 113 |
#[must_use] |
| 114 |
pub fn new() -> Self { |
| 115 |
Self { |
| 116 |
state: FrameReaderState::GetType { |
| 117 |
decoder: IncrementalDecoderUint::default(), |
| 118 |
}, |
| 119 |
frame_type: HFrameType(u64::MAX), |
| 120 |
frame_len: 0, |
| 121 |
buffer: [0; MAX_READ_SIZE], |
| 122 |
} |
| 123 |
} |
| 124 |
|
| 125 |
#[must_use] |
| 126 |
pub fn new_with_type(frame_type: HFrameType) -> Self { |
| 127 |
Self { |
| 128 |
state: FrameReaderState::GetLength { |
| 129 |
decoder: IncrementalDecoderUint::default(), |
| 130 |
}, |
| 131 |
frame_type, |
| 132 |
frame_len: 0, |
| 133 |
buffer: [0; MAX_READ_SIZE], |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
fn reset(&mut self) { |
| 138 |
self.state = FrameReaderState::GetType { |
| 139 |
decoder: IncrementalDecoderUint::default(), |
| 140 |
}; |
| 141 |
} |
| 142 |
|
| 143 |
fn min_remaining(&self) -> usize { |
| 144 |
match &self.state { |
| 145 |
FrameReaderState::GetType { decoder } | FrameReaderState::GetLength { decoder } => { |
| 146 |
decoder.min_remaining() |
| 147 |
} |
| 148 |
FrameReaderState::GetData { decoder } => decoder.min_remaining(), |
| 149 |
FrameReaderState::UnknownFrameDischargeData { decoder } => decoder.min_remaining(), |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
const fn decoding_in_progress(&self) -> bool { |
| 154 |
if let FrameReaderState::GetType { decoder } = &self.state { |
| 155 |
decoder.decoding_in_progress() |
| 156 |
} else { |
| 157 |
true |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
/// Returns true if QUIC stream was closed. |
| 162 |
/// |
| 163 |
/// # Errors |
| 164 |
/// |
| 165 |
/// May return `HttpFrame` if a frame cannot be decoded. |
| 166 |
/// and `TransportStreamDoesNotExist` if `stream_recv` fails. |
| 167 |
pub fn receive<T: FrameDecoder<T>>( |
| 168 |
&mut self, |
| 169 |
stream_reader: &mut dyn StreamReader, |
| 170 |
) -> Res<(Option<T>, bool)> { |
| 171 |
loop { |
| 172 |
let to_read = min(self.min_remaining(), self.buffer.len()); |
| 173 |
let (output, read, fin) = match stream_reader |
| 174 |
.read_data(&mut self.buffer[..to_read]) |
| 175 |
.map_err(|e| Error::map_stream_recv_errors(&e))? |
| 176 |
{ |
| 177 |
(0, f) => (None, false, f), |
| 178 |
(amount, f) => { |
| 179 |
qtrace!("FrameReader::receive: reading {amount} byte, fin={f}"); |
| 180 |
(self.consume::<T>(amount)?, true, f) |
| 181 |
} |
| 182 |
}; |
| 183 |
|
| 184 |
if output.is_some() { |
| 185 |
break Ok((output, fin)); |
| 186 |
} |
| 187 |
|
| 188 |
if fin { |
| 189 |
if self.decoding_in_progress() { |
| 190 |
break Err(Error::HttpFrame); |
| 191 |
} |
| 192 |
break Ok((None, fin)); |
| 193 |
} |
| 194 |
|
| 195 |
if !read { |
| 196 |
// There was no new data, exit the loop. |
| 197 |
break Ok((None, false)); |
| 198 |
} |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
/// # Errors |
| 203 |
/// |
| 204 |
/// May return `HttpFrame` if a frame cannot be decoded. |
| 205 |
fn consume<T: FrameDecoder<T>>(&mut self, amount: usize) -> Res<Option<T>> { |
| 206 |
let mut input = Decoder::from(&self.buffer[..amount]); |
| 207 |
match &mut self.state { |
| 208 |
FrameReaderState::GetType { decoder } => { |
| 209 |
if let Some(v) = decoder.consume(&mut input) { |
| 210 |
qtrace!("FrameReader::receive: read frame type {v}"); |
| 211 |
self.frame_type_decoded::<T>(HFrameType(v))?; |
| 212 |
} |
| 213 |
} |
| 214 |
FrameReaderState::GetLength { decoder } => { |
| 215 |
if let Some(len) = decoder.consume(&mut input) { |
| 216 |
qtrace!( |
| 217 |
"FrameReader::receive: frame type {:?} length {len}", |
| 218 |
self.frame_type |
| 219 |
); |
| 220 |
return self.frame_length_decoded::<T>(len); |
| 221 |
} |
| 222 |
} |
| 223 |
FrameReaderState::GetData { decoder } => { |
| 224 |
if let Some(data) = decoder.consume(&mut input) { |
| 225 |
qtrace!( |
| 226 |
"received frame {:?}: {}", |
| 227 |
self.frame_type, |
| 228 |
hex_with_len(&data[..]) |
| 229 |
); |
| 230 |
return self.frame_data_decoded::<T>(&data); |
| 231 |
} |
| 232 |
} |
| 233 |
FrameReaderState::UnknownFrameDischargeData { decoder } => { |
| 234 |
if decoder.consume(&mut input) { |
| 235 |
self.reset(); |
| 236 |
} |
| 237 |
} |
| 238 |
} |
| 239 |
Ok(None) |
| 240 |
} |
| 241 |
fn frame_type_decoded<T: FrameDecoder<T>>(&mut self, frame_type: HFrameType) -> Res<()> { |
| 242 |
T::frame_type_allowed(frame_type)?; |
| 243 |
self.frame_type = frame_type; |
| 244 |
self.state = FrameReaderState::GetLength { |
| 245 |
decoder: IncrementalDecoderUint::default(), |
| 246 |
}; |
| 247 |
Ok(()) |
| 248 |
} |
| 249 |
|
| 250 |
fn frame_length_decoded<T: FrameDecoder<T>>(&mut self, len: u64) -> Res<Option<T>> { |
| 251 |
self.frame_len = len; |
| 252 |
if let Some(f) = T::decode( |
| 253 |
self.frame_type, |
| 254 |
self.frame_len, |
| 255 |
if len > 0 { None } else { Some(&[]) }, |
| 256 |
)? { |
| 257 |
self.reset(); |
| 258 |
return Ok(Some(f)); |
| 259 |
} else if T::is_known_type(self.frame_type) { |
| 260 |
self.state = FrameReaderState::GetData { |
| 261 |
decoder: IncrementalDecoderBuffer::new( |
| 262 |
usize::try_from(len).or(Err(Error::HttpFrame))?, |
| 263 |
), |
| 264 |
}; |
| 265 |
} else if self.frame_len == 0 { |
| 266 |
self.reset(); |
| 267 |
} else { |
| 268 |
self.state = FrameReaderState::UnknownFrameDischargeData { |
| 269 |
decoder: IncrementalDecoderIgnore::new( |
| 270 |
usize::try_from(len).or(Err(Error::HttpFrame))?, |
| 271 |
), |
| 272 |
}; |
| 273 |
} |
| 274 |
Ok(None) |
| 275 |
} |
| 276 |
|
| 277 |
fn frame_data_decoded<T: FrameDecoder<T>>(&mut self, data: &[u8]) -> Res<Option<T>> { |
| 278 |
let res = T::decode(self.frame_type, self.frame_len, Some(data))?; |
| 279 |
self.reset(); |
| 280 |
Ok(res) |
| 281 |
} |
| 282 |
} |