Skip to main content

iris_core/protocols/packet/
mod.rs

1//! Types for parsing and manipulating packet-level network protocols.
2//!
3//! The structure of this module is adapted from
4//! [capsule::packets](https://docs.rs/capsule/0.1.5/capsule/packets/index.html) and
5//! [pnet::packet](https://docs.rs/pnet/latest/pnet/packet/index.html). Every packet type represents
6//! a single frame on the wire.
7
8pub mod ethernet;
9pub mod ipv4;
10pub mod ipv6;
11pub mod tcp;
12pub mod udp;
13use crate::memory::mbuf::Mbuf;
14
15use thiserror::Error;
16
17/// Represents a single packet.
18pub trait Packet<'a> {
19    /// Reference to the underlying packet buffer.
20    fn mbuf(&self) -> &Mbuf;
21
22    /// Offset from the beginning of the header to the start of the payload.
23    fn header_len(&self) -> usize;
24
25    /// Offset from the beginning of the packet buffer to the start of the payload.
26    fn next_header_offset(&self) -> usize;
27
28    /// Next level IANA protocol number.
29    fn next_header(&self) -> Option<usize>;
30
31    /// Parses the `Packet`'s payload as a new `Packet` of type `T`.
32    ///
33    /// Returns the concrete [`PacketParseError`] if parsing fails.
34    fn parse_to<T: Packet<'a>>(&'a self) -> Result<T, PacketParseError>
35    where
36        Self: Sized,
37    {
38        T::parse_from(self)
39    }
40
41    /// Parses a `Packet` from the outer encapsulating `Packet`'s payload.
42    fn parse_from(outer: &'a impl Packet<'a>) -> Result<Self, PacketParseError>
43    where
44        Self: Sized;
45}
46
47/// Represents a packet header.
48pub trait PacketHeader {
49    /// Offset from beginning of the header to start of the payload. It includes the length of any
50    /// variable-sized options and tags.
51    fn length(&self) -> usize;
52
53    /// Size of the fixed portion of the header in bytes.
54    fn size_of() -> usize
55    where
56        Self: Sized,
57    {
58        std::mem::size_of::<Self>()
59    }
60}
61
62#[derive(Error, Debug)]
63pub enum PacketParseError {
64    #[error("Invalid protocol")]
65    InvalidProtocol,
66
67    #[error("Invalid data read")]
68    InvalidRead,
69}