Skip to content

Commit

Permalink
fix(program-types/xdp): remove duplicated text/code
Browse files Browse the repository at this point in the history
  • Loading branch information
shard77 authored and vadorovsky committed Dec 11, 2024
1 parent 8234571 commit 6499acc
Showing 1 changed file with 4 additions and 85 deletions.
89 changes: 4 additions & 85 deletions docs/book/programs/xdp.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,27 +151,6 @@ static BLOCKLIST: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
Here, we define our blocklist with a `HashMap`,
which stores integers (u32), with a maximum of 1024 entries.

```rust
#[xdp]
pub fn xdp_firewall(ctx: XdpContext) -> u32 {
match try_xdp_firewall(ctx) {
Ok(ret) => ret,
Err(_) => xdp_action::XDP_ABORTED,
}
```

An eBPF-compatible panic handler is provided, because eBPF programs cannot use
the default panic behavior.

```rust
#[map]
static BLOCKLIST: HashMap<u32, u32> =
HashMap::<u32, u32>::with_max_entries(1024, 0);
```

Here, we define our blocklist with a `HashMap`, which stores integers (`u32`),
with a maximum of 1024 entries.

```rust
#[xdp]
pub fn xdp_firewall(ctx: XdpContext) -> u32 {
Expand Down Expand Up @@ -332,71 +311,11 @@ fn try_xdp_firewall(ctx: XdpContext) -> Result<u32, ()> {
xdp_action::XDP_DROP
} else {
xdp_action::XDP_PASS
};
use aya_log_ebpf::info;

use core::mem;
use network_types::{
eth::{EthHdr, EtherType},
ip::Ipv4Hdr,
};

#[panic_handler]
fn panic(_info: &core::panic::PanicInfo) -> ! {
unsafe { core::hint::unreachable_unchecked() }
}

#[map]
static IP_BLOCKLIST: HashMap<u32, u32> =
HashMap::<u32, u32>::with_max_entries(1024, 0);

#[xdp]
pub fn xdp_firewall(ctx: XdpContext) -> u32 {
match try_xdp_firewall(ctx) {
Ok(ret) => ret,
Err(_) => xdp_action::XDP_ABORTED,
}
}

#[inline(always)]
unsafe fn ptr_at<T>(
ctx: &XdpContext, offset: usize
) -> Result<*const T, ()> {
let start = ctx.data();
let end = ctx.data_end();
let len = mem::size_of::<T>();

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

let ptr = (start + offset) as *const T;
Ok(&*ptr)
}

fn block_ip(address: u32) -> bool {
unsafe { IP_BLOCKLIST.get(&address).is_some() }
}

fn try_xdp_firewall(ctx: XdpContext) -> Result<u32, ()> {
let ethhdr: *const EthHdr = unsafe { ptr_at(&ctx, 0)? };
match unsafe { (*ethhdr).ether_type } {
EtherType::Ipv4 => {}
_ => return Ok(xdp_action::XDP_PASS),
}

let ipv4hdr: *const Ipv4Hdr = unsafe { ptr_at(&ctx, EthHdr::LEN)? };
let source = u32::from_be(unsafe { (*ipv4hdr).src_addr });

let action = if block_ip(source) {
xdp_action::XDP_DROP
} else {
xdp_action::XDP_PASS
};
info!(&ctx, "SRC: {:i}, ACTION: {}", source, action);
};
info!(&ctx, "SRC: {:i}, ACTION: {}", source, action);

Ok(action)
}
Ok(action)
}
```

### Populating our map from user-space
Expand Down

0 comments on commit 6499acc

Please sign in to comment.