diff options
author | Costin-Robert Sin <sin.costinrobert@gmail.com> | 2022-06-21 15:36:05 +0300 |
---|---|---|
committer | Costin-Robert Sin <sin.costinrobert@gmail.com> | 2022-06-24 00:35:52 +0300 |
commit | 3e6cb639f0d9afde57d9cc03526c2e488641231b (patch) | |
tree | c882f2947fa5b22e67a58918c45012655b892b30 /test | |
parent | 8f08a69c28fad5ee875d69e4c8a1b8eed2203cb4 (diff) | |
download | nix-3e6cb639f0d9afde57d9cc03526c2e488641231b.zip |
Fix all formating problems to pass CI formating test
Signed-off-by: Costin-Robert Sin <sin.costinrobert@gmail.com>
Diffstat (limited to 'test')
37 files changed, 2142 insertions, 1233 deletions
diff --git a/test/common/mod.rs b/test/common/mod.rs index caa39ab4..bb056aab 100644 --- a/test/common/mod.rs +++ b/test/common/mod.rs @@ -1,6 +1,7 @@ use cfg_if::cfg_if; -#[macro_export] macro_rules! skip { +#[macro_export] +macro_rules! skip { ($($reason: expr),+) => { use ::std::io::{self, Write}; @@ -33,7 +34,8 @@ cfg_if! { /// Skip the test if we don't have the ability to mount file systems. #[cfg(target_os = "freebsd")] -#[macro_export] macro_rules! require_mount { +#[macro_export] +macro_rules! require_mount { ($name:expr) => { use ::sysctl::{CtlValue, Sysctl}; use nix::unistd::Uid; @@ -41,35 +43,40 @@ cfg_if! { let ctl = ::sysctl::Ctl::new("vfs.usermount").unwrap(); if !Uid::current().is_root() && CtlValue::Int(0) == ctl.value().unwrap() { - skip!("{} requires the ability to mount file systems. Skipping test.", $name); + skip!( + "{} requires the ability to mount file systems. Skipping test.", + $name + ); } - } + }; } -#[cfg(any(target_os = "linux", target_os= "android"))] -#[macro_export] macro_rules! skip_if_cirrus { +#[cfg(any(target_os = "linux", target_os = "android"))] +#[macro_export] +macro_rules! skip_if_cirrus { ($reason:expr) => { if std::env::var_os("CIRRUS_CI").is_some() { skip!("{}", $reason); } - } + }; } #[cfg(target_os = "freebsd")] -#[macro_export] macro_rules! skip_if_jailed { +#[macro_export] +macro_rules! skip_if_jailed { ($name:expr) => { use ::sysctl::{CtlValue, Sysctl}; let ctl = ::sysctl::Ctl::new("security.jail.jailed").unwrap(); - if let CtlValue::Int(1) = ctl.value().unwrap() - { + if let CtlValue::Int(1) = ctl.value().unwrap() { skip!("{} cannot run in a jail. Skipping test.", $name); } - } + }; } #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] -#[macro_export] macro_rules! skip_if_not_root { +#[macro_export] +macro_rules! skip_if_not_root { ($name:expr) => { use nix::unistd::Uid; 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), } diff --git a/test/test.rs b/test/test.rs index 240d6e37..f725ef97 100644 --- a/test/test.rs +++ b/test/test.rs @@ -10,38 +10,46 @@ mod sys; #[cfg(not(target_os = "redox"))] mod test_dir; mod test_fcntl; -#[cfg(any(target_os = "android", - target_os = "linux"))] +#[cfg(any(target_os = "android", target_os = "linux"))] mod test_kmod; -#[cfg(target_os = "freebsd")] -mod test_nmount; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "fushsia", - target_os = "linux", - target_os = "netbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "fushsia", + target_os = "linux", + target_os = "netbsd" +))] mod test_mq; #[cfg(not(target_os = "redox"))] mod test_net; mod test_nix_path; -mod test_resource; +#[cfg(target_os = "freebsd")] +mod test_nmount; mod test_poll; -#[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_pty; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "linux"))] +mod test_resource; +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "linux" +))] mod test_sched; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos" +))] mod test_sendfile; mod test_stat; mod test_time; -mod test_unistd; #[cfg(all( any( target_os = "freebsd", @@ -53,15 +61,15 @@ mod test_unistd; feature = "signal" ))] mod test_timer; +mod test_unistd; +use nix::unistd::{chdir, getcwd, read}; +use parking_lot::{Mutex, RwLock, RwLockWriteGuard}; use std::os::unix::io::RawFd; use std::path::PathBuf; -use parking_lot::{Mutex, RwLock, RwLockWriteGuard}; -use nix::unistd::{chdir, getcwd, read}; - /// Helper function analogous to `std::io::Read::read_exact`, but for `RawFD`s -fn read_exact(f: RawFd, buf: &mut [u8]) { +fn read_exact(f: RawFd, buf: &mut [u8]) { let mut len = 0; while len < buf.len() { // get_mut would be better than split_at_mut, but it requires nightly @@ -92,13 +100,13 @@ lazy_static! { /// RAII object that restores a test's original directory on drop struct DirRestore<'a> { d: PathBuf, - _g: RwLockWriteGuard<'a, ()> + _g: RwLockWriteGuard<'a, ()>, } impl<'a> DirRestore<'a> { fn new() -> Self { let guard = crate::CWD_LOCK.write(); - DirRestore{ + DirRestore { _g: guard, d: getcwd().unwrap(), } diff --git a/test/test_dir.rs b/test/test_dir.rs index aaef34e4..9d2780c0 100644 --- a/test/test_dir.rs +++ b/test/test_dir.rs @@ -4,7 +4,6 @@ use nix::sys::stat::Mode; use std::fs::File; use tempfile::tempdir; - #[cfg(test)] fn flags() -> OFlag { #[cfg(target_os = "illumos")] @@ -17,7 +16,7 @@ fn flags() -> OFlag { } #[test] -#[allow(clippy::unnecessary_sort_by)] // False positive +#[allow(clippy::unnecessary_sort_by)] // False positive fn read() { let tmp = tempdir().unwrap(); File::create(&tmp.path().join("foo")).unwrap(); @@ -43,9 +42,18 @@ fn read() { fn rewind() { let tmp = tempdir().unwrap(); let mut dir = Dir::open(tmp.path(), flags(), Mode::empty()).unwrap(); - let entries1: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect(); - let entries2: Vec<_> = dir.iter().map(|e| e.unwrap().file_name().to_owned()).collect(); - let entries3: Vec<_> = dir.into_iter().map(|e| e.unwrap().file_name().to_owned()).collect(); + let entries1: Vec<_> = dir + .iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); + let entries2: Vec<_> = dir + .iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); + let entries3: Vec<_> = dir + .into_iter() + .map(|e| e.unwrap().file_name().to_owned()) + .collect(); assert_eq!(entries1, entries2); assert_eq!(entries2, entries3); } diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 5f2e53bd..d4a12718 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -1,7 +1,7 @@ #[cfg(not(target_os = "redox"))] use nix::errno::*; #[cfg(not(target_os = "redox"))] -use nix::fcntl::{open, OFlag, readlink}; +use nix::fcntl::{open, readlink, OFlag}; #[cfg(not(target_os = "redox"))] use nix::fcntl::{openat, readlinkat, renameat}; #[cfg(all( @@ -14,19 +14,19 @@ use nix::fcntl::{openat, readlinkat, renameat}; target_arch = "s390x" ) ))] -use nix::fcntl::{RenameFlags, renameat2}; +use nix::fcntl::{renameat2, RenameFlags}; #[cfg(not(target_os = "redox"))] use nix::sys::stat::Mode; #[cfg(not(target_os = "redox"))] use nix::unistd::{close, read}; #[cfg(not(target_os = "redox"))] -use tempfile::{self, NamedTempFile}; -#[cfg(not(target_os = "redox"))] use std::fs::File; #[cfg(not(target_os = "redox"))] use std::io::prelude::*; #[cfg(not(target_os = "redox"))] use std::os::unix::fs; +#[cfg(not(target_os = "redox"))] +use tempfile::{self, NamedTempFile}; #[test] #[cfg(not(target_os = "redox"))] @@ -38,13 +38,16 @@ fn test_openat() { let mut tmp = NamedTempFile::new().unwrap(); tmp.write_all(CONTENTS).unwrap(); - let dirfd = open(tmp.path().parent().unwrap(), - OFlag::empty(), - Mode::empty()).unwrap(); - let fd = openat(dirfd, - tmp.path().file_name().unwrap(), - OFlag::O_RDONLY, - Mode::empty()).unwrap(); + let dirfd = + open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty()) + .unwrap(); + let fd = openat( + dirfd, + tmp.path().file_name().unwrap(), + OFlag::O_RDONLY, + Mode::empty(), + ) + .unwrap(); let mut buf = [0u8; 1024]; assert_eq!(4, read(fd, &mut buf).unwrap()); @@ -58,14 +61,18 @@ fn test_openat() { #[cfg(not(target_os = "redox"))] fn test_renameat() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap(); - assert_eq!(renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap_err(), - Errno::ENOENT); + assert_eq!( + renameat(Some(old_dirfd), "old", Some(new_dirfd), "new").unwrap_err(), + Errno::ENOENT + ); close(old_dirfd).unwrap(); close(new_dirfd).unwrap(); assert!(new_dir.path().join("new").exists()); @@ -84,11 +91,13 @@ fn test_renameat() { ))] fn test_renameat2_behaves_like_renameat_with_no_flags() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); renameat2( Some(old_dirfd), "old", @@ -126,14 +135,16 @@ fn test_renameat2_behaves_like_renameat_with_no_flags() { ))] fn test_renameat2_exchange() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); { let mut old_f = File::create(&old_path).unwrap(); old_f.write_all(b"old").unwrap(); } let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let new_path = new_dir.path().join("new"); { let mut new_f = File::create(&new_path).unwrap(); @@ -172,11 +183,13 @@ fn test_renameat2_exchange() { ))] fn test_renameat2_noreplace() { let old_dir = tempfile::tempdir().unwrap(); - let old_dirfd = open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let old_dirfd = + open(old_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let old_path = old_dir.path().join("old"); File::create(&old_path).unwrap(); let new_dir = tempfile::tempdir().unwrap(); - let new_dirfd = open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); + let new_dirfd = + open(new_dir.path(), OFlag::empty(), Mode::empty()).unwrap(); let new_path = new_dir.path().join("new"); File::create(&new_path).unwrap(); assert_eq!( @@ -196,7 +209,6 @@ fn test_renameat2_noreplace() { assert!(old_dir.path().join("old").exists()); } - #[test] #[cfg(not(target_os = "redox"))] fn test_readlink() { @@ -205,22 +217,22 @@ fn test_readlink() { let dst = tempdir.path().join("b"); println!("a: {:?}, b: {:?}", &src, &dst); fs::symlink(&src.as_path(), &dst.as_path()).unwrap(); - let dirfd = open(tempdir.path(), - OFlag::empty(), - Mode::empty()).unwrap(); + let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); let expected_dir = src.to_str().unwrap(); assert_eq!(readlink(&dst).unwrap().to_str().unwrap(), expected_dir); - assert_eq!(readlinkat(dirfd, "b").unwrap().to_str().unwrap(), expected_dir); - + assert_eq!( + readlinkat(dirfd, "b").unwrap().to_str().unwrap(), + expected_dir + ); } #[cfg(any(target_os = "linux", target_os = "android"))] mod linux_android { + use libc::loff_t; use std::io::prelude::*; use std::io::{IoSlice, SeekFrom}; use std::os::unix::prelude::*; - use libc::loff_t; use nix::fcntl::*; use nix::unistd::{close, pipe, read, write}; @@ -275,8 +287,15 @@ mod linux_android { let (rd, wr) = pipe().unwrap(); let mut offset: loff_t = 5; - let res = splice(tmp.as_raw_fd(), Some(&mut offset), - wr, None, 2, SpliceFFlags::empty()).unwrap(); + let res = splice( + tmp.as_raw_fd(), + Some(&mut offset), + wr, + None, + 2, + SpliceFFlags::empty(), + ) + .unwrap(); assert_eq!(2, res); @@ -321,10 +340,7 @@ mod linux_android { let buf1 = b"abcdef"; let buf2 = b"defghi"; - let iovecs = vec![ - IoSlice::new(&buf1[0..3]), - IoSlice::new(&buf2[0..3]) - ]; + let iovecs = vec![IoSlice::new(&buf1[0..3]), IoSlice::new(&buf2[0..3])]; let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap(); @@ -359,7 +375,7 @@ mod linux_android { #[test] #[cfg(all(target_os = "linux", not(target_env = "musl")))] - #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile + #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile fn test_ofd_write_lock() { use nix::sys::stat::fstat; use std::mem; @@ -377,7 +393,7 @@ mod linux_android { let inode = fstat(fd).expect("fstat failed").st_ino as usize; let mut flock: libc::flock = unsafe { - mem::zeroed() // required for Linux/mips + mem::zeroed() // required for Linux/mips }; flock.l_type = libc::F_WRLCK as libc::c_short; flock.l_whence = libc::SEEK_SET as libc::c_short; @@ -397,7 +413,7 @@ mod linux_android { #[test] #[cfg(all(target_os = "linux", not(target_env = "musl")))] - #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile + #[cfg_attr(target_env = "uclibc", ignore)] // uclibc doesn't support OFD locks, but the test should still compile fn test_ofd_read_lock() { use nix::sys::stat::fstat; use std::mem; @@ -415,7 +431,7 @@ mod linux_android { let inode = fstat(fd).expect("fstat failed").st_ino as usize; let mut flock: libc::flock = unsafe { - mem::zeroed() // required for Linux/mips + mem::zeroed() // required for Linux/mips }; flock.l_type = libc::F_RDLCK as libc::c_short; flock.l_whence = libc::SEEK_SET as libc::c_short; @@ -435,10 +451,7 @@ mod linux_android { #[cfg(all(target_os = "linux", not(target_env = "musl")))] fn lock_info(inode: usize) -> Option<(String, String)> { - use std::{ - fs::File, - io::BufReader - }; + use std::{fs::File, io::BufReader}; let file = File::open("/proc/locks").expect("open /proc/locks failed"); let buf = BufReader::new(file); @@ -458,26 +471,29 @@ mod linux_android { } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "wasi", - target_env = "uclibc", - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "wasi", + target_env = "uclibc", + target_os = "freebsd" +))] mod test_posix_fadvise { - use tempfile::NamedTempFile; - use std::os::unix::io::{RawFd, AsRawFd}; use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; + use std::os::unix::io::{AsRawFd, RawFd}; + use tempfile::NamedTempFile; #[test] fn test_success() { let tmp = NamedTempFile::new().unwrap(); let fd = tmp.as_raw_fd(); - let res = posix_fadvise(fd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED); + let res = + posix_fadvise(fd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED); assert!(res.is_ok()); } @@ -485,25 +501,35 @@ mod test_posix_fadvise { #[test] fn test_errno() { let (rd, _wr) = pipe().unwrap(); - let res = posix_fadvise(rd as RawFd, 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED); + let res = posix_fadvise( + rd as RawFd, + 0, + 100, + PosixFadviseAdvice::POSIX_FADV_WILLNEED, + ); assert_eq!(res, Err(Errno::ESPIPE)); } } -#[cfg(any(target_os = "linux", - target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "wasi", - target_os = "freebsd"))] +#[cfg(any( + target_os = "linux", + target_os = "android", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "fuchsia", + target_os = "wasi", + target_os = "freebsd" +))] mod test_posix_fallocate { - use tempfile::NamedTempFile; - use std::{io::Read, os::unix::io::{RawFd, AsRawFd}}; use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; + use std::{ + io::Read, + os::unix::io::{AsRawFd, RawFd}, + }; + use tempfile::NamedTempFile; #[test] fn success() { @@ -535,11 +561,7 @@ mod test_posix_fallocate { let err = posix_fallocate(rd as RawFd, 0, 100).unwrap_err(); match err { Errno::EINVAL | Errno::ENODEV | Errno::ESPIPE | Errno::EBADF => (), - errno => - panic!( - "unexpected errno {}", - errno, - ), + errno => panic!("unexpected errno {}", errno,), } } } diff --git a/test/test_kmod/mod.rs b/test/test_kmod/mod.rs index 8eef5384..5ebc2423 100644 --- a/test/test_kmod/mod.rs +++ b/test/test_kmod/mod.rs @@ -1,22 +1,25 @@ +use crate::*; use std::fs::copy; use std::path::PathBuf; use std::process::Command; use tempfile::{tempdir, TempDir}; -use crate::*; fn compile_kernel_module() -> (PathBuf, String, TempDir) { let _m = crate::FORK_MTX.lock(); - let tmp_dir = tempdir().expect("unable to create temporary build directory"); + let tmp_dir = + tempdir().expect("unable to create temporary build directory"); copy( "test/test_kmod/hello_mod/hello.c", &tmp_dir.path().join("hello.c"), - ).expect("unable to copy hello.c to temporary build directory"); + ) + .expect("unable to copy hello.c to temporary build directory"); copy( "test/test_kmod/hello_mod/Makefile", &tmp_dir.path().join("Makefile"), - ).expect("unable to copy Makefile to temporary build directory"); + ) + .expect("unable to copy Makefile to temporary build directory"); let status = Command::new("make") .current_dir(tmp_dir.path()) @@ -51,12 +54,16 @@ fn test_finit_and_delete_module() { delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] fn test_finit_and_delete_module_with_params() { - require_capability!("test_finit_and_delete_module_with_params", CAP_SYS_MODULE); + require_capability!( + "test_finit_and_delete_module_with_params", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -67,12 +74,14 @@ fn test_finit_and_delete_module_with_params() { &f, &CString::new("who=Rust number=2018").unwrap(), ModuleInitFlags::empty(), - ).expect("unable to load kernel module"); + ) + .expect("unable to load kernel module"); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -87,17 +96,22 @@ fn test_init_and_delete_module() { let mut contents: Vec<u8> = Vec::new(); f.read_to_end(&mut contents) .expect("unable to read kernel module content to buffer"); - init_module(&contents, &CString::new("").unwrap()).expect("unable to load kernel module"); + init_module(&contents, &CString::new("").unwrap()) + .expect("unable to load kernel module"); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] fn test_init_and_delete_module_with_params() { - require_capability!("test_init_and_delete_module_with_params", CAP_SYS_MODULE); + require_capability!( + "test_init_and_delete_module_with_params", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -113,7 +127,8 @@ fn test_init_and_delete_module_with_params() { delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -125,14 +140,18 @@ fn test_finit_module_invalid() { let kmod_path = "/dev/zero"; let f = File::open(kmod_path).expect("unable to open kernel module"); - let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); + let result = + finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); assert_eq!(result.unwrap_err(), Errno::EINVAL); } #[test] fn test_finit_module_twice_and_delete_module() { - require_capability!("test_finit_module_twice_and_delete_module", CAP_SYS_MODULE); + require_capability!( + "test_finit_module_twice_and_delete_module", + CAP_SYS_MODULE + ); let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); @@ -142,14 +161,16 @@ fn test_finit_module_twice_and_delete_module() { finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()) .expect("unable to load kernel module"); - let result = finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); + let result = + finit_module(&f, &CString::new("").unwrap(), ModuleInitFlags::empty()); assert_eq!(result.unwrap_err(), Errno::EEXIST); delete_module( &CString::new(kmod_name).unwrap(), DeleteModuleFlags::empty(), - ).expect("unable to unload kernel module"); + ) + .expect("unable to unload kernel module"); } #[test] @@ -158,7 +179,10 @@ fn test_delete_module_not_loaded() { let _m0 = crate::KMOD_MTX.lock(); let _m1 = crate::CWD_LOCK.read(); - let result = delete_module(&CString::new("hello").unwrap(), DeleteModuleFlags::empty()); + let result = delete_module( + &CString::new("hello").unwrap(), + DeleteModuleFlags::empty(), + ); assert_eq!(result.unwrap_err(), Errno::ENOENT); } diff --git a/test/test_mount.rs b/test/test_mount.rs index 1ddfcfe9..febcadfb 100644 --- a/test/test_mount.rs +++ b/test/test_mount.rs @@ -27,16 +27,18 @@ exit 23"; const EXPECTED_STATUS: i32 = 23; const NONE: Option<&'static [u8]> = None; - #[allow(clippy::bind_instead_of_map)] // False positive + #[allow(clippy::bind_instead_of_map)] // False positive pub fn test_mount_tmpfs_without_flags_allows_rwx() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::empty(), - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::empty(), + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -46,8 +48,10 @@ exit 23"; .write(true) .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) .open(&test_path) - .or_else(|e| - if Errno::from_i32(e.raw_os_error().unwrap()) == Errno::EOVERFLOW { + .or_else(|e| { + if Errno::from_i32(e.raw_os_error().unwrap()) + == Errno::EOVERFLOW + { // Skip tests on certain Linux kernels which have a bug // regarding tmpfs in namespaces. // Ubuntu 14.04 and 16.04 are known to be affected; 16.10 is @@ -56,13 +60,16 @@ exit 23"; // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1659087 let stderr = io::stderr(); let mut handle = stderr.lock(); - writeln!(handle, "Buggy Linux kernel detected. Skipping test.") + writeln!( + handle, + "Buggy Linux kernel detected. Skipping test." + ) .unwrap(); process::exit(0); - } else { - panic!("open failed: {}", e); - } - ) + } else { + panic!("open failed: {}", e); + } + }) .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {}", e)); @@ -74,42 +81,55 @@ exit 23"; assert_eq!(buf, SCRIPT_CONTENTS); // Verify execute. - assert_eq!(EXPECTED_STATUS, - Command::new(&test_path) - .status() - .unwrap_or_else(|e| panic!("exec failed: {}", e)) - .code() - .unwrap_or_else(|| panic!("child killed by signal"))); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EXPECTED_STATUS, + Command::new(&test_path) + .status() + .unwrap_or_else(|e| panic!("exec failed: {}", e)) + .code() + .unwrap_or_else(|| panic!("child killed by signal")) + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_rdonly_disallows_write() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_RDONLY, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_RDONLY, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); // EROFS: Read-only file system - assert_eq!(EROFS as i32, - File::create(tempdir.path().join("test")).unwrap_err().raw_os_error().unwrap()); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EROFS as i32, + File::create(tempdir.path().join("test")) + .unwrap_err() + .raw_os_error() + .unwrap() + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_noexec_disallows_exec() { let tempdir = tempfile::tempdir().unwrap(); - mount(NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_NOEXEC, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_NOEXEC, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); let test_path = tempdir.path().join("test"); @@ -122,21 +142,30 @@ exit 23"; .unwrap_or_else(|e| panic!("write failed: {}", e)); // Verify that we cannot execute despite a+x permissions being set. - let mode = stat::Mode::from_bits_truncate(fs::metadata(&test_path) - .map(|md| md.permissions().mode()) - .unwrap_or_else(|e| { - panic!("metadata failed: {}", e) - })); - - assert!(mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), - "{:?} did not have execute permissions", - &test_path); + let mode = stat::Mode::from_bits_truncate( + fs::metadata(&test_path) + .map(|md| md.permissions().mode()) + .unwrap_or_else(|e| panic!("metadata failed: {}", e)), + ); + + assert!( + mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), + "{:?} did not have execute permissions", + &test_path + ); // EACCES: Permission denied - assert_eq!(EACCES as i32, - Command::new(&test_path).status().unwrap_err().raw_os_error().unwrap()); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + assert_eq!( + EACCES as i32, + Command::new(&test_path) + .status() + .unwrap_err() + .raw_os_error() + .unwrap() + ); + + umount(tempdir.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } pub fn test_mount_bind() { @@ -146,12 +175,14 @@ exit 23"; { let mount_point = tempfile::tempdir().unwrap(); - mount(Some(tempdir.path()), - mount_point.path(), - NONE, - MsFlags::MS_BIND, - NONE) - .unwrap_or_else(|e| panic!("mount failed: {}", e)); + mount( + Some(tempdir.path()), + mount_point.path(), + NONE, + MsFlags::MS_BIND, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {}", e)); fs::OpenOptions::new() .create(true) @@ -161,7 +192,8 @@ exit 23"; .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {}", e)); - umount(mount_point.path()).unwrap_or_else(|e| panic!("umount failed: {}", e)); + umount(mount_point.path()) + .unwrap_or_else(|e| panic!("umount failed: {}", e)); } // Verify the file written in the mount shows up in source directory, even @@ -199,7 +231,6 @@ exit 23"; } } - // Test runner /// Mimic normal test output (hackishly). @@ -220,16 +251,20 @@ macro_rules! run_tests { #[cfg(target_os = "linux")] fn main() { - use test_mount::{setup_namespaces, test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, test_mount_noexec_disallows_exec, - test_mount_bind}; + use test_mount::{ + setup_namespaces, test_mount_bind, test_mount_noexec_disallows_exec, + test_mount_rdonly_disallows_write, + test_mount_tmpfs_without_flags_allows_rwx, + }; skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1351"); setup_namespaces(); - run_tests!(test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, - test_mount_noexec_disallows_exec, - test_mount_bind); + run_tests!( + test_mount_tmpfs_without_flags_allows_rwx, + test_mount_rdonly_disallows_write, + test_mount_noexec_disallows_exec, + test_mount_bind + ); } #[cfg(not(target_os = "linux"))] diff --git a/test/test_mq.rs b/test/test_mq.rs index 8aff840d..7b48e7ac 100644 --- a/test/test_mq.rs +++ b/test/test_mq.rs @@ -3,8 +3,8 @@ use std::ffi::CString; use std::str; use nix::errno::Errno; -use nix::mqueue::{mq_open, mq_close, mq_send, mq_receive, mq_attr_member_t}; -use nix::mqueue::{MqAttr, MQ_OFlag}; +use nix::mqueue::{mq_attr_member_t, mq_close, mq_open, mq_receive, mq_send}; +use nix::mqueue::{MQ_OFlag, MqAttr}; use nix::sys::stat::Mode; // Defined as a macro such that the error source is reported as the caller's location. @@ -29,8 +29,8 @@ macro_rules! assert_attr_eq { #[test] fn test_mq_send_and_receive() { const MSG_SIZE: mq_attr_member_t = 32; - let attr = MqAttr::new(0, 10, MSG_SIZE, 0); - let mq_name= &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); + let attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let mq_name = &CString::new(b"/a_nix_test_queue".as_ref()).unwrap(); let oflag0 = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -55,12 +55,11 @@ fn test_mq_send_and_receive() { assert_eq!(msg_to_send, str::from_utf8(&buf[0..len]).unwrap()); } - #[test] fn test_mq_getattr() { use nix::mqueue::mq_getattr; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -78,15 +77,14 @@ fn test_mq_getattr() { // FIXME: Fix failures for mips in QEMU #[test] -#[cfg_attr(all( - qemu, - any(target_arch = "mips", target_arch = "mips64") - ), ignore +#[cfg_attr( + all(qemu, any(target_arch = "mips", target_arch = "mips64")), + ignore )] fn test_mq_setattr() { use nix::mqueue::{mq_getattr, mq_setattr}; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -109,7 +107,12 @@ fn test_mq_setattr() { assert_ne!(new_attr_get, new_attr); } - let new_attr_non_blocking = MqAttr::new(MQ_OFlag::O_NONBLOCK.bits() as mq_attr_member_t, 10, MSG_SIZE, 0); + let new_attr_non_blocking = MqAttr::new( + MQ_OFlag::O_NONBLOCK.bits() as mq_attr_member_t, + 10, + MSG_SIZE, + 0, + ); mq_setattr(&mqd, &new_attr_non_blocking).unwrap(); let new_attr_get = mq_getattr(&mqd).unwrap(); @@ -124,15 +127,14 @@ fn test_mq_setattr() { // FIXME: Fix failures for mips in QEMU #[test] -#[cfg_attr(all( - qemu, - any(target_arch = "mips", target_arch = "mips64") - ), ignore +#[cfg_attr( + all(qemu, any(target_arch = "mips", target_arch = "mips64")), + ignore )] fn test_mq_set_nonblocking() { - use nix::mqueue::{mq_getattr, mq_set_nonblock, mq_remove_nonblock}; + use nix::mqueue::{mq_getattr, mq_remove_nonblock, mq_set_nonblock}; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name = &CString::new(b"/attr_test_get_attr".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; @@ -156,10 +158,11 @@ fn test_mq_set_nonblocking() { fn test_mq_unlink() { use nix::mqueue::mq_unlink; const MSG_SIZE: mq_attr_member_t = 32; - let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); + let initial_attr = MqAttr::new(0, 10, MSG_SIZE, 0); let mq_name_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); #[cfg(not(any(target_os = "dragonfly", target_os = "netbsd")))] - let mq_name_not_opened = &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); + let mq_name_not_opened = + &CString::new(b"/mq_unlink_test".as_ref()).unwrap(); let oflag = MQ_OFlag::O_CREAT | MQ_OFlag::O_WRONLY; let mode = Mode::S_IWUSR | Mode::S_IRUSR | Mode::S_IRGRP | Mode::S_IROTH; let r = mq_open(mq_name_opened, oflag, mode, Some(&initial_attr)); @@ -170,7 +173,7 @@ fn test_mq_unlink() { let mqd = r.unwrap(); let res_unlink = mq_unlink(mq_name_opened); - assert_eq!(res_unlink, Ok(()) ); + assert_eq!(res_unlink, Ok(())); // NetBSD (and others which inherit its implementation) defer removing the message // queue name until all references are closed, whereas Linux and others remove the @@ -178,10 +181,10 @@ fn test_mq_unlink() { #[cfg(not(any(target_os = "dragonfly", target_os = "netbsd")))] { let res_unlink_not_opened = mq_unlink(mq_name_not_opened); - assert_eq!(res_unlink_not_opened, Err(Errno::ENOENT) ); + assert_eq!(res_unlink_not_opened, Err(Errno::ENOENT)); } mq_close(mqd).unwrap(); let res_unlink_after_close = mq_unlink(mq_name_opened); - assert_eq!(res_unlink_after_close, Err(Errno::ENOENT) ); + assert_eq!(res_unlink_after_close, Err(Errno::ENOENT)); } diff --git a/test/test_net.rs b/test/test_net.rs index 78a09b6c..d1050c16 100644 --- a/test/test_net.rs +++ b/test/test_net.rs @@ -3,7 +3,11 @@ use nix::net::if_::*; #[cfg(any(target_os = "android", target_os = "linux"))] const LOOPBACK: &[u8] = b"lo"; -#[cfg(not(any(target_os = "android", target_os = "linux", target_os = "haiku")))] +#[cfg(not(any( + target_os = "android", + target_os = "linux", + target_os = "haiku" +)))] const LOOPBACK: &[u8] = b"lo0"; #[cfg(target_os = "haiku")] diff --git a/test/test_nix_path.rs b/test/test_nix_path.rs index e69de29b..8b137891 100644 --- a/test/test_nix_path.rs +++ b/test/test_nix_path.rs @@ -0,0 +1 @@ + diff --git a/test/test_nmount.rs b/test/test_nmount.rs index 4c74ecf6..dec806a5 100644 --- a/test/test_nmount.rs +++ b/test/test_nmount.rs @@ -1,13 +1,9 @@ use crate::*; use nix::{ errno::Errno, - mount::{MntFlags, Nmount, unmount} -}; -use std::{ - ffi::CString, - fs::File, - path::Path + mount::{unmount, MntFlags, Nmount}, }; +use std::{ffi::CString, fs::File, path::Path}; use tempfile::tempdir; #[test] @@ -24,14 +20,15 @@ fn ok() { .str_opt(&fstype, &nullfs) .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) .str_opt_owned("target", target.path().to_str().unwrap()) - .nmount(MntFlags::empty()).unwrap(); - + .nmount(MntFlags::empty()) + .unwrap(); + // Now check that the sentry is visible through the mountpoint let exists = Path::exists(&mountpoint.path().join("sentry")); // Cleanup the mountpoint before asserting unmount(mountpoint.path(), MntFlags::empty()).unwrap(); - + assert!(exists); } @@ -44,8 +41,9 @@ fn bad_fstype() { let e = Nmount::new() .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) .str_opt_owned("target", target.path().to_str().unwrap()) - .nmount(MntFlags::empty()).unwrap_err(); - + .nmount(MntFlags::empty()) + .unwrap_err(); + assert_eq!(e.error(), Errno::EINVAL); assert_eq!(e.errmsg(), Some("Invalid fstype")); } diff --git a/test/test_poll.rs b/test/test_poll.rs index 120e8e56..53964e26 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -1,7 +1,7 @@ use nix::{ errno::Errno, - poll::{PollFlags, poll, PollFd}, - unistd::{write, pipe} + poll::{poll, PollFd, PollFlags}, + unistd::{pipe, write}, }; macro_rules! loop_while_eintr { @@ -10,10 +10,10 @@ macro_rules! loop_while_eintr { match $poll_expr { Ok(nfds) => break nfds, Err(Errno::EINTR) => (), - Err(e) => panic!("{}", e) + Err(e) => panic!("{}", e), } } - } + }; } #[test] @@ -37,10 +37,12 @@ fn test_poll() { // ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating the test for poll(2) should be sufficient to check that our // bindings are correct. -#[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" +))] #[test] fn test_ppoll() { use nix::poll::ppoll; diff --git a/test/test_pty.rs b/test/test_pty.rs index 1a7cab81..3b52289e 100644 --- a/test/test_pty.rs +++ b/test/test_pty.rs @@ -1,15 +1,15 @@ use std::fs::File; use std::io::{Read, Write}; -use std::path::Path; use std::os::unix::prelude::*; +use std::path::Path; use tempfile::tempfile; use libc::{_exit, STDOUT_FILENO}; -use nix::fcntl::{OFlag, open}; +use nix::fcntl::{open, OFlag}; use nix::pty::*; use nix::sys::stat; use nix::sys::termios::*; -use nix::unistd::{write, close, pause}; +use nix::unistd::{close, pause, write}; /// Regression test for Issue #659 /// This is the correct way to explicitly close a `PtyMaster` @@ -36,7 +36,7 @@ fn test_ptsname_equivalence() { assert!(master_fd.as_raw_fd() > 0); // Get the name of the slave - let slave_name = unsafe { ptsname(&master_fd) }.unwrap() ; + let slave_name = unsafe { ptsname(&master_fd) }.unwrap(); let slave_name_r = ptsname_r(&master_fd).unwrap(); assert_eq!(slave_name, slave_name_r); } @@ -111,7 +111,9 @@ fn open_ptty_pair() -> (PtyMaster, File) { let slave_name = unsafe { ptsname(&master) }.expect("ptsname failed"); // Open the slave device - let slave_fd = open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()).unwrap(); + let slave_fd = + open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()) + .unwrap(); #[cfg(target_os = "illumos")] // TODO: rewrite using ioctl! @@ -279,9 +281,9 @@ fn test_openpty_with_termios() { #[test] fn test_forkpty() { - use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::wait; + use nix::unistd::ForkResult::*; // forkpty calls openpty which uses ptname(3) internally. let _m0 = crate::PTSNAME_MTX.lock(); // forkpty spawns a child process @@ -289,15 +291,15 @@ fn test_forkpty() { let string = "naninani\n"; let echoed_string = "naninani\r\n"; - let pty = unsafe { - forkpty(None, None).unwrap() - }; + let pty = unsafe { forkpty(None, None).unwrap() }; match pty.fork_result { Child => { write(STDOUT_FILENO, string.as_bytes()).unwrap(); - pause(); // we need the child to stay alive until the parent calls read - unsafe { _exit(0); } - }, + pause(); // we need the child to stay alive until the parent calls read + unsafe { + _exit(0); + } + } Parent { child } => { let mut buf = [0u8; 10]; assert!(child.as_raw() > 0); @@ -306,6 +308,6 @@ fn test_forkpty() { wait().unwrap(); // keep other tests using generic wait from getting our child assert_eq!(&buf, echoed_string.as_bytes()); close(pty.master).unwrap(); - }, + } } } diff --git a/test/test_ptymaster_drop.rs b/test/test_ptymaster_drop.rs index a68f81ee..ffbaa569 100644 --- a/test/test_ptymaster_drop.rs +++ b/test/test_ptymaster_drop.rs @@ -15,6 +15,6 @@ mod t { fn test_double_close() { let m = posix_openpt(OFlag::O_RDWR).unwrap(); close(m.as_raw_fd()).unwrap(); - drop(m); // should panic here + drop(m); // should panic here } } diff --git a/test/test_resource.rs b/test/test_resource.rs index f96bf903..2ab581ba 100644 --- a/test/test_resource.rs +++ b/test/test_resource.rs @@ -1,4 +1,9 @@ -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "illumos", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "illumos", + target_os = "haiku" +)))] use nix::sys::resource::{getrlimit, setrlimit, Resource}; /// Tests the RLIMIT_NOFILE functionality of getrlimit(), where the resource RLIMIT_NOFILE refers @@ -10,9 +15,15 @@ use nix::sys::resource::{getrlimit, setrlimit, Resource}; /// to put the new soft limit in effect, and then getrlimit() once more to ensure the limits have /// been updated. #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "illumos", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "illumos", + target_os = "haiku" +)))] pub fn test_resource_limits_nofile() { - let (mut soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap(); + let (mut soft_limit, hard_limit) = + getrlimit(Resource::RLIMIT_NOFILE).unwrap(); soft_limit -= 1; assert_ne!(soft_limit, hard_limit); diff --git a/test/test_sched.rs b/test/test_sched.rs index 922196a3..ebf346db 100644 --- a/test/test_sched.rs +++ b/test/test_sched.rs @@ -24,7 +24,10 @@ fn test_sched_affinity() { let updated_affinity = sched_getaffinity(Pid::from_raw(0)).unwrap(); for field in 0..CpuSet::count() { // Should be set only for the CPU we set previously - assert_eq!(updated_affinity.is_set(field).unwrap(), field==last_valid_cpu) + assert_eq!( + updated_affinity.is_set(field).unwrap(), + field == last_valid_cpu + ) } // Finally, reset the initial CPU set diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index e56ff12f..f73a3b56 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -62,7 +62,8 @@ fn test_sendfile64_linux() { #[test] fn test_sendfile_freebsd() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -72,8 +73,10 @@ fn test_sendfile_freebsd() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -93,8 +96,9 @@ fn test_sendfile_freebsd() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); @@ -109,7 +113,8 @@ fn test_sendfile_freebsd() { #[test] fn test_sendfile_dragonfly() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -119,8 +124,10 @@ fn test_sendfile_dragonfly() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -138,8 +145,9 @@ fn test_sendfile_dragonfly() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); @@ -154,7 +162,8 @@ fn test_sendfile_dragonfly() { #[test] fn test_sendfile_darwin() { // Declare the content - let header_strings = vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let header_strings = + vec!["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; let body = "Xabcdef123456"; let body_offset = 1; let trailer_strings = vec!["\n", "Served by Make Believe\n"]; @@ -164,8 +173,10 @@ fn test_sendfile_darwin() { tmp.write_all(body.as_bytes()).unwrap(); // Prepare headers and trailers for sendfile - let headers: Vec<&[u8]> = header_strings.iter().map(|s| s.as_bytes()).collect(); - let trailers: Vec<&[u8]> = trailer_strings.iter().map(|s| s.as_bytes()).collect(); + let headers: Vec<&[u8]> = + header_strings.iter().map(|s| s.as_bytes()).collect(); + let trailers: Vec<&[u8]> = + trailer_strings.iter().map(|s| s.as_bytes()).collect(); // Prepare socket pair let (mut rd, wr) = UnixStream::pair().unwrap(); @@ -183,8 +194,9 @@ fn test_sendfile_darwin() { wr.shutdown(Shutdown::Both).unwrap(); // Prepare the expected result - let expected_string = - header_strings.concat() + &body[body_offset..] + &trailer_strings.concat(); + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); // Verify the message that was sent assert_eq!(bytes_written as usize, expected_string.as_bytes().len()); diff --git a/test/test_stat.rs b/test/test_stat.rs index 3a09eca5..de5a964e 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -2,43 +2,45 @@ use std::fs; use std::fs::File; #[cfg(not(target_os = "redox"))] -use std::os::unix::fs::{symlink}; +use std::os::unix::fs::symlink; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use std::os::unix::fs::{PermissionsExt}; +use std::os::unix::fs::PermissionsExt; use std::os::unix::prelude::AsRawFd; -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use std::time::{Duration, UNIX_EPOCH}; #[cfg(not(target_os = "redox"))] use std::path::Path; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use std::time::{Duration, UNIX_EPOCH}; -#[cfg(not(any(target_os = "netbsd", target_os = "redox")))] -use libc::{S_IFMT, S_IFLNK}; use libc::mode_t; +#[cfg(not(any(target_os = "netbsd", target_os = "redox")))] +use libc::{S_IFLNK, S_IFMT}; #[cfg(not(target_os = "redox"))] +use nix::errno::Errno; +#[cfg(not(target_os = "redox"))] use nix::fcntl; +#[cfg(any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] +use nix::sys::stat::lutimes; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::sys::stat::utimensat; #[cfg(not(target_os = "redox"))] -use nix::errno::Errno; +use nix::sys::stat::FchmodatFlags; +use nix::sys::stat::Mode; +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +use nix::sys::stat::UtimensatFlags; #[cfg(not(target_os = "redox"))] use nix::sys::stat::{self}; -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use nix::sys::stat::{futimens, utimes}; use nix::sys::stat::{fchmod, stat}; #[cfg(not(target_os = "redox"))] use nix::sys::stat::{fchmodat, mkdirat}; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use nix::sys::stat::{utimensat}; -#[cfg(any(target_os = "linux", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd"))] -use nix::sys::stat::lutimes; -#[cfg(not(target_os = "redox"))] -use nix::sys::stat::{FchmodatFlags}; -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use nix::sys::stat::{UtimensatFlags}; -use nix::sys::stat::Mode; +use nix::sys::stat::{futimens, utimes}; #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] use nix::sys::stat::FileStat; @@ -54,32 +56,35 @@ use nix::Result; #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] fn assert_stat_results(stat_result: Result<FileStat>) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer - assert_eq!(stats.st_nlink, 1); // there links created, must be 1 - assert_eq!(stats.st_size, 0); // size is 0 because we did not write anything to the file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer + assert_eq!(stats.st_nlink, 1); // there links created, must be 1 + assert_eq!(stats.st_size, 0); // size is 0 because we did not write anything to the file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_blocks <= 16); // Up to 16 blocks can be allocated for a blank file } #[cfg(not(any(target_os = "netbsd", target_os = "redox")))] // (Android's st_blocks is ulonglong which is always non-negative.) #[cfg_attr(target_os = "android", allow(unused_comparisons))] -#[allow(clippy::absurd_extreme_comparisons)] // Not absurd on all OSes +#[allow(clippy::absurd_extreme_comparisons)] // Not absurd on all OSes fn assert_lstat_results(stat_result: Result<FileStat>) { let stats = stat_result.expect("stat call failed"); - assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent - assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent - assert!(stats.st_mode > 0); // must be positive integer + assert!(stats.st_dev > 0); // must be positive integer, exact number machine dependent + assert!(stats.st_ino > 0); // inode is positive integer, exact number machine dependent + assert!(stats.st_mode > 0); // must be positive integer // st_mode is c_uint (u32 on Android) while S_IFMT is mode_t // (u16 on Android), and that will be a compile error. // On other platforms they are the same (either both are u16 or u32). - assert_eq!((stats.st_mode as usize) & (S_IFMT as usize), S_IFLNK as usize); // should be a link - assert_eq!(stats.st_nlink, 1); // there links created, must be 1 - assert!(stats.st_size > 0); // size is > 0 because it points to another file - assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent + assert_eq!( + (stats.st_mode as usize) & (S_IFMT as usize), + S_IFLNK as usize + ); // should be a link + assert_eq!(stats.st_nlink, 1); // there links created, must be 1 + assert!(stats.st_size > 0); // size is > 0 because it points to another file + assert!(stats.st_blksize > 0); // must be positive integer, exact number machine dependent // st_blocks depends on whether the machine's file system uses fast // or slow symlinks, so just make sure it's not negative @@ -108,13 +113,11 @@ fn test_fstatat() { let tempdir = tempfile::tempdir().unwrap(); let filename = tempdir.path().join("foo.txt"); File::create(&filename).unwrap(); - let dirfd = fcntl::open(tempdir.path(), - fcntl::OFlag::empty(), - stat::Mode::empty()); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()); - let result = stat::fstatat(dirfd.unwrap(), - &filename, - fcntl::AtFlags::empty()); + let result = + stat::fstatat(dirfd.unwrap(), &filename, fcntl::AtFlags::empty()); assert_stat_results(result); } @@ -174,12 +177,15 @@ fn test_fchmodat() { let fullpath = tempdir.path().join(filename); File::create(&fullpath).unwrap(); - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); let mut mode1 = Mode::empty(); mode1.insert(Mode::S_IRUSR); mode1.insert(Mode::S_IWUSR); - fchmodat(Some(dirfd), filename, mode1, FchmodatFlags::FollowSymlink).unwrap(); + fchmodat(Some(dirfd), filename, mode1, FchmodatFlags::FollowSymlink) + .unwrap(); let file_stat1 = stat(&fullpath).unwrap(); assert_eq!(file_stat1.st_mode as mode_t & 0o7777, mode1.bits()); @@ -199,13 +205,19 @@ fn test_fchmodat() { /// The atime and mtime are expressed with a resolution of seconds because some file systems /// (like macOS's HFS+) do not have higher granularity. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -fn assert_times_eq(exp_atime_sec: u64, exp_mtime_sec: u64, attr: &fs::Metadata) { +fn assert_times_eq( + exp_atime_sec: u64, + exp_mtime_sec: u64, + attr: &fs::Metadata, +) { assert_eq!( Duration::new(exp_atime_sec, 0), - attr.accessed().unwrap().duration_since(UNIX_EPOCH).unwrap()); + attr.accessed().unwrap().duration_since(UNIX_EPOCH).unwrap() + ); assert_eq!( Duration::new(exp_mtime_sec, 0), - attr.modified().unwrap().duration_since(UNIX_EPOCH).unwrap()); + attr.modified().unwrap().duration_since(UNIX_EPOCH).unwrap() + ); } #[test] @@ -215,16 +227,19 @@ fn test_utimes() { let fullpath = tempdir.path().join("file"); drop(File::create(&fullpath).unwrap()); - utimes(&fullpath, &TimeVal::seconds(9990), &TimeVal::seconds(5550)).unwrap(); + utimes(&fullpath, &TimeVal::seconds(9990), &TimeVal::seconds(5550)) + .unwrap(); assert_times_eq(9990, 5550, &fs::metadata(&fullpath).unwrap()); } #[test] -#[cfg(any(target_os = "linux", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd"))] +#[cfg(any( + target_os = "linux", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] fn test_lutimes() { let tempdir = tempfile::tempdir().unwrap(); let target = tempdir.path().join("target"); @@ -233,14 +248,21 @@ fn test_lutimes() { symlink(&target, &fullpath).unwrap(); let exp_target_metadata = fs::symlink_metadata(&target).unwrap(); - lutimes(&fullpath, &TimeVal::seconds(4560), &TimeVal::seconds(1230)).unwrap(); + lutimes(&fullpath, &TimeVal::seconds(4560), &TimeVal::seconds(1230)) + .unwrap(); assert_times_eq(4560, 1230, &fs::symlink_metadata(&fullpath).unwrap()); let target_metadata = fs::symlink_metadata(&target).unwrap(); - assert_eq!(exp_target_metadata.accessed().unwrap(), target_metadata.accessed().unwrap(), - "atime of symlink target was unexpectedly modified"); - assert_eq!(exp_target_metadata.modified().unwrap(), target_metadata.modified().unwrap(), - "mtime of symlink target was unexpectedly modified"); + assert_eq!( + exp_target_metadata.accessed().unwrap(), + target_metadata.accessed().unwrap(), + "atime of symlink target was unexpectedly modified" + ); + assert_eq!( + exp_target_metadata.modified().unwrap(), + target_metadata.modified().unwrap(), + "mtime of symlink target was unexpectedly modified" + ); } #[test] @@ -250,7 +272,8 @@ fn test_futimens() { let fullpath = tempdir.path().join("file"); drop(File::create(&fullpath).unwrap()); - let fd = fcntl::open(&fullpath, fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let fd = fcntl::open(&fullpath, fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); futimens(fd, &TimeSpec::seconds(10), &TimeSpec::seconds(20)).unwrap(); assert_times_eq(10, 20, &fs::metadata(&fullpath).unwrap()); @@ -265,16 +288,30 @@ fn test_utimensat() { let fullpath = tempdir.path().join(filename); drop(File::create(&fullpath).unwrap()); - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); - utimensat(Some(dirfd), filename, &TimeSpec::seconds(12345), &TimeSpec::seconds(678), - UtimensatFlags::FollowSymlink).unwrap(); + utimensat( + Some(dirfd), + filename, + &TimeSpec::seconds(12345), + &TimeSpec::seconds(678), + UtimensatFlags::FollowSymlink, + ) + .unwrap(); assert_times_eq(12345, 678, &fs::metadata(&fullpath).unwrap()); chdir(tempdir.path()).unwrap(); - utimensat(None, filename, &TimeSpec::seconds(500), &TimeSpec::seconds(800), - UtimensatFlags::FollowSymlink).unwrap(); + utimensat( + None, + filename, + &TimeSpec::seconds(500), + &TimeSpec::seconds(800), + UtimensatFlags::FollowSymlink, + ) + .unwrap(); assert_times_eq(500, 800, &fs::metadata(&fullpath).unwrap()); } @@ -283,7 +320,9 @@ fn test_utimensat() { fn test_mkdirat_success_path() { let tempdir = tempfile::tempdir().unwrap(); let filename = "example_subdir"; - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); assert!((mkdirat(dirfd, filename, Mode::S_IRWXU)).is_ok()); assert!(Path::exists(&tempdir.path().join(filename))); } @@ -291,12 +330,17 @@ fn test_mkdirat_success_path() { #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_mkdirat_success_mode() { - let expected_bits = stat::SFlag::S_IFDIR.bits() | stat::Mode::S_IRWXU.bits(); + let expected_bits = + stat::SFlag::S_IFDIR.bits() | stat::Mode::S_IRWXU.bits(); let tempdir = tempfile::tempdir().unwrap(); let filename = "example_subdir"; - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); assert!((mkdirat(dirfd, filename, Mode::S_IRWXU)).is_ok()); - let permissions = fs::metadata(tempdir.path().join(filename)).unwrap().permissions(); + let permissions = fs::metadata(tempdir.path().join(filename)) + .unwrap() + .permissions(); let mode = permissions.mode(); assert_eq!(mode as mode_t, expected_bits) } @@ -305,21 +349,27 @@ fn test_mkdirat_success_mode() { #[cfg(not(target_os = "redox"))] fn test_mkdirat_fail() { let tempdir = tempfile::tempdir().unwrap(); - let not_dir_filename= "example_not_dir"; + let not_dir_filename = "example_not_dir"; let filename = "example_subdir_dir"; - let dirfd = fcntl::open(&tempdir.path().join(not_dir_filename), fcntl::OFlag::O_CREAT, - stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + &tempdir.path().join(not_dir_filename), + fcntl::OFlag::O_CREAT, + stat::Mode::empty(), + ) + .unwrap(); let result = mkdirat(dirfd, filename, Mode::S_IRWXU).unwrap_err(); assert_eq!(result, Errno::ENOTDIR); } #[test] -#[cfg(not(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "haiku", - target_os = "redox")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "haiku", + target_os = "redox" +)))] fn test_mknod() { use stat::{lstat, mknod, SFlag}; @@ -333,13 +383,15 @@ fn test_mknod() { } #[test] -#[cfg(not(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "ios", - target_os = "macos", - target_os = "haiku", - target_os = "redox")))] +#[cfg(not(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "illumos", + target_os = "ios", + target_os = "macos", + target_os = "haiku", + target_os = "redox" +)))] fn test_mknodat() { use fcntl::{AtFlags, OFlag}; use nix::dir::Dir; @@ -347,7 +399,8 @@ fn test_mknodat() { let file_name = "test_file"; let tempdir = tempfile::tempdir().unwrap(); - let target_dir = Dir::open(tempdir.path(), OFlag::O_DIRECTORY, Mode::S_IRWXU).unwrap(); + let target_dir = + Dir::open(tempdir.path(), OFlag::O_DIRECTORY, Mode::S_IRWXU).unwrap(); mknodat( target_dir.as_raw_fd(), file_name, diff --git a/test/test_timer.rs b/test/test_timer.rs index d07d9633..ffd14686 100644 --- a/test/test_timer.rs +++ b/test/test_timer.rs @@ -1,5 +1,6 @@ use nix::sys::signal::{ - sigaction, SaFlags, SigAction, SigEvent, SigHandler, SigSet, SigevNotify, Signal, + sigaction, SaFlags, SigAction, SigEvent, SigHandler, SigSet, SigevNotify, + Signal, }; use nix::sys::timer::{Expiration, Timer, TimerSetTimeFlags}; use nix::time::ClockId; @@ -32,9 +33,12 @@ fn alarm_fires() { // Create a handler for the test signal, `SIG`. The handler is responsible // for flipping `ALARM_CALLED`. let handler = SigHandler::Handler(handle_sigalarm); - let signal_action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); - let old_handler = - unsafe { sigaction(SIG, &signal_action).expect("unable to set signal handler for alarm") }; + let signal_action = + SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); + let old_handler = unsafe { + sigaction(SIG, &signal_action) + .expect("unable to set signal handler for alarm") + }; // Create the timer. We use the monotonic clock here, though any would do // really. The timer is set to fire every 250 milliseconds with no delay for @@ -44,7 +48,8 @@ fn alarm_fires() { signal: SIG, si_value: 0, }); - let mut timer = Timer::new(clockid, sigevent).expect("failed to create timer"); + let mut timer = + Timer::new(clockid, sigevent).expect("failed to create timer"); let expiration = Expiration::Interval(TIMER_PERIOD.into()); let flags = TimerSetTimeFlags::empty(); timer.set(expiration, flags).expect("could not set timer"); @@ -60,12 +65,10 @@ fn alarm_fires() { // represents a delay to the next expiration. We're only interested in the // timer still being extant. match timer.get() { - Ok(Some(exp)) => { - assert!(matches!( - exp, - Expiration::Interval(..) | Expiration::IntervalDelayed(..) - )) - } + Ok(Some(exp)) => assert!(matches!( + exp, + Expiration::Interval(..) | Expiration::IntervalDelayed(..) + )), _ => panic!("timer lost its expiration"), } diff --git a/test/test_unistd.rs b/test/test_unistd.rs index b3b69bbb..23392834 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -1,17 +1,24 @@ -#[cfg(not(target_os = "redox"))] -use nix::fcntl::{self, open}; +use libc::{_exit, mode_t, off_t}; +use nix::errno::Errno; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -use nix::fcntl::{readlink}; +use nix::fcntl::readlink; use nix::fcntl::OFlag; -use nix::unistd::*; -use nix::unistd::ForkResult::*; #[cfg(not(target_os = "redox"))] -use nix::sys::signal::{SaFlags, SigAction, SigHandler, SigSet, Signal, sigaction}; -use nix::sys::wait::*; +use nix::fcntl::{self, open}; +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] +use nix::pty::{grantpt, posix_openpt, ptsname, unlockpt}; +#[cfg(not(target_os = "redox"))] +use nix::sys::signal::{ + sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal, +}; use nix::sys::stat::{self, Mode, SFlag}; -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] -use nix::pty::{posix_openpt, grantpt, unlockpt, ptsname}; -use nix::errno::Errno; +use nix::sys::wait::*; +use nix::unistd::ForkResult::*; +use nix::unistd::*; use std::env; #[cfg(not(any(target_os = "fuchsia", target_os = "redox")))] use std::ffi::CString; @@ -20,10 +27,13 @@ use std::fs::DirBuilder; use std::fs::{self, File}; use std::io::Write; use std::os::unix::prelude::*; -#[cfg(not(any(target_os = "fuchsia", target_os = "redox", target_os = "haiku")))] +#[cfg(not(any( + target_os = "fuchsia", + target_os = "redox", + target_os = "haiku" +)))] use std::path::Path; use tempfile::{tempdir, tempfile}; -use libc::{_exit, mode_t, off_t}; use crate::*; @@ -33,7 +43,7 @@ fn test_fork_and_waitpid() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is signal-safe - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => unsafe { _exit(0) }, Parent { child } => { // assert that child was created and pid > 0 @@ -42,16 +52,17 @@ fn test_fork_and_waitpid() { let wait_status = waitpid(child, None); match wait_status { // assert that waitpid returned correct status and the pid is the one of the child - Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child), + Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child), // panic, must never happen - s @ Ok(_) => panic!("Child exited {:?}, should never happen", s), + s @ Ok(_) => { + panic!("Child exited {:?}, should never happen", s) + } // panic, waitpid should never fail - Err(s) => panic!("Error: waitpid returned Err({:?}", s) + Err(s) => panic!("Error: waitpid returned Err({:?}", s), } - - }, + } } } @@ -61,14 +72,14 @@ fn test_wait() { let _m = crate::FORK_MTX.lock(); // Safe: Child only calls `_exit`, which is signal-safe - match unsafe{fork()}.expect("Error: Fork Failed") { + match unsafe { fork() }.expect("Error: Fork Failed") { Child => unsafe { _exit(0) }, Parent { child } => { let wait_status = wait(); // just assert that (any) one child returns with WaitStatus::Exited assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0))); - }, + } } } @@ -82,8 +93,8 @@ fn test_mkstemp() { Ok((fd, path)) => { close(fd).unwrap(); unlink(path.as_path()).unwrap(); - }, - Err(e) => panic!("mkstemp failed: {}", e) + } + Err(e) => panic!("mkstemp failed: {}", e), } } @@ -115,8 +126,12 @@ fn test_mkfifo_directory() { #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox", target_os = "haiku")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_none() { let _m = crate::CWD_LOCK.read(); @@ -132,8 +147,12 @@ fn test_mkfifoat_none() { #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox", target_os = "haiku")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat() { use nix::fcntl; @@ -143,15 +162,20 @@ fn test_mkfifoat() { mkfifoat(Some(dirfd), mkfifoat_name, Mode::S_IRUSR).unwrap(); - let stats = stat::fstatat(dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap(); + let stats = + stat::fstatat(dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap(); let typ = stat::SFlag::from_bits_truncate(stats.st_mode); assert_eq!(typ, SFlag::S_IFIFO); } #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox", target_os = "haiku")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_directory_none() { let _m = crate::CWD_LOCK.read(); @@ -161,8 +185,12 @@ fn test_mkfifoat_directory_none() { #[test] #[cfg(not(any( - target_os = "macos", target_os = "ios", - target_os = "android", target_os = "redox", target_os = "haiku")))] + target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "redox", + target_os = "haiku" +)))] fn test_mkfifoat_directory() { // mkfifoat should fail if a directory is given let tempdir = tempdir().unwrap(); @@ -203,7 +231,13 @@ mod linux_android { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_setgroups() { // Skip this test when not run as root as `setgroups()` requires root. skip_if_not_root!("test_setgroups"); @@ -226,12 +260,14 @@ fn test_setgroups() { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms -#[cfg(not(any(target_os = "ios", - target_os = "macos", - target_os = "redox", - target_os = "fuchsia", - target_os = "haiku", - target_os = "illumos")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku", + target_os = "illumos" +)))] fn test_initgroups() { // Skip this test when not run as root as `initgroups()` and `setgroups()` // require root. @@ -362,7 +398,7 @@ macro_rules! execve_test_factory( ) ); -cfg_if!{ +cfg_if! { if #[cfg(target_os = "android")] { execve_test_factory!(test_execve, execve, CString::new("/system/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd()); @@ -387,7 +423,7 @@ cfg_if!{ #[cfg(any(target_os = "haiku", target_os = "linux", target_os = "openbsd"))] execve_test_factory!(test_execvpe, execvpe, &CString::new("sh").unwrap()); -cfg_if!{ +cfg_if! { if #[cfg(target_os = "android")] { use nix::fcntl::AtFlags; execve_test_factory!(test_execveat_empty, execveat, @@ -501,7 +537,8 @@ fn test_fchownat() { let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); - fchownat(Some(dirfd), "file", uid, gid, FchownatFlags::FollowSymlink).unwrap(); + fchownat(Some(dirfd), "file", uid, gid, FchownatFlags::FollowSymlink) + .unwrap(); chdir(tempdir.path()).unwrap(); fchownat(None, "file", uid, gid, FchownatFlags::FollowSymlink).unwrap(); @@ -544,7 +581,7 @@ fn test_lseek64() { close(tmpfd).unwrap(); } -cfg_if!{ +cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { macro_rules! require_acct{ () => { @@ -568,11 +605,15 @@ cfg_if!{ } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_acct() { - use tempfile::NamedTempFile; use std::process::Command; use std::{thread, time}; + use tempfile::NamedTempFile; let _m = crate::FORK_MTX.lock(); require_acct!(); @@ -583,12 +624,11 @@ fn test_acct() { acct::enable(path).unwrap(); loop { - Command::new("echo") - .arg("Hello world") - .output() - .unwrap(); + Command::new("echo").arg("Hello world").output().unwrap(); let len = fs::metadata(path).unwrap().len(); - if len > 0 { break; } + if len > 0 { + break; + } thread::sleep(time::Duration::from_millis(10)); } acct::disable().unwrap(); @@ -599,21 +639,36 @@ fn test_fpathconf_limited() { let f = tempfile().unwrap(); // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX); - assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("fpathconf failed") + .expect("PATH_MAX is unlimited") + > 0 + ); } #[test] fn test_pathconf_limited() { // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test let path_max = pathconf("/", PathconfVar::PATH_MAX); - assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0); + assert!( + path_max + .expect("pathconf failed") + .expect("PATH_MAX is unlimited") + > 0 + ); } #[test] fn test_sysconf_limited() { // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test let open_max = sysconf(SysconfVar::OPEN_MAX); - assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0); + assert!( + open_max + .expect("sysconf failed") + .expect("OPEN_MAX is unlimited") + > 0 + ); } #[cfg(target_os = "freebsd")] @@ -626,12 +681,13 @@ fn test_sysconf_unsupported() { assert!(open_max.expect("sysconf failed").is_none()) } - -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] #[test] fn test_getresuid() { let resuids = getresuid().unwrap(); @@ -640,11 +696,13 @@ fn test_getresuid() { assert!(resuids.saved.as_raw() != libc::uid_t::max_value()); } -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "openbsd" +))] #[test] fn test_getresgid() { let resgids = getresgid().unwrap(); @@ -658,25 +716,31 @@ fn test_getresgid() { #[test] fn test_pipe() { let (fd0, fd1) = pipe().unwrap(); - let m0 = stat::SFlag::from_bits_truncate(stat::fstat(fd0).unwrap().st_mode as mode_t); + let m0 = stat::SFlag::from_bits_truncate( + stat::fstat(fd0).unwrap().st_mode as mode_t, + ); // S_IFIFO means it's a pipe assert_eq!(m0, SFlag::S_IFIFO); - let m1 = stat::SFlag::from_bits_truncate(stat::fstat(fd1).unwrap().st_mode as mode_t); + let m1 = stat::SFlag::from_bits_truncate( + stat::fstat(fd1).unwrap().st_mode as mode_t, + ); assert_eq!(m1, SFlag::S_IFIFO); } // pipe2(2) is the same as pipe(2), except it allows setting some flags. Check // that we can set a flag. -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox", - target_os = "solaris"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "emscripten", + target_os = "freebsd", + target_os = "illumos", + target_os = "linux", + target_os = "netbsd", + target_os = "openbsd", + target_os = "redox", + target_os = "solaris" +))] #[test] fn test_pipe2() { use nix::fcntl::{fcntl, FcntlArg, FdFlag}; @@ -731,8 +795,13 @@ static mut ALARM_CALLED: bool = false; // Used in `test_alarm`. #[cfg(not(target_os = "redox"))] -pub extern fn alarm_signal_handler(raw_signal: libc::c_int) { - assert_eq!(raw_signal, libc::SIGALRM, "unexpected signal: {}", raw_signal); +pub extern "C" fn alarm_signal_handler(raw_signal: libc::c_int) { + assert_eq!( + raw_signal, + libc::SIGALRM, + "unexpected signal: {}", + raw_signal + ); unsafe { ALARM_CALLED = true }; } @@ -740,15 +809,16 @@ pub extern fn alarm_signal_handler(raw_signal: libc::c_int) { #[cfg(not(target_os = "redox"))] fn test_alarm() { use std::{ - time::{Duration, Instant,}, - thread + thread, + time::{Duration, Instant}, }; // Maybe other tests that fork interfere with this one? let _m = crate::SIGNAL_MTX.lock(); let handler = SigHandler::Handler(alarm_signal_handler); - let signal_action = SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); + let signal_action = + SigAction::new(handler, SaFlags::SA_RESTART, SigSet::empty()); let old_handler = unsafe { sigaction(Signal::SIGALRM, &signal_action) .expect("unable to set signal handler for alarm") @@ -765,7 +835,7 @@ fn test_alarm() { let starttime = Instant::now(); loop { thread::sleep(Duration::from_millis(100)); - if unsafe { ALARM_CALLED} { + if unsafe { ALARM_CALLED } { break; } if starttime.elapsed() > Duration::from_secs(3) { @@ -833,10 +903,19 @@ fn test_linkat_file() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt hard link file at relative path - linkat(Some(dirfd), oldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + oldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } @@ -857,11 +936,23 @@ fn test_linkat_olddirfd_none() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory of new file - let dirfd = fcntl::open(tempdir_newfile.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + tempdir_newfile.path(), + fcntl::OFlag::empty(), + stat::Mode::empty(), + ) + .unwrap(); // Attempt hard link file using curent working directory as relative path for old file path chdir(tempdir_oldfile.path()).unwrap(); - linkat(None, oldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + None, + oldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } @@ -882,16 +973,33 @@ fn test_linkat_newdirfd_none() { File::create(&oldfilepath).unwrap(); // Get file descriptor for base directory of old file - let dirfd = fcntl::open(tempdir_oldfile.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = fcntl::open( + tempdir_oldfile.path(), + fcntl::OFlag::empty(), + stat::Mode::empty(), + ) + .unwrap(); // Attempt hard link file using current working directory as relative path for new file path chdir(tempdir_newfile.path()).unwrap(); - linkat(Some(dirfd), oldfilename, None, newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + oldfilename, + None, + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); assert!(newfilepath.exists()); } #[test] -#[cfg(not(any(target_os = "ios", target_os = "macos", target_os = "redox", target_os = "haiku")))] +#[cfg(not(any( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "haiku" +)))] fn test_linkat_no_follow_symlink() { let _m = crate::CWD_LOCK.read(); @@ -912,17 +1020,23 @@ fn test_linkat_no_follow_symlink() { symlinkat(&oldfilepath, None, &symoldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt link symlink of file at relative path - linkat(Some(dirfd), symoldfilename, Some(dirfd), newfilename, LinkatFlags::NoSymlinkFollow).unwrap(); + linkat( + Some(dirfd), + symoldfilename, + Some(dirfd), + newfilename, + LinkatFlags::NoSymlinkFollow, + ) + .unwrap(); // Assert newfile is actually a symlink to oldfile. assert_eq!( - readlink(&newfilepath) - .unwrap() - .to_str() - .unwrap(), + readlink(&newfilepath).unwrap().to_str().unwrap(), oldfilepath.to_str().unwrap() ); } @@ -949,15 +1063,26 @@ fn test_linkat_follow_symlink() { symlinkat(&oldfilepath, None, &symoldfilepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt link target of symlink of file at relative path - linkat(Some(dirfd), symoldfilename, Some(dirfd), newfilename, LinkatFlags::SymlinkFollow).unwrap(); + linkat( + Some(dirfd), + symoldfilename, + Some(dirfd), + newfilename, + LinkatFlags::SymlinkFollow, + ) + .unwrap(); let newfilestat = stat::stat(&newfilepath).unwrap(); // Check the file type of the new link - assert_eq!((stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) & SFlag::S_IFMT), + assert_eq!( + (stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) + & SFlag::S_IFMT), SFlag::S_IFREG ); @@ -976,12 +1101,15 @@ fn test_unlinkat_dir_noremovedir() { DirBuilder::new().recursive(true).create(&dirpath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink dir at relative path without proper flag - let err_result = unlinkat(Some(dirfd), dirname, UnlinkatFlags::NoRemoveDir).unwrap_err(); + let err_result = + unlinkat(Some(dirfd), dirname, UnlinkatFlags::NoRemoveDir).unwrap_err(); assert!(err_result == Errno::EISDIR || err_result == Errno::EPERM); - } +} #[test] #[cfg(not(target_os = "redox"))] @@ -994,12 +1122,14 @@ fn test_unlinkat_dir_removedir() { DirBuilder::new().recursive(true).create(&dirpath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink dir at relative path with proper flag unlinkat(Some(dirfd), dirname, UnlinkatFlags::RemoveDir).unwrap(); assert!(!dirpath.exists()); - } +} #[test] #[cfg(not(target_os = "redox"))] @@ -1012,25 +1142,29 @@ fn test_unlinkat_file() { File::create(&filepath).unwrap(); // Get file descriptor for base directory - let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()).unwrap(); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); // Attempt unlink file at relative path unlinkat(Some(dirfd), filename, UnlinkatFlags::NoRemoveDir).unwrap(); assert!(!filepath.exists()); - } +} #[test] fn test_access_not_existing() { let tempdir = tempdir().unwrap(); let dir = tempdir.path().join("does_not_exist.txt"); - assert_eq!(access(&dir, AccessFlags::F_OK).err().unwrap(), - Errno::ENOENT); + assert_eq!( + access(&dir, AccessFlags::F_OK).err().unwrap(), + Errno::ENOENT + ); } #[test] fn test_access_file_exists() { let tempdir = tempdir().unwrap(); - let path = tempdir.path().join("does_exist.txt"); + let path = tempdir.path().join("does_exist.txt"); let _file = File::create(path.clone()).unwrap(); assert!(access(&path, AccessFlags::R_OK | AccessFlags::W_OK).is_ok()); } @@ -1090,7 +1224,11 @@ fn test_setfsuid() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_ttyname() { let fd = posix_openpt(OFlag::O_RDWR).expect("posix_openpt failed"); assert!(fd.as_raw_fd() > 0); @@ -1101,11 +1239,8 @@ fn test_ttyname() { grantpt(&fd).expect("grantpt failed"); unlockpt(&fd).expect("unlockpt failed"); let sname = unsafe { ptsname(&fd) }.expect("ptsname failed"); - let fds = open( - Path::new(&sname), - OFlag::O_RDWR, - stat::Mode::empty(), - ).expect("open failed"); + let fds = open(Path::new(&sname), OFlag::O_RDWR, stat::Mode::empty()) + .expect("open failed"); assert!(fds > 0); let name = ttyname(fds).expect("ttyname failed"); @@ -1121,7 +1256,11 @@ fn test_ttyname_not_pty() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "fuchsia", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + target_os = "haiku" +)))] fn test_ttyname_invalid_fd() { assert_eq!(ttyname(-1), Err(Errno::EBADF)); } |