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.
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
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}, };
pub fn xdpfirewall(ctx: XdpContext) -> u32 { match tryxdpfirewall(ctx) { Ok(ret) => ret, Err() => xdpaction::XDPPASS, } }
unsafe fn ptrat
if start + offset + len > end {
return Err(());
}
Ok((start + offset) as *const T)
}
fn tryxdpfirewall(ctx: XdpContext) -> Result
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)
}
fn panic(info: &core::panic::PanicInfo) -> ! { unsafe { core::hint::unreachableunchecked() } } ```