Skip to content

Commit

Permalink
Update ned_fd.
Browse files Browse the repository at this point in the history
  • Loading branch information
reitermarkus committed Mar 6, 2021
1 parent d045009 commit b2c8c70
Show file tree
Hide file tree
Showing 2 changed files with 160 additions and 85 deletions.
2 changes: 1 addition & 1 deletion library/std/src/sys/unix/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub mod netc {
#[cfg(target_os = "freertos")]
extern "C" {
#[link_name = "lwip_fcntl"]
pub fn fcntl(s: c_int, cmd: c_int, val: c_int) -> c_int;
pub fn fcntl(s: c_int, cmd: c_int, ...) -> c_int;
#[link_name = "lwip_close"]
pub fn close(s: c_int) -> ssize_t;
#[link_name = "lwip_read"]
Expand Down
243 changes: 159 additions & 84 deletions library/std/src/sys/unix/net_fd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,72 @@
use crate::cmp;
use crate::io::{self, Initializer, IoSlice, IoSliceMut, Read};
use crate::mem;
use crate::sync::atomic::{AtomicBool, Ordering};
use crate::sys::{
cvt,
net::netc::{self, c_int, c_void, ssize_t},
net::netc::{self, c_int, c_void},
};
use crate::sys_common::AsInner;

#[derive(Debug)]
#[rustc_layout_scalar_valid_range_start(0)]
// libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
// 32-bit c_int. Below is -2, in two's complement, but that only works out
// because c_int is 32 bits.
#[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
pub struct NetFileDesc {
fd: c_int,
}

fn max_len() -> usize {
// The maximum read limit on most posix-like systems is `SSIZE_MAX`,
// with the man page quoting that if the count of bytes to read is
// greater than `SSIZE_MAX` the result is "unspecified".
//
// On macOS, however, apparently the 64-bit libc is either buggy or
// intentionally showing odd behavior by rejecting any read with a size
// larger than or equal to INT_MAX. To handle both of these the read
// size is capped on both platforms.
if cfg!(target_os = "macos") {
<c_int>::max_value() as usize - 1
} else {
<ssize_t>::max_value() as usize
}
// The maximum read limit on most POSIX-like systems is `SSIZE_MAX`,
// with the man page quoting that if the count of bytes to read is
// greater than `SSIZE_MAX` the result is "unspecified".
//
// On macOS, however, apparently the 64-bit libc is either buggy or
// intentionally showing odd behavior by rejecting any read with a size
// larger than or equal to INT_MAX. To handle both of these the read
// size is capped on both platforms.
#[cfg(target_os = "macos")]
const READ_LIMIT: usize = c_int::MAX as usize - 1;
#[cfg(not(target_os = "macos"))]
const READ_LIMIT: usize = netc::ssize_t::MAX as usize;

#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "ios",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
))]
const fn max_iov() -> usize {
netc::IOV_MAX as usize
}

#[cfg(any(target_os = "android", target_os = "emscripten", target_os = "linux"))]
const fn max_iov() -> usize {
netc::UIO_MAXIOV as usize
}

#[cfg(not(any(
target_os = "android",
target_os = "dragonfly",
target_os = "emscripten",
target_os = "freebsd",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
)))]
const fn max_iov() -> usize {
16 // The minimum value required by POSIX.
}

impl NetFileDesc {
pub fn new(fd: c_int) -> NetFileDesc {
NetFileDesc { fd }
assert_ne!(fd, -1i32);
// SAFETY: we just asserted that the value is in the valid range and isn't `-1` (the only value bigger than `0xFF_FF_FF_FE` unsigned)
unsafe { NetFileDesc { fd } }
}

pub fn raw(&self) -> c_int {
Expand All @@ -49,7 +84,7 @@ impl NetFileDesc {

pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
let ret = cvt(unsafe {
netc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), max_len()))
netc::read(self.fd, buf.as_mut_ptr() as *mut c_void, cmp::min(buf.len(), READ_LIMIT))
})?;
Ok(ret as usize)
}
Expand All @@ -59,7 +94,7 @@ impl NetFileDesc {
netc::readv(
self.fd,
bufs.as_ptr() as *const netc::iovec,
cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
cmp::min(bufs.len(), max_iov()) as c_int,
)
})?;
Ok(ret as usize)
Expand All @@ -75,9 +110,38 @@ impl NetFileDesc {
(&mut me).read_to_end(buf)
}

pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
#[cfg(target_os = "android")]
use super::android::cvt_pread64;

#[cfg(not(target_os = "android"))]
unsafe fn cvt_pread64(
fd: c_int,
buf: *mut c_void,
count: usize,
offset: i64,
) -> io::Result<isize> {
#[cfg(not(target_os = "linux"))]
use netc::pread as pread64;
#[cfg(target_os = "linux")]
use netc::pread64;
cvt(pread64(fd, buf, count, offset))
}

unsafe {
cvt_pread64(
self.fd,
buf.as_mut_ptr() as *mut c_void,
cmp::min(buf.len(), READ_LIMIT),
offset as i64,
)
.map(|n| n as usize)
}
}

pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
let ret = cvt(unsafe {
netc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), max_len()))
netc::write(self.fd, buf.as_ptr() as *const c_void, cmp::min(buf.len(), READ_LIMIT))
})?;
Ok(ret as usize)
}
Expand All @@ -87,7 +151,7 @@ impl NetFileDesc {
netc::writev(
self.fd,
bufs.as_ptr() as *const netc::iovec,
cmp::min(bufs.len(), c_int::max_value() as usize) as c_int,
cmp::min(bufs.len(), max_iov()) as c_int,
)
})?;
Ok(ret as usize)
Expand All @@ -98,10 +162,45 @@ impl NetFileDesc {
true
}

pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
#[cfg(target_os = "android")]
use super::android::cvt_pwrite64;

#[cfg(not(target_os = "android"))]
unsafe fn cvt_pwrite64(
fd: c_int,
buf: *const c_void,
count: usize,
offset: i64,
) -> io::Result<isize> {
#[cfg(not(target_os = "linux"))]
use netc::pwrite as pwrite64;
#[cfg(target_os = "linux")]
use netc::pwrite64;
cvt(pwrite64(fd, buf, count, offset))
}

unsafe {
cvt_pwrite64(
self.fd,
buf.as_ptr() as *const c_void,
cmp::min(buf.len(), READ_LIMIT),
offset as i64,
)
.map(|n| n as usize)
}
}

#[cfg(target_os = "linux")]
pub fn get_cloexec(&self) -> io::Result<bool> {
unsafe { Ok((cvt(netc::fcntl(self.fd, netc::F_GETFD))? & netc::FD_CLOEXEC) != 0) }
}
// Setting `FD_CLOEXEC` is not supported on FreeRTOS
// since there is no `exec` functionality.
#[cfg(target_os = "freertos")]
pub fn set_cloexec(&self) -> io::Result<()> {
Ok(())
}

#[cfg(not(any(
target_env = "newlib",
Expand All @@ -112,27 +211,26 @@ impl NetFileDesc {
target_os = "l4re",
target_os = "linux",
target_os = "haiku",
target_os = "redox"
target_os = "redox",
target_os = "vxworks"
)))]
pub fn set_cloexec(&self) -> io::Result<()> {
unsafe {
cvt(netc::ioctl(self.fd, netc::FIOCLEX))?;
Ok(())
}
}
#[cfg(all(
any(
target_env = "newlib",
target_os = "solaris",
target_os = "illumos",
target_os = "emscripten",
target_os = "fuchsia",
target_os = "l4re",
target_os = "linux",
target_os = "haiku",
target_os = "redox"
),
not(target_os = "freertos")
#[cfg(any(
all(target_env = "newlib", not(target_os = "freertos")),
target_os = "solaris",
target_os = "illumos",
target_os = "emscripten",
target_os = "fuchsia",
target_os = "l4re",
target_os = "linux",
target_os = "haiku",
target_os = "redox",
target_os = "vxworks"
))]
pub fn set_cloexec(&self) -> io::Result<()> {
unsafe {
Expand All @@ -145,60 +243,37 @@ impl NetFileDesc {
}
}

// Setting `FD_CLOEXEC` is not supported on FreeRTOS
// since there is no `exec` functionality.
#[cfg(target_os = "freertos")]
pub fn set_cloexec(&self) -> io::Result<()> {
Ok(())
#[cfg(target_os = "linux")]
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
unsafe {
let v = nonblocking as c_int;
cvt(netc::ioctl(self.fd, netc::FIONBIO, &v))?;
Ok(())
}
}

#[cfg(not(target_os = "linux"))]
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
unsafe {
let previous = cvt(netc::fcntl(self.fd, netc::F_GETFL))?;
let new = if nonblocking {
previous | netc::O_NONBLOCK
} else {
previous & !netc::O_NONBLOCK
};
if new != previous {
cvt(netc::fcntl(self.fd, netc::F_SETFL, new))?;
}
Ok(())
}
}

pub fn duplicate(&self) -> io::Result<NetFileDesc> {
// We want to atomically duplicate this file descriptor and set the
// CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
// flag, however, isn't supported on older Linux kernels (earlier than
// 2.6.24).
//
// To detect this and ensure that CLOEXEC is still set, we
// follow a strategy similar to musl [1] where if passing
// F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
// supported (the third parameter, 0, is always valid), so we stop
// trying that.
//
// Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
// resolve so we at least compile this.
//
// [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
#[cfg(any(target_os = "android", target_os = "haiku"))]
use netc::F_DUPFD as F_DUPFD_CLOEXEC;
#[cfg(not(any(target_os = "android", target_os = "haiku")))]
use netc::F_DUPFD_CLOEXEC;

let make_filedesc = |fd| {
let fd = NetFileDesc::new(fd);
fd.set_cloexec()?;
Ok(fd)
};
static TRY_CLOEXEC: AtomicBool = AtomicBool::new(!cfg!(target_os = "android"));
let fd = self.raw();
if TRY_CLOEXEC.load(Ordering::Relaxed) {
match cvt(unsafe { netc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
// We *still* call the `set_cloexec` method as apparently some
// linux kernel at some point stopped setting CLOEXEC even
// though it reported doing so on F_DUPFD_CLOEXEC.
Ok(fd) => {
return Ok(if cfg!(target_os = "linux") {
make_filedesc(fd)?
} else {
NetFileDesc::new(fd)
});
}
Err(ref e) if e.raw_os_error() == Some(netc::EINVAL) => {
TRY_CLOEXEC.store(false, Ordering::Relaxed);
}
Err(e) => return Err(e),
}
}
cvt(unsafe { netc::fcntl(fd, netc::F_DUPFD, 0) }).and_then(make_filedesc)
// is a POSIX flag that was added to Linux in 2.6.24.
let fd = cvt(unsafe { netc::fcntl(self.raw(), netc::F_DUPFD_CLOEXEC, 0) })?;
Ok(NetFileDesc::new(fd))
}
}

Expand Down

0 comments on commit b2c8c70

Please sign in to comment.