From c1317e477fe6c4ca84f53ab39a0f78269b4d6d21 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Mon, 5 Dec 2022 11:18:18 -0700 Subject: [PATCH] Add I/O safety to sockopt and some socket functions * socket * socketpair * listen * setsockopt * getsockopt --- src/sys/socket/addr.rs | 8 +- src/sys/socket/mod.rs | 66 +++--- src/sys/socket/sockopt.rs | 41 ++-- test/sys/test_socket.rs | 456 ++++++++++++++++++++++---------------- test/sys/test_sockopt.rs | 121 +++++----- 5 files changed, 393 insertions(+), 299 deletions(-) diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index f3c0a05da2..1783531d49 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -875,9 +875,10 @@ pub trait SockaddrLike: private::SockaddrLikePriv { /// One common use is to match on the family of a union type, like this: /// ``` /// # use nix::sys::socket::*; + /// # use std::os::unix::io::AsRawFd; /// let fd = socket(AddressFamily::Inet, SockType::Stream, /// SockFlag::empty(), None).unwrap(); - /// let ss: SockaddrStorage = getsockname(fd).unwrap(); + /// let ss: SockaddrStorage = getsockname(fd.as_raw_fd()).unwrap(); /// match ss.family().unwrap() { /// AddressFamily::Inet => println!("{}", ss.as_sockaddr_in().unwrap()), /// AddressFamily::Inet6 => println!("{}", ss.as_sockaddr_in6().unwrap()), @@ -1261,11 +1262,12 @@ impl std::str::FromStr for SockaddrIn6 { /// ``` /// # use nix::sys::socket::*; /// # use std::str::FromStr; +/// # use std::os::unix::io::AsRawFd; /// let localhost = SockaddrIn::from_str("127.0.0.1:8081").unwrap(); /// let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), /// None).unwrap(); -/// bind(fd, &localhost).expect("bind"); -/// let ss: SockaddrStorage = getsockname(fd).expect("getsockname"); +/// bind(fd.as_raw_fd(), &localhost).expect("bind"); +/// let ss: SockaddrStorage = getsockname(fd.as_raw_fd()).expect("getsockname"); /// assert_eq!(&localhost, ss.as_sockaddr_in().unwrap()); /// ``` #[derive(Clone, Copy, Eq)] diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 6c858c8735..2e2897dbb2 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -18,7 +18,7 @@ use libc::{ use std::io::{IoSlice, IoSliceMut}; #[cfg(feature = "net")] use std::net; -use std::os::unix::io::RawFd; +use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, RawFd, OwnedFd}; use std::{mem, ptr}; #[deny(missing_docs)] @@ -693,6 +693,7 @@ pub enum ControlMessageOwned { /// # use std::io::{IoSlice, IoSliceMut}; /// # use std::time::*; /// # use std::str::FromStr; + /// # use std::os::unix::io::AsRawFd; /// # fn main() { /// // Set up /// let message = "Ohayƍ!".as_bytes(); @@ -701,22 +702,22 @@ pub enum ControlMessageOwned { /// SockType::Datagram, /// SockFlag::empty(), /// None).unwrap(); - /// setsockopt(in_socket, sockopt::ReceiveTimestamp, &true).unwrap(); + /// setsockopt(&in_socket, sockopt::ReceiveTimestamp, &true).unwrap(); /// let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); - /// bind(in_socket, &localhost).unwrap(); - /// let address: SockaddrIn = getsockname(in_socket).unwrap(); + /// bind(in_socket.as_raw_fd(), &localhost).unwrap(); + /// let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap(); /// // Get initial time /// let time0 = SystemTime::now(); /// // Send the message /// let iov = [IoSlice::new(message)]; /// let flags = MsgFlags::empty(); - /// let l = sendmsg(in_socket, &iov, &[], flags, Some(&address)).unwrap(); + /// let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address)).unwrap(); /// assert_eq!(message.len(), l); /// // Receive the message /// let mut buffer = vec![0u8; message.len()]; /// let mut cmsgspace = cmsg_space!(TimeVal); /// let mut iov = [IoSliceMut::new(&mut buffer)]; - /// let r = recvmsg::(in_socket, &mut iov, Some(&mut cmsgspace), flags) + /// let r = recvmsg::(in_socket.as_raw_fd(), &mut iov, Some(&mut cmsgspace), flags) /// .unwrap(); /// let rtime = match r.cmsgs().next() { /// Some(ControlMessageOwned::ScmTimestamp(rtime)) => rtime, @@ -732,7 +733,6 @@ pub enum ControlMessageOwned { /// assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); /// assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); /// // Close socket - /// nix::unistd::close(in_socket).unwrap(); /// # } /// ``` ScmTimestamp(TimeVal), @@ -1451,6 +1451,7 @@ impl<'a> ControlMessage<'a> { /// # use nix::sys::socket::*; /// # use nix::unistd::pipe; /// # use std::io::IoSlice; +/// # use std::os::unix::io::AsRawFd; /// let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, /// SockFlag::empty()) /// .unwrap(); @@ -1459,7 +1460,7 @@ impl<'a> ControlMessage<'a> { /// let iov = [IoSlice::new(b"hello")]; /// let fds = [r]; /// let cmsg = ControlMessage::ScmRights(&fds); -/// sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(); +/// sendmsg::<()>(fd1.as_raw_fd(), &iov, &[cmsg], MsgFlags::empty(), None).unwrap(); /// ``` /// When directing to a specific address, the generic type will be inferred. /// ``` @@ -1467,6 +1468,7 @@ impl<'a> ControlMessage<'a> { /// # use nix::unistd::pipe; /// # use std::io::IoSlice; /// # use std::str::FromStr; +/// # use std::os::unix::io::AsRawFd; /// let localhost = SockaddrIn::from_str("1.2.3.4:8080").unwrap(); /// let fd = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), /// None).unwrap(); @@ -1475,7 +1477,7 @@ impl<'a> ControlMessage<'a> { /// let iov = [IoSlice::new(b"hello")]; /// let fds = [r]; /// let cmsg = ControlMessage::ScmRights(&fds); -/// sendmsg(fd, &iov, &[cmsg], MsgFlags::empty(), Some(&localhost)).unwrap(); +/// sendmsg(fd.as_raw_fd(), &iov, &[cmsg], MsgFlags::empty(), Some(&localhost)).unwrap(); /// ``` pub fn sendmsg(fd: RawFd, iov: &[IoSlice<'_>], cmsgs: &[ControlMessage], flags: MsgFlags, addr: Option<&S>) -> Result @@ -1823,6 +1825,7 @@ mod test { use crate::sys::socket::{AddressFamily, ControlMessageOwned}; use crate::*; use std::str::FromStr; + use std::os::unix::io::AsRawFd; #[cfg_attr(qemu, ignore)] #[test] @@ -1849,9 +1852,9 @@ mod test { None, )?; - crate::sys::socket::bind(rsock, &sock_addr)?; + crate::sys::socket::bind(rsock.as_raw_fd(), &sock_addr)?; - setsockopt(rsock, Timestamping, &TimestampingFlag::all())?; + setsockopt(&rsock, Timestamping, &TimestampingFlag::all())?; let sbuf = (0..400).map(|i| i as u8).collect::>(); @@ -1873,13 +1876,13 @@ mod test { let iov1 = [IoSlice::new(&sbuf)]; let cmsg = cmsg_space!(crate::sys::socket::Timestamps); - sendmsg(ssock, &iov1, &[], flags, Some(&sock_addr)).unwrap(); + sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); let mut data = super::MultiHeaders::<()>::preallocate(recv_iovs.len(), Some(cmsg)); let t = sys::time::TimeSpec::from_duration(std::time::Duration::from_secs(10)); - let recv = super::recvmmsg(rsock, &mut data, recv_iovs.iter(), flags, Some(t))?; + let recv = super::recvmmsg(rsock.as_raw_fd(), &mut data, recv_iovs.iter(), flags, Some(t))?; for rmsg in recv { #[cfg(not(any(qemu, target_arch = "aarch64")))] @@ -2091,7 +2094,7 @@ pub fn socket>>( ty: SockType, flags: SockFlag, protocol: T, -) -> Result { +) -> Result { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, @@ -2105,7 +2108,13 @@ pub fn socket>>( let res = unsafe { libc::socket(domain as c_int, ty, protocol) }; - Errno::result(res) + match res { + -1 => Err(Errno::last()), + fd => { + // Safe because libc::socket returned success + unsafe { Ok(OwnedFd::from_raw_fd(fd)) } + } + } } /// Create a pair of connected sockets @@ -2116,7 +2125,7 @@ pub fn socketpair>>( ty: SockType, protocol: T, flags: SockFlag, -) -> Result<(RawFd, RawFd)> { +) -> Result<(OwnedFd, OwnedFd)> { let protocol = match protocol.into() { None => 0, Some(p) => p as c_int, @@ -2135,14 +2144,18 @@ pub fn socketpair>>( }; Errno::result(res)?; - Ok((fds[0], fds[1])) + // Safe because socketpair returned success. + unsafe { + Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) + } } /// Listen for connections on a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html) -pub fn listen(sockfd: RawFd, backlog: usize) -> Result<()> { - let res = unsafe { libc::listen(sockfd, backlog as c_int) }; +pub fn listen(sock: &F, backlog: usize) -> Result<()> { + let fd = sock.as_fd().as_raw_fd(); + let res = unsafe { libc::listen(fd, backlog as c_int) }; Errno::result(res).map(drop) } @@ -2302,7 +2315,7 @@ pub trait GetSockOpt: Copy { type Val; /// Look up the value of this socket option on the given socket. - fn get(&self, fd: RawFd) -> Result; + fn get(&self, fd: &F) -> Result; } /// Represents a socket option that can be set. @@ -2310,13 +2323,13 @@ pub trait SetSockOpt: Clone { type Val; /// Set the value of this socket option on the given socket. - fn set(&self, fd: RawFd, val: &Self::Val) -> Result<()>; + fn set(&self, fd: &F, val: &Self::Val) -> Result<()>; } /// Get the current value for the requested socket option /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getsockopt.html) -pub fn getsockopt(fd: RawFd, opt: O) -> Result { +pub fn getsockopt(fd: &F, opt: O) -> Result { opt.get(fd) } @@ -2330,15 +2343,14 @@ pub fn getsockopt(fd: RawFd, opt: O) -> Result { /// use nix::sys::socket::setsockopt; /// use nix::sys::socket::sockopt::KeepAlive; /// use std::net::TcpListener; -/// use std::os::unix::io::AsRawFd; /// /// let listener = TcpListener::bind("0.0.0.0:0").unwrap(); -/// let fd = listener.as_raw_fd(); -/// let res = setsockopt(fd, KeepAlive, &true); +/// let fd = listener; +/// let res = setsockopt(&fd, KeepAlive, &true); /// assert!(res.is_ok()); /// ``` -pub fn setsockopt( - fd: RawFd, +pub fn setsockopt( + fd: &F, opt: O, val: &O::Val, ) -> Result<()> { diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index e4a22693c8..eec61dd416 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -9,7 +9,7 @@ use std::ffi::{OsStr, OsString}; use std::mem::{self, MaybeUninit}; #[cfg(target_family = "unix")] use std::os::unix::ffi::OsStrExt; -use std::os::unix::io::RawFd; +use std::os::unix::io::{AsFd, AsRawFd}; // Constants // TCP_CA_NAME_MAX isn't defined in user space include files @@ -44,12 +44,12 @@ macro_rules! setsockopt_impl { impl SetSockOpt for $name { type Val = $ty; - fn set(&self, fd: RawFd, val: &$ty) -> Result<()> { + fn set(&self, fd: &F, val: &$ty) -> Result<()> { unsafe { let setter: $setter = Set::new(val); let res = libc::setsockopt( - fd, + fd.as_fd().as_raw_fd(), $level, $flag, setter.ffi_ptr(), @@ -89,12 +89,12 @@ macro_rules! getsockopt_impl { impl GetSockOpt for $name { type Val = $ty; - fn get(&self, fd: RawFd) -> Result<$ty> { + fn get(&self, fd: &F) -> Result<$ty> { unsafe { let mut getter: $getter = Get::uninit(); let res = libc::getsockopt( - fd, + fd.as_fd().as_raw_fd(), $level, $flag, getter.ffi_ptr(), @@ -1033,10 +1033,10 @@ pub struct AlgSetAeadAuthSize; impl SetSockOpt for AlgSetAeadAuthSize { type Val = usize; - fn set(&self, fd: RawFd, val: &usize) -> Result<()> { + fn set(&self, fd: &F, val: &usize) -> Result<()> { unsafe { let res = libc::setsockopt( - fd, + fd.as_fd().as_raw_fd(), libc::SOL_ALG, libc::ALG_SET_AEAD_AUTHSIZE, ::std::ptr::null(), @@ -1067,10 +1067,10 @@ where { type Val = T; - fn set(&self, fd: RawFd, val: &T) -> Result<()> { + fn set(&self, fd: &F, val: &T) -> Result<()> { unsafe { let res = libc::setsockopt( - fd, + fd.as_fd().as_raw_fd(), libc::SOL_ALG, libc::ALG_SET_KEY, val.as_ref().as_ptr() as *const _, @@ -1383,8 +1383,8 @@ mod test { SockFlag::empty(), ) .unwrap(); - let a_cred = getsockopt(a, super::PeerCredentials).unwrap(); - let b_cred = getsockopt(b, super::PeerCredentials).unwrap(); + let a_cred = getsockopt(&a, super::PeerCredentials).unwrap(); + let b_cred = getsockopt(&b, super::PeerCredentials).unwrap(); assert_eq!(a_cred, b_cred); assert_ne!(a_cred.pid(), 0); } @@ -1392,25 +1392,21 @@ mod test { #[test] fn is_socket_type_unix() { use super::super::*; - use crate::unistd::close; - let (a, b) = socketpair( + let (a, _b) = socketpair( AddressFamily::Unix, SockType::Stream, None, SockFlag::empty(), ) .unwrap(); - let a_type = getsockopt(a, super::SockType).unwrap(); + let a_type = getsockopt(&a, super::SockType).unwrap(); assert_eq!(a_type, SockType::Stream); - close(a).unwrap(); - close(b).unwrap(); } #[test] fn is_socket_type_dgram() { use super::super::*; - use crate::unistd::close; let s = socket( AddressFamily::Inet, @@ -1419,16 +1415,14 @@ mod test { None, ) .unwrap(); - let s_type = getsockopt(s, super::SockType).unwrap(); + let s_type = getsockopt(&s, super::SockType).unwrap(); assert_eq!(s_type, SockType::Datagram); - close(s).unwrap(); } #[cfg(any(target_os = "freebsd", target_os = "linux"))] #[test] fn can_get_listen_on_tcp_socket() { use super::super::*; - use crate::unistd::close; let s = socket( AddressFamily::Inet, @@ -1437,11 +1431,10 @@ mod test { None, ) .unwrap(); - let s_listening = getsockopt(s, super::AcceptConn).unwrap(); + let s_listening = getsockopt(&s, super::AcceptConn).unwrap(); assert!(!s_listening); - listen(s, 10).unwrap(); - let s_listening2 = getsockopt(s, super::AcceptConn).unwrap(); + listen(&s, 10).unwrap(); + let s_listening2 = getsockopt(&s, super::AcceptConn).unwrap(); assert!(s_listening2); - close(s).unwrap(); } } diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 0759dc609a..f93a7339c3 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -5,7 +5,7 @@ use nix::sys::socket::{getsockname, AddressFamily, UnixAddr}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::net::{SocketAddrV4, SocketAddrV6}; -use std::os::unix::io::RawFd; +use std::os::unix::io::{AsRawFd, RawFd}; use std::path::Path; use std::slice; use std::str::FromStr; @@ -38,9 +38,9 @@ pub fn test_timestamping() { None, ) .unwrap(); - nix::sys::socket::bind(rsock, &sock_addr).unwrap(); + nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap(); - setsockopt(rsock, Timestamping, &TimestampingFlag::all()).unwrap(); + setsockopt(&rsock, Timestamping, &TimestampingFlag::all()).unwrap(); let sbuf = [0u8; 2048]; let mut rbuf = [0u8; 2048]; @@ -49,8 +49,10 @@ pub fn test_timestamping() { let mut iov2 = [IoSliceMut::new(&mut rbuf)]; let mut cmsg = cmsg_space!(nix::sys::socket::Timestamps); - sendmsg(ssock, &iov1, &[], flags, Some(&sock_addr)).unwrap(); - let recv = recvmsg::<()>(rsock, &mut iov2, Some(&mut cmsg), flags).unwrap(); + sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); + let recv = + recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags) + .unwrap(); let mut ts = None; for c in recv.cmsgs() { @@ -179,8 +181,11 @@ pub fn test_getsockname() { ) .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); - bind(sock, &sockaddr).expect("bind failed"); - assert_eq!(sockaddr, getsockname(sock).expect("getsockname failed")); + bind(sock.as_raw_fd(), &sockaddr).expect("bind failed"); + assert_eq!( + sockaddr, + getsockname(sock.as_raw_fd()).expect("getsockname failed") + ); } #[test] @@ -195,9 +200,9 @@ pub fn test_socketpair() { SockFlag::empty(), ) .unwrap(); - write(fd1, b"hello").unwrap(); + write(fd1.as_raw_fd(), b"hello").unwrap(); let mut buf = [0; 5]; - read(fd2, &mut buf).unwrap(); + read(fd2.as_raw_fd(), &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } @@ -218,12 +223,12 @@ pub fn test_recvmsg_sockaddr_un() { ) .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); - bind(sock, &sockaddr).expect("bind failed"); + bind(sock.as_raw_fd(), &sockaddr).expect("bind failed"); // Send a message let send_buffer = "hello".as_bytes(); if let Err(e) = socket::sendmsg( - sock, + sock.as_raw_fd(), &[std::io::IoSlice::new(send_buffer)], &[], MsgFlags::empty(), @@ -235,7 +240,7 @@ pub fn test_recvmsg_sockaddr_un() { // Receive the message let mut recv_buffer = [0u8; 32]; let received = socket::recvmsg( - sock, + sock.as_raw_fd(), &mut [std::io::IoSliceMut::new(&mut recv_buffer)], None, MsgFlags::empty(), @@ -308,7 +313,7 @@ mod recvfrom { ) .unwrap(); // Ignore from for stream sockets - let _ = sendrecv(fd1, fd2, send, |_, _| {}); + let _ = sendrecv(fd1.as_raw_fd(), fd2.as_raw_fd(), send, |_, _| {}); } #[test] @@ -322,7 +327,7 @@ mod recvfrom { None, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, @@ -331,9 +336,9 @@ mod recvfrom { ) .expect("send socket failed"); let from = sendrecv( - rsock, - ssock, - move |s, m, flags| sendto(s, m, &sock_addr, flags), + rsock.as_raw_fd(), + ssock.as_raw_fd(), + move |s, m, flags| sendto(s.as_raw_fd(), m, &sock_addr, flags), |_, _| {}, ); // UDP sockets should set the from address @@ -367,10 +372,10 @@ mod recvfrom { ) .unwrap(); - setsockopt(rsock, UdpGsoSegment, &(segment_size as _)) + setsockopt(&rsock, UdpGsoSegment, &(segment_size as _)) .expect("setsockopt UDP_SEGMENT failed"); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, @@ -382,12 +387,18 @@ mod recvfrom { let mut num_packets_received: i32 = 0; sendrecv( - rsock, - ssock, + rsock.as_raw_fd(), + ssock.as_raw_fd(), move |s, m, flags| { let iov = [IoSlice::new(m)]; let cmsg = ControlMessage::UdpGsoSegments(&segment_size); - sendmsg(s, &iov, &[cmsg], flags, Some(&sock_addr)) + sendmsg( + s.as_raw_fd(), + &iov, + &[cmsg], + flags, + Some(&sock_addr), + ) }, { let num_packets_received_ref = &mut num_packets_received; @@ -424,7 +435,7 @@ mod recvfrom { ) .unwrap(); - setsockopt(rsock, UdpGroSegment, &true) + setsockopt(&rsock, UdpGroSegment, &true) .expect("setsockopt UDP_GRO failed"); } } @@ -451,7 +462,7 @@ mod recvfrom { None, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, @@ -461,8 +472,8 @@ mod recvfrom { .expect("send socket failed"); let from = sendrecv( - rsock, - ssock, + rsock.as_raw_fd(), + ssock.as_raw_fd(), move |s, m, flags| { let batch_size = 15; let mut iovs = Vec::with_capacity(1 + batch_size); @@ -520,7 +531,7 @@ mod recvfrom { None, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, @@ -531,8 +542,13 @@ mod recvfrom { let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) - .unwrap(); + sendto( + ssock.as_raw_fd(), + &DATA[..], + &sock_addr, + MsgFlags::empty(), + ) + .unwrap(); } }); @@ -549,10 +565,15 @@ mod recvfrom { let mut data = MultiHeaders::::preallocate(msgs.len(), None); - let res: Vec> = - recvmmsg(rsock, &mut data, msgs.iter(), MsgFlags::empty(), None) - .expect("recvmmsg") - .collect(); + let res: Vec> = recvmmsg( + rsock.as_raw_fd(), + &mut data, + msgs.iter(), + MsgFlags::empty(), + None, + ) + .expect("recvmmsg") + .collect(); assert_eq!(res.len(), DATA.len()); for RecvMsg { address, bytes, .. } in res.into_iter() { @@ -591,7 +612,7 @@ mod recvfrom { None, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, @@ -602,8 +623,13 @@ mod recvfrom { let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) - .unwrap(); + sendto( + ssock.as_raw_fd(), + &DATA[..], + &sock_addr, + MsgFlags::empty(), + ) + .unwrap(); } }); // Ensure we've sent all the messages before continuing so `recvmmsg` @@ -628,7 +654,7 @@ mod recvfrom { ); let res: Vec> = recvmmsg( - rsock, + rsock.as_raw_fd(), &mut data, msgs.iter(), MsgFlags::MSG_DONTWAIT, @@ -664,7 +690,7 @@ mod recvfrom { None, ) .expect("receive socket failed"); - match bind(rsock, &raddr) { + match bind(rsock.as_raw_fd(), &raddr) { Err(Errno::EADDRNOTAVAIL) => { println!("IPv6 not available, skipping test."); return; @@ -679,11 +705,11 @@ mod recvfrom { None, ) .expect("send socket failed"); - bind(ssock, &saddr).unwrap(); + bind(ssock.as_raw_fd(), &saddr).unwrap(); let from = sendrecv( - rsock, - ssock, - move |s, m, flags| sendto(s, m, &raddr, flags), + rsock.as_raw_fd(), + ssock.as_raw_fd(), + move |s, m, flags| sendto(s.as_raw_fd(), m, &raddr, flags), |_, _| {}, ); assert_eq!(AddressFamily::Inet6, from.unwrap().family().unwrap()); @@ -705,7 +731,7 @@ pub fn test_recvmsg_ebadf() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let fd = -1; // Bad file descriptor - let r = recvmsg::<()>(fd, &mut iov, None, MsgFlags::empty()); + let r = recvmsg::<()>(fd.as_raw_fd(), &mut iov, None, MsgFlags::empty()); assert_eq!(r.err().unwrap(), Errno::EBADF); } @@ -737,11 +763,17 @@ pub fn test_scm_rights() { let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!( - sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), + sendmsg::<()>( + fd1.as_raw_fd(), + &iov, + &[cmsg], + MsgFlags::empty(), + None + ) + .unwrap(), 5 ); close(r).unwrap(); - close(fd1).unwrap(); } { @@ -750,7 +782,7 @@ pub fn test_scm_rights() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!([RawFd; 1]); let msg = recvmsg::<()>( - fd2, + fd2.as_raw_fd(), &mut iov, Some(&mut cmsgspace), MsgFlags::empty(), @@ -770,14 +802,13 @@ pub fn test_scm_rights() { assert!(!msg .flags .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); - close(fd2).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works - write(w, b"world").unwrap(); + write(w.as_raw_fd(), b"world").unwrap(); let mut buf = [0u8; 5]; - read(received_r, &mut buf).unwrap(); + read(received_r.as_raw_fd(), &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); @@ -821,25 +852,32 @@ pub fn test_af_alg_cipher() { .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); - bind(sock, &sockaddr).expect("bind failed"); + bind(sock.as_raw_fd(), &sockaddr).expect("bind failed"); assert_eq!(sockaddr.alg_name().to_string_lossy(), alg_name); assert_eq!(sockaddr.alg_type().to_string_lossy(), alg_type); - setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt"); - let session_socket = accept(sock).expect("accept failed"); + setsockopt(&sock, AlgSetKey::default(), &key).expect("setsockopt"); + let session_socket = accept(sock.as_raw_fd()).expect("accept failed"); let msgs = [ ControlMessage::AlgSetOp(&libc::ALG_OP_ENCRYPT), ControlMessage::AlgSetIv(iv.as_slice()), ]; let iov = IoSlice::new(&payload); - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) - .expect("sendmsg encrypt"); + sendmsg::<()>( + session_socket.as_raw_fd(), + &[iov], + &msgs, + MsgFlags::empty(), + None, + ) + .expect("sendmsg encrypt"); // allocate buffer for encrypted data let mut encrypted = vec![0u8; payload_len]; - let num_bytes = read(session_socket, &mut encrypted).expect("read encrypt"); + let num_bytes = + read(session_socket.as_raw_fd(), &mut encrypted).expect("read encrypt"); assert_eq!(num_bytes, payload_len); let iov = IoSlice::new(&encrypted); @@ -850,12 +888,19 @@ pub fn test_af_alg_cipher() { ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT), ControlMessage::AlgSetIv(iv.as_slice()), ]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) - .expect("sendmsg decrypt"); + sendmsg::<()>( + session_socket.as_raw_fd(), + &[iov], + &msgs, + MsgFlags::empty(), + None, + ) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data let mut decrypted = vec![0u8; payload_len]; - let num_bytes = read(session_socket, &mut decrypted).expect("read decrypt"); + let num_bytes = + read(session_socket.as_raw_fd(), &mut decrypted).expect("read decrypt"); assert_eq!(num_bytes, payload_len); assert_eq!(decrypted, payload); @@ -874,7 +919,7 @@ pub fn test_af_alg_aead() { accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr, ControlMessage, MsgFlags, SockFlag, SockType, }; - use nix::unistd::{close, read}; + use nix::unistd::read; use std::io::IoSlice; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1352"); @@ -916,12 +961,13 @@ pub fn test_af_alg_aead() { .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); - bind(sock, &sockaddr).expect("bind failed"); + bind(sock.as_raw_fd(), &sockaddr).expect("bind failed"); - setsockopt(sock, AlgSetAeadAuthSize, &auth_size) + setsockopt(&sock, AlgSetAeadAuthSize, &auth_size) .expect("setsockopt AlgSetAeadAuthSize"); - setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt AlgSetKey"); - let session_socket = accept(sock).expect("accept failed"); + setsockopt(&sock, AlgSetKey::default(), &key) + .expect("setsockopt AlgSetKey"); + let session_socket = accept(sock.as_raw_fd()).expect("accept failed"); let msgs = [ ControlMessage::AlgSetOp(&ALG_OP_ENCRYPT), @@ -930,15 +976,21 @@ pub fn test_af_alg_aead() { ]; let iov = IoSlice::new(&payload); - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) - .expect("sendmsg encrypt"); + sendmsg::<()>( + session_socket.as_raw_fd(), + &[iov], + &msgs, + MsgFlags::empty(), + None, + ) + .expect("sendmsg encrypt"); // allocate buffer for encrypted data let mut encrypted = vec![0u8; (assoc_size as usize) + payload_len + auth_size]; - let num_bytes = read(session_socket, &mut encrypted).expect("read encrypt"); + let num_bytes = + read(session_socket.as_raw_fd(), &mut encrypted).expect("read encrypt"); assert_eq!(num_bytes, payload_len + auth_size + (assoc_size as usize)); - close(session_socket).expect("close"); for i in 0..assoc_size { encrypted[i as usize] = 10; @@ -948,15 +1000,21 @@ pub fn test_af_alg_aead() { let iv = vec![1u8; iv_len]; - let session_socket = accept(sock).expect("accept failed"); + let session_socket = accept(sock.as_raw_fd()).expect("accept failed"); let msgs = [ ControlMessage::AlgSetOp(&ALG_OP_DECRYPT), ControlMessage::AlgSetIv(iv.as_slice()), ControlMessage::AlgSetAeadAssoclen(&assoc_size), ]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) - .expect("sendmsg decrypt"); + sendmsg::<()>( + session_socket.as_raw_fd(), + &[iov], + &msgs, + MsgFlags::empty(), + None, + ) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data let mut decrypted = @@ -967,7 +1025,8 @@ pub fn test_af_alg_aead() { // Do not block on read, as we may have fewer bytes than buffer size fcntl(session_socket, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)) .expect("fcntl non_blocking"); - let num_bytes = read(session_socket, &mut decrypted).expect("read decrypt"); + let num_bytes = + read(session_socket.as_raw_fd(), &mut decrypted).expect("read decrypt"); assert!(num_bytes >= payload_len + (assoc_size as usize)); assert_eq!( @@ -1003,7 +1062,7 @@ pub fn test_sendmsg_ipv4packetinfo() { let sock_addr = SockaddrIn::new(127, 0, 0, 1, 4000); - bind(sock, &sock_addr).expect("bind failed"); + bind(sock.as_raw_fd(), &sock_addr).expect("bind failed"); let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; let iov = [IoSlice::new(&slice)]; @@ -1025,8 +1084,14 @@ pub fn test_sendmsg_ipv4packetinfo() { let cmsg = [ControlMessage::Ipv4PacketInfo(&pi)]; - sendmsg(sock, &iov, &cmsg, MsgFlags::empty(), Some(&sock_addr)) - .expect("sendmsg"); + sendmsg( + sock.as_raw_fd(), + &iov, + &cmsg, + MsgFlags::empty(), + Some(&sock_addr), + ) + .expect("sendmsg"); } // Verify `ControlMessage::Ipv6PacketInfo` for `sendmsg`. @@ -1063,7 +1128,7 @@ pub fn test_sendmsg_ipv6packetinfo() { let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap(); let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa); - if let Err(Errno::EADDRNOTAVAIL) = bind(sock, &sock_addr) { + if let Err(Errno::EADDRNOTAVAIL) = bind(sock.as_raw_fd(), &sock_addr) { println!("IPv6 not available, skipping test."); return; } @@ -1079,7 +1144,7 @@ pub fn test_sendmsg_ipv6packetinfo() { let cmsg = [ControlMessage::Ipv6PacketInfo(&pi)]; sendmsg::( - sock, + sock.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), @@ -1119,8 +1184,8 @@ pub fn test_sendmsg_ipv4sendsrcaddr() { .expect("socket failed"); let unspec_sock_addr = SockaddrIn::new(0, 0, 0, 0, 0); - bind(sock, &unspec_sock_addr).expect("bind failed"); - let bound_sock_addr: SockaddrIn = getsockname(sock).unwrap(); + bind(sock.as_raw_fd(), &unspec_sock_addr).expect("bind failed"); + let bound_sock_addr: SockaddrIn = getsockname(sock.as_raw_fd()).unwrap(); let localhost_sock_addr: SockaddrIn = SockaddrIn::new(127, 0, 0, 1, bound_sock_addr.port()); @@ -1131,7 +1196,7 @@ pub fn test_sendmsg_ipv4sendsrcaddr() { )]; sendmsg( - sock, + sock.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), @@ -1208,7 +1273,6 @@ pub fn test_sendmsg_empty_cmsgs() { recvmsg, sendmsg, socketpair, AddressFamily, MsgFlags, SockFlag, SockType, }; - use nix::unistd::close; use std::io::{IoSlice, IoSliceMut}; let (fd1, fd2) = socketpair( @@ -1222,10 +1286,10 @@ pub fn test_sendmsg_empty_cmsgs() { { let iov = [IoSlice::new(b"hello")]; assert_eq!( - sendmsg::<()>(fd1, &iov, &[], MsgFlags::empty(), None).unwrap(), + sendmsg::<()>(fd1.as_raw_fd(), &iov, &[], MsgFlags::empty(), None) + .unwrap(), 5 ); - close(fd1).unwrap(); } { @@ -1234,7 +1298,7 @@ pub fn test_sendmsg_empty_cmsgs() { let mut cmsgspace = cmsg_space!([RawFd; 1]); let msg = recvmsg::<()>( - fd2, + fd2.as_raw_fd(), &mut iov, Some(&mut cmsgspace), MsgFlags::empty(), @@ -1248,7 +1312,6 @@ pub fn test_sendmsg_empty_cmsgs() { .flags .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); assert_eq!(msg.bytes, 5); - close(fd2).unwrap(); } } @@ -1266,7 +1329,7 @@ fn test_scm_credentials() { }; #[cfg(any(target_os = "android", target_os = "linux"))] use nix::sys::socket::{setsockopt, sockopt::PassCred}; - use nix::unistd::{close, getgid, getpid, getuid}; + use nix::unistd::{getgid, getpid, getuid}; use std::io::{IoSlice, IoSliceMut}; let (send, recv) = socketpair( @@ -1277,7 +1340,7 @@ fn test_scm_credentials() { ) .unwrap(); #[cfg(any(target_os = "android", target_os = "linux"))] - setsockopt(recv, PassCred, &true).unwrap(); + setsockopt(&recv, PassCred, &true).unwrap(); { let iov = [IoSlice::new(b"hello")]; @@ -1288,11 +1351,16 @@ fn test_scm_credentials() { #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] let cmsg = ControlMessage::ScmCreds; assert_eq!( - sendmsg::<()>(send, &iov, &[cmsg], MsgFlags::empty(), None) - .unwrap(), + sendmsg::<()>( + send.as_raw_fd(), + &iov, + &[cmsg], + MsgFlags::empty(), + None + ) + .unwrap(), 5 ); - close(send).unwrap(); } { @@ -1301,7 +1369,7 @@ fn test_scm_credentials() { let mut cmsgspace = cmsg_space!(UnixCredentials); let msg = recvmsg::<()>( - recv, + recv.as_raw_fd(), &mut iov, Some(&mut cmsgspace), MsgFlags::empty(), @@ -1328,7 +1396,6 @@ fn test_scm_credentials() { assert!(!msg .flags .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); - close(recv).unwrap(); } } @@ -1374,7 +1441,7 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { SockFlag::empty(), ) .unwrap(); - setsockopt(recv, PassCred, &true).unwrap(); + setsockopt(&recv, PassCred, &true).unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option = None; @@ -1393,19 +1460,29 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { ControlMessage::ScmRights(&fds), ]; assert_eq!( - sendmsg::<()>(send, &iov, &cmsgs, MsgFlags::empty(), None).unwrap(), + sendmsg::<()>( + send.as_raw_fd(), + &iov, + &cmsgs, + MsgFlags::empty(), + None + ) + .unwrap(), 5 ); close(r).unwrap(); - close(send).unwrap(); } { let mut buf = [0u8; 5]; let mut iov = [IoSliceMut::new(&mut buf[..])]; - let msg = - recvmsg::<()>(recv, &mut iov, Some(&mut space), MsgFlags::empty()) - .unwrap(); + let msg = recvmsg::<()>( + recv.as_raw_fd(), + &mut iov, + Some(&mut space), + MsgFlags::empty(), + ) + .unwrap(); let mut received_cred = None; assert_eq!(msg.cmsgs().count(), 2, "expected 2 cmsgs"); @@ -1432,14 +1509,13 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { assert!(!msg .flags .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); - close(recv).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works - write(w, b"world").unwrap(); + write(w.as_raw_fd(), b"world").unwrap(); let mut buf = [0u8; 5]; - read(received_r, &mut buf).unwrap(); + read(received_r.as_raw_fd(), &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); @@ -1450,7 +1526,7 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { pub fn test_named_unixdomain() { use nix::sys::socket::{accept, bind, connect, listen, socket, UnixAddr}; use nix::sys::socket::{SockFlag, SockType}; - use nix::unistd::{close, read, write}; + use nix::unistd::{read, write}; use std::thread; let tempdir = tempfile::tempdir().unwrap(); @@ -1463,8 +1539,8 @@ pub fn test_named_unixdomain() { ) .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); - bind(s1, &sockaddr).expect("bind failed"); - listen(s1, 10).expect("listen failed"); + bind(s1.as_raw_fd(), &sockaddr).expect("bind failed"); + listen(&s1, 10).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket( @@ -1474,17 +1550,14 @@ pub fn test_named_unixdomain() { None, ) .expect("socket failed"); - connect(s2, &sockaddr).expect("connect failed"); - write(s2, b"hello").expect("write failed"); - close(s2).unwrap(); + connect(s2.as_raw_fd(), &sockaddr).expect("connect failed"); + write(s2.as_raw_fd(), b"hello").expect("write failed"); }); - let s3 = accept(s1).expect("accept failed"); + let s3 = accept(s1.as_raw_fd()).expect("accept failed"); let mut buf = [0; 5]; - read(s3, &mut buf).unwrap(); - close(s3).unwrap(); - close(s1).unwrap(); + read(s3.as_raw_fd(), &mut buf).unwrap(); thr.join().unwrap(); assert_eq!(&buf[..], b"hello"); @@ -1496,9 +1569,8 @@ pub fn test_named_unixdomain() { pub fn test_unnamed_unixdomain() { use nix::sys::socket::{getsockname, socketpair}; use nix::sys::socket::{SockFlag, SockType}; - use nix::unistd::close; - let (fd_1, fd_2) = socketpair( + let (fd_1, _fd_2) = socketpair( AddressFamily::Unix, SockType::Stream, None, @@ -1506,11 +1578,9 @@ pub fn test_unnamed_unixdomain() { ) .expect("socketpair failed"); - let addr_1: UnixAddr = getsockname(fd_1).expect("getsockname failed"); + let addr_1: UnixAddr = + getsockname(fd_1.as_raw_fd()).expect("getsockname failed"); assert!(addr_1.is_unnamed()); - - close(fd_1).unwrap(); - close(fd_2).unwrap(); } // Test creating and using unnamed unix domain addresses for autobinding sockets @@ -1519,7 +1589,6 @@ pub fn test_unnamed_unixdomain() { pub fn test_unnamed_unixdomain_autobind() { use nix::sys::socket::{bind, getsockname, socket}; use nix::sys::socket::{SockFlag, SockType}; - use nix::unistd::close; let fd = socket( AddressFamily::Unix, @@ -1531,16 +1600,15 @@ pub fn test_unnamed_unixdomain_autobind() { // unix(7): "If a bind(2) call specifies addrlen as `sizeof(sa_family_t)`, or [...], then the // socket is autobound to an abstract address" - bind(fd, &UnixAddr::new_unnamed()).expect("bind failed"); + bind(fd.as_raw_fd(), &UnixAddr::new_unnamed()).expect("bind failed"); - let addr: UnixAddr = getsockname(fd).expect("getsockname failed"); + let addr: UnixAddr = + getsockname(fd.as_raw_fd()).expect("getsockname failed"); let addr = addr.as_abstract().unwrap(); // changed from 8 to 5 bytes in Linux 2.3.15, and rust's minimum supported Linux version is 3.2 // (as of 2022-11) assert_eq!(addr.len(), 5); - - close(fd).unwrap(); } // Test creating and using named system control sockets @@ -1559,15 +1627,15 @@ pub fn test_syscontrol() { SockProtocol::KextControl, ) .expect("socket failed"); - SysControlAddr::from_name(fd, "com.apple.net.utun_control", 0) + SysControlAddr::from_name(fd.as_raw_fd(), "com.apple.net.utun_control", 0) .expect("resolving sys_control name failed"); assert_eq!( - SysControlAddr::from_name(fd, "foo.bar.lol", 0).err(), + SysControlAddr::from_name(fd.as_raw_fd(), "foo.bar.lol", 0).err(), Some(Errno::ENOENT) ); // requires root privileges - // connect(fd, &sockaddr).expect("connect failed"); + // connect(fd.as_raw_fd(), &sockaddr).expect("connect failed"); } #[cfg(any( @@ -1648,9 +1716,10 @@ pub fn test_recv_ipv4pktinfo() { None, ) .expect("receive socket failed"); - bind(receive, &lo).expect("bind failed"); - let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv4PacketInfo, &true).expect("setsockopt failed"); + bind(receive.as_raw_fd(), &lo).expect("bind failed"); + let sa: SockaddrIn = + getsockname(receive.as_raw_fd()).expect("getsockname failed"); + setsockopt(&receive, Ipv4PacketInfo, &true).expect("setsockopt failed"); { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; @@ -1663,7 +1732,7 @@ pub fn test_recv_ipv4pktinfo() { None, ) .expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa)) .expect("sendmsg failed"); } @@ -1673,7 +1742,7 @@ pub fn test_recv_ipv4pktinfo() { let mut space = cmsg_space!(libc::in_pktinfo); let msg = recvmsg::<()>( - receive, + receive.as_raw_fd(), &mut iovec, Some(&mut space), MsgFlags::empty(), @@ -1742,11 +1811,12 @@ pub fn test_recvif() { None, ) .expect("receive socket failed"); - bind(receive, &lo).expect("bind failed"); - let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv4RecvIf, &true) + bind(receive.as_raw_fd(), &lo).expect("bind failed"); + let sa: SockaddrIn = + getsockname(receive.as_raw_fd()).expect("getsockname failed"); + setsockopt(&receive, Ipv4RecvIf, &true) .expect("setsockopt IP_RECVIF failed"); - setsockopt(receive, Ipv4RecvDstAddr, &true) + setsockopt(&receive, Ipv4RecvDstAddr, &true) .expect("setsockopt IP_RECVDSTADDR failed"); { @@ -1760,7 +1830,7 @@ pub fn test_recvif() { None, ) .expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa)) .expect("sendmsg failed"); } @@ -1769,7 +1839,7 @@ pub fn test_recvif() { let mut iovec = [IoSliceMut::new(&mut buf)]; let mut space = cmsg_space!(libc::sockaddr_dl, libc::in_addr); let msg = recvmsg::<()>( - receive, + receive.as_raw_fd(), &mut iovec, Some(&mut space), MsgFlags::empty(), @@ -1841,9 +1911,10 @@ pub fn test_recvif_ipv4() { None, ) .expect("receive socket failed"); - bind(receive, &lo).expect("bind failed"); - let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv4OrigDstAddr, &true) + bind(receive.as_raw_fd(), &lo).expect("bind failed"); + let sa: SockaddrIn = + getsockname(receive.as_raw_fd()).expect("getsockname failed"); + setsockopt(&receive, Ipv4OrigDstAddr, &true) .expect("setsockopt IP_ORIGDSTADDR failed"); { @@ -1857,7 +1928,7 @@ pub fn test_recvif_ipv4() { None, ) .expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa)) .expect("sendmsg failed"); } @@ -1866,7 +1937,7 @@ pub fn test_recvif_ipv4() { let mut iovec = [IoSliceMut::new(&mut buf)]; let mut space = cmsg_space!(libc::sockaddr_in); let msg = recvmsg::<()>( - receive, + receive.as_raw_fd(), &mut iovec, Some(&mut space), MsgFlags::empty(), @@ -1926,9 +1997,10 @@ pub fn test_recvif_ipv6() { None, ) .expect("receive socket failed"); - bind(receive, &lo).expect("bind failed"); - let sa: SockaddrIn6 = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv6OrigDstAddr, &true) + bind(receive.as_raw_fd(), &lo).expect("bind failed"); + let sa: SockaddrIn6 = + getsockname(receive.as_raw_fd()).expect("getsockname failed"); + setsockopt(&receive, Ipv6OrigDstAddr, &true) .expect("setsockopt IP_ORIGDSTADDR failed"); { @@ -1942,7 +2014,7 @@ pub fn test_recvif_ipv6() { None, ) .expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa)) .expect("sendmsg failed"); } @@ -1951,7 +2023,7 @@ pub fn test_recvif_ipv6() { let mut iovec = [IoSliceMut::new(&mut buf)]; let mut space = cmsg_space!(libc::sockaddr_in6); let msg = recvmsg::<()>( - receive, + receive.as_raw_fd(), &mut iovec, Some(&mut space), MsgFlags::empty(), @@ -2031,9 +2103,10 @@ pub fn test_recv_ipv6pktinfo() { None, ) .expect("receive socket failed"); - bind(receive, &lo).expect("bind failed"); - let sa: SockaddrIn6 = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv6RecvPacketInfo, &true).expect("setsockopt failed"); + bind(receive.as_raw_fd(), &lo).expect("bind failed"); + let sa: SockaddrIn6 = + getsockname(receive.as_raw_fd()).expect("getsockname failed"); + setsockopt(&receive, Ipv6RecvPacketInfo, &true).expect("setsockopt failed"); { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; @@ -2046,7 +2119,7 @@ pub fn test_recv_ipv6pktinfo() { None, ) .expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa)) .expect("sendmsg failed"); } @@ -2056,7 +2129,7 @@ pub fn test_recv_ipv6pktinfo() { let mut space = cmsg_space!(libc::in6_pktinfo); let msg = recvmsg::<()>( - receive, + receive.as_raw_fd(), &mut iovec, Some(&mut space), MsgFlags::empty(), @@ -2185,24 +2258,30 @@ fn test_recvmsg_timestampns() { None, ) .unwrap(); - setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); + setsockopt(&in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::new(127, 0, 0, 1, 0); - bind(in_socket, &localhost).unwrap(); - let address: SockaddrIn = getsockname(in_socket).unwrap(); + bind(in_socket.as_raw_fd(), &localhost).unwrap(); + let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap(); // Get initial time let time0 = SystemTime::now(); // Send the message let iov = [IoSlice::new(message)]; let flags = MsgFlags::empty(); - let l = sendmsg(in_socket, &iov, &[], flags, Some(&address)).unwrap(); + let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address)) + .unwrap(); assert_eq!(message.len(), l); // Receive the message let mut buffer = vec![0u8; message.len()]; let mut cmsgspace = nix::cmsg_space!(TimeSpec); let mut iov = [IoSliceMut::new(&mut buffer)]; - let r = recvmsg::<()>(in_socket, &mut iov, Some(&mut cmsgspace), flags) - .unwrap(); + let r = recvmsg::<()>( + in_socket.as_raw_fd(), + &mut iov, + Some(&mut cmsgspace), + flags, + ) + .unwrap(); let rtime = match r.cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), @@ -2216,8 +2295,6 @@ fn test_recvmsg_timestampns() { Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32); assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); - // Close socket - nix::unistd::close(in_socket).unwrap(); } // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack @@ -2240,16 +2317,17 @@ fn test_recvmmsg_timestampns() { None, ) .unwrap(); - setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); + setsockopt(&in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); - bind(in_socket, &localhost).unwrap(); - let address: SockaddrIn = getsockname(in_socket).unwrap(); + bind(in_socket.as_raw_fd(), &localhost).unwrap(); + let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap(); // Get initial time let time0 = SystemTime::now(); // Send the message let iov = [IoSlice::new(message)]; let flags = MsgFlags::empty(); - let l = sendmsg(in_socket, &iov, &[], flags, Some(&address)).unwrap(); + let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address)) + .unwrap(); assert_eq!(message.len(), l); // Receive the message let mut buffer = vec![0u8; message.len()]; @@ -2257,7 +2335,7 @@ fn test_recvmmsg_timestampns() { let iov = vec![[IoSliceMut::new(&mut buffer)]]; let mut data = MultiHeaders::preallocate(1, Some(cmsgspace)); let r: Vec> = - recvmmsg(in_socket, &mut data, iov.iter(), flags, None) + recvmmsg(in_socket.as_raw_fd(), &mut data, iov.iter(), flags, None) .unwrap() .collect(); let rtime = match r[0].cmsgs().next() { @@ -2273,8 +2351,6 @@ fn test_recvmmsg_timestampns() { Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32); assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration); assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap()); - // Close socket - nix::unistd::close(in_socket).unwrap(); } // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack @@ -2307,16 +2383,16 @@ fn test_recvmsg_rxq_ovfl() { .unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); - bind(in_socket, &localhost).unwrap(); + bind(in_socket.as_raw_fd(), &localhost).unwrap(); - let address: SockaddrIn = getsockname(in_socket).unwrap(); - connect(out_socket, &address).unwrap(); + let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap(); + connect(out_socket.as_raw_fd(), &address).unwrap(); // Set SO_RXQ_OVFL flag. - setsockopt(in_socket, RxqOvfl, &1).unwrap(); + setsockopt(&in_socket, RxqOvfl, &1).unwrap(); // Set the receiver buffer size to hold only 2 messages. - setsockopt(in_socket, RcvBuf, &bufsize).unwrap(); + setsockopt(&in_socket, RcvBuf, &bufsize).unwrap(); let mut drop_counter = 0; @@ -2327,8 +2403,14 @@ fn test_recvmsg_rxq_ovfl() { // Send the 3 messages (the receiver buffer can only hold 2 messages) // to create an overflow. for _ in 0..3 { - let l = - sendmsg(out_socket, &iov, &[], flags, Some(&address)).unwrap(); + let l = sendmsg( + out_socket.as_raw_fd(), + &iov, + &[], + flags, + Some(&address), + ) + .unwrap(); assert_eq!(message.len(), l); } @@ -2340,7 +2422,7 @@ fn test_recvmsg_rxq_ovfl() { let mut iov = [IoSliceMut::new(&mut buffer)]; match recvmsg::<()>( - in_socket, + in_socket.as_raw_fd(), &mut iov, Some(&mut cmsgspace), MsgFlags::MSG_DONTWAIT, @@ -2366,16 +2448,13 @@ fn test_recvmsg_rxq_ovfl() { // One packet lost. assert_eq!(drop_counter, 1); - - // Close sockets - nix::unistd::close(in_socket).unwrap(); - nix::unistd::close(out_socket).unwrap(); } #[cfg(any(target_os = "linux", target_os = "android",))] mod linux_errqueue { use super::FromStr; use nix::sys::socket::*; + use std::os::unix::io::AsRawFd; // Send a UDP datagram to a bogus destination address and observe an ICMP error (v4). // @@ -2496,9 +2575,9 @@ mod linux_errqueue { let sock_addr = SockaddrStorage::from(std_sa); let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None) .unwrap(); - setsockopt(sock, opt, &true).unwrap(); + setsockopt(&sock, opt, &true).unwrap(); if let Err(e) = sendto( - sock, + sock.as_raw_fd(), MESSAGE_CONTENTS.as_bytes(), &sock_addr, MsgFlags::empty(), @@ -2513,7 +2592,7 @@ mod linux_errqueue { let mut cspace = cmsg_space!(libc::sock_extended_err, SA); let msg = recvmsg( - sock, + sock.as_raw_fd(), &mut iovec, Some(&mut cspace), MsgFlags::MSG_ERRQUEUE, @@ -2576,7 +2655,7 @@ pub fn test_txtime() { clockid: libc::CLOCK_MONOTONIC, flags: 0, }; - setsockopt(ssock, sockopt::TxTime, &txtime_cfg).unwrap(); + setsockopt(&ssock, sockopt::TxTime, &txtime_cfg).unwrap(); let rsock = socket( AddressFamily::Inet, @@ -2585,7 +2664,7 @@ pub fn test_txtime() { None, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let sbuf = [0u8; 2048]; let iov1 = [std::io::IoSlice::new(&sbuf)]; @@ -2595,10 +2674,17 @@ pub fn test_txtime() { let txtime = (now + delay).num_nanoseconds() as u64; let cmsg = ControlMessage::TxTime(&txtime); - sendmsg(ssock, &iov1, &[cmsg], MsgFlags::empty(), Some(&sock_addr)) - .unwrap(); + sendmsg( + ssock.as_raw_fd(), + &iov1, + &[cmsg], + MsgFlags::empty(), + Some(&sock_addr), + ) + .unwrap(); let mut rbuf = [0u8; 2048]; let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)]; - recvmsg::<()>(rsock, &mut iov2, None, MsgFlags::empty()).unwrap(); + recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, None, MsgFlags::empty()) + .unwrap(); } diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index a498bdfa2c..0e34917325 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -5,6 +5,7 @@ use nix::sys::socket::{ SockProtocol, SockType, }; use rand::{thread_rng, Rng}; +use std::os::unix::io::AsRawFd; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. #[cfg(any(target_os = "dragonfly", target_os = "freebsd",))] @@ -22,7 +23,7 @@ pub fn test_local_peercred_seqpacket() { SockFlag::empty(), ) .unwrap(); - let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); + let xucred = getsockopt(&fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); assert_eq!(Gid::from_raw(xucred.groups()[0]), Gid::current()); @@ -48,7 +49,7 @@ pub fn test_local_peercred_stream() { SockFlag::empty(), ) .unwrap(); - let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); + let xucred = getsockopt(&fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); assert_eq!(Gid::from_raw(xucred.groups()[0]), Gid::current()); @@ -66,7 +67,7 @@ pub fn test_local_peer_pid() { SockFlag::empty(), ) .unwrap(); - let pid = getsockopt(fd1, sockopt::LocalPeerPid).unwrap(); + let pid = getsockopt(&fd1, sockopt::LocalPeerPid).unwrap(); assert_eq!(pid, std::process::id() as _); } @@ -84,8 +85,8 @@ fn is_so_mark_functional() { None, ) .unwrap(); - setsockopt(s, sockopt::Mark, &1337).unwrap(); - let mark = getsockopt(s, sockopt::Mark).unwrap(); + setsockopt(&s, sockopt::Mark, &1337).unwrap(); + let mark = getsockopt(&s, sockopt::Mark).unwrap(); assert_eq!(mark, 1337); } @@ -99,18 +100,18 @@ fn test_so_buf() { ) .unwrap(); let bufsize: usize = thread_rng().gen_range(4096..131_072); - setsockopt(fd, sockopt::SndBuf, &bufsize).unwrap(); - let actual = getsockopt(fd, sockopt::SndBuf).unwrap(); + setsockopt(&fd, sockopt::SndBuf, &bufsize).unwrap(); + let actual = getsockopt(&fd, sockopt::SndBuf).unwrap(); assert!(actual >= bufsize); - setsockopt(fd, sockopt::RcvBuf, &bufsize).unwrap(); - let actual = getsockopt(fd, sockopt::RcvBuf).unwrap(); + setsockopt(&fd, sockopt::RcvBuf, &bufsize).unwrap(); + let actual = getsockopt(&fd, sockopt::RcvBuf).unwrap(); assert!(actual >= bufsize); } #[test] fn test_so_tcp_maxseg() { use nix::sys::socket::{accept, bind, connect, listen, SockaddrIn}; - use nix::unistd::{close, write}; + use nix::unistd::write; use std::net::SocketAddrV4; use std::str::FromStr; @@ -124,9 +125,9 @@ fn test_so_tcp_maxseg() { SockProtocol::Tcp, ) .unwrap(); - bind(rsock, &sock_addr).unwrap(); - listen(rsock, 10).unwrap(); - let initial = getsockopt(rsock, sockopt::TcpMaxSeg).unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + listen(&rsock, 10).unwrap(); + let initial = getsockopt(&rsock, sockopt::TcpMaxSeg).unwrap(); // Initial MSS is expected to be 536 (https://tools.ietf.org/html/rfc879#section-1) but some // platforms keep it even lower. This might fail if you've tuned your initial MSS to be larger // than 700 @@ -134,7 +135,7 @@ fn test_so_tcp_maxseg() { if #[cfg(any(target_os = "android", target_os = "linux"))] { let segsize: u32 = 873; assert!(initial < segsize); - setsockopt(rsock, sockopt::TcpMaxSeg, &segsize).unwrap(); + setsockopt(&rsock, sockopt::TcpMaxSeg, &segsize).unwrap(); } else { assert!(initial < 700); } @@ -148,10 +149,10 @@ fn test_so_tcp_maxseg() { SockProtocol::Tcp, ) .unwrap(); - connect(ssock, &sock_addr).unwrap(); - let rsess = accept(rsock).unwrap(); + connect(ssock.as_raw_fd(), &sock_addr).unwrap(); + let rsess = accept(rsock.as_raw_fd()).unwrap(); write(rsess, b"hello").unwrap(); - let actual = getsockopt(ssock, sockopt::TcpMaxSeg).unwrap(); + let actual = getsockopt(&ssock, sockopt::TcpMaxSeg).unwrap(); // Actual max segment size takes header lengths into account, max IPv4 options (60 bytes) + max // TCP options (40 bytes) are subtracted from the requested maximum as a lower boundary. cfg_if! { @@ -163,8 +164,6 @@ fn test_so_tcp_maxseg() { assert!(536 < actual); } } - close(rsock).unwrap(); - close(ssock).unwrap(); } #[test] @@ -177,7 +176,7 @@ fn test_so_type() { ) .unwrap(); - assert_eq!(Ok(SockType::Stream), getsockopt(sockfd, sockopt::SockType)); + assert_eq!(Ok(SockType::Stream), getsockopt(&sockfd, sockopt::SockType)); } /// getsockopt(_, sockopt::SockType) should gracefully handle unknown socket @@ -186,12 +185,14 @@ fn test_so_type() { #[test] fn test_so_type_unknown() { use nix::errno::Errno; + use std::os::unix::io::{FromRawFd, OwnedFd}; require_capability!("test_so_type", CAP_NET_RAW); - let sockfd = unsafe { libc::socket(libc::AF_PACKET, libc::SOCK_PACKET, 0) }; - assert!(sockfd >= 0, "Error opening socket: {}", nix::Error::last()); + let raw_fd = unsafe { libc::socket(libc::AF_PACKET, libc::SOCK_PACKET, 0) }; + assert!(raw_fd >= 0, "Error opening socket: {}", nix::Error::last()); + let sockfd = unsafe { OwnedFd::from_raw_fd(raw_fd) }; - assert_eq!(Err(Errno::EINVAL), getsockopt(sockfd, sockopt::SockType)); + assert_eq!(Err(Errno::EINVAL), getsockopt(&sockfd, sockopt::SockType)); } // The CI doesn't supported getsockopt and setsockopt on emulated processors. @@ -214,17 +215,17 @@ fn test_tcp_congestion() { ) .unwrap(); - let val = getsockopt(fd, sockopt::TcpCongestion).unwrap(); - setsockopt(fd, sockopt::TcpCongestion, &val).unwrap(); + let val = getsockopt(&fd, sockopt::TcpCongestion).unwrap(); + setsockopt(&fd, sockopt::TcpCongestion, &val).unwrap(); setsockopt( - fd, + &fd, sockopt::TcpCongestion, &OsString::from("tcp_congestion_does_not_exist"), ) .unwrap_err(); - assert_eq!(getsockopt(fd, sockopt::TcpCongestion).unwrap(), val); + assert_eq!(getsockopt(&fd, sockopt::TcpCongestion).unwrap(), val); } #[test] @@ -240,10 +241,10 @@ fn test_bindtodevice() { ) .unwrap(); - let val = getsockopt(fd, sockopt::BindToDevice).unwrap(); - setsockopt(fd, sockopt::BindToDevice, &val).unwrap(); + let val = getsockopt(&fd, sockopt::BindToDevice).unwrap(); + setsockopt(&fd, sockopt::BindToDevice, &val).unwrap(); - assert_eq!(getsockopt(fd, sockopt::BindToDevice).unwrap(), val); + assert_eq!(getsockopt(&fd, sockopt::BindToDevice).unwrap(), val); } #[test] @@ -255,8 +256,8 @@ fn test_so_tcp_keepalive() { SockProtocol::Tcp, ) .unwrap(); - setsockopt(fd, sockopt::KeepAlive, &true).unwrap(); - assert!(getsockopt(fd, sockopt::KeepAlive).unwrap()); + setsockopt(&fd, sockopt::KeepAlive, &true).unwrap(); + assert!(getsockopt(&fd, sockopt::KeepAlive).unwrap()); #[cfg(any( target_os = "android", @@ -265,17 +266,17 @@ fn test_so_tcp_keepalive() { target_os = "linux" ))] { - let x = getsockopt(fd, sockopt::TcpKeepIdle).unwrap(); - setsockopt(fd, sockopt::TcpKeepIdle, &(x + 1)).unwrap(); - assert_eq!(getsockopt(fd, sockopt::TcpKeepIdle).unwrap(), x + 1); + let x = getsockopt(&fd, sockopt::TcpKeepIdle).unwrap(); + setsockopt(&fd, sockopt::TcpKeepIdle, &(x + 1)).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::TcpKeepIdle).unwrap(), x + 1); - let x = getsockopt(fd, sockopt::TcpKeepCount).unwrap(); - setsockopt(fd, sockopt::TcpKeepCount, &(x + 1)).unwrap(); - assert_eq!(getsockopt(fd, sockopt::TcpKeepCount).unwrap(), x + 1); + let x = getsockopt(&fd, sockopt::TcpKeepCount).unwrap(); + setsockopt(&fd, sockopt::TcpKeepCount, &(x + 1)).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::TcpKeepCount).unwrap(), x + 1); - let x = getsockopt(fd, sockopt::TcpKeepInterval).unwrap(); - setsockopt(fd, sockopt::TcpKeepInterval, &(x + 1)).unwrap(); - assert_eq!(getsockopt(fd, sockopt::TcpKeepInterval).unwrap(), x + 1); + let x = getsockopt(&fd, sockopt::TcpKeepInterval).unwrap(); + setsockopt(&fd, sockopt::TcpKeepInterval, &(x + 1)).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::TcpKeepInterval).unwrap(), x + 1); } } @@ -299,11 +300,11 @@ fn test_get_mtu() { .unwrap(); // Bind and initiate connection - bind(usock, &SockaddrIn::from(std_sa)).unwrap(); - connect(usock, &SockaddrIn::from(std_sb)).unwrap(); + bind(usock.as_raw_fd(), &SockaddrIn::from(std_sa)).unwrap(); + connect(usock.as_raw_fd(), &SockaddrIn::from(std_sb)).unwrap(); // Loopback connections have 2^16 - the maximum - MTU - assert_eq!(getsockopt(usock, sockopt::IpMtu), Ok(u16::MAX as i32)) + assert_eq!(getsockopt(&usock, sockopt::IpMtu), Ok(u16::MAX as i32)) } #[test] @@ -316,7 +317,7 @@ fn test_ttl_opts() { None, ) .unwrap(); - setsockopt(fd4, sockopt::Ipv4Ttl, &1) + setsockopt(&fd4, sockopt::Ipv4Ttl, &1) .expect("setting ipv4ttl on an inet socket should succeed"); let fd6 = socket( AddressFamily::Inet6, @@ -325,7 +326,7 @@ fn test_ttl_opts() { None, ) .unwrap(); - setsockopt(fd6, sockopt::Ipv6Ttl, &1) + setsockopt(&fd6, sockopt::Ipv6Ttl, &1) .expect("setting ipv6ttl on an inet6 socket should succeed"); } @@ -339,9 +340,9 @@ fn test_dontfrag_opts() { SockProtocol::Tcp, ) .unwrap(); - setsockopt(fd4, sockopt::IpDontFrag, &true) + setsockopt(&fd4, sockopt::IpDontFrag, &true) .expect("setting IP_DONTFRAG on an inet stream socket should succeed"); - setsockopt(fd4, sockopt::IpDontFrag, &false).expect( + setsockopt(&fd4, sockopt::IpDontFrag, &false).expect( "unsetting IP_DONTFRAG on an inet stream socket should succeed", ); let fd4d = socket( @@ -351,10 +352,10 @@ fn test_dontfrag_opts() { None, ) .unwrap(); - setsockopt(fd4d, sockopt::IpDontFrag, &true).expect( + setsockopt(&fd4d, sockopt::IpDontFrag, &true).expect( "setting IP_DONTFRAG on an inet datagram socket should succeed", ); - setsockopt(fd4d, sockopt::IpDontFrag, &false).expect( + setsockopt(&fd4d, sockopt::IpDontFrag, &false).expect( "unsetting IP_DONTFRAG on an inet datagram socket should succeed", ); } @@ -377,10 +378,10 @@ fn test_v6dontfrag_opts() { SockProtocol::Tcp, ) .unwrap(); - setsockopt(fd6, sockopt::Ipv6DontFrag, &true).expect( + setsockopt(&fd6, sockopt::Ipv6DontFrag, &true).expect( "setting IPV6_DONTFRAG on an inet6 stream socket should succeed", ); - setsockopt(fd6, sockopt::Ipv6DontFrag, &false).expect( + setsockopt(&fd6, sockopt::Ipv6DontFrag, &false).expect( "unsetting IPV6_DONTFRAG on an inet6 stream socket should succeed", ); let fd6d = socket( @@ -390,10 +391,10 @@ fn test_v6dontfrag_opts() { None, ) .unwrap(); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &true).expect( + setsockopt(&fd6d, sockopt::Ipv6DontFrag, &true).expect( "setting IPV6_DONTFRAG on an inet6 datagram socket should succeed", ); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &false).expect( + setsockopt(&fd6d, sockopt::Ipv6DontFrag, &false).expect( "unsetting IPV6_DONTFRAG on an inet6 datagram socket should succeed", ); } @@ -409,8 +410,8 @@ fn test_so_priority() { ) .unwrap(); let priority = 3; - setsockopt(fd, sockopt::Priority, &priority).unwrap(); - assert_eq!(getsockopt(fd, sockopt::Priority).unwrap(), priority); + setsockopt(&fd, sockopt::Priority, &priority).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::Priority).unwrap(), priority); } #[test] @@ -424,8 +425,8 @@ fn test_ip_tos() { ) .unwrap(); let tos = 0x80; // CS4 - setsockopt(fd, sockopt::IpTos, &tos).unwrap(); - assert_eq!(getsockopt(fd, sockopt::IpTos).unwrap(), tos); + setsockopt(&fd, sockopt::IpTos, &tos).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::IpTos).unwrap(), tos); } #[test] @@ -442,6 +443,6 @@ fn test_ipv6_tclass() { ) .unwrap(); let class = 0x80; // CS4 - setsockopt(fd, sockopt::Ipv6TClass, &class).unwrap(); - assert_eq!(getsockopt(fd, sockopt::Ipv6TClass).unwrap(), class); + setsockopt(&fd, sockopt::Ipv6TClass, &class).unwrap(); + assert_eq!(getsockopt(&fd, sockopt::Ipv6TClass).unwrap(), class); }