Skip to main content

libbpf_rs/
netfilter.rs

1use std::mem::size_of;
2
3/// Netfilter protocol family for IPv4.
4pub const NFPROTO_IPV4: i32 = libc::NFPROTO_IPV4;
5/// Netfilter protocol family for IPv6.
6pub const NFPROTO_IPV6: i32 = libc::NFPROTO_IPV6;
7
8/// Netfilter hook number for pre-routing (0).
9pub const NF_INET_PRE_ROUTING: i32 = libc::NF_INET_PRE_ROUTING;
10/// Netfilter hook number for local input (1).
11pub const NF_INET_LOCAL_IN: i32 = libc::NF_INET_LOCAL_IN;
12/// Netfilter hook number for packet forwarding (2).
13pub const NF_INET_FORWARD: i32 = libc::NF_INET_FORWARD;
14/// Netfilter hook number for local output (3).
15pub const NF_INET_LOCAL_OUT: i32 = libc::NF_INET_LOCAL_OUT;
16/// Netfilter hook number for post-routing (4).
17pub const NF_INET_POST_ROUTING: i32 = libc::NF_INET_POST_ROUTING;
18
19/// Options to be provided when attaching a program to a netfilter hook.
20#[derive(Clone, Debug, Default)]
21#[doc(alias = "bpf_netfilter_opts")]
22pub struct NetfilterOpts {
23    /// Protocol family for netfilter; supported values are `NFPROTO_IPV4` (2) for IPv4
24    /// and `NFPROTO_IPV6` (10) for IPv6.
25    pub protocol_family: i32,
26
27    /// Hook number for netfilter; supported values include:
28    /// - `NF_INET_PRE_ROUTING` (0) - Pre-routing
29    /// - `NF_INET_LOCAL_IN` (1) - Local input
30    /// - `NF_INET_FORWARD` (2) - Forwarding
31    /// - `NF_INET_LOCAL_OUT` (3) - Local output
32    /// - `NF_INET_POST_ROUTING` (4) - Post-routing
33    pub hooknum: i32,
34
35    /// Priority of the netfilter hook. Lower values are invoked first.
36    /// Values `NF_IP_PRI_FIRST` (-2147483648) and `NF_IP_PRI_LAST` (2147483647) are
37    /// not allowed. If `BPF_F_NETFILTER_IP_DEFRAG` is set in `flags`, the priority
38    /// must be higher than `NF_IP_PRI_CONNTRACK_DEFRAG` (-400).
39    pub priority: i32,
40
41    /// Bitmask of flags for the netfilter hook.
42    /// - `BPF_F_NETFILTER_IP_DEFRAG` - Enables defragmentation of IP fragments. This hook will
43    ///   only see defragmented packets.
44    pub flags: u32,
45    #[doc(hidden)]
46    pub _non_exhaustive: (),
47}
48
49impl From<NetfilterOpts> for libbpf_sys::bpf_netfilter_opts {
50    fn from(opts: NetfilterOpts) -> Self {
51        let NetfilterOpts {
52            protocol_family,
53            hooknum,
54            priority,
55            flags,
56            _non_exhaustive,
57        } = opts;
58
59        #[allow(clippy::needless_update)]
60        Self {
61            sz: size_of::<Self>() as _,
62            pf: protocol_family as u32,
63            hooknum: hooknum as u32,
64            priority,
65            flags,
66            ..Default::default()
67        }
68    }
69}