Skip to content

Commit

Permalink
Fix unsoundness in FdSet methods
Browse files Browse the repository at this point in the history
Ensure file descriptors are nonnegative and less than `FD_SETSIZE`.
(Fixes #1572.)
  • Loading branch information
taylordotfish committed Oct 19, 2021
1 parent c5db0ea commit ccbcdb7
Showing 1 changed file with 11 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/sys/select.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//! Portably monitor a group of file descriptors for readiness.
use std::convert::TryFrom;
use std::iter::FusedIterator;
use std::mem;
use std::ops::Range;
Expand All @@ -17,6 +18,13 @@ pub use libc::FD_SETSIZE;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct FdSet(libc::fd_set);

fn assert_fd_valid(fd: RawFd) {
assert!(
usize::try_from(fd).map_or(false, |fd| fd < FD_SETSIZE),
"fd must be in the range 0..FD_SETSIZE",
);
}

impl FdSet {
/// Create an empty `FdSet`
pub fn new() -> FdSet {
Expand All @@ -29,16 +37,19 @@ impl FdSet {

/// Add a file descriptor to an `FdSet`
pub fn insert(&mut self, fd: RawFd) {
assert_fd_valid(fd);
unsafe { libc::FD_SET(fd, &mut self.0) };
}

/// Remove a file descriptor from an `FdSet`
pub fn remove(&mut self, fd: RawFd) {
assert_fd_valid(fd);
unsafe { libc::FD_CLR(fd, &mut self.0) };
}

/// Test an `FdSet` for the presence of a certain file descriptor.
pub fn contains(&self, fd: RawFd) -> bool {
assert_fd_valid(fd);
unsafe { libc::FD_ISSET(fd, &self.0) }
}

Expand Down

0 comments on commit ccbcdb7

Please sign in to comment.