diff options
Diffstat (limited to 'test/sys')
-rw-r--r-- | test/sys/mod.rs | 48 | ||||
-rw-r--r-- | test/sys/test_aio.rs | 26 | ||||
-rw-r--r-- | test/sys/test_aio_drop.rs | 30 | ||||
-rw-r--r-- | test/sys/test_epoll.rs | 7 | ||||
-rw-r--r-- | test/sys/test_inotify.rs | 16 | ||||
-rw-r--r-- | test/sys/test_ioctl.rs | 83 | ||||
-rw-r--r-- | test/sys/test_mman.rs | 118 | ||||
-rw-r--r-- | test/sys/test_ptrace.rs | 127 | ||||
-rw-r--r-- | test/sys/test_select.rs | 5 | ||||
-rw-r--r-- | test/sys/test_signal.rs | 50 | ||||
-rw-r--r-- | test/sys/test_signalfd.rs | 2 | ||||
-rw-r--r-- | test/sys/test_socket.rs | 1050 | ||||
-rw-r--r-- | test/sys/test_sockopt.rs | 227 | ||||
-rw-r--r-- | test/sys/test_sysinfo.rs | 12 | ||||
-rw-r--r-- | test/sys/test_termios.rs | 26 | ||||
-rw-r--r-- | test/sys/test_timerfd.rs | 18 | ||||
-rw-r--r-- | test/sys/test_uio.rs | 98 | ||||
-rw-r--r-- | test/sys/test_wait.rs | 137 |
18 files changed, 1327 insertions, 753 deletions
diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 768d4d30..ed4ad736 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -5,43 +5,55 @@ mod test_signal; // works or not heavily depends on which pthread implementation is chosen // by the user at link time. For this reason we do not want to run aio test // cases on DragonFly. -#[cfg(any(target_os = "freebsd", - target_os = "ios", - all(target_os = "linux", not(target_env = "uclibc")), - target_os = "macos", - target_os = "netbsd"))] +#[cfg(any( + target_os = "freebsd", + target_os = "ios", + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + target_os = "netbsd" +))] mod test_aio; +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] +mod test_ioctl; #[cfg(not(target_os = "redox"))] mod test_mman; +#[cfg(not(target_os = "redox"))] +mod test_select; #[cfg(target_os = "linux")] mod test_signalfd; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] mod test_socket; #[cfg(not(any(target_os = "redox")))] mod test_sockopt; -#[cfg(not(target_os = "redox"))] -mod test_select; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_sysinfo; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] mod test_termios; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] -mod test_ioctl; -mod test_wait; mod test_uio; +mod test_wait; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_epoll; #[cfg(target_os = "linux")] mod test_inotify; mod test_pthread; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] mod test_ptrace; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_timerfd; diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index ca35b5f8..b4ea6757 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -4,8 +4,7 @@ use std::{ os::unix::io::AsRawFd, pin::Pin, sync::atomic::{AtomicBool, Ordering}, - thread, - time, + thread, time, }; use libc::c_int; @@ -14,12 +13,7 @@ use nix::{ sys::{ aio::*, signal::{ - sigaction, - SaFlags, - SigAction, - SigHandler, - SigSet, - SigevNotify, + sigaction, SaFlags, SigAction, SigHandler, SigSet, SigevNotify, Signal, }, time::{TimeSpec, TimeValLike}, @@ -58,7 +52,7 @@ mod aio_fsync { AioFsyncMode::O_SYNC, 42, SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 99, }, ); @@ -126,7 +120,7 @@ mod aio_read { &mut rbuf, 42, //priority SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 99, }, ); @@ -254,7 +248,7 @@ mod aio_readv { &mut rbufs, 42, //priority SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 99, }, ); @@ -314,7 +308,7 @@ mod aio_write { &wbuf, 42, //priority SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 99, }, ); @@ -455,7 +449,7 @@ mod aio_writev { &wbufs, 42, //priority SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 99, }, ); @@ -536,7 +530,7 @@ fn sigev_signal() { WBUF, 0, //priority SigevNotify::SigevSignal { - signal: Signal::SIGUSR2, + signal: Signal::SIGUSR2, si_value: 0, //TODO: validate in sigfunc }, )); @@ -624,8 +618,8 @@ fn test_aio_suspend() { Ok(_) => (), }; } - if rcb.as_mut().error() != Err(Errno::EINPROGRESS) && - wcb.as_mut().error() != Err(Errno::EINPROGRESS) + if rcb.as_mut().error() != Err(Errno::EINPROGRESS) + && wcb.as_mut().error() != Err(Errno::EINPROGRESS) { break; } diff --git a/test/sys/test_aio_drop.rs b/test/sys/test_aio_drop.rs index 0836a542..bbe6623f 100644 --- a/test/sys/test_aio_drop.rs +++ b/test/sys/test_aio_drop.rs @@ -3,13 +3,17 @@ // the AIO subsystem and causes subsequent tests to fail #[test] #[should_panic(expected = "Dropped an in-progress AioCb")] -#[cfg(all(not(target_env = "musl"), - not(target_env = "uclibc"), - any(target_os = "linux", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd")))] +#[cfg(all( + not(target_env = "musl"), + not(target_env = "uclibc"), + any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" + ) +))] fn test_drop() { use nix::sys::aio::*; use nix::sys::signal::*; @@ -20,10 +24,12 @@ fn test_drop() { let f = tempfile().unwrap(); f.set_len(6).unwrap(); - let mut aiocb = Box::pin(AioWrite::new(f.as_raw_fd(), - 2, //offset - WBUF, - 0, //priority - SigevNotify::SigevNone)); + let mut aiocb = Box::pin(AioWrite::new( + f.as_raw_fd(), + 2, //offset + WBUF, + 0, //priority + SigevNotify::SigevNone, + )); aiocb.as_mut().submit().unwrap(); } diff --git a/test/sys/test_epoll.rs b/test/sys/test_epoll.rs index 8d44cd08..fafbd749 100644 --- a/test/sys/test_epoll.rs +++ b/test/sys/test_epoll.rs @@ -1,6 +1,6 @@ -use nix::sys::epoll::{EpollCreateFlags, EpollFlags, EpollOp, EpollEvent}; -use nix::sys::epoll::{epoll_create1, epoll_ctl}; use nix::errno::Errno; +use nix::sys::epoll::{epoll_create1, epoll_ctl}; +use nix::sys::epoll::{EpollCreateFlags, EpollEvent, EpollFlags, EpollOp}; #[test] pub fn test_epoll_errno() { @@ -17,7 +17,8 @@ pub fn test_epoll_errno() { #[test] pub fn test_epoll_ctl() { let efd = epoll_create1(EpollCreateFlags::empty()).unwrap(); - let mut event = EpollEvent::new(EpollFlags::EPOLLIN | EpollFlags::EPOLLERR, 1); + let mut event = + EpollEvent::new(EpollFlags::EPOLLIN | EpollFlags::EPOLLERR, 1); epoll_ctl(efd, EpollOp::EpollCtlAdd, 1, &mut event).unwrap(); epoll_ctl(efd, EpollOp::EpollCtlDel, 1, None).unwrap(); } diff --git a/test/sys/test_inotify.rs b/test/sys/test_inotify.rs index 137816a3..bb5851a9 100644 --- a/test/sys/test_inotify.rs +++ b/test/sys/test_inotify.rs @@ -1,15 +1,16 @@ -use nix::sys::inotify::{AddWatchFlags,InitFlags,Inotify}; use nix::errno::Errno; +use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify}; use std::ffi::OsString; use std::fs::{rename, File}; #[test] pub fn test_inotify() { - let instance = Inotify::init(InitFlags::IN_NONBLOCK) - .unwrap(); + let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap(); let tempdir = tempfile::tempdir().unwrap(); - instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap(); + instance + .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS) + .unwrap(); let events = instance.read_events(); assert_eq!(events.unwrap_err(), Errno::EAGAIN); @@ -22,11 +23,12 @@ pub fn test_inotify() { #[test] pub fn test_inotify_multi_events() { - let instance = Inotify::init(InitFlags::IN_NONBLOCK) - .unwrap(); + let instance = Inotify::init(InitFlags::IN_NONBLOCK).unwrap(); let tempdir = tempfile::tempdir().unwrap(); - instance.add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS).unwrap(); + instance + .add_watch(tempdir.path(), AddWatchFlags::IN_ALL_EVENTS) + .unwrap(); let events = instance.read_events(); assert_eq!(events.unwrap_err(), Errno::EAGAIN); diff --git a/test/sys/test_ioctl.rs b/test/sys/test_ioctl.rs index 236d2426..7a603c5b 100644 --- a/test/sys/test_ioctl.rs +++ b/test/sys/test_ioctl.rs @@ -32,7 +32,12 @@ ioctl_readwrite_buf!(readwritebuf_test, 0, 0, u32); mod linux { #[test] fn test_op_none() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_none!(b'q', 10) as u32, 0x2000_710A); assert_eq!(request_code_none!(b'a', 255) as u32, 0x2000_61FF); } else { @@ -43,7 +48,12 @@ mod linux { #[test] fn test_op_write() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_write!(b'z', 10, 1) as u32, 0x8001_7A0A); assert_eq!(request_code_write!(b'z', 10, 512) as u32, 0x8200_7A0A); } else { @@ -55,19 +65,27 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ - assert_eq!(request_code_write!(b'z', 10, 1u64 << 32) as u32, - 0x8000_7A0A); + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + assert_eq!( + request_code_write!(b'z', 10, 1u64 << 32) as u32, + 0x8000_7A0A + ); } else { - assert_eq!(request_code_write!(b'z', 10, 1u64 << 32) as u32, - 0x4000_7A0A); + assert_eq!( + request_code_write!(b'z', 10, 1u64 << 32) as u32, + 0x4000_7A0A + ); } - } #[test] fn test_op_read() { - if cfg!(any(target_arch = "mips", target_arch = "mips64", target_arch="powerpc", target_arch="powerpc64")){ + if cfg!(any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc", + target_arch = "powerpc64" + )) { assert_eq!(request_code_read!(b'z', 10, 1) as u32, 0x4001_7A0A); assert_eq!(request_code_read!(b'z', 10, 512) as u32, 0x4200_7A0A); } else { @@ -79,12 +97,16 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { - if cfg!(any(target_arch = "mips64", target_arch="powerpc64")){ - assert_eq!(request_code_read!(b'z', 10, 1u64 << 32) as u32, - 0x4000_7A0A); + if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + assert_eq!( + request_code_read!(b'z', 10, 1u64 << 32) as u32, + 0x4000_7A0A + ); } else { - assert_eq!(request_code_read!(b'z', 10, 1u64 << 32) as u32, - 0x8000_7A0A); + assert_eq!( + request_code_read!(b'z', 10, 1u64 << 32) as u32, + 0x8000_7A0A + ); } } @@ -97,17 +119,21 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_write_64() { - assert_eq!(request_code_readwrite!(b'z', 10, 1u64 << 32) as u32, - 0xC000_7A0A); + assert_eq!( + request_code_readwrite!(b'z', 10, 1u64 << 32) as u32, + 0xC000_7A0A + ); } } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] mod bsd { #[test] fn test_op_none() { @@ -164,8 +190,8 @@ mod linux_ioctls { use std::mem; use std::os::unix::io::AsRawFd; + use libc::{termios, TCGETS, TCSBRK, TCSETS, TIOCNXCL}; use tempfile::tempfile; - use libc::{TCGETS, TCSBRK, TCSETS, TIOCNXCL, termios}; use nix::errno::Errno; @@ -255,7 +281,7 @@ mod linux_ioctls { } // From linux/videodev2.h - ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); + ioctl_readwrite!(enum_audio, b'V', 65, v4l2_audio); #[test] fn test_ioctl_readwrite() { let file = tempfile().unwrap(); @@ -281,7 +307,12 @@ mod linux_ioctls { } // From linux/spi/spidev.h - ioctl_write_buf!(spi_ioc_message, super::SPI_IOC_MAGIC, super::SPI_IOC_MESSAGE, spi_ioc_transfer); + ioctl_write_buf!( + spi_ioc_message, + super::SPI_IOC_MAGIC, + super::SPI_IOC_MESSAGE, + spi_ioc_transfer + ); #[test] fn test_ioctl_write_buf() { let file = tempfile().unwrap(); @@ -298,8 +329,8 @@ mod freebsd_ioctls { use std::mem; use std::os::unix::io::AsRawFd; - use tempfile::tempfile; use libc::termios; + use tempfile::tempfile; use nix::errno::Errno; diff --git a/test/sys/test_mman.rs b/test/sys/test_mman.rs index 8858375a..75cbf6ce 100644 --- a/test/sys/test_mman.rs +++ b/test/sys/test_mman.rs @@ -3,53 +3,73 @@ use nix::sys::mman::{mmap, MapFlags, ProtFlags}; #[test] fn test_mmap_anonymous() { unsafe { - let ptr = mmap(std::ptr::null_mut(), 1, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, -1, 0) - .unwrap() as *mut u8; - assert_eq !(*ptr, 0x00u8); + let ptr = mmap( + std::ptr::null_mut(), + 1, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, + -1, + 0, + ) + .unwrap() as *mut u8; + assert_eq!(*ptr, 0x00u8); *ptr = 0xffu8; - assert_eq !(*ptr, 0xffu8); + assert_eq!(*ptr, 0xffu8); } } #[test] #[cfg(any(target_os = "linux", target_os = "netbsd"))] fn test_mremap_grow() { - use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; + use nix::sys::mman::{mremap, MRemapFlags}; - const ONE_K : size_t = 1024; - let slice : &mut[u8] = unsafe { - let mem = mmap(std::ptr::null_mut(), ONE_K, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + const ONE_K: size_t = 1024; + let slice: &mut [u8] = unsafe { + let mem = mmap( + std::ptr::null_mut(), + ONE_K, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, + -1, + 0, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; - assert_eq !(slice[ONE_K - 1], 0x00); + assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); - let slice : &mut[u8] = unsafe { + let slice: &mut [u8] = unsafe { #[cfg(target_os = "linux")] - let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, - MRemapFlags::MREMAP_MAYMOVE, None) - .unwrap(); + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + ONE_K, + 10 * ONE_K, + MRemapFlags::MREMAP_MAYMOVE, + None, + ) + .unwrap(); #[cfg(target_os = "netbsd")] - let mem = mremap(slice.as_mut_ptr() as * mut c_void, ONE_K, 10 * ONE_K, - MRemapFlags::MAP_REMAPDUP, None) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, 10 * ONE_K) + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + ONE_K, + 10 * ONE_K, + MRemapFlags::MAP_REMAPDUP, + None, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, 10 * ONE_K) }; // The first KB should still have the old data in it. - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); // The additional range should be zero-init'd and accessible. - assert_eq !(slice[10 * ONE_K - 1], 0x00); + assert_eq!(slice[10 * ONE_K - 1], 0x00); slice[10 * ONE_K - 1] = 0xFF; - assert_eq !(slice[10 * ONE_K - 1], 0xFF); + assert_eq!(slice[10 * ONE_K - 1], 0xFF); } #[test] @@ -57,31 +77,41 @@ fn test_mremap_grow() { // Segfaults for unknown reasons under QEMU for 32-bit targets #[cfg_attr(all(target_pointer_width = "32", qemu), ignore)] fn test_mremap_shrink() { - use nix::sys::mman::{mremap, MRemapFlags}; use nix::libc::{c_void, size_t}; + use nix::sys::mman::{mremap, MRemapFlags}; - const ONE_K : size_t = 1024; - let slice : &mut[u8] = unsafe { - let mem = mmap(std::ptr::null_mut(), 10 * ONE_K, - ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, -1, 0) - .unwrap(); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + const ONE_K: size_t = 1024; + let slice: &mut [u8] = unsafe { + let mem = mmap( + std::ptr::null_mut(), + 10 * ONE_K, + ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, + MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, + -1, + 0, + ) + .unwrap(); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; - assert_eq !(slice[ONE_K - 1], 0x00); + assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); - let slice : &mut[u8] = unsafe { - let mem = mremap(slice.as_mut_ptr() as * mut c_void, 10 * ONE_K, ONE_K, - MRemapFlags::empty(), None) - .unwrap(); + let slice: &mut [u8] = unsafe { + let mem = mremap( + slice.as_mut_ptr() as *mut c_void, + 10 * ONE_K, + ONE_K, + MRemapFlags::empty(), + None, + ) + .unwrap(); // Since we didn't supply MREMAP_MAYMOVE, the address should be the // same. - assert_eq !(mem, slice.as_mut_ptr() as * mut c_void); - std::slice::from_raw_parts_mut(mem as * mut u8, ONE_K) + assert_eq!(mem, slice.as_mut_ptr() as *mut c_void); + std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; // The first KB should still be accessible and have the old data in it. - assert_eq !(slice[ONE_K - 1], 0xFF); + assert_eq!(slice[ONE_K - 1], 0xFF); } diff --git a/test/sys/test_ptrace.rs b/test/sys/test_ptrace.rs index 8556a548..e514832b 100644 --- a/test/sys/test_ptrace.rs +++ b/test/sys/test_ptrace.rs @@ -1,13 +1,14 @@ -#[cfg(all(target_os = "linux", - any(target_arch = "x86_64", - target_arch = "x86"), - target_env = "gnu"))] +#[cfg(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "x86"), + target_env = "gnu" +))] use memoffset::offset_of; use nix::errno::Errno; -use nix::unistd::getpid; use nix::sys::ptrace; #[cfg(any(target_os = "android", target_os = "linux"))] use nix::sys::ptrace::Options; +use nix::unistd::getpid; #[cfg(any(target_os = "android", target_os = "linux"))] use std::mem; @@ -20,8 +21,9 @@ fn test_ptrace() { // FIXME: qemu-user doesn't implement ptrace on all arches, so permit ENOSYS require_capability!("test_ptrace", CAP_SYS_PTRACE); let err = ptrace::attach(getpid()).unwrap_err(); - assert!(err == Errno::EPERM || err == Errno::EINVAL || - err == Errno::ENOSYS); + assert!( + err == Errno::EPERM || err == Errno::EINVAL || err == Errno::ENOSYS + ); } // Just make sure ptrace_setoptions can be called at all, for now. @@ -29,7 +31,8 @@ fn test_ptrace() { #[cfg(any(target_os = "android", target_os = "linux"))] fn test_ptrace_setoptions() { require_capability!("test_ptrace_setoptions", CAP_SYS_PTRACE); - let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD).unwrap_err(); + let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD) + .unwrap_err(); assert!(err != Errno::EOPNOTSUPP); } @@ -63,7 +66,6 @@ fn test_ptrace_setsiginfo() { } } - #[test] fn test_ptrace_cont() { use nix::sys::ptrace; @@ -87,7 +89,7 @@ fn test_ptrace_cont() { return; } - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => { ptrace::traceme().unwrap(); // As recommended by ptrace(2), raise SIGTRAP to pause the child @@ -95,15 +97,22 @@ fn test_ptrace_cont() { loop { raise(Signal::SIGTRAP).unwrap(); } - - }, + } Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTRAP)) + ); ptrace::cont(child, Some(Signal::SIGKILL)).unwrap(); match waitpid(child, None) { - Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) if pid == child => { + Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) + if pid == child => + { // FIXME It's been observed on some systems (apple) the // tracee may not be killed but remain as a zombie process // affecting other wait based tests. Add an extra kill just @@ -115,7 +124,7 @@ fn test_ptrace_cont() { } _ => panic!("The process should have been killed"), } - }, + } } } @@ -134,22 +143,28 @@ fn test_ptrace_interrupt() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - loop { - sleep(Duration::from_millis(1000)); - } - + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => loop { + sleep(Duration::from_millis(1000)); }, Parent { child } => { - ptrace::seize(child, ptrace::Options::PTRACE_O_TRACESYSGOOD).unwrap(); + ptrace::seize(child, ptrace::Options::PTRACE_O_TRACESYSGOOD) + .unwrap(); ptrace::interrupt(child).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceEvent(child, Signal::SIGTRAP, 128))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceEvent(child, Signal::SIGTRAP, 128)) + ); ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); ptrace::detach(child, Some(Signal::SIGKILL)).unwrap(); match waitpid(child, None) { - Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) if pid == child => { + Ok(WaitStatus::Signaled(pid, Signal::SIGKILL, _)) + if pid == child => + { let _ = waitpid(child, Some(WaitPidFlag::WNOHANG)); while ptrace::cont(child, Some(Signal::SIGKILL)).is_ok() { let _ = waitpid(child, Some(WaitPidFlag::WNOHANG)); @@ -157,19 +172,20 @@ fn test_ptrace_interrupt() { } _ => panic!("The process should have been killed"), } - }, + } } } // ptrace::{setoptions, getregs} are only available in these platforms -#[cfg(all(target_os = "linux", - any(target_arch = "x86_64", - target_arch = "x86"), - target_env = "gnu"))] +#[cfg(all( + target_os = "linux", + any(target_arch = "x86_64", target_arch = "x86"), + target_env = "gnu" +))] #[test] fn test_ptrace_syscall() { - use nix::sys::signal::kill; use nix::sys::ptrace; + use nix::sys::signal::kill; use nix::sys::signal::Signal; use nix::sys::wait::{waitpid, WaitStatus}; use nix::unistd::fork; @@ -180,27 +196,35 @@ fn test_ptrace_syscall() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => { ptrace::traceme().unwrap(); // first sigstop until parent is ready to continue let pid = getpid(); kill(pid, Signal::SIGSTOP).unwrap(); kill(pid, Signal::SIGTERM).unwrap(); - unsafe { ::libc::_exit(0); } - }, + unsafe { + ::libc::_exit(0); + } + } Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGSTOP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGSTOP)) + ); // set this option to recognize syscall-stops - ptrace::setoptions(child, ptrace::Options::PTRACE_O_TRACESYSGOOD).unwrap(); + ptrace::setoptions(child, ptrace::Options::PTRACE_O_TRACESYSGOOD) + .unwrap(); #[cfg(target_arch = "x86_64")] - let get_syscall_id = || ptrace::getregs(child).unwrap().orig_rax as libc::c_long; + let get_syscall_id = + || ptrace::getregs(child).unwrap().orig_rax as libc::c_long; #[cfg(target_arch = "x86")] - let get_syscall_id = || ptrace::getregs(child).unwrap().orig_eax as libc::c_long; + let get_syscall_id = + || ptrace::getregs(child).unwrap().orig_eax as libc::c_long; // this duplicates `get_syscall_id` for the purpose of testing `ptrace::read_user`. #[cfg(target_arch = "x86_64")] @@ -211,28 +235,41 @@ fn test_ptrace_syscall() { let get_syscall_from_user_area = || { // Find the offset of `user.regs.rax` (or `user.regs.eax` for x86) let rax_offset = offset_of!(libc::user, regs) + rax_offset; - ptrace::read_user(child, rax_offset as _).unwrap() as libc::c_long + ptrace::read_user(child, rax_offset as _).unwrap() + as libc::c_long }; // kill entry ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); assert_eq!(get_syscall_id(), ::libc::SYS_kill); assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill); // kill exit ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceSyscall(child)) + ); assert_eq!(get_syscall_id(), ::libc::SYS_kill); assert_eq!(get_syscall_from_user_area(), ::libc::SYS_kill); // receive signal ptrace::syscall(child, None).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, Signal::SIGTERM))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, Signal::SIGTERM)) + ); // inject signal ptrace::syscall(child, Signal::SIGTERM).unwrap(); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, Signal::SIGTERM, false))); - }, + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Signaled(child, Signal::SIGTERM, false)) + ); + } } } diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index 2f7396b1..40bda4d9 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -1,7 +1,7 @@ use nix::sys::select::*; -use nix::unistd::{pipe, write}; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; +use nix::unistd::{pipe, write}; #[test] pub fn test_pselect() { @@ -45,7 +45,8 @@ pub fn test_pselect_nfds2() { None, &timeout, None - ).unwrap() + ) + .unwrap() ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index fdd2568d..3ad14f40 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -52,9 +52,12 @@ fn test_sigprocmask() { // Make sure the old set doesn't contain the signal, otherwise the following // test don't make sense. - assert!(!old_signal_set.contains(SIGNAL), - "the {:?} signal is already blocked, please change to a \ - different one", SIGNAL); + assert!( + !old_signal_set.contains(SIGNAL), + "the {:?} signal is already blocked, please change to a \ + different one", + SIGNAL + ); // Now block the signal. let mut signal_set = SigSet::empty(); @@ -66,8 +69,11 @@ fn test_sigprocmask() { old_signal_set.clear(); sigprocmask(SigmaskHow::SIG_BLOCK, None, Some(&mut old_signal_set)) .expect("expect to be able to retrieve old signals"); - assert!(old_signal_set.contains(SIGNAL), - "expected the {:?} to be blocked", SIGNAL); + assert!( + old_signal_set.contains(SIGNAL), + "expected the {:?} to be blocked", + SIGNAL + ); // Reset the signal. sigprocmask(SigmaskHow::SIG_UNBLOCK, Some(&signal_set), None) @@ -78,13 +84,18 @@ lazy_static! { static ref SIGNALED: AtomicBool = AtomicBool::new(false); } -extern fn test_sigaction_handler(signal: libc::c_int) { +extern "C" fn test_sigaction_handler(signal: libc::c_int) { let signal = Signal::try_from(signal).unwrap(); SIGNALED.store(signal == Signal::SIGINT, Ordering::Relaxed); } #[cfg(not(target_os = "redox"))] -extern fn test_sigaction_action(_: libc::c_int, _: *mut libc::siginfo_t, _: *mut libc::c_void) {} +extern "C" fn test_sigaction_action( + _: libc::c_int, + _: *mut libc::siginfo_t, + _: *mut libc::c_void, +) { +} #[test] #[cfg(not(target_os = "redox"))] @@ -92,7 +103,10 @@ fn test_signal_sigaction() { let _m = crate::SIGNAL_MTX.lock(); let action_handler = SigHandler::SigAction(test_sigaction_action); - assert_eq!(unsafe { signal(Signal::SIGINT, action_handler) }.unwrap_err(), Errno::ENOTSUP); + assert_eq!( + unsafe { signal(Signal::SIGINT, action_handler) }.unwrap_err(), + Errno::ENOTSUP + ); } #[test] @@ -101,20 +115,32 @@ fn test_signal() { unsafe { signal(Signal::SIGINT, SigHandler::SigIgn) }.unwrap(); raise(Signal::SIGINT).unwrap(); - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), SigHandler::SigIgn); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + SigHandler::SigIgn + ); let handler = SigHandler::Handler(test_sigaction_handler); - assert_eq!(unsafe { signal(Signal::SIGINT, handler) }.unwrap(), SigHandler::SigDfl); + assert_eq!( + unsafe { signal(Signal::SIGINT, handler) }.unwrap(), + SigHandler::SigDfl + ); raise(Signal::SIGINT).unwrap(); assert!(SIGNALED.load(Ordering::Relaxed)); #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), handler); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + handler + ); // System V based OSes (e.g. illumos and Solaris) always resets the // disposition to SIG_DFL prior to calling the signal handler #[cfg(any(target_os = "illumos", target_os = "solaris"))] - assert_eq!(unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), SigHandler::SigDfl); + assert_eq!( + unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), + SigHandler::SigDfl + ); // Restore default signal handler unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(); diff --git a/test/sys/test_signalfd.rs b/test/sys/test_signalfd.rs index b6f748b4..87153c95 100644 --- a/test/sys/test_signalfd.rs +++ b/test/sys/test_signalfd.rs @@ -2,8 +2,8 @@ use std::convert::TryFrom; #[test] fn test_signalfd() { + use nix::sys::signal::{self, raise, SigSet, Signal}; use nix::sys::signalfd::SignalFd; - use nix::sys::signal::{self, raise, Signal, SigSet}; // Grab the mutex for altering signals so we don't interfere with other tests. let _m = crate::SIGNAL_MTX.lock(); diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index c742960a..067717bb 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1,7 +1,11 @@ +#[cfg(any(target_os = "linux", target_os = "android"))] +use crate::*; +use libc::{c_char, sockaddr_storage}; #[allow(deprecated)] use nix::sys::socket::InetAddr; -use nix::sys::socket::{AddressFamily, - UnixAddr, getsockname, sockaddr, sockaddr_in6}; +use nix::sys::socket::{ + getsockname, sockaddr, sockaddr_in6, AddressFamily, UnixAddr, +}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::mem::{self, MaybeUninit}; @@ -10,9 +14,6 @@ use std::os::unix::io::RawFd; use std::path::Path; use std::slice; use std::str::FromStr; -use libc::{c_char, sockaddr_storage}; -#[cfg(any(target_os = "linux", target_os= "android"))] -use crate::*; #[allow(deprecated)] #[test] @@ -41,7 +42,7 @@ pub fn test_inetv4_addr_to_sock_addr() { #[allow(deprecated)] #[test] pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { - use nix::sys::socket::{SockAddr, sockaddr_storage_to_addr}; + use nix::sys::socket::{sockaddr_storage_to_addr, SockAddr}; let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); @@ -58,9 +59,12 @@ pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { } }; - let from_storage = sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); assert_eq!(from_storage, sockaddr); - let from_storage = sockaddr_storage_to_addr(&storage, mem::size_of::<sockaddr_storage>()).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, mem::size_of::<sockaddr_storage>()) + .unwrap(); assert_eq!(from_storage, sockaddr); } @@ -69,8 +73,9 @@ pub fn test_inetv4_addr_roundtrip_sockaddr_storage_to_addr() { #[test] pub fn test_timestamping() { use nix::sys::socket::{ - recvmsg, sendmsg, setsockopt, socket, sockopt::Timestamping, ControlMessageOwned, MsgFlags, - SockaddrIn, SockFlag, SockType, TimestampingFlag, + recvmsg, sendmsg, setsockopt, socket, sockopt::Timestamping, + ControlMessageOwned, MsgFlags, SockFlag, SockType, SockaddrIn, + TimestampingFlag, }; use std::io::{IoSlice, IoSliceMut}; @@ -112,7 +117,9 @@ pub fn test_timestamping() { } } let ts = ts.expect("ScmTimestampns is present"); - let sys_time = ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME).unwrap(); + let sys_time = + ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME) + .unwrap(); let diff = if ts > sys_time { ts - sys_time } else { @@ -124,14 +131,15 @@ pub fn test_timestamping() { #[allow(deprecated)] #[test] pub fn test_inetv6_addr_roundtrip_sockaddr_storage_to_addr() { - use nix::sys::socket::{SockAddr, sockaddr_storage_to_addr}; + use nix::sys::socket::{sockaddr_storage_to_addr, SockAddr}; let port: u16 = 3000; let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); - let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); + let actual = + SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); let sockaddr = SockAddr::new_inet(addr); @@ -141,14 +149,20 @@ pub fn test_inetv6_addr_roundtrip_sockaddr_storage_to_addr() { let (ffi_ptr, ffi_size) = sockaddr.as_ffi_pair(); assert_eq!(mem::size_of::<sockaddr_in6>(), ffi_size as usize); unsafe { - storage_ptr.copy_from_nonoverlapping((ffi_ptr as *const sockaddr).cast::<sockaddr_in6>(), 1); + storage_ptr.copy_from_nonoverlapping( + (ffi_ptr as *const sockaddr).cast::<sockaddr_in6>(), + 1, + ); (storage.assume_init(), ffi_size) } }; - let from_storage = sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, ffi_size as usize).unwrap(); assert_eq!(from_storage, sockaddr); - let from_storage = sockaddr_storage_to_addr(&storage, mem::size_of::<sockaddr_storage>()).unwrap(); + let from_storage = + sockaddr_storage_to_addr(&storage, mem::size_of::<sockaddr_storage>()) + .unwrap(); assert_eq!(from_storage, sockaddr); } @@ -220,7 +234,8 @@ pub fn test_abstract_uds_addr() { let name = String::from("nix\0abstract\0test"); let addr = UnixAddr::new_abstract(name.as_bytes()).unwrap(); let sun_path = [ - 110u8, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101, 115, 116 + 110u8, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101, + 115, 116, ]; assert_eq!(addr.as_abstract(), Some(&sun_path[..])); assert_eq!(addr.path(), None); @@ -231,13 +246,18 @@ pub fn test_abstract_uds_addr() { #[test] pub fn test_getsockname() { - use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::bind; + use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType}; let tempdir = tempfile::tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr, getsockname(sock).expect("getsockname failed")); @@ -245,13 +265,18 @@ pub fn test_getsockname() { #[test] pub fn test_socketpair() { + use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType}; use nix::unistd::{read, write}; - use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); write(fd1, b"hello").unwrap(); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); @@ -271,17 +296,22 @@ pub fn test_std_conversions() { } mod recvfrom { - use nix::Result; + use super::*; use nix::sys::socket::*; + use nix::Result; use std::thread; - use super::*; const MSG: &[u8] = b"Hello, World!"; - fn sendrecv<Fs, Fr>(rsock: RawFd, ssock: RawFd, f_send: Fs, mut f_recv: Fr) -> Option<SockaddrStorage> - where - Fs: Fn(RawFd, &[u8], MsgFlags) -> Result<usize> + Send + 'static, - Fr: FnMut(usize, Option<SockaddrStorage>), + fn sendrecv<Fs, Fr>( + rsock: RawFd, + ssock: RawFd, + f_send: Fs, + mut f_recv: Fr, + ) -> Option<SockaddrStorage> + where + Fs: Fn(RawFd, &[u8], MsgFlags) -> Result<usize> + Send + 'static, + Fr: FnMut(usize, Option<SockaddrStorage>), { let mut buf: [u8; 13] = [0u8; 13]; let mut l = 0; @@ -307,33 +337,42 @@ mod recvfrom { #[test] pub fn stream() { - let (fd2, fd1) = socketpair(AddressFamily::Unix, SockType::Stream, - None, SockFlag::empty()).unwrap(); + let (fd2, fd1) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); // Ignore from for stream sockets - let _ = sendrecv(fd1, fd2, |s, m, flags| { - send(s, m, flags) - }, |_, _| {}); + let _ = sendrecv(fd1, fd2, |s, m, flags| send(s, m, flags), |_, _| {}); } #[test] pub fn udp() { let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap(); let sock_addr = SockaddrIn::from(std_sa); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - let from = sendrecv(rsock, ssock, move |s, m, flags| { - sendto(s, m, &sock_addr, flags) - },|_, _| {}); + ) + .expect("send socket failed"); + let from = sendrecv( + rsock, + ssock, + move |s, m, flags| sendto(s, m, &sock_addr, flags), + |_, _| {}, + ); // UDP sockets should set the from address assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap()); } @@ -357,11 +396,13 @@ mod recvfrom { let segment_size: u16 = 2; let sock_addr = SockaddrIn::new(127, 0, 0, 1, 6791); - let rsock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None - ).unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(rsock, UdpGsoSegment, &(segment_size as _)) .expect("setsockopt UDP_SEGMENT failed"); @@ -372,24 +413,30 @@ mod recvfrom { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let mut num_packets_received: i32 = 0; - sendrecv(rsock, ssock, move |s, m, flags| { - let iov = [IoSlice::new(m)]; - let cmsg = ControlMessage::UdpGsoSegments(&segment_size); - sendmsg(s, &iov, &[cmsg], flags, Some(&sock_addr)) - }, { - let num_packets_received_ref = &mut num_packets_received; - - move |len, _| { - // check that we receive UDP packets with payload size - // less or equal to segment size - assert!(len <= segment_size as usize); - *num_packets_received_ref += 1; - } - }); + sendrecv( + rsock, + ssock, + move |s, m, flags| { + let iov = [IoSlice::new(m)]; + let cmsg = ControlMessage::UdpGsoSegments(&segment_size); + sendmsg(s, &iov, &[cmsg], flags, Some(&sock_addr)) + }, + { + let num_packets_received_ref = &mut num_packets_received; + + move |len, _| { + // check that we receive UDP packets with payload size + // less or equal to segment size + assert!(len <= segment_size as usize); + *num_packets_received_ref += 1; + } + }, + ); // Buffer size is 13, we will receive six packets of size 2, // and one packet of size 1. @@ -406,11 +453,13 @@ mod recvfrom { // It's hard to guarantee receiving GRO packets. Just checking // that `setsockopt` doesn't fail with error - let rsock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None - ).unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(rsock, UdpGroSegment, &true) .expect("setsockopt UDP_GRO failed"); @@ -432,51 +481,54 @@ mod recvfrom { let sock_addr = SockaddrIn::from(std_sa); let sock_addr2 = SockaddrIn::from(std_sa2); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); - let from = sendrecv(rsock, ssock, move |s, m, flags| { - let iov = [IoSlice::new(m)]; - let mut msgs = vec![ - SendMmsgData { + let from = sendrecv( + rsock, + ssock, + move |s, m, flags| { + let iov = [IoSlice::new(m)]; + let mut msgs = vec![SendMmsgData { iov: &iov, cmsgs: &[], addr: Some(sock_addr), _lt: Default::default(), - } - ]; + }]; - let batch_size = 15; + let batch_size = 15; - for _ in 0..batch_size { - msgs.push( - SendMmsgData { + for _ in 0..batch_size { + msgs.push(SendMmsgData { iov: &iov, cmsgs: &[], addr: Some(sock_addr2), _lt: Default::default(), - } - ); - } - sendmmsg(s, msgs.iter(), flags) - .map(move |sent_bytes| { + }); + } + sendmmsg(s, msgs.iter(), flags).map(move |sent_bytes| { assert!(!sent_bytes.is_empty()); for sent in &sent_bytes { assert_eq!(*sent, m.len()); } sent_bytes.len() }) - }, |_, _ | {}); + }, + |_, _| {}, + ); // UDP sockets should set the from address assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap()); } @@ -489,31 +541,35 @@ mod recvfrom { ))] #[test] pub fn udp_recvmmsg() { + use nix::sys::socket::{recvmmsg, MsgFlags}; use std::io::IoSliceMut; - use nix::sys::socket::{MsgFlags, recvmmsg}; const NUM_MESSAGES_SENT: usize = 2; - const DATA: [u8; 2] = [1,2]; + const DATA: [u8; 2] = [1, 2]; let inet_addr = SocketAddrV4::from_str("127.0.0.1:6798").unwrap(); let sock_addr = SockaddrIn::from(inet_addr); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()).unwrap(); + sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) + .unwrap(); } }); @@ -521,18 +577,21 @@ mod recvfrom { // Buffers to receive exactly `NUM_MESSAGES_SENT` messages let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT]; - let iovs: Vec<_> = receive_buffers.iter_mut().map(|buf| { - [IoSliceMut::new(&mut buf[..])] - }).collect(); + let iovs: Vec<_> = receive_buffers + .iter_mut() + .map(|buf| [IoSliceMut::new(&mut buf[..])]) + .collect(); for iov in &iovs { msgs.push_back(RecvMmsgData { iov, cmsg_buffer: None, }) - }; + } - let res: Vec<RecvMsg<SockaddrIn>> = recvmmsg(rsock, &mut msgs, MsgFlags::empty(), None).expect("recvmmsg"); + let res: Vec<RecvMsg<SockaddrIn>> = + recvmmsg(rsock, &mut msgs, MsgFlags::empty(), None) + .expect("recvmmsg"); assert_eq!(res.len(), DATA.len()); for RecvMsg { address, bytes, .. } in res.into_iter() { @@ -555,31 +614,35 @@ mod recvfrom { ))] #[test] pub fn udp_recvmmsg_dontwait_short_read() { - use nix::sys::socket::{MsgFlags, recvmmsg}; + use nix::sys::socket::{recvmmsg, MsgFlags}; use std::io::IoSliceMut; const NUM_MESSAGES_SENT: usize = 2; - const DATA: [u8; 4] = [1,2,3,4]; + const DATA: [u8; 4] = [1, 2, 3, 4]; let inet_addr = SocketAddrV4::from_str("127.0.0.1:6799").unwrap(); let sock_addr = SockaddrIn::from(inet_addr); - let rsock = socket(AddressFamily::Inet, + let rsock = socket( + AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None - ).unwrap(); + None, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); let ssock = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); + ) + .expect("send socket failed"); let send_thread = thread::spawn(move || { for _ in 0..NUM_MESSAGES_SENT { - sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()).unwrap(); + sendto(ssock, &DATA[..], &sock_addr, MsgFlags::empty()) + .unwrap(); } }); // Ensure we've sent all the messages before continuing so `recvmmsg` @@ -592,18 +655,21 @@ mod recvfrom { // will return when there are fewer than requested messages in the // kernel buffers when using `MSG_DONTWAIT`. let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT + 2]; - let iovs: Vec<_> = receive_buffers.iter_mut().map(|buf| { - [IoSliceMut::new(&mut buf[..])] - }).collect(); + let iovs: Vec<_> = receive_buffers + .iter_mut() + .map(|buf| [IoSliceMut::new(&mut buf[..])]) + .collect(); for iov in &iovs { msgs.push_back(RecvMmsgData { iov, cmsg_buffer: None, }) - }; + } - let res: Vec<RecvMsg<SockaddrIn>> = recvmmsg(rsock, &mut msgs, MsgFlags::MSG_DONTWAIT, None).expect("recvmmsg"); + let res: Vec<RecvMsg<SockaddrIn>> = + recvmmsg(rsock, &mut msgs, MsgFlags::MSG_DONTWAIT, None) + .expect("recvmmsg"); assert_eq!(res.len(), NUM_MESSAGES_SENT); for RecvMsg { address, bytes, .. } in res.into_iter() { @@ -621,13 +687,13 @@ mod recvfrom { #[test] pub fn test_recvmsg_ebadf() { use nix::errno::Errno; - use nix::sys::socket::{MsgFlags, recvmsg}; + use nix::sys::socket::{recvmsg, MsgFlags}; use std::io::IoSliceMut; let mut buf = [0u8; 5]; let mut iov = [IoSliceMut::new(&mut buf[..])]; - let fd = -1; // Bad file descriptor + let fd = -1; // Bad file descriptor let r = recvmsg::<()>(fd, &mut iov, None, MsgFlags::empty()); assert_eq!(r.err().unwrap(), Errno::EBADF); @@ -638,14 +704,20 @@ pub fn test_recvmsg_ebadf() { #[cfg_attr(qemu, ignore)] #[test] pub fn test_scm_rights() { - use nix::unistd::{pipe, read, write, close}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags}; + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, pipe, read, write}; use std::io::{IoSlice, IoSliceMut}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option<RawFd> = None; @@ -653,7 +725,10 @@ pub fn test_scm_rights() { let iov = [IoSlice::new(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); - assert_eq!(sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), + 5 + ); close(r).unwrap(); close(fd1).unwrap(); } @@ -663,7 +738,13 @@ pub fn test_scm_rights() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!([RawFd; 1]); - let msg = recvmsg::<()>(fd2, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + fd2, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); for cmsg in msg.cmsgs() { if let ControlMessageOwned::ScmRights(fd) = cmsg { @@ -675,7 +756,9 @@ pub fn test_scm_rights() { } } assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(fd2).unwrap(); } @@ -690,15 +773,16 @@ pub fn test_scm_rights() { } // Disable the test on emulated platforms due to not enabled support of AF_ALG in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os= "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_cipher() { - use nix::unistd::read; - use nix::sys::socket::{socket, sendmsg, bind, accept, setsockopt, - AddressFamily, SockType, SockFlag, AlgAddr, - ControlMessage, MsgFlags}; use nix::sys::socket::sockopt::AlgSetKey; + use nix::sys::socket::{ + accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr, + ControlMessage, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::read; use std::io::IoSlice; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1352"); @@ -717,8 +801,13 @@ pub fn test_af_alg_cipher() { let payload_len = 256; let payload = vec![2u8; payload_len]; - let sock = socket(AddressFamily::Alg, SockType::SeqPacket, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Alg, + SockType::SeqPacket, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); bind(sock, &sockaddr).expect("bind failed"); @@ -729,9 +818,13 @@ pub fn test_af_alg_cipher() { setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt"); let session_socket = accept(sock).expect("accept failed"); - let msgs = [ControlMessage::AlgSetOp(&libc::ALG_OP_ENCRYPT), ControlMessage::AlgSetIv(iv.as_slice())]; + 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, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg encrypt"); // allocate buffer for encrypted data let mut encrypted = vec![0u8; payload_len]; @@ -742,8 +835,12 @@ pub fn test_af_alg_cipher() { let iv = vec![1u8; iv_len]; - let msgs = [ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT), ControlMessage::AlgSetIv(iv.as_slice())]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg decrypt"); + let msgs = [ + ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT), + ControlMessage::AlgSetIv(iv.as_slice()), + ]; + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data let mut decrypted = vec![0u8; payload_len]; @@ -755,17 +852,18 @@ pub fn test_af_alg_cipher() { // Disable the test on emulated platforms due to not enabled support of AF_ALG // in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os= "android"))] +#[cfg(any(target_os = "linux", target_os = "android"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_aead() { use libc::{ALG_OP_DECRYPT, ALG_OP_ENCRYPT}; use nix::fcntl::{fcntl, FcntlArg, OFlag}; - use nix::unistd::{read, close}; - use nix::sys::socket::{socket, sendmsg, bind, accept, setsockopt, - AddressFamily, SockType, SockFlag, AlgAddr, - ControlMessage, MsgFlags}; - use nix::sys::socket::sockopt::{AlgSetKey, AlgSetAeadAuthSize}; + use nix::sys::socket::sockopt::{AlgSetAeadAuthSize, AlgSetKey}; + use nix::sys::socket::{ + accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr, + ControlMessage, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, read}; use std::io::IoSlice; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1352"); @@ -785,7 +883,8 @@ pub fn test_af_alg_aead() { let iv = vec![1u8; iv_len]; // 256-bytes plain payload let payload_len = 256; - let mut payload = vec![2u8; payload_len + (assoc_size as usize) + auth_size]; + let mut payload = + vec![2u8; payload_len + (assoc_size as usize) + auth_size]; for i in 0..assoc_size { payload[i as usize] = 10; @@ -797,26 +896,35 @@ pub fn test_af_alg_aead() { payload[len - 1 - i] = 0; } - let sock = socket(AddressFamily::Alg, SockType::SeqPacket, SockFlag::empty(), None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Alg, + SockType::SeqPacket, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = AlgAddr::new(alg_type, alg_name); bind(sock, &sockaddr).expect("bind failed"); - setsockopt(sock, AlgSetAeadAuthSize, &auth_size).expect("setsockopt AlgSetAeadAuthSize"); + setsockopt(sock, AlgSetAeadAuthSize, &auth_size) + .expect("setsockopt AlgSetAeadAuthSize"); setsockopt(sock, AlgSetKey::default(), &key).expect("setsockopt AlgSetKey"); let session_socket = accept(sock).expect("accept failed"); let msgs = [ ControlMessage::AlgSetOp(&ALG_OP_ENCRYPT), ControlMessage::AlgSetIv(iv.as_slice()), - ControlMessage::AlgSetAeadAssoclen(&assoc_size)]; + ControlMessage::AlgSetAeadAssoclen(&assoc_size), + ]; let iov = IoSlice::new(&payload); - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg encrypt"); + sendmsg::<()>(session_socket, &[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 mut encrypted = + vec![0u8; (assoc_size as usize) + payload_len + auth_size]; let num_bytes = read(session_socket, &mut encrypted).expect("read encrypt"); assert_eq!(num_bytes, payload_len + auth_size + (assoc_size as usize)); close(session_socket).expect("close"); @@ -836,19 +944,25 @@ pub fn test_af_alg_aead() { ControlMessage::AlgSetIv(iv.as_slice()), ControlMessage::AlgSetAeadAssoclen(&assoc_size), ]; - sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None).expect("sendmsg decrypt"); + sendmsg::<()>(session_socket, &[iov], &msgs, MsgFlags::empty(), None) + .expect("sendmsg decrypt"); // allocate buffer for decrypted data - let mut decrypted = vec![0u8; payload_len + (assoc_size as usize) + auth_size]; + let mut decrypted = + vec![0u8; payload_len + (assoc_size as usize) + auth_size]; // Starting with kernel 4.9, the interface changed slightly such that the // authentication tag memory is only needed in the output buffer for encryption // and in the input buffer for decryption. // 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"); + fcntl(session_socket, FcntlArg::F_SETFL(OFlag::O_NONBLOCK)) + .expect("fcntl non_blocking"); let num_bytes = read(session_socket, &mut decrypted).expect("read decrypt"); assert!(num_bytes >= payload_len + (assoc_size as usize)); - assert_eq!(decrypted[(assoc_size as usize)..(payload_len + (assoc_size as usize))], payload[(assoc_size as usize)..payload_len + (assoc_size as usize)]); + assert_eq!( + decrypted[(assoc_size as usize)..(payload_len + (assoc_size as usize))], + payload[(assoc_size as usize)..payload_len + (assoc_size as usize)] + ); } // Verify `ControlMessage::Ipv4PacketInfo` for `sendmsg`. @@ -858,24 +972,25 @@ pub fn test_af_alg_aead() { // This would be a more interesting test if we could assume that the test host // has more than one IP address (since we could select a different address to // test from). -#[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "netbsd"))] +#[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))] #[test] pub fn test_sendmsg_ipv4packetinfo() { use cfg_if::cfg_if; - use nix::sys::socket::{socket, sendmsg, bind, - AddressFamily, SockType, SockFlag, SockaddrIn, - ControlMessage, MsgFlags}; + use nix::sys::socket::{ + bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags, + SockFlag, SockType, SockaddrIn, + }; use std::io::IoSlice; - let sock = socket(AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("socket failed"); - let sock_addr = SockaddrIn::new(127,0,0,1, 4000); + let sock_addr = SockaddrIn::new(127, 0, 0, 1, 4000); bind(sock, &sock_addr).expect("bind failed"); @@ -911,23 +1026,28 @@ pub fn test_sendmsg_ipv4packetinfo() { // This would be a more interesting test if we could assume that the test host // has more than one IP address (since we could select a different address to // test from). -#[cfg(any(target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "freebsd" +))] #[test] pub fn test_sendmsg_ipv6packetinfo() { use nix::errno::Errno; - use nix::sys::socket::{socket, sendmsg, bind, - AddressFamily, SockType, SockFlag, SockaddrIn6, - ControlMessage, MsgFlags}; + use nix::sys::socket::{ + bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags, + SockFlag, SockType, SockaddrIn6, + }; use std::io::IoSlice; - let sock = socket(AddressFamily::Inet6, - SockType::Datagram, - SockFlag::empty(), - None) - .expect("socket failed"); + let sock = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap(); let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa); @@ -947,8 +1067,14 @@ pub fn test_sendmsg_ipv6packetinfo() { let cmsg = [ControlMessage::Ipv6PacketInfo(&pi)]; - sendmsg::<SockaddrIn6>(sock, &iov, &cmsg, MsgFlags::empty(), Some(&sock_addr)) - .expect("sendmsg"); + sendmsg::<SockaddrIn6>( + sock, + &iov, + &cmsg, + MsgFlags::empty(), + Some(&sock_addr), + ) + .expect("sendmsg"); } /// Tests that passing multiple fds using a single `ControlMessage` works. @@ -957,12 +1083,13 @@ pub fn test_sendmsg_ipv6packetinfo() { #[cfg_attr(qemu, ignore)] #[test] fn test_scm_rights_single_cmsg_multiple_fds() { + use nix::sys::socket::{ + recvmsg, sendmsg, ControlMessage, ControlMessageOwned, MsgFlags, + }; + use std::io::{IoSlice, IoSliceMut}; + use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; - use std::os::unix::io::{RawFd, AsRawFd}; use std::thread; - use nix::sys::socket::{ControlMessage, ControlMessageOwned, MsgFlags, - sendmsg, recvmsg}; - use std::io::{IoSlice, IoSliceMut}; let (send, receive) = UnixDatagram::pair().unwrap(); let thread = thread::spawn(move || { @@ -974,17 +1101,23 @@ fn test_scm_rights_single_cmsg_multiple_fds() { receive.as_raw_fd(), &mut iovec, Some(&mut space), - MsgFlags::empty() - ).unwrap(); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + MsgFlags::empty(), + ) + .unwrap(); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); match cmsgs.next() { Some(ControlMessageOwned::ScmRights(fds)) => { - assert_eq!(fds.len(), 2, - "unexpected fd count (expected 2 fds, got {})", - fds.len()); - }, + assert_eq!( + fds.len(), + 2, + "unexpected fd count (expected 2 fds, got {})", + fds.len() + ); + } _ => panic!(), } assert!(cmsgs.next().is_none(), "unexpected control msg"); @@ -995,9 +1128,10 @@ fn test_scm_rights_single_cmsg_multiple_fds() { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; let iov = [IoSlice::new(&slice)]; - let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout + let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout let cmsg = [ControlMessage::ScmRights(&fds)]; - sendmsg::<()>(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None).unwrap(); + sendmsg::<()>(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None) + .unwrap(); thread.join().unwrap(); } @@ -1007,17 +1141,27 @@ fn test_scm_rights_single_cmsg_multiple_fds() { // raw `sendmsg`. #[test] pub fn test_sendmsg_empty_cmsgs() { + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, MsgFlags, SockFlag, + SockType, + }; use nix::unistd::close; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; - let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (fd1, fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); { let iov = [IoSlice::new(b"hello")]; - assert_eq!(sendmsg::<()>(fd1, &iov, &[], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(fd1, &iov, &[], MsgFlags::empty(), None).unwrap(), + 5 + ); close(fd1).unwrap(); } @@ -1026,12 +1170,20 @@ pub fn test_sendmsg_empty_cmsgs() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!([RawFd; 1]); - let msg = recvmsg::<()>(fd2, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + fd2, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); for _ in msg.cmsgs() { panic!("unexpected cmsg"); } - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); assert_eq!(msg.bytes, 5); close(fd2).unwrap(); } @@ -1045,17 +1197,22 @@ pub fn test_sendmsg_empty_cmsgs() { ))] #[test] fn test_scm_credentials() { - use nix::unistd::{close, getpid, getuid, getgid}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, - AddressFamily, SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags, - UnixCredentials}; + use nix::sys::socket::{ + recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, UnixCredentials, + }; #[cfg(any(target_os = "android", target_os = "linux"))] use nix::sys::socket::{setsockopt, sockopt::PassCred}; + use nix::unistd::{close, getgid, getpid, getuid}; use std::io::{IoSlice, IoSliceMut}; - let (send, recv) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (send, recv) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); #[cfg(any(target_os = "android", target_os = "linux"))] setsockopt(recv, PassCred, &true).unwrap(); @@ -1067,7 +1224,11 @@ fn test_scm_credentials() { let cmsg = ControlMessage::ScmCredentials(&cred); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] let cmsg = ControlMessage::ScmCreds; - assert_eq!(sendmsg::<()>(send, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(send, &iov, &[cmsg], MsgFlags::empty(), None) + .unwrap(), + 5 + ); close(send).unwrap(); } @@ -1076,7 +1237,13 @@ fn test_scm_credentials() { let mut iov = [IoSliceMut::new(&mut buf[..])]; let mut cmsgspace = cmsg_space!(UnixCredentials); - let msg = recvmsg::<()>(recv, &mut iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); + let msg = recvmsg::<()>( + recv, + &mut iov, + Some(&mut cmsgspace), + MsgFlags::empty(), + ) + .unwrap(); let mut received_cred = None; for cmsg in msg.cmsgs() { @@ -1095,7 +1262,9 @@ fn test_scm_credentials() { } received_cred.expect("no creds received"); assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(recv).unwrap(); } } @@ -1127,15 +1296,21 @@ fn test_too_large_cmsgspace() { #[cfg(any(target_os = "android", target_os = "linux"))] fn test_impl_scm_credentials_and_rights(mut space: Vec<u8>) { use libc::ucred; - use nix::unistd::{pipe, write, close, getpid, getuid, getgid}; - use nix::sys::socket::{socketpair, sendmsg, recvmsg, setsockopt, - SockType, SockFlag, - ControlMessage, ControlMessageOwned, MsgFlags}; use nix::sys::socket::sockopt::PassCred; + use nix::sys::socket::{ + recvmsg, sendmsg, setsockopt, socketpair, ControlMessage, + ControlMessageOwned, MsgFlags, SockFlag, SockType, + }; + use nix::unistd::{close, getgid, getpid, getuid, pipe, write}; use std::io::{IoSlice, IoSliceMut}; - let (send, recv) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()) - .unwrap(); + let (send, recv) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); setsockopt(recv, PassCred, &true).unwrap(); let (r, w) = pipe().unwrap(); @@ -1147,13 +1322,17 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec<u8>) { pid: getpid().as_raw(), uid: getuid().as_raw(), gid: getgid().as_raw(), - }.into(); + } + .into(); let fds = [r]; let cmsgs = [ ControlMessage::ScmCredentials(&cred), ControlMessage::ScmRights(&fds), ]; - assert_eq!(sendmsg::<()>(send, &iov, &cmsgs, MsgFlags::empty(), None).unwrap(), 5); + assert_eq!( + sendmsg::<()>(send, &iov, &cmsgs, MsgFlags::empty(), None).unwrap(), + 5 + ); close(r).unwrap(); close(send).unwrap(); } @@ -1161,7 +1340,9 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec<u8>) { { 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, &mut iov, Some(&mut space), MsgFlags::empty()) + .unwrap(); let mut received_cred = None; assert_eq!(msg.cmsgs().count(), 2, "expected 2 cmsgs"); @@ -1185,7 +1366,9 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec<u8>) { } received_cred.expect("no creds received"); assert_eq!(msg.bytes, 5); - assert!(!msg.flags.intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); close(recv).unwrap(); } @@ -1202,22 +1385,32 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec<u8>) { // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { - use nix::sys::socket::{SockType, SockFlag}; - use nix::sys::socket::{bind, socket, connect, listen, accept, UnixAddr}; - use nix::unistd::{read, write, close}; + use nix::sys::socket::{accept, bind, connect, listen, socket, UnixAddr}; + use nix::sys::socket::{SockFlag, SockType}; + use nix::unistd::{close, read, write}; use std::thread; let tempdir = tempfile::tempdir().unwrap(); let sockname = tempdir.path().join("sock"); - let s1 = socket(AddressFamily::Unix, SockType::Stream, - SockFlag::empty(), None).expect("socket failed"); + let s1 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { - let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), None) - .expect("socket failed"); + let s2 = socket( + AddressFamily::Unix, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); @@ -1225,7 +1418,7 @@ pub fn test_unixdomain() { let s3 = accept(s1).expect("accept failed"); - let mut buf = [0;5]; + let mut buf = [0; 5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); @@ -1239,14 +1432,23 @@ pub fn test_unixdomain() { #[test] pub fn test_syscontrol() { use nix::errno::Errno; - use nix::sys::socket::{socket, SysControlAddr, SockType, SockFlag, SockProtocol}; + use nix::sys::socket::{ + socket, SockFlag, SockProtocol, SockType, SysControlAddr, + }; - let fd = socket(AddressFamily::System, SockType::Datagram, - SockFlag::empty(), SockProtocol::KextControl) - .expect("socket failed"); + let fd = socket( + AddressFamily::System, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::KextControl, + ) + .expect("socket failed"); SysControlAddr::from_name(fd, "com.apple.net.utun_control", 0) .expect("resolving sys_control name failed"); - assert_eq!(SysControlAddr::from_name(fd, "foo.bar.lol", 0).err(), Some(Errno::ENOENT)); + assert_eq!( + SysControlAddr::from_name(fd, "foo.bar.lol", 0).err(), + Some(Errno::ENOENT) + ); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); @@ -1261,12 +1463,14 @@ pub fn test_syscontrol() { target_os = "netbsd", target_os = "openbsd", ))] -fn loopback_address(family: AddressFamily) -> Option<nix::ifaddrs::InterfaceAddress> { - use std::io; - use std::io::Write; +fn loopback_address( + family: AddressFamily, +) -> Option<nix::ifaddrs::InterfaceAddress> { use nix::ifaddrs::getifaddrs; use nix::net::if_::*; use nix::sys::socket::SockaddrLike; + use std::io; + use std::io::Write; let addrs = match getifaddrs() { Ok(iter) => iter, @@ -1275,14 +1479,15 @@ fn loopback_address(family: AddressFamily) -> Option<nix::ifaddrs::InterfaceAddr let mut handle = stdioerr.lock(); writeln!(handle, "getifaddrs: {:?}", e).unwrap(); return None; - }, + } }; // return first address matching family for ifaddr in addrs { - if ifaddr.flags.contains(InterfaceFlags::IFF_LOOPBACK) && - ifaddr.address.as_ref().and_then(SockaddrLike::family) == Some(family) + if ifaddr.flags.contains(InterfaceFlags::IFF_LOOPBACK) + && ifaddr.address.as_ref().and_then(SockaddrLike::family) + == Some(family) { - return Some(ifaddr) + return Some(ifaddr); } } None @@ -1296,35 +1501,41 @@ fn loopback_address(family: AddressFamily) -> Option<nix::ifaddrs::InterfaceAddr target_os = "netbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures -#[cfg_attr(all( - qemu, - any( - target_arch = "mips", - target_arch = "mips64", - target_arch = "powerpc64", - ) -), ignore)] +#[cfg_attr( + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc64", + ) + ), + ignore +)] #[test] pub fn test_recv_ipv4pktinfo() { + use nix::net::if_::*; use nix::sys::socket::sockopt::Ipv4PacketInfo; - use nix::sys::socket::{bind, SockaddrIn, SockFlag, SockType}; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn}; use nix::sys::socket::{getsockname, setsockopt, socket}; use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; - use nix::net::if_::*; use std::io::{IoSlice, IoSliceMut}; let lo_ifaddr = loopback_address(AddressFamily::Inet); let (lo_name, lo) = match lo_ifaddr { - Some(ifaddr) => (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), None => return, }; let receive = socket( - AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None, - ).expect("receive socket failed"); + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + 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"); @@ -1338,8 +1549,10 @@ pub fn test_recv_ipv4pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1352,29 +1565,25 @@ pub fn test_recv_ipv4pktinfo() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); - if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next() { + if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next() + { let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); assert_eq!( - pktinfo.ipi_ifindex as libc::c_uint, - i, + pktinfo.ipi_ifindex as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - pktinfo.ipi_ifindex + i, pktinfo.ipi_ifindex ); } assert!(cmsgs.next().is_none(), "unexpected additional control msg"); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1386,27 +1595,32 @@ pub fn test_recv_ipv4pktinfo() { target_os = "openbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures -#[cfg_attr(all( - qemu, - any( - target_arch = "mips", - target_arch = "mips64", - target_arch = "powerpc64", - ) -), ignore)] +#[cfg_attr( + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc64", + ) + ), + ignore +)] #[test] pub fn test_recvif() { use nix::net::if_::*; - use nix::sys::socket::sockopt::{Ipv4RecvIf, Ipv4RecvDstAddr}; - use nix::sys::socket::{bind, SockaddrIn, SockFlag, SockType}; + use nix::sys::socket::sockopt::{Ipv4RecvDstAddr, Ipv4RecvIf}; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn}; use nix::sys::socket::{getsockname, setsockopt, socket}; use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; let lo_ifaddr = loopback_address(AddressFamily::Inet); let (lo_name, lo) = match lo_ifaddr { - Some(ifaddr) => (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), None => return, }; let receive = socket( @@ -1414,11 +1628,14 @@ pub fn test_recvif() { SockType::Datagram, SockFlag::empty(), None, - ).expect("receive socket failed"); + ) + .expect("receive socket failed"); bind(receive, &lo).expect("bind failed"); let sa: SockaddrIn = getsockname(receive).expect("getsockname failed"); - setsockopt(receive, Ipv4RecvIf, &true).expect("setsockopt IP_RECVIF failed"); - setsockopt(receive, Ipv4RecvDstAddr, &true).expect("setsockopt IP_RECVDSTADDR failed"); + setsockopt(receive, Ipv4RecvIf, &true) + .expect("setsockopt IP_RECVIF failed"); + setsockopt(receive, Ipv4RecvDstAddr, &true) + .expect("setsockopt IP_RECVDSTADDR failed"); { let slice = [1u8, 2, 3, 4, 5, 6, 7, 8]; @@ -1429,8 +1646,10 @@ pub fn test_recvif() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1442,11 +1661,11 @@ pub fn test_recvif() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); assert_eq!(msg.cmsgs().count(), 2, "expected 2 cmsgs"); let mut rx_recvif = false; @@ -1455,15 +1674,14 @@ pub fn test_recvif() { match cmsg { ControlMessageOwned::Ipv4RecvIf(dl) => { rx_recvif = true; - let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); + let i = if_nametoindex(lo_name.as_bytes()) + .expect("if_nametoindex"); assert_eq!( - dl.sdl_index as libc::c_uint, - i, + dl.sdl_index as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - dl.sdl_index + i, dl.sdl_index ); - }, + } ControlMessageOwned::Ipv4RecvDstAddr(addr) => { rx_recvdstaddr = true; if let Some(sin) = lo.as_sockaddr_in() { @@ -1475,17 +1693,14 @@ pub fn test_recvif() { } else { panic!("unexpected Sockaddr"); } - }, + } _ => panic!("unexpected additional control msg"), } } assert!(rx_recvif); assert!(rx_recvdstaddr); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1499,27 +1714,32 @@ pub fn test_recvif() { target_os = "openbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures -#[cfg_attr(all( - qemu, - any( - target_arch = "mips", - target_arch = "mips64", - target_arch = "powerpc64", - ) -), ignore)] +#[cfg_attr( + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips64", + target_arch = "powerpc64", + ) + ), + ignore +)] #[test] pub fn test_recv_ipv6pktinfo() { use nix::net::if_::*; use nix::sys::socket::sockopt::Ipv6RecvPacketInfo; - use nix::sys::socket::{bind, SockaddrIn6, SockFlag, SockType}; + use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn6}; use nix::sys::socket::{getsockname, setsockopt, socket}; use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags}; use std::io::{IoSlice, IoSliceMut}; let lo_ifaddr = loopback_address(AddressFamily::Inet6); let (lo_name, lo) = match lo_ifaddr { - Some(ifaddr) => (ifaddr.interface_name, - ifaddr.address.expect("Expect IPv4 address on interface")), + Some(ifaddr) => ( + ifaddr.interface_name, + ifaddr.address.expect("Expect IPv4 address on interface"), + ), None => return, }; let receive = socket( @@ -1527,7 +1747,8 @@ pub fn test_recv_ipv6pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("receive socket failed"); + ) + .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"); @@ -1541,8 +1762,10 @@ pub fn test_recv_ipv6pktinfo() { SockType::Datagram, SockFlag::empty(), None, - ).expect("send socket failed"); - sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)).expect("sendmsg failed"); + ) + .expect("send socket failed"); + sendmsg(send, &iov, &[], MsgFlags::empty(), Some(&sa)) + .expect("sendmsg failed"); } { @@ -1555,30 +1778,25 @@ pub fn test_recv_ipv6pktinfo() { &mut iovec, Some(&mut space), MsgFlags::empty(), - ).expect("recvmsg failed"); - assert!( - !msg.flags - .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC) - ); + ) + .expect("recvmsg failed"); + assert!(!msg + .flags + .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)); let mut cmsgs = msg.cmsgs(); if let Some(ControlMessageOwned::Ipv6PacketInfo(pktinfo)) = cmsgs.next() { let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex"); assert_eq!( - pktinfo.ipi6_ifindex as libc::c_uint, - i, + pktinfo.ipi6_ifindex as libc::c_uint, i, "unexpected ifindex (expected {}, got {})", - i, - pktinfo.ipi6_ifindex + i, pktinfo.ipi6_ifindex ); } assert!(cmsgs.next().is_none(), "unexpected additional control msg"); assert_eq!(msg.bytes, 8); - assert_eq!( - *iovec[0], - [1u8, 2, 3, 4, 5, 6, 7, 8] - ); + assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]); } } @@ -1587,21 +1805,26 @@ pub fn test_recv_ipv6pktinfo() { #[test] pub fn test_vsock() { use nix::errno::Errno; - use nix::sys::socket::{AddressFamily, socket, bind, connect, listen, - SockType, SockFlag, VsockAddr}; - use nix::unistd::{close}; + use nix::sys::socket::{ + bind, connect, listen, socket, AddressFamily, SockFlag, SockType, + VsockAddr, + }; + use nix::unistd::close; use std::thread; let port: u32 = 3000; - let s1 = socket(AddressFamily::Vsock, SockType::Stream, - SockFlag::empty(), None) - .expect("socket failed"); + let s1 = socket( + AddressFamily::Vsock, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); // VMADDR_CID_HYPERVISOR is reserved, so we expect an EADDRNOTAVAIL error. let sockaddr_hv = VsockAddr::new(libc::VMADDR_CID_HYPERVISOR, port); - assert_eq!(bind(s1, &sockaddr_hv).err(), - Some(Errno::EADDRNOTAVAIL)); + assert_eq!(bind(s1, &sockaddr_hv).err(), Some(Errno::EADDRNOTAVAIL)); let sockaddr_any = VsockAddr::new(libc::VMADDR_CID_ANY, port); assert_eq!(bind(s1, &sockaddr_any), Ok(())); @@ -1610,9 +1833,13 @@ pub fn test_vsock() { let thr = thread::spawn(move || { let cid: u32 = libc::VMADDR_CID_HOST; - let s2 = socket(AddressFamily::Vsock, SockType::Stream, - SockFlag::empty(), None) - .expect("socket failed"); + let s2 = socket( + AddressFamily::Vsock, + SockType::Stream, + SockFlag::empty(), + None, + ) + .expect("socket failed"); let sockaddr_host = VsockAddr::new(cid, port); @@ -1634,8 +1861,8 @@ pub fn test_vsock() { #[test] fn test_recvmsg_timestampns() { use nix::sys::socket::*; - use std::io::{IoSlice, IoSliceMut}; use nix::sys::time::*; + use std::io::{IoSlice, IoSliceMut}; use std::time::*; // Set up @@ -1644,7 +1871,9 @@ fn test_recvmsg_timestampns() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::new(127, 0, 0, 1, 0); bind(in_socket, &localhost).unwrap(); @@ -1661,18 +1890,19 @@ fn test_recvmsg_timestampns() { 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, &mut iov, Some(&mut cmsgspace), flags) + .unwrap(); let rtime = match r.cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), - None => panic!("No control message") + None => panic!("No control message"), }; // Check the final time let time1 = SystemTime::now(); // the packet's received timestamp should lie in-between the two system // times, unless the system clock was adjusted in the meantime. - let rduration = Duration::new(rtime.tv_sec() as u64, - rtime.tv_nsec() as u32); + let rduration = + 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 @@ -1686,8 +1916,8 @@ fn test_recvmsg_timestampns() { #[test] fn test_recvmmsg_timestampns() { use nix::sys::socket::*; - use std::io::{IoSlice, IoSliceMut}; use nix::sys::time::*; + use std::io::{IoSlice, IoSliceMut}; use std::time::*; // Set up @@ -1696,7 +1926,9 @@ fn test_recvmmsg_timestampns() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); setsockopt(in_socket, sockopt::ReceiveTimestampns, &true).unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); bind(in_socket, &localhost).unwrap(); @@ -1712,24 +1944,23 @@ fn test_recvmmsg_timestampns() { let mut buffer = vec![0u8; message.len()]; let mut cmsgspace = nix::cmsg_space!(TimeSpec); let iov = [IoSliceMut::new(&mut buffer)]; - let mut data = vec![ - RecvMmsgData { - iov, - cmsg_buffer: Some(&mut cmsgspace), - }, - ]; - let r: Vec<RecvMsg<()>> = recvmmsg(in_socket, &mut data, flags, None).unwrap(); + let mut data = vec![RecvMmsgData { + iov, + cmsg_buffer: Some(&mut cmsgspace), + }]; + let r: Vec<RecvMsg<()>> = + recvmmsg(in_socket, &mut data, flags, None).unwrap(); let rtime = match r[0].cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), - None => panic!("No control message") + None => panic!("No control message"), }; // Check the final time let time1 = SystemTime::now(); // the packet's received timestamp should lie in-between the two system // times, unless the system clock was adjusted in the meantime. - let rduration = Duration::new(rtime.tv_sec() as u64, - rtime.tv_nsec() as u32); + let rduration = + 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 @@ -1742,10 +1973,10 @@ fn test_recvmmsg_timestampns() { #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] #[test] fn test_recvmsg_rxq_ovfl() { - use nix::Error; + use nix::sys::socket::sockopt::{RcvBuf, RxqOvfl}; use nix::sys::socket::*; + use nix::Error; use std::io::{IoSlice, IoSliceMut}; - use nix::sys::socket::sockopt::{RxqOvfl, RcvBuf}; let message = [0u8; 2048]; let bufsize = message.len() * 2; @@ -1754,12 +1985,16 @@ fn test_recvmsg_rxq_ovfl() { AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); let out_socket = socket( AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), - None).unwrap(); + None, + ) + .unwrap(); let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap(); bind(in_socket, &localhost).unwrap(); @@ -1782,7 +2017,8 @@ 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, &iov, &[], flags, Some(&address)).unwrap(); assert_eq!(message.len(), l); } @@ -1797,16 +2033,23 @@ fn test_recvmsg_rxq_ovfl() { in_socket, &mut iov, Some(&mut cmsgspace), - MsgFlags::MSG_DONTWAIT) { + MsgFlags::MSG_DONTWAIT, + ) { Ok(r) => { drop_counter = match r.cmsgs().next() { - Some(ControlMessageOwned::RxqOvfl(drop_counter)) => drop_counter, + Some(ControlMessageOwned::RxqOvfl(drop_counter)) => { + drop_counter + } Some(_) => panic!("Unexpected control message"), None => 0, }; - }, - Err(Error::EAGAIN) => { break; }, - _ => { panic!("unknown recvmsg() error"); }, + } + Err(Error::EAGAIN) => { + break; + } + _ => { + panic!("unknown recvmsg() error"); + } } } } @@ -1819,13 +2062,10 @@ fn test_recvmsg_rxq_ovfl() { nix::unistd::close(out_socket).unwrap(); } -#[cfg(any( - target_os = "linux", - target_os = "android", -))] +#[cfg(any(target_os = "linux", target_os = "android",))] mod linux_errqueue { - use nix::sys::socket::*; use super::FromStr; + use nix::sys::socket::*; // Send a UDP datagram to a bogus destination address and observe an ICMP error (v4). // @@ -1853,11 +2093,16 @@ mod linux_errqueue { // Closure handles protocol-specific testing and returns generic sock_extended_err for // protocol-independent test impl. |cmsg| { - if let ControlMessageOwned::Ipv4RecvErr(ext_err, err_addr) = cmsg { + if let ControlMessageOwned::Ipv4RecvErr(ext_err, err_addr) = + cmsg + { if let Some(origin) = err_addr { // Validate that our network error originated from 127.0.0.1:0. assert_eq!(origin.sin_family, AddressFamily::Inet as _); - assert_eq!(origin.sin_addr.s_addr, u32::from_be(0x7f000001)); + assert_eq!( + origin.sin_addr.s_addr, + u32::from_be(0x7f000001) + ); assert_eq!(origin.sin_port, 0); } else { panic!("Expected some error origin"); @@ -1896,10 +2141,15 @@ mod linux_errqueue { // Closure handles protocol-specific testing and returns generic sock_extended_err for // protocol-independent test impl. |cmsg| { - if let ControlMessageOwned::Ipv6RecvErr(ext_err, err_addr) = cmsg { + if let ControlMessageOwned::Ipv6RecvErr(ext_err, err_addr) = + cmsg + { if let Some(origin) = err_addr { // Validate that our network error originated from localhost:0. - assert_eq!(origin.sin6_family, AddressFamily::Inet6 as _); + assert_eq!( + origin.sin6_family, + AddressFamily::Inet6 as _ + ); assert_eq!( origin.sin6_addr.s6_addr, std::net::Ipv6Addr::LOCALHOST.octets() @@ -1916,16 +2166,17 @@ mod linux_errqueue { ) } - fn test_recverr_impl<SA, OPT, TESTF>(sa: &str, - af: AddressFamily, - opt: OPT, - ee_origin: u8, - ee_type: u8, - ee_code: u8, - testf: TESTF) - where - OPT: SetSockOpt<Val = bool>, - TESTF: FnOnce(&ControlMessageOwned) -> libc::sock_extended_err, + fn test_recverr_impl<SA, OPT, TESTF>( + sa: &str, + af: AddressFamily, + opt: OPT, + ee_origin: u8, + ee_type: u8, + ee_code: u8, + testf: TESTF, + ) where + OPT: SetSockOpt<Val = bool>, + TESTF: FnOnce(&ControlMessageOwned) -> libc::sock_extended_err, { use nix::errno::Errno; use std::io::IoSliceMut; @@ -1933,9 +2184,15 @@ mod linux_errqueue { const MESSAGE_CONTENTS: &str = "ABCDEF"; let std_sa = std::net::SocketAddr::from_str(sa).unwrap(); let sock_addr = SockaddrStorage::from(std_sa); - let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None).unwrap(); + let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None) + .unwrap(); setsockopt(sock, opt, &true).unwrap(); - if let Err(e) = sendto(sock, MESSAGE_CONTENTS.as_bytes(), &sock_addr, MsgFlags::empty()) { + if let Err(e) = sendto( + sock, + MESSAGE_CONTENTS.as_bytes(), + &sock_addr, + MsgFlags::empty(), + ) { assert_eq!(e, Errno::EADDRNOTAVAIL); println!("{:?} not available, skipping test.", af); return; @@ -1945,7 +2202,13 @@ mod linux_errqueue { let mut iovec = [IoSliceMut::new(&mut buf)]; let mut cspace = cmsg_space!(libc::sock_extended_err, SA); - let msg = recvmsg(sock, &mut iovec, Some(&mut cspace), MsgFlags::MSG_ERRQUEUE).unwrap(); + let msg = recvmsg( + sock, + &mut iovec, + Some(&mut cspace), + MsgFlags::MSG_ERRQUEUE, + ) + .unwrap(); // The sent message / destination associated with the error is returned: assert_eq!(msg.bytes, MESSAGE_CONTENTS.as_bytes().len()); // recvmsg(2): "The original destination address of the datagram that caused the error is @@ -1982,10 +2245,10 @@ mod linux_errqueue { pub fn test_txtime() { use nix::sys::socket::{ bind, recvmsg, sendmsg, setsockopt, socket, sockopt, ControlMessage, - MsgFlags, SockaddrIn, SockFlag, SockType, + MsgFlags, SockFlag, SockType, SockaddrIn, }; use nix::sys::time::TimeValLike; - use nix::time::{ClockId, clock_gettime}; + use nix::time::{clock_gettime, ClockId}; require_kernel_version!(test_txtime, ">= 5.8"); @@ -2022,7 +2285,8 @@ 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, &iov1, &[cmsg], MsgFlags::empty(), Some(&sock_addr)) + .unwrap(); let mut rbuf = [0u8; 2048]; let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)]; diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index a17bc09f..2ddbf77b 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -1,22 +1,27 @@ -use rand::{thread_rng, Rng}; -use nix::sys::socket::{socket, sockopt, getsockopt, setsockopt, AddressFamily, SockType, SockFlag, SockProtocol}; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::*; +use nix::sys::socket::{ + getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, + SockProtocol, SockType, +}; +use rand::{thread_rng, Rng}; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", -))] +#[cfg(any(target_os = "dragonfly", target_os = "freebsd",))] #[test] pub fn test_local_peercred_seqpacket() { use nix::{ + sys::socket::socketpair, unistd::{Gid, Uid}, - sys::socket::socketpair }; - let (fd1, _fd2) = socketpair(AddressFamily::Unix, SockType::SeqPacket, None, - SockFlag::empty()).unwrap(); + let (fd1, _fd2) = socketpair( + AddressFamily::Unix, + SockType::SeqPacket, + None, + SockFlag::empty(), + ) + .unwrap(); let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); @@ -24,20 +29,25 @@ pub fn test_local_peercred_seqpacket() { } #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "ios" + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "ios" ))] #[test] pub fn test_local_peercred_stream() { use nix::{ + sys::socket::socketpair, unistd::{Gid, Uid}, - sys::socket::socketpair }; - let (fd1, _fd2) = socketpair(AddressFamily::Unix, SockType::Stream, None, - SockFlag::empty()).unwrap(); + let (fd1, _fd2) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); let xucred = getsockopt(fd1, sockopt::LocalPeerCred).unwrap(); assert_eq!(xucred.version(), 0); assert_eq!(Uid::from_raw(xucred.uid()), Uid::current()); @@ -51,7 +61,13 @@ fn is_so_mark_functional() { require_capability!("is_so_mark_functional", CAP_NET_ADMIN); - let s = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let s = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(s, sockopt::Mark, &1337).unwrap(); let mark = getsockopt(s, sockopt::Mark).unwrap(); assert_eq!(mark, 1337); @@ -59,8 +75,13 @@ fn is_so_mark_functional() { #[test] fn test_so_buf() { - let fd = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), SockProtocol::Udp) - .unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + SockProtocol::Udp, + ) + .unwrap(); let bufsize: usize = thread_rng().gen_range(4096..131_072); setsockopt(fd, sockopt::SndBuf, &bufsize).unwrap(); let actual = getsockopt(fd, sockopt::SndBuf).unwrap(); @@ -72,16 +93,21 @@ fn test_so_buf() { #[test] fn test_so_tcp_maxseg() { - use std::net::SocketAddrV4; - use std::str::FromStr; use nix::sys::socket::{accept, bind, connect, listen, SockaddrIn}; use nix::unistd::{close, write}; + use std::net::SocketAddrV4; + use std::str::FromStr; let std_sa = SocketAddrV4::from_str("127.0.0.1:4001").unwrap(); let sock_addr = SockaddrIn::from(std_sa); - let rsock = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp) - .unwrap(); + let rsock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); bind(rsock, &sock_addr).unwrap(); listen(rsock, 10).unwrap(); let initial = getsockopt(rsock, sockopt::TcpMaxSeg).unwrap(); @@ -99,8 +125,13 @@ fn test_so_tcp_maxseg() { } // Connect and check the MSS that was advertised - let ssock = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp) - .unwrap(); + let ssock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); connect(ssock, &sock_addr).unwrap(); let rsess = accept(rsock).unwrap(); write(rsess, b"hello").unwrap(); @@ -132,17 +163,25 @@ fn test_so_tcp_maxseg() { fn test_tcp_congestion() { use std::ffi::OsString; - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); let val = getsockopt(fd, sockopt::TcpCongestion).unwrap(); setsockopt(fd, sockopt::TcpCongestion, &val).unwrap(); - setsockopt(fd, sockopt::TcpCongestion, &OsString::from("tcp_congestion_does_not_exist")).unwrap_err(); + setsockopt( + 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] @@ -150,27 +189,39 @@ fn test_tcp_congestion() { fn test_bindtodevice() { skip_if_not_root!("test_bindtodevice"); - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .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] fn test_so_tcp_keepalive() { - let fd = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); setsockopt(fd, sockopt::KeepAlive, &true).unwrap(); assert!(getsockopt(fd, sockopt::KeepAlive).unwrap()); - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux"))] { + #[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + 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); @@ -188,10 +239,22 @@ fn test_so_tcp_keepalive() { #[test] #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] fn test_ttl_opts() { - let fd4 = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); + let fd4 = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(fd4, sockopt::Ipv4Ttl, &1) .expect("setting ipv4ttl on an inet socket should succeed"); - let fd6 = socket(AddressFamily::Inet6, SockType::Datagram, SockFlag::empty(), None).unwrap(); + let fd6 = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); setsockopt(fd6, sockopt::Ipv6Ttl, &1) .expect("setting ipv6ttl on an inet6 socket should succeed"); } @@ -199,38 +262,68 @@ fn test_ttl_opts() { #[test] #[cfg(any(target_os = "ios", target_os = "macos"))] fn test_dontfrag_opts() { - let fd4 = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); + let fd4 = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); setsockopt(fd4, sockopt::IpDontFrag, &true) .expect("setting IP_DONTFRAG on an inet stream socket should succeed"); - setsockopt(fd4, sockopt::IpDontFrag, &false) - .expect("unsetting IP_DONTFRAG on an inet stream socket should succeed"); - let fd4d = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); - setsockopt(fd4d, sockopt::IpDontFrag, &true) - .expect("setting IP_DONTFRAG on an inet datagram socket should succeed"); - setsockopt(fd4d, sockopt::IpDontFrag, &false) - .expect("unsetting IP_DONTFRAG on an inet datagram socket should succeed"); + setsockopt(fd4, sockopt::IpDontFrag, &false).expect( + "unsetting IP_DONTFRAG on an inet stream socket should succeed", + ); + let fd4d = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(fd4d, sockopt::IpDontFrag, &true).expect( + "setting IP_DONTFRAG on an inet datagram socket should succeed", + ); + setsockopt(fd4d, sockopt::IpDontFrag, &false).expect( + "unsetting IP_DONTFRAG on an inet datagram socket should succeed", + ); } #[test] #[cfg(any( - target_os = "android", - target_os = "ios", - target_os = "linux", - target_os = "macos", - ) -)] + target_os = "android", + target_os = "ios", + target_os = "linux", + target_os = "macos", +))] // Disable the test under emulation because it fails in Cirrus-CI. Lack // of QEMU support is suspected. #[cfg_attr(qemu, ignore)] fn test_v6dontfrag_opts() { - let fd6 = socket(AddressFamily::Inet6, SockType::Stream, SockFlag::empty(), SockProtocol::Tcp).unwrap(); - setsockopt(fd6, sockopt::Ipv6DontFrag, &true) - .expect("setting IPV6_DONTFRAG on an inet6 stream socket should succeed"); - setsockopt(fd6, sockopt::Ipv6DontFrag, &false) - .expect("unsetting IPV6_DONTFRAG on an inet6 stream socket should succeed"); - let fd6d = socket(AddressFamily::Inet6, SockType::Datagram, SockFlag::empty(), None).unwrap(); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &true) - .expect("setting IPV6_DONTFRAG on an inet6 datagram socket should succeed"); - setsockopt(fd6d, sockopt::Ipv6DontFrag, &false) - .expect("unsetting IPV6_DONTFRAG on an inet6 datagram socket should succeed"); + let fd6 = socket( + AddressFamily::Inet6, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + setsockopt(fd6, sockopt::Ipv6DontFrag, &true).expect( + "setting IPV6_DONTFRAG on an inet6 stream socket should succeed", + ); + setsockopt(fd6, sockopt::Ipv6DontFrag, &false).expect( + "unsetting IPV6_DONTFRAG on an inet6 stream socket should succeed", + ); + let fd6d = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(fd6d, sockopt::Ipv6DontFrag, &true).expect( + "setting IPV6_DONTFRAG on an inet6 datagram socket should succeed", + ); + setsockopt(fd6d, sockopt::Ipv6DontFrag, &false).expect( + "unsetting IPV6_DONTFRAG on an inet6 datagram socket should succeed", + ); } diff --git a/test/sys/test_sysinfo.rs b/test/sys/test_sysinfo.rs index 73e6586f..2897366e 100644 --- a/test/sys/test_sysinfo.rs +++ b/test/sys/test_sysinfo.rs @@ -9,10 +9,12 @@ fn sysinfo_works() { assert!(l5 >= 0.0); assert!(l15 >= 0.0); - info.uptime(); // just test Duration construction + info.uptime(); // just test Duration construction - assert!(info.swap_free() <= info.swap_total(), - "more swap available than installed (free: {}, total: {})", - info.swap_free(), - info.swap_total()); + assert!( + info.swap_free() <= info.swap_total(), + "more swap available than installed (free: {}, total: {})", + info.swap_free(), + info.swap_total() + ); } diff --git a/test/sys/test_termios.rs b/test/sys/test_termios.rs index 4a861543..e567a52c 100644 --- a/test/sys/test_termios.rs +++ b/test/sys/test_termios.rs @@ -1,11 +1,11 @@ use std::os::unix::prelude::*; use tempfile::tempfile; -use nix::fcntl; use nix::errno::Errno; +use nix::fcntl; use nix::pty::openpty; -use nix::sys::termios::{self, LocalFlags, OutputFlags, tcgetattr}; -use nix::unistd::{read, write, close}; +use nix::sys::termios::{self, tcgetattr, LocalFlags, OutputFlags}; +use nix::unistd::{close, read, write}; /// Helper function analogous to `std::io::Write::write_all`, but for `RawFd`s fn write_all(f: RawFd, buf: &[u8]) { @@ -31,15 +31,16 @@ fn test_tcgetattr_pty() { #[test] fn test_tcgetattr_enotty() { let file = tempfile().unwrap(); - assert_eq!(termios::tcgetattr(file.as_raw_fd()).err(), - Some(Errno::ENOTTY)); + assert_eq!( + termios::tcgetattr(file.as_raw_fd()).err(), + Some(Errno::ENOTTY) + ); } // Test tcgetattr on an invalid file descriptor #[test] fn test_tcgetattr_ebadf() { - assert_eq!(termios::tcgetattr(-1).err(), - Some(Errno::EBADF)); + assert_eq!(termios::tcgetattr(-1).err(), Some(Errno::EBADF)); } // Test modifying output flags @@ -60,11 +61,15 @@ fn test_output_flags() { }; // Make sure postprocessing '\r' isn't specified by default or this test is useless. - assert!(!termios.output_flags.contains(OutputFlags::OPOST | OutputFlags::OCRNL)); + assert!(!termios + .output_flags + .contains(OutputFlags::OPOST | OutputFlags::OCRNL)); // Specify that '\r' characters should be transformed to '\n' // OPOST is specified to enable post-processing - termios.output_flags.insert(OutputFlags::OPOST | OutputFlags::OCRNL); + termios + .output_flags + .insert(OutputFlags::OPOST | OutputFlags::OCRNL); // Open a pty let pty = openpty(None, &termios).unwrap(); @@ -114,7 +119,8 @@ fn test_local_flags() { // Set the master is in nonblocking mode or reading will never return. let flags = fcntl::fcntl(pty.master, fcntl::F_GETFL).unwrap(); - let new_flags = fcntl::OFlag::from_bits_truncate(flags) | fcntl::OFlag::O_NONBLOCK; + let new_flags = + fcntl::OFlag::from_bits_truncate(flags) | fcntl::OFlag::O_NONBLOCK; fcntl::fcntl(pty.master, fcntl::F_SETFL(new_flags)).unwrap(); // Write into the master diff --git a/test/sys/test_timerfd.rs b/test/sys/test_timerfd.rs index 24fb2ac0..927cc70d 100644 --- a/test/sys/test_timerfd.rs +++ b/test/sys/test_timerfd.rs @@ -1,10 +1,13 @@ use nix::sys::time::{TimeSpec, TimeValLike}; -use nix::sys::timerfd::{ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags}; +use nix::sys::timerfd::{ + ClockId, Expiration, TimerFd, TimerFlags, TimerSetTimeFlags, +}; use std::time::Instant; #[test] pub fn test_timerfd_oneshot() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); let before = Instant::now(); @@ -23,12 +26,16 @@ pub fn test_timerfd_oneshot() { #[test] pub fn test_timerfd_interval() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); let before = Instant::now(); timer .set( - Expiration::IntervalDelayed(TimeSpec::seconds(1), TimeSpec::seconds(2)), + Expiration::IntervalDelayed( + TimeSpec::seconds(1), + TimeSpec::seconds(2), + ), TimerSetTimeFlags::empty(), ) .unwrap(); @@ -46,7 +53,8 @@ pub fn test_timerfd_interval() { #[test] pub fn test_timerfd_unset() { - let timer = TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); + let timer = + TimerFd::new(ClockId::CLOCK_MONOTONIC, TimerFlags::empty()).unwrap(); timer .set( diff --git a/test/sys/test_uio.rs b/test/sys/test_uio.rs index fc2dfabe..f46b1940 100644 --- a/test/sys/test_uio.rs +++ b/test/sys/test_uio.rs @@ -1,18 +1,18 @@ use nix::sys::uio::*; use nix::unistd::*; -use rand::{thread_rng, Rng}; use rand::distributions::Alphanumeric; -use std::{cmp, iter}; -use std::fs::{OpenOptions}; +use rand::{thread_rng, Rng}; +use std::fs::OpenOptions; use std::io::IoSlice; use std::os::unix::io::AsRawFd; +use std::{cmp, iter}; #[cfg(not(target_os = "redox"))] use std::io::IoSliceMut; +use tempfile::tempdir; #[cfg(not(target_os = "redox"))] use tempfile::tempfile; -use tempfile::tempdir; #[test] fn test_writev() { @@ -31,8 +31,12 @@ fn test_writev() { let mut consumed = 0; while consumed < to_write.len() { let left = to_write.len() - consumed; - let slice_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) }; - let b = &to_write[consumed..consumed+slice_len]; + let slice_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64..cmp::min(256, left)) + }; + let b = &to_write[consumed..consumed + slice_len]; iovecs.push(IoSlice::new(b)); consumed += slice_len; } @@ -65,7 +69,7 @@ fn test_writev() { #[test] #[cfg(not(target_os = "redox"))] fn test_readv() { - let s:String = thread_rng() + let s: String = thread_rng() .sample_iter(&Alphanumeric) .map(char::from) .take(128) @@ -75,7 +79,11 @@ fn test_readv() { let mut allocated = 0; while allocated < to_write.len() { let left = to_write.len() - allocated; - let vec_len = if left <= 64 { left } else { thread_rng().gen_range(64..cmp::min(256, left)) }; + let vec_len = if left <= 64 { + left + } else { + thread_rng().gen_range(64..cmp::min(256, left)) + }; let v: Vec<u8> = iter::repeat(0u8).take(vec_len).collect(); storage.push(v); allocated += vec_len; @@ -117,12 +125,12 @@ fn test_pwrite() { use std::io::Read; let mut file = tempfile().unwrap(); - let buf = [1u8;8]; + let buf = [1u8; 8]; assert_eq!(Ok(8), pwrite(file.as_raw_fd(), &buf, 8)); let mut file_content = Vec::new(); file.read_to_end(&mut file_content).unwrap(); - let mut expected = vec![0u8;8]; - expected.extend(vec![1;8]); + let mut expected = vec![0u8; 8]; + expected.extend(vec![1; 8]); assert_eq!(file_content, expected); } @@ -133,12 +141,17 @@ fn test_pread() { let tempdir = tempdir().unwrap(); let path = tempdir.path().join("pread_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let file_content: Vec<u8> = (0..64).collect(); file.write_all(&file_content).unwrap(); - let mut buf = [0u8;16]; + let mut buf = [0u8; 16]; assert_eq!(Ok(16), pread(file.as_raw_fd(), &mut buf, 16)); let expected: Vec<_> = (16..32).collect(); assert_eq!(&buf[..], &expected[..]); @@ -150,7 +163,7 @@ fn test_pwritev() { use std::io::Read; let to_write: Vec<u8> = (0..128).collect(); - let expected: Vec<u8> = [vec![0;100], to_write.clone()].concat(); + let expected: Vec<u8> = [vec![0; 100], to_write.clone()].concat(); let iovecs = [ IoSlice::new(&to_write[0..17]), @@ -162,8 +175,13 @@ fn test_pwritev() { // pwritev them into a temporary file let path = tempdir.path().join("pwritev_test_file"); - let mut file = OpenOptions::new().write(true).read(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .write(true) + .read(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); let written = pwritev(file.as_raw_fd(), &iovecs, 100).ok().unwrap(); assert_eq!(written, to_write.len()); @@ -186,20 +204,23 @@ fn test_preadv() { let path = tempdir.path().join("preadv_test_file"); - let mut file = OpenOptions::new().read(true).write(true).create(true) - .truncate(true).open(path).unwrap(); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(true) + .open(path) + .unwrap(); file.write_all(&to_write).unwrap(); - let mut buffers: Vec<Vec<u8>> = vec![ - vec![0; 24], - vec![0; 1], - vec![0; 75], - ]; + let mut buffers: Vec<Vec<u8>> = vec![vec![0; 24], vec![0; 1], vec![0; 75]]; { // Borrow the buffers into IoVecs and preadv into them - let mut iovecs: Vec<_> = buffers.iter_mut().map( - |buf| IoSliceMut::new(&mut buf[..])).collect(); + let mut iovecs: Vec<_> = buffers + .iter_mut() + .map(|buf| IoSliceMut::new(&mut buf[..])) + .collect(); assert_eq!(Ok(100), preadv(file.as_raw_fd(), &mut iovecs, 100)); } @@ -208,14 +229,15 @@ fn test_preadv() { } #[test] -#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] // uclibc doesn't implement process_vm_readv +#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] +// uclibc doesn't implement process_vm_readv // qemu-user doesn't implement process_vm_readv/writev on most arches #[cfg_attr(qemu, ignore)] fn test_process_vm_readv() { - use nix::unistd::ForkResult::*; + use crate::*; use nix::sys::signal::*; use nix::sys::wait::*; - use crate::*; + use nix::unistd::ForkResult::*; require_capability!("test_process_vm_readv", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); @@ -225,7 +247,7 @@ fn test_process_vm_readv() { let mut vector = vec![1u8, 2, 3, 4, 5]; let (r, w) = pipe().unwrap(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Parent { child } => { close(w).unwrap(); // wait for child @@ -236,16 +258,18 @@ fn test_process_vm_readv() { let remote_iov = RemoteIoVec { base: ptr, len: 5 }; let mut buf = vec![0u8; 5]; - let ret = process_vm_readv(child, - &mut [IoSliceMut::new(&mut buf)], - &[remote_iov]); + let ret = process_vm_readv( + child, + &mut [IoSliceMut::new(&mut buf)], + &[remote_iov], + ); kill(child, SIGTERM).unwrap(); waitpid(child, None).unwrap(); assert_eq!(Ok(5), ret); assert_eq!(20u8, buf.iter().sum()); - }, + } Child => { let _ = close(r); for i in &mut vector { @@ -253,7 +277,9 @@ fn test_process_vm_readv() { } let _ = write(w, b"\0"); let _ = close(w); - loop { pause(); } - }, + loop { + pause(); + } + } } } diff --git a/test/sys/test_wait.rs b/test/sys/test_wait.rs index 058573a1..1a4a0f87 100644 --- a/test/sys/test_wait.rs +++ b/test/sys/test_wait.rs @@ -1,9 +1,9 @@ +use libc::_exit; use nix::errno::Errno; -use nix::unistd::*; -use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; -use libc::_exit; +use nix::unistd::ForkResult::*; +use nix::unistd::*; #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] @@ -11,15 +11,18 @@ fn test_wait_signal() { let _m = crate::FORK_MTX.lock(); // Safe: The child only calls `pause` and/or `_exit`, which are async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - pause(); - unsafe { _exit(123) } - }, - Parent { child } => { - kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); - assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false))); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => { + pause(); + unsafe { _exit(123) } + } + Parent { child } => { + kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Signaled(child, SIGKILL, false)) + ); + } } } @@ -35,18 +38,18 @@ fn test_waitid_signal() { let _m = crate::FORK_MTX.lock(); // Safe: The child only calls `pause` and/or `_exit`, which are async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => { - pause(); - unsafe { _exit(123) } - }, - Parent { child } => { - kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); - assert_eq!( - waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::Signaled(child, SIGKILL, false)), - ); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => { + pause(); + unsafe { _exit(123) } + } + Parent { child } => { + kill(child, Some(SIGKILL)).expect("Error: Kill Failed"); + assert_eq!( + waitid(Id::Pid(child), WaitPidFlag::WEXITED), + Ok(WaitStatus::Signaled(child, SIGKILL, false)), + ); + } } } @@ -55,11 +58,13 @@ fn test_wait_exit() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => unsafe { _exit(12); }, - Parent { child } => { - assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); - }, + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => unsafe { + _exit(12); + }, + Parent { child } => { + assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); + } } } @@ -76,22 +81,30 @@ fn test_waitid_exit() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is async-signal-safe. - match unsafe{fork()}.expect("Error: Fork Failed") { - Child => unsafe { _exit(12); }, - Parent { child } => { - assert_eq!( - waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::Exited(child, 12)), - ); - } + match unsafe { fork() }.expect("Error: Fork Failed") { + Child => unsafe { + _exit(12); + }, + Parent { child } => { + assert_eq!( + waitid(Id::Pid(child), WaitPidFlag::WEXITED), + Ok(WaitStatus::Exited(child, 12)), + ); + } } } #[test] fn test_waitstatus_from_raw() { let pid = Pid::from_raw(1); - assert_eq!(WaitStatus::from_raw(pid, 0x0002), Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false))); - assert_eq!(WaitStatus::from_raw(pid, 0x0200), Ok(WaitStatus::Exited(pid, 2))); + assert_eq!( + WaitStatus::from_raw(pid, 0x0002), + Ok(WaitStatus::Signaled(pid, Signal::SIGINT, false)) + ); + assert_eq!( + WaitStatus::from_raw(pid, 0x0200), + Ok(WaitStatus::Exited(pid, 2)) + ); assert_eq!(WaitStatus::from_raw(pid, 0x7f7f), Err(Errno::EINVAL)); } @@ -99,7 +112,7 @@ fn test_waitstatus_from_raw() { fn test_waitstatus_pid() { let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.unwrap() { + match unsafe { fork() }.unwrap() { Child => unsafe { _exit(0) }, Parent { child } => { let status = waitpid(child, None).unwrap(); @@ -131,13 +144,13 @@ fn test_waitid_pid() { // FIXME: qemu-user doesn't implement ptrace on most arches #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod ptrace { - use nix::sys::ptrace::{self, Options, Event}; + use crate::*; + use libc::_exit; + use nix::sys::ptrace::{self, Event, Options}; use nix::sys::signal::*; use nix::sys::wait::*; - use nix::unistd::*; use nix::unistd::ForkResult::*; - use libc::_exit; - use crate::*; + use nix::unistd::*; fn ptrace_child() -> ! { ptrace::traceme().unwrap(); @@ -149,16 +162,30 @@ mod ptrace { fn ptrace_wait_parent(child: Pid) { // Wait for the raised SIGTRAP - assert_eq!(waitpid(child, None), Ok(WaitStatus::Stopped(child, SIGTRAP))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::Stopped(child, SIGTRAP)) + ); // We want to test a syscall stop and a PTRACE_EVENT stop - assert!(ptrace::setoptions(child, Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT).is_ok()); + assert!(ptrace::setoptions( + child, + Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT + ) + .is_ok()); // First, stop on the next system call, which will be exit() assert!(ptrace::syscall(child, None).is_ok()); assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceSyscall(child))); // Then get the ptrace event for the process exiting assert!(ptrace::cont(child, None).is_ok()); - assert_eq!(waitpid(child, None), Ok(WaitStatus::PtraceEvent(child, SIGTRAP, Event::PTRACE_EVENT_EXIT as i32))); + assert_eq!( + waitpid(child, None), + Ok(WaitStatus::PtraceEvent( + child, + SIGTRAP, + Event::PTRACE_EVENT_EXIT as i32 + )) + ); // Finally get the normal wait() result, now that the process has exited assert!(ptrace::cont(child, None).is_ok()); assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 0))); @@ -175,7 +202,11 @@ mod ptrace { Ok(WaitStatus::PtraceEvent(child, SIGTRAP, 0)), ); // We want to test a syscall stop and a PTRACE_EVENT stop - assert!(ptrace::setoptions(child, Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT).is_ok()); + assert!(ptrace::setoptions( + child, + Options::PTRACE_O_TRACESYSGOOD | Options::PTRACE_O_TRACEEXIT + ) + .is_ok()); // First, stop on the next system call, which will be exit() assert!(ptrace::syscall(child, None).is_ok()); @@ -187,7 +218,11 @@ mod ptrace { assert!(ptrace::cont(child, None).is_ok()); assert_eq!( waitid(Id::Pid(child), WaitPidFlag::WEXITED), - Ok(WaitStatus::PtraceEvent(child, SIGTRAP, Event::PTRACE_EVENT_EXIT as i32)), + Ok(WaitStatus::PtraceEvent( + child, + SIGTRAP, + Event::PTRACE_EVENT_EXIT as i32 + )), ); // Finally get the normal wait() result, now that the process has exited assert!(ptrace::cont(child, None).is_ok()); @@ -202,7 +237,7 @@ mod ptrace { require_capability!("test_wait_ptrace", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => ptrace_child(), Parent { child } => ptrace_wait_parent(child), } @@ -214,7 +249,7 @@ mod ptrace { require_capability!("test_waitid_ptrace", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => ptrace_child(), Parent { child } => ptrace_waitid_parent(child), } |