Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

socket::sockopt AttachReusePortCbpf for Linux addition. #2621

Merged
merged 1 commit into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/2621.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `socket::sockopt::AttachReusePortCbpf` for Linux
12 changes: 12 additions & 0 deletions src/sys/socket/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1269,6 +1269,18 @@ sockopt_impl!(
libc::SO_EXCLBIND,
bool
);
#[cfg(target_os = "linux")]
sockopt_impl!(
/// To be used with `ReusePort`,
/// we can then attach a BPF (classic)
/// to set how the packets are assigned
/// to the socket (e.g. cpu distribution).
AttachReusePortCbpf,
SetOnly,
libc::SOL_SOCKET,
libc::SO_ATTACH_REUSEPORT_CBPF,
libc::sock_fprog
);

#[allow(missing_docs)]
// Not documented by Linux!
Expand Down
25 changes: 25 additions & 0 deletions test/sys/test_sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,3 +1194,28 @@ fn test_solfilter() {
assert_eq!(Err(Errno::ENOENT), setsockopt(&s, attach, data));
assert_eq!(Err(Errno::ENOENT), setsockopt(&s, detach, data));
}

#[cfg(target_os = "linux")]
#[test]
pub fn test_so_attach_reuseport_cbpf() {
let fd = socket(
AddressFamily::Inet6,
SockType::Datagram,
SockFlag::empty(),
None,
)
.unwrap();
setsockopt(&fd, sockopt::ReusePort, &true).unwrap();
setsockopt(&fd, sockopt::ReuseAddr, &true).unwrap();
let mut flt: [libc::sock_filter; 2] = unsafe { std::mem::zeroed() };
flt[0].code = (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16;
flt[0].k = (libc::SKF_AD_OFF + libc::SKF_AD_CPU) as u32;
flt[1].code = (libc::BPF_RET | 0x10) as u16;
let fp = libc::sock_fprog {
len: flt.len() as u16,
filter: flt.as_mut_ptr(),
};
setsockopt(&fd, sockopt::AttachReusePortCbpf, &fp).unwrap_or_else(|e| {
assert_eq!(e, nix::errno::Errno::ENOPROTOOPT);
});
}