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

Add connect_unspec #895

Closed
wants to merge 1 commit into from
Closed
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
22 changes: 21 additions & 1 deletion src/backend/libc/net/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use {
use {
super::read_sockaddr::{initialize_family_to_unspec, maybe_read_sockaddr_os, read_sockaddr_os},
super::send_recv::{RecvFlags, SendFlags},
super::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6},
super::write_sockaddr::{encode_sockaddr_unspec, encode_sockaddr_v4, encode_sockaddr_v6},
crate::net::{AddressFamily, Protocol, Shutdown, SocketFlags, SocketType},
core::ptr::null_mut,
};
Expand Down Expand Up @@ -248,6 +248,26 @@ pub(crate) fn connect_unix(sockfd: BorrowedFd<'_>, addr: &SocketAddrUnix) -> io:
}
}

#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
pub(crate) fn connect_unspec(sockfd: BorrowedFd<'_>) -> io::Result<()> {
#[cfg(bsd)]
unsafe {
ret(c::connect(
borrowed_fd(sockfd),
as_ptr(&encode_sockaddr_unspec()).cast(),
0,
))
}
#[cfg(not(bsd))]
unsafe {
ret(c::connect(
borrowed_fd(sockfd),
as_ptr(&encode_sockaddr_unspec()).cast(),
size_of::<c::sockaddr_in6>() as c::socklen_t,
))
}
}

#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
pub(crate) fn listen(sockfd: BorrowedFd<'_>, backlog: c::c_int) -> io::Result<()> {
unsafe { ret(c::listen(borrowed_fd(sockfd), backlog)) }
Expand Down
35 changes: 35 additions & 0 deletions src/backend/libc/net/write_sockaddr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,38 @@ unsafe fn write_sockaddr_unix(unix: &SocketAddrUnix, storage: *mut SocketAddrSto
core::ptr::write(storage.cast(), unix.unix);
unix.len()
}

/// Even though an AF_UNSPEC socket address contains only the family, they're
/// still required to be at least as big as the socket's regular address structure.
/// We (ab)use `sockaddr_in6` to push the size up to satisfy both IPv4 and IPv6 sockets.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you say more about what requires the encoded socket to be as big as the socket's regular address structure? If the socket is not IPv4 or IPv6, what would happen here? Would it make sense to use c::sockaddr_storage here instead?

pub(crate) fn encode_sockaddr_unspec() -> c::sockaddr_in6 {
#[cfg(any(
bsd,
target_os = "aix",
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "vita"
))]
{
sockaddr_in6_new(
size_of::<c::sockaddr_in6>() as _,
c::AF_UNSPEC as _,
0,
0,
in6_addr_new([0; 16]),
0,
)
}
#[cfg(not(any(
bsd,
target_os = "aix",
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "vita"
)))]
{
sockaddr_in6_new(c::AF_UNSPEC as _, 0, 0, in6_addr_new([0; 16]), 0)
}
}
27 changes: 26 additions & 1 deletion src/backend/linux_raw/net/syscalls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use super::msghdr::{
};
use super::read_sockaddr::{initialize_family_to_unspec, maybe_read_sockaddr_os, read_sockaddr_os};
use super::send_recv::{RecvFlags, SendFlags};
use super::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6};
use super::write_sockaddr::{encode_sockaddr_unspec, encode_sockaddr_v4, encode_sockaddr_v6};
use crate::backend::c;
use crate::backend::conv::{
by_mut, by_ref, c_int, c_uint, ret, ret_owned_fd, ret_usize, size_of, slice, slice_mut,
Expand Down Expand Up @@ -904,6 +904,31 @@ pub(crate) fn connect_unix(fd: BorrowedFd<'_>, addr: &SocketAddrUnix) -> io::Res
}
}

#[inline]
pub(crate) fn connect_unspec(fd: BorrowedFd<'_>) -> io::Result<()> {
#[cfg(not(target_arch = "x86"))]
unsafe {
ret(syscall_readonly!(
__NR_connect,
fd,
by_ref(&encode_sockaddr_unspec()),
size_of::<sockaddr_in6, _>()
))
}
#[cfg(target_arch = "x86")]
unsafe {
ret(syscall_readonly!(
__NR_socketcall,
x86_sys(SYS_CONNECT),
slice_just_addr::<ArgReg<'_, SocketArg>, _>(&[
fd.into(),
by_ref(&encode_sockaddr_unspec()),
size_of::<sockaddr_in6, _>(),
])
))
}
}

