Skip to content

Implement socket_bind_device and set_socket_bind_device #1426

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
38 changes: 38 additions & 0 deletions src/backend/libc/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@ use alloc::borrow::ToOwned as _;
target_os = "illumos"
))]
use alloc::string::String;
#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
use alloc::vec::Vec;
#[cfg(apple)]
use c::TCP_KEEPALIVE as TCP_KEEPIDLE;
#[cfg(not(any(apple, target_os = "haiku", target_os = "nto", target_os = "openbsd")))]
Expand Down Expand Up @@ -357,6 +360,41 @@ pub(crate) fn socket_recv_buffer_size(fd: BorrowedFd<'_>) -> io::Result<usize> {
getsockopt(fd, c::SOL_SOCKET, c::SO_RCVBUF).map(|size: u32| size as usize)
}

#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
#[inline]
pub(crate) fn socket_bind_device(fd: BorrowedFd<'_>) -> io::Result<Vec<u8>> {
let mut value = MaybeUninit::<[MaybeUninit<u8>; 16]>::uninit();
let mut optlen = 16;
getsockopt_raw(
fd,
c::SOL_SOCKET,
c::SO_BINDTODEVICE,
&mut value,
&mut optlen,
)?;
unsafe {
let value = value.assume_init();
let slice: &[u8] = core::mem::transmute(&value[..optlen as usize]);
assert!(slice.contains(&b'\0'));
Ok(slice[..optlen as usize - 1].to_vec())
}
}

#[cfg(any(linux_kernel, target_os = "fuchsia"))]
#[inline]
pub(crate) fn set_socket_bind_device(
fd: BorrowedFd<'_>,
interface: Option<&[u8]>,
) -> io::Result<()> {
setsockopt(
fd,
c::SOL_SOCKET,
c::SO_BINDTODEVICE,
interface.unwrap_or(&[]),
)
}

#[inline]
pub(crate) fn set_socket_send_buffer_size(fd: BorrowedFd<'_>, size: usize) -> io::Result<()> {
let size: c::c_int = size.try_into().map_err(|_| io::Errno::INVAL)?;
Expand Down
26 changes: 25 additions & 1 deletion src/backend/linux_raw/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ use crate::net::{
use alloc::borrow::ToOwned as _;
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::mem::{size_of, MaybeUninit};
use core::time::Duration;
use linux_raw_sys::general::{__kernel_old_timeval, __kernel_sock_timeval};
use linux_raw_sys::net::{IPV6_MTU, IPV6_MULTICAST_IF, IP_MTU, IP_MULTICAST_IF};
use linux_raw_sys::net::{IPV6_MTU, IPV6_MULTICAST_IF, IP_MTU, IP_MULTICAST_IF, SO_BINDTODEVICE};
#[cfg(target_os = "linux")]
use linux_raw_sys::xdp::{xdp_mmap_offsets, xdp_statistics, xdp_statistics_v1};
#[cfg(target_arch = "x86")]
Expand Down Expand Up @@ -432,6 +434,28 @@ pub(crate) fn set_socket_incoming_cpu(fd: BorrowedFd<'_>, value: u32) -> io::Res
setsockopt(fd, c::SOL_SOCKET, c::SO_INCOMING_CPU, value)
}

#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn socket_bind_device(fd: BorrowedFd<'_>) -> io::Result<Vec<u8>> {
let mut value = MaybeUninit::<[MaybeUninit<u8>; 16]>::uninit();
let mut optlen = 16;
getsockopt_raw(fd, c::SOL_SOCKET, SO_BINDTODEVICE, &mut value, &mut optlen)?;
unsafe {
let value = value.assume_init();
let slice: &[u8] = core::mem::transmute(&value[..optlen as usize]);
assert!(slice.contains(&b'\0'));
Ok(slice[..optlen as usize - 1].to_vec())
}
}

#[inline]
pub(crate) fn set_socket_bind_device(
fd: BorrowedFd<'_>,
interface: Option<&[u8]>,
) -> io::Result<()> {
setsockopt(fd, c::SOL_SOCKET, SO_BINDTODEVICE, interface.unwrap_or(&[]))
}

#[inline]
pub(crate) fn set_ip_ttl(fd: BorrowedFd<'_>, ttl: u32) -> io::Result<()> {
setsockopt(fd, c::IPPROTO_IP, c::IP_TTL, ttl)
Expand Down
24 changes: 24 additions & 0 deletions src/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,30 @@ pub fn set_socket_incoming_cpu<Fd: AsFd>(fd: Fd, value: u32) -> io::Result<()> {
backend::net::sockopt::set_socket_incoming_cpu(fd.as_fd(), value)
}

/// `getsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE)`
///
/// See the [module-level documentation] for more.
///
/// [module-level documentation]: self#references-for-get_socket_-and-set_socket_-functions
#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
#[inline]
#[doc(alias = "SO_BINDTODEVICE")]
pub fn socket_bind_device<Fd: AsFd>(fd: Fd) -> io::Result<Vec<u8>> {
backend::net::sockopt::socket_bind_device(fd.as_fd())
}

/// `setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, interface)`
///
/// See the [module-level documentation] for more.
///
/// [module-level documentation]: self#references-for-get_socket_-and-set_socket_-functions
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
#[doc(alias = "SO_BINDTODEVICE")]
pub fn set_socket_bind_device<Fd: AsFd>(fd: Fd, interface: Option<&[u8]>) -> io::Result<()> {
backend::net::sockopt::set_socket_bind_device(fd.as_fd(), interface)
}

/// `setsockopt(fd, IPPROTO_IP, IP_TTL, value)`
///
/// See the [module-level documentation] for more.
Expand Down
23 changes: 23 additions & 0 deletions tests/net/sockopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -633,3 +633,26 @@ fn test_sockopts_multicast_ifv6() {
Err(e) => panic!("{e}"),
}
}

#[cfg(feature = "alloc")]
#[cfg(any(linux_kernel, target_os = "fuchsia"))]
#[test]
fn test_socket_bind_device() {
let fd = rustix::net::socket(AddressFamily::INET, SocketType::STREAM, None).unwrap();

let loopback_index = std::fs::read_to_string("/sys/class/net/lo/ifindex")
.unwrap()
.as_str()
.split_at(1)
.0
.parse::<u32>()
.unwrap();
let name = rustix::net::netdevice::index_to_name(&fd, loopback_index).unwrap();

sockopt::set_socket_bind_device(&fd, Some(name.as_bytes())).unwrap();

assert_eq!(
name.as_bytes(),
sockopt::socket_bind_device(&fd).unwrap().as_slice()
);
}
Loading