use std::net::IpAddr;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum PacketError {
#[error("{field} cannot describe {actual} bytes; the most it can hold is {limit}")]
TooLong {
field: &'static str,
actual: usize,
limit: usize,
},
#[error("cannot checksum from {src} to {dst}: an IPv4 and an IPv6 address")]
FamilyMismatch {
src: IpAddr,
dst: IpAddr,
},
#[error("an {protocol} checksum covers {expected} addresses, and {got} is not one")]
WrongFamily {
protocol: &'static str,
expected: &'static str,
got: IpAddr,
},
#[error("an MTU of {mtu} cannot fragment past a {minimum}-byte floor")]
MtuTooSmall {
mtu: usize,
minimum: usize,
},
#[error("cannot fragment an IPv4 header carrying {options} bytes of options")]
HeaderHasOptions {
options: usize,
},
#[error(
"{what} carrying {options} bytes of options cannot be measured: its length field holds at most {limit}"
)]
OptionsTooLong {
what: &'static str,
options: usize,
limit: usize,
},
#[error(
"{what} carrying {options} bytes of options is not a whole number of the four-byte words its length field counts"
)]
OptionsMisaligned {
what: &'static str,
options: usize,
},
#[error("nothing here reads ethertype {0:#06x}")]
UnsupportedEtherType(u16),
#[error("{what} could not be read: {detail}")]
Unreadable {
what: &'static str,
detail: String,
},
#[error("expected {expected} and got {got}")]
UnexpectedMessage {
expected: &'static str,
got: &'static str,
},
#[error("{name} is not a name this can write: {detail}")]
UnwritableName {
name: String,
detail: String,
},
#[error("{what} needs at least {needed} bytes and got {got}")]
Truncated {
what: &'static str,
needed: usize,
got: usize,
},
}
impl PacketError {
pub(crate) fn too_long(field: &'static str, header: usize, payload: usize) -> Self {
Self::TooLong {
field,
actual: header.saturating_add(payload),
limit: u16::MAX as usize,
}
}
pub(crate) fn truncated(what: &'static str, needed: usize, got: usize) -> Self {
Self::Truncated { what, needed, got }
}
pub(crate) fn check_options(
what: &'static str,
options: usize,
) -> std::result::Result<(), Self> {
const LARGEST: usize = (15 - 5) * 4;
if !options.is_multiple_of(4) {
return Err(Self::OptionsMisaligned { what, options });
}
if options > LARGEST {
return Err(Self::OptionsTooLong {
what,
options,
limit: LARGEST,
});
}
Ok(())
}
pub(crate) fn unreadable(what: &'static str, detail: impl std::fmt::Display) -> Self {
Self::Unreadable {
what,
detail: detail.to_string(),
}
}
pub(crate) fn unwritable_name(name: &str, detail: impl std::fmt::Display) -> Self {
Self::UnwritableName {
name: name.to_string(),
detail: detail.to_string(),
}
}
}
pub type Result<T> = std::result::Result<T, PacketError>;