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)]
21pub struct NetfilterOpts {
22    /// Protocol family for netfilter; supported values are `NFPROTO_IPV4` (2) for IPv4
23    /// and `NFPROTO_IPV6` (10) for IPv6.
24    pub protocol_family: i32,
25
26    /// Hook number for netfilter; supported values include:
27    /// - `NF_INET_PRE_ROUTING` (0) - Pre-routing
28    /// - `NF_INET_LOCAL_IN` (1) - Local input
29    /// - `NF_INET_FORWARD` (2) - Forwarding
30    /// - `NF_INET_LOCAL_OUT` (3) - Local output
31    /// - `NF_INET_POST_ROUTING` (4) - Post-routing
32    pub hooknum: i32,
33
34    /// Priority of the netfilter hook. Lower values are invoked first.
35    /// Values `NF_IP_PRI_FIRST` (-2147483648) and `NF_IP_PRI_LAST` (2147483647) are
36    /// not allowed. If `BPF_F_NETFILTER_IP_DEFRAG` is set in `flags`, the priority
37    /// must be higher than `NF_IP_PRI_CONNTRACK_DEFRAG` (-400).
38    pub priority: i32,
39
40    /// Bitmask of flags for the netfilter hook.
41    /// - `NF_IP_PRI_CONNTRACK_DEFRAG` - Enables defragmentation of IP fragments. This hook will
42    ///   only see defragmented packets.
43    pub flags: u32,
44    #[doc(hidden)]
45    pub _non_exhaustive: (),
46}
47
48impl From<NetfilterOpts> for libbpf_sys::bpf_netfilter_opts {
49    fn from(opts: NetfilterOpts) -> Self {
50        let NetfilterOpts {
51            protocol_family,
52            hooknum,
53            priority,
54            flags,
55            _non_exhaustive,
56        } = opts;
57
58        #[allow(clippy::needless_update)]
59        libbpf_sys::bpf_netfilter_opts {
60            sz: size_of::<Self>() as _,
61            pf: protocol_family as u32,
62            hooknum: hooknum as u32,
63            priority,
64            flags,
65            ..Default::default()
66        }
67    }
68}