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 anyhow::Result;
16use thiserror::Error;
17
18/// Represents a single packet.
19pub trait Packet<'a> {
20    /// Reference to the underlying packet buffer.
21    fn mbuf(&self) -> &Mbuf;
22
23    /// Offset from the beginning of the header to the start of the payload.
24    fn header_len(&self) -> usize;
25
26    /// Offset from the beginning of the packet buffer to the start of the payload.
27    fn next_header_offset(&self) -> usize;
28
29    /// Next level IANA protocol number.
30    fn next_header(&self) -> Option<usize>;
31
32    /// Parses the `Packet`'s payload as a new `Packet` of type `T`.
33    fn parse_to<T: Packet<'a>>(&'a self) -> Result<T>
34    where
35        Self: Sized,
36    {
37        T::parse_from(self)
38    }
39
40    /// Parses a `Packet` from the outer encapsulating `Packet`'s payload.
41    fn parse_from(outer: &'a impl Packet<'a>) -> Result<Self>
42    where
43        Self: Sized;
44}
45
46/// Represents a packet header.
47pub trait PacketHeader {
48    /// Offset from beginning of the header to start of the payload. It includes the length of any
49    /// variable-sized options and tags.
50    fn length(&self) -> usize;
51
52    /// Size of the fixed portion of the header in bytes.
53    fn size_of() -> usize
54    where
55        Self: Sized,
56    {
57        std::mem::size_of::<Self>()
58    }
59}
60
61#[derive(Error, Debug)]
62pub(crate) enum PacketParseError {
63    #[error("Invalid protocol")]
64    InvalidProtocol,
65
66    #[error("Invalid data read")]
67    InvalidRead,
68}