mod varint;
pub use varint::QuicVarInt;
use crate::{packet::Packet, parse::ParseError};
use bytes::Bytes;
use std::ops::Range;
pub const QUIC_VERSION_1: u32 = 1;
pub const QUIC_VERSION_2: u32 = 0x6b33_43cf;
pub const MAX_CONNECTION_ID_LEN: usize = 20;
pub const RETRY_INTEGRITY_TAG_LEN: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum QuicVersion {
V1,
V2,
}
impl QuicVersion {
pub const fn value(self) -> u32 {
match self {
Self::V1 => QUIC_VERSION_1,
Self::V2 => QUIC_VERSION_2,
}
}
pub const fn from_value(value: u32) -> Option<Self> {
match value {
QUIC_VERSION_1 => Some(Self::V1),
QUIC_VERSION_2 => Some(Self::V2),
_ => None,
}
}
pub(crate) fn packet_type(self, first: u8) -> QuicPacketType {
let bits = (first >> 4) & 3;
let v1_bits = match self {
Self::V1 => bits,
Self::V2 => (bits + 3) & 3,
};
match v1_bits {
0 => QuicPacketType::Initial,
1 => QuicPacketType::ZeroRtt,
2 => QuicPacketType::Handshake,
_ => QuicPacketType::Retry,
}
}
pub(crate) fn type_bits(self, kind: QuicPacketType) -> Option<u8> {
let bits = match kind {
QuicPacketType::Initial => 0,
QuicPacketType::ZeroRtt => 1,
QuicPacketType::Handshake => 2,
QuicPacketType::Retry => 3,
_ => return None,
};
Some(
match self {
Self::V1 => bits,
Self::V2 => (bits + 1) & 3,
} << 4,
)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum QuicPacketType {
Initial,
ZeroRtt,
Handshake,
Retry,
VersionNegotiation,
OneRtt,
UnknownVersion,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct QuicParseOptions {
pub short_header_dcid_len: Option<usize>,
pub allow_greased_fixed_bit: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Layout {
kind: QuicPacketType,
version: Option<u32>,
dcid: Range<usize>,
scid: Option<Range<usize>>,
token: Option<Range<usize>>,
tag: Option<Range<usize>>,
header_end: usize,
end: usize,
length: Option<u64>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuicPacketSlice<'a> {
data: &'a [u8],
layout: Layout,
}
impl<'a> QuicPacketSlice<'a> {
pub fn try_from_buf(data: &'a [u8]) -> Result<Self, ParseError> {
Self::try_from_buf_with_options(data, QuicParseOptions::default())
}
pub fn try_from_buf_with_options(
data: &'a [u8],
options: QuicParseOptions,
) -> Result<Self, ParseError> {
let layout = parse_layout(data, options)?;
Ok(Self {
data: &data[..layout.end],
layout,
})
}
pub fn packet(&self) -> &'a [u8] {
self.data
}
pub fn first_byte(&self) -> u8 {
self.data[0]
}
pub fn packet_type(&self) -> QuicPacketType {
self.layout.kind
}
pub fn version(&self) -> Option<u32> {
self.layout.version
}
pub fn destination_connection_id(&self) -> &'a [u8] {
&self.data[self.layout.dcid.clone()]
}
pub fn source_connection_id(&self) -> Option<&'a [u8]> {
self.layout.scid.clone().map(|r| &self.data[r])
}
pub fn token(&self) -> Option<&'a [u8]> {
self.layout.token.clone().map(|r| &self.data[r])
}
pub fn retry_integrity_tag(&self) -> Option<&'a [u8]> {
self.layout.tag.clone().map(|r| &self.data[r])
}
pub fn declared_length(&self) -> Option<u64> {
self.layout.length
}
pub fn header(&self) -> &'a [u8] {
&self.data[..self.layout.header_end]
}
pub fn payload(&self) -> &'a [u8] {
&self.data[self.layout.header_end..]
}
pub fn packet_number_offset(&self) -> Option<usize> {
matches!(
self.layout.kind,
QuicPacketType::Initial
| QuicPacketType::ZeroRtt
| QuicPacketType::Handshake
| QuicPacketType::OneRtt
)
.then_some(self.layout.header_end)
}
pub fn supported_versions(&self) -> Option<impl ExactSizeIterator<Item = u32> + 'a> {
(self.layout.kind == QuicPacketType::VersionNegotiation).then(|| {
self.payload()
.as_chunks::<4>()
.0
.iter()
.copied()
.map(u32::from_be_bytes)
})
}
pub fn to_owned(&self) -> QuicPacket {
QuicPacket {
data: Bytes::copy_from_slice(self.data),
layout: self.layout.clone(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QuicPacket {
data: Bytes,
layout: Layout,
}
impl QuicPacket {
pub fn try_from_buf(data: &[u8]) -> Result<Self, ParseError> {
Self::try_from_buf_with_options(data, QuicParseOptions::default())
}
pub fn try_from_buf_with_options(
data: &[u8],
options: QuicParseOptions,
) -> Result<Self, ParseError> {
Ok(QuicPacketSlice::try_from_buf_with_options(data, options)?.to_owned())
}
pub fn try_from_bytes(data: Bytes) -> Result<Self, ParseError> {
Self::try_from_bytes_with_options(data, QuicParseOptions::default())
}
pub fn try_from_bytes_with_options(
data: Bytes,
options: QuicParseOptions,
) -> Result<Self, ParseError> {
let layout = parse_layout(&data, options)?;
Ok(Self {
data: data.slice(..layout.end),
layout,
})
}
pub fn as_slice(&self) -> QuicPacketSlice<'_> {
QuicPacketSlice {
data: &self.data,
layout: self.layout.clone(),
}
}
}
impl Packet for QuicPacket {
type Header = Bytes;
fn try_from_buf(data: &[u8]) -> Result<Self, ParseError> {
Self::try_from_buf(data)
}
fn try_from_bytes(data: Bytes) -> Result<Self, ParseError> {
Self::try_from_bytes(data)
}
fn to_bytes(&self) -> Bytes {
self.data.clone()
}
fn header(&self) -> Bytes {
self.data.slice(..self.layout.header_end)
}
fn payload(&self) -> Bytes {
self.data.slice(self.layout.header_end..)
}
fn header_len(&self) -> usize {
self.layout.header_end
}
fn payload_len(&self) -> usize {
self.data.len() - self.layout.header_end
}
fn total_len(&self) -> usize {
self.data.len()
}
fn into_parts(self) -> (Bytes, Bytes) {
(self.header(), self.payload())
}
}
#[derive(Clone, Debug)]
pub struct QuicDatagram<'a> {
remaining: &'a [u8],
options: QuicParseOptions,
}
impl<'a> QuicDatagram<'a> {
pub fn new(payload: &'a [u8], options: QuicParseOptions) -> Self {
Self {
remaining: payload,
options,
}
}
}
impl<'a> Iterator for QuicDatagram<'a> {
type Item = Result<QuicPacketSlice<'a>, ParseError>;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining.is_empty() {
return None;
}
match QuicPacketSlice::try_from_buf_with_options(self.remaining, self.options) {
Ok(packet) => {
self.remaining = &self.remaining[packet.packet().len()..];
Some(Ok(packet))
}
Err(error) => {
self.remaining = &[];
Some(Err(error))
}
}
}
}
impl std::iter::FusedIterator for QuicDatagram<'_> {}
fn take(
data: &[u8],
cursor: &mut usize,
length: usize,
context: &'static str,
) -> Result<Range<usize>, ParseError> {
let end = cursor
.checked_add(length)
.ok_or(ParseError::InvalidLength {
context,
value: length,
})?;
if end > data.len() {
return Err(ParseError::Truncated {
context,
expected: end,
actual: data.len(),
});
}
let range = *cursor..end;
*cursor = end;
Ok(range)
}
fn read_varint(data: &[u8], cursor: &mut usize) -> Result<u64, ParseError> {
let (value, length) = QuicVarInt::decode(&data[*cursor..])?;
*cursor += length;
Ok(value.value())
}
fn size(value: u64, context: &'static str) -> Result<usize, ParseError> {
usize::try_from(value).map_err(|_| ParseError::InvalidLength {
context,
value: usize::MAX,
})
}
fn check_fixed(first: u8, options: QuicParseOptions) -> Result<(), ParseError> {
if first & 0x40 == 0 && !options.allow_greased_fixed_bit {
return Err(ParseError::Malformed {
context: "QUIC fixed bit",
});
}
Ok(())
}
fn parse_layout(data: &[u8], options: QuicParseOptions) -> Result<Layout, ParseError> {
let first = *data.first().ok_or(ParseError::BufferTooShort {
context: "QUIC packet",
minimum: 1,
actual: 0,
})?;
let mut cursor = 1;
if first & 0x80 == 0 {
check_fixed(first, options)?;
let length = options.short_header_dcid_len.ok_or(ParseError::Malformed {
context: "QUIC short header requires destination CID length",
})?;
if length > MAX_CONNECTION_ID_LEN {
return Err(ParseError::InvalidLength {
context: "QUIC destination CID",
value: length,
});
}
let dcid = take(data, &mut cursor, length, "QUIC destination CID")?;
let header_end = cursor;
take(data, &mut cursor, 1, "QUIC protected packet number")?;
return Ok(Layout {
kind: QuicPacketType::OneRtt,
version: None,
dcid,
scid: None,
token: None,
tag: None,
header_end,
end: data.len(),
length: None,
});
}
let version_range = take(data, &mut cursor, 4, "QUIC version")?;
let v = &data[version_range];
let version = u32::from_be_bytes([v[0], v[1], v[2], v[3]]);
let known = QuicVersion::from_value(version);
let mut cid = |context| -> Result<Range<usize>, ParseError> {
let field = take(data, &mut cursor, 1, context)?;
let length = data[field.start] as usize;
if known.is_some() && length > MAX_CONNECTION_ID_LEN {
return Err(ParseError::InvalidLength {
context,
value: length,
});
}
take(data, &mut cursor, length, context)
};
let dcid = cid("QUIC destination CID")?;
let scid = cid("QUIC source CID")?;
let mut layout = Layout {
kind: QuicPacketType::UnknownVersion,
version: Some(version),
dcid,
scid: Some(scid),
token: None,
tag: None,
header_end: cursor,
end: data.len(),
length: None,
};
if version == 0 {
let length = data.len() - cursor;
if length == 0 || !length.is_multiple_of(4) {
return Err(ParseError::InvalidLength {
context: "QUIC supported versions",
value: length,
});
}
layout.kind = QuicPacketType::VersionNegotiation;
return Ok(layout);
}
let Some(known) = known else {
return Ok(layout);
};
check_fixed(first, options)?;
layout.kind = known.packet_type(first);
if layout.kind == QuicPacketType::Retry {
let length = data.len() - cursor;
if length <= RETRY_INTEGRITY_TAG_LEN {
return Err(ParseError::InvalidLength {
context: "QUIC Retry token and tag",
value: length,
});
}
let tag_start = data.len() - RETRY_INTEGRITY_TAG_LEN;
layout.token = Some(cursor..tag_start);
layout.tag = Some(tag_start..data.len());
return Ok(layout);
}
if layout.kind == QuicPacketType::Initial {
let length = size(read_varint(data, &mut cursor)?, "QUIC token length")?;
layout.token = Some(take(data, &mut cursor, length, "QUIC Initial token")?);
}
let length = read_varint(data, &mut cursor)?;
if length == 0 {
return Err(ParseError::InvalidLength {
context: "QUIC protected body",
value: 0,
});
}
layout.header_end = cursor;
layout.length = Some(length);
take(
data,
&mut cursor,
size(length, "QUIC Length")?,
"QUIC protected body",
)?;
layout.end = cursor;
Ok(layout)
}