network-types

Rust structs representing network-related types (on Layer 2, 3 and 4) in Linux.

The crate is no_std and the structures are fully compatible with the ones provided by the Linux kernel, which makes it a great fit for eBPF programs written with Aya.

Example with Aya

This crate can be used for parsing packet headers in TC classifier and XDP.

A small example of an XDP program logging information about addresses and ports for incoming packets:

```rust

![no_std]

![no_main]

use ayabpf::{bindings::xdpaction, macros::xdp, programs::XdpContext}; use ayalogebpf::info;

use core::mem; use networktypes::{ l2::ethernet::{EthHdr, ETHHDRLEN}, l3::{ ip::{Ipv4Hdr, IPV4HDR_LEN}, L3Protocol, }, l4::{tcp::TcpHdr, udp::UdpHdr, L4Protocol}, };

[xdp]

pub fn xdpfirewall(ctx: XdpContext) -> u32 { match tryxdpfirewall(ctx) { Ok(ret) => ret, Err() => xdpaction::XDPPASS, } }

[inline(always)]

unsafe fn ptrat(ctx: &XdpContext, offset: usize) -> Result<*const T, ()> { let start = ctx.data(); let end = ctx.dataend(); let len = mem::size_of::();

if start + offset + len > end {
    return Err(());
}

Ok((start + offset) as *const T)

}

fn tryxdpfirewall(ctx: XdpContext) -> Resultat(&ctx, 0)? }; match unsafe { *ethhdr }.protocol()? { L3Protocol::Ipv4 => {} _ => return Ok(xdpaction::XDP_PASS), }

let ipv4hdr: *const Ipv4Hdr = unsafe { ptr_at(&ctx, ETH_HDR_LEN)? };
let saddr = unsafe { *ipv4hdr }.saddr_from_be();

let sport = match unsafe { *ipv4hdr }.protocol()? {
    L4Protocol::Tcp => {
        let tcphdr: *const TcpHdr =
            unsafe { ptr_at(&ctx, ETH_HDR_LEN + IPV4_HDR_LEN) }?;
        u16::from_be(unsafe { *tcphdr }.source)
    }
    L4Protocol::Udp => {
        let udphdr: *const UdpHdr =
            unsafe { ptr_at(&ctx, ETH_HDR_LEN + IPV4_HDR_LEN) }?;
        u16::from_be(unsafe { *udphdr }.source)
    }
    _ => return Err(()),
};

info!(&ctx, "SRC IP: {}, SRC PORT: {}", saddr, sport);

Ok(xdp_action::XDP_PASS)

}

[panic_handler]

fn panic(info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachableunchecked() } } ```