#[inline]
pub(crate) fn listen(fd: BorrowedFd<'_>, backlog: c::c_int) -> io::Result<()> {
#[cfg(not(target_arch = "x86"))]
Expand Down
15 changes: 15 additions & 0 deletions src/backend/linux_raw/net/write_sockaddr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,18 @@ unsafe fn write_sockaddr_unix(unix: &SocketAddrUnix, storage: *mut SocketAddrSto
core::ptr::write(storage.cast(), unix.unix);
unix.len()
}

/// Even though an AF_UNSPEC socket address contains only the family, they're
/// still required to be at least as big as the socket's regular address structure.
/// We (ab)use `sockaddr_in6` to push the size up to satisfy both IPv4 and IPv6 sockets.
pub(crate) fn encode_sockaddr_unspec() -> c::sockaddr_in6 {
c::sockaddr_in6 {
sin6_family: c::AF_UNSPEC as _,
sin6_port: 0,
sin6_flowinfo: 0,
sin6_addr: c::in6_addr {
in6_u: linux_raw_sys::net::in6_addr__bindgen_ty_1 { u6_addr8: [0; 16] },
},
sin6_scope_id: 0,
}
}
33 changes: 33 additions & 0 deletions src/net/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,39 @@ pub fn connect_unix<Fd: AsFd>(sockfd: Fd, addr: &SocketAddrUnix) -> io::Result<(
backend::net::syscalls::connect_unix(sockfd.as_fd(), addr)
}

/// `connect(sockfd, {.sa_family = AF_UNSPEC}, sizeof(struct sockaddr))`
/// — Dissolve the socket's association.
///
/// # References
/// - [Beej's Guide to Network Programming]
/// - [POSIX]
/// - [Linux]
/// - [Apple]
/// - [Winsock2]
/// - [FreeBSD]
/// - [NetBSD]
/// - [OpenBSD]
/// - [DragonFly BSD]
/// - [illumos]
/// - [glibc]
///
/// [Beej's Guide to Network Programming]: https://beej.us/guide/bgnet/html/split/system-calls-or-bust.html#connect
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html
/// [Linux]: https://man7.org/linux/man-pages/man2/connect.2.html
/// [Apple]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/connect.2.html
/// [Winsock2]: https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect
/// [FreeBSD]: https://man.freebsd.org/cgi/man.cgi?query=connect&sektion=2
/// [NetBSD]: https://man.netbsd.org/connect.2
/// [OpenBSD]: https://man.openbsd.org/connect.2
/// [DragonFly BSD]: https://man.dragonflybsd.org/?command=connect&section=2
/// [illumos]: https://illumos.org/man/3SOCKET/connect
/// [glibc]: https://www.gnu.org/software/libc/manual/html_node/Connecting.html
#[inline]
#[doc(alias = "connect")]
pub fn connect_unspec<Fd: AsFd>(sockfd: Fd) -> io::Result<()> {
backend::net::syscalls::connect_unspec(sockfd.as_fd())
}

/// `listen(fd, backlog)`—Enables listening for incoming connections.
///
/// # References
Expand Down
66 changes: 66 additions & 0 deletions tests/net/connect_bind_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,72 @@ fn net_v6_connect() {
assert_eq!(request, &response[..n]);
}

/// Test `connect_unspec`.
#[test]
fn net_v4_connect_unspec() {
const SOME_PORT: u16 = 47;
let localhost_addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, SOME_PORT);

let socket = rustix::net::socket(AddressFamily::INET, SocketType::DGRAM, None).unwrap();

rustix::net::connect_v4(&socket, &localhost_addr).expect("connect_v4");
let peer = getpeername_v4(&socket).unwrap();
assert_eq!(peer.ip().to_owned(), Ipv4Addr::LOCALHOST);

match rustix::net::connect_unspec(&socket) {
#[cfg(apple)]
Err(rustix::io::Errno::INVAL) => {} // Apple platforms return an error even when the call succeeded.
r => r.expect("connect_unspec"),
}
let peer_result = getpeername_v4(&socket);
assert_eq!(peer_result, Err(rustix::io::Errno::NOTCONN));

rustix::net::connect_v4(&socket, &localhost_addr).expect("connect_v4");
let peer = getpeername_v4(&socket).unwrap();
assert_eq!(peer.ip().to_owned(), Ipv4Addr::LOCALHOST);

fn getpeername_v4<Fd: rustix::fd::AsFd>(sockfd: Fd) -> rustix::io::Result<SocketAddrV4> {
match rustix::net::getpeername(sockfd)? {
Some(SocketAddrAny::V4(addr_v4)) => Ok(addr_v4),
None => Err(rustix::io::Errno::NOTCONN),
_ => Err(rustix::io::Errno::AFNOSUPPORT),
}
}
}

/// Test `connect_unspec`.
#[test]
fn net_v6_connect_unspec() {
const SOME_PORT: u16 = 47;
let localhost_addr = SocketAddrV6::new(Ipv6Addr::LOCALHOST, SOME_PORT, 0, 0);

let socket = rustix::net::socket(AddressFamily::INET6, SocketType::DGRAM, None).unwrap();

rustix::net::connect_v6(&socket, &localhost_addr).expect("connect_v6");
let peer = getpeername_v6(&socket).unwrap();
assert_eq!(peer.ip().to_owned(), Ipv6Addr::LOCALHOST);

match rustix::net::connect_unspec(&socket) {
#[cfg(apple)]
Err(rustix::io::Errno::AFNOSUPPORT) => {} // Apple platforms return an error even when the call succeeded.
r => r.expect("connect_unspec"),
}
let peer_result = getpeername_v6(&socket);
assert_eq!(peer_result, Err(rustix::io::Errno::NOTCONN));

rustix::net::connect_v6(&socket, &localhost_addr).expect("connect_v6");
let peer = getpeername_v6(&socket).unwrap();
assert_eq!(peer.ip().to_owned(), Ipv6Addr::LOCALHOST);

fn getpeername_v6<Fd: rustix::fd::AsFd>(sockfd: Fd) -> rustix::io::Result<SocketAddrV6> {
match rustix::net::getpeername(sockfd)? {
Some(SocketAddrAny::V6(addr_v6)) => Ok(addr_v6),
None => Err(rustix::io::Errno::NOTCONN),
_ => Err(rustix::io::Errno::AFNOSUPPORT),
}
}
}

/// Test `bind_any`.
#[test]
fn net_v4_bind_any() {
Expand Down
Loading