Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 91 additions & 5 deletions crates/openshell-sandbox/src/boundary_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,45 @@ mod linux {
}
static BOUNDARY_TERMINATION_REQUESTED: AtomicBool = AtomicBool::new(false);
static BOUNDARY_TERMINATION_SIGNAL: AtomicI32 = AtomicI32::new(0);
// Self-pipe that wakes `wait_for_termination_signal`, so an idle boundary
// sleeps in the kernel instead of polling the termination flag. In a
// microVM every timer wakeup is a VM exit.
static BOUNDARY_TERMINATION_WAKE_READ: AtomicI32 = AtomicI32::new(-1);
static BOUNDARY_TERMINATION_WAKE_WRITE: AtomicI32 = AtomicI32::new(-1);

extern "C" fn request_boundary_termination(signal: libc::c_int) {
BOUNDARY_TERMINATION_SIGNAL.store(signal, Ordering::Release);
BOUNDARY_TERMINATION_REQUESTED.store(true, Ordering::Release);
let fd = BOUNDARY_TERMINATION_WAKE_WRITE.load(Ordering::Acquire);
if fd >= 0 {
// SAFETY: errno access and write(2) are async-signal-safe. The pipe
// is nonblocking; when it is full a wakeup is already pending.
unsafe {
let errno = *libc::__errno_location();
let byte = 1u8;
let _ = libc::write(fd, std::ptr::addr_of!(byte).cast(), 1);
*libc::__errno_location() = errno;
}
}
}

/// Block until a termination signal is delivered, `readable` (when given)
/// has input, or `timeout` elapses.
fn wait_for_termination_signal(readable: Option<std::os::fd::RawFd>, timeout: Duration) {
let wake = BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire);
if wake < 0 {
std::thread::sleep(Duration::from_millis(10));
return;
}
// poll(2) ignores entries with a negative descriptor.
let mut fds = [wake, readable.unwrap_or(-1)].map(|fd| libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
});
let timeout = libc::c_int::try_from(timeout.as_millis()).unwrap_or(libc::c_int::MAX);
// SAFETY: `fds` holds two valid pollfds for the duration of the call.
unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
}

pub fn run_boundary(
Expand Down Expand Up @@ -331,9 +366,33 @@ mod linux {
.map_err(|error| format!("disable sandbox core dumps: {error}"))
}

fn create_termination_wake_pipe() -> Result<(), String> {
let wake = BOUNDARY_TERMINATION_WAKE_READ.load(Ordering::Acquire);
if wake >= 0 {
// A stale wakeup would turn every idle wait into a busy loop.
let mut buf = [0u8; 64];
// SAFETY: `buf` is valid for `buf.len()` bytes and the pipe is
// nonblocking, so the loop ends once it is empty.
while unsafe { libc::read(wake, buf.as_mut_ptr().cast(), buf.len()) } > 0 {}
return Ok(());
}
let mut fds = [-1; 2];
// SAFETY: `fds` has room for the two descriptors pipe2 returns.
if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) } != 0 {
return Err(format!(
"create boundary termination pipe: {}",
io::Error::last_os_error()
));
}
BOUNDARY_TERMINATION_WAKE_WRITE.store(fds[1], Ordering::Release);
BOUNDARY_TERMINATION_WAKE_READ.store(fds[0], Ordering::Release);
Ok(())
}

fn install_boundary_signal_handlers() -> Result<(), String> {
BOUNDARY_TERMINATION_REQUESTED.store(false, Ordering::Release);
BOUNDARY_TERMINATION_SIGNAL.store(0, Ordering::Release);
create_termination_wake_pipe()?;
let action = nix::sys::signal::SigAction::new(
nix::sys::signal::SigHandler::Handler(request_boundary_termination),
nix::sys::signal::SaFlags::empty(),
Expand All @@ -343,9 +402,10 @@ mod linux {
nix::sys::signal::Signal::SIGTERM,
nix::sys::signal::Signal::SIGINT,
] {
// SAFETY: the installed handler only performs a lock-free atomic
// store, which is async-signal-safe, and remains valid for the
// lifetime of the boundary process.
// SAFETY: the installed handler only performs lock-free atomic
// operations and a write(2) to a nonblocking pipe, which are
// async-signal-safe, and remains valid for the lifetime of the
// boundary process.
unsafe { nix::sys::signal::sigaction(signal, &action) }
.map_err(|error| format!("install boundary {signal:?} handler: {error}"))?;
}
Expand Down Expand Up @@ -701,7 +761,7 @@ mod linux {
});
}
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10));
wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_secs(1));
}
Err(error) => match control_accept_error_action(&error) {
ControlAcceptErrorAction::Continue => {}
Expand Down Expand Up @@ -745,7 +805,7 @@ mod linux {
dialer.abort();
return result;
}
std::thread::sleep(Duration::from_millis(10));
wait_for_termination_signal(None, Duration::from_secs(1));
}
}

Expand Down Expand Up @@ -4827,6 +4887,14 @@ mod linux {
}

impl ControlListener {
fn as_raw_fd(&self) -> std::os::fd::RawFd {
match self {
Self::Vsock { listener, .. } => listener.as_raw_fd(),
Self::Unix { listener, .. } => listener.as_raw_fd(),
Self::Tcp { listener, .. } => listener.as_raw_fd(),
}
}

fn bind(config: &BoundaryListenerConfig) -> io::Result<Self> {
match config {
BoundaryListenerConfig::Vsock { control_port, tls } => {
Expand Down Expand Up @@ -5789,6 +5857,24 @@ mod linux {
assert_eq!(boundary_termination_signal_name(0), "unknown signal");
}

#[test]
fn an_idle_listener_wait_wakes_for_a_pending_connection() {
create_termination_wake_pipe().unwrap();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("control.sock");
let listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
listener.set_nonblocking(true).unwrap();

let started = std::time::Instant::now();
wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_millis(50));
assert!(started.elapsed() >= Duration::from_millis(50));

let _client = std::os::unix::net::UnixStream::connect(&path).unwrap();
let started = std::time::Instant::now();
wait_for_termination_signal(Some(listener.as_raw_fd()), Duration::from_secs(30));
assert!(started.elapsed() < Duration::from_secs(5));
}

#[test]
fn supplementary_group_measurement_rejects_unexpected_groups_by_default() {
assert!(!supplementary_groups_match(&[44, 992], &[], false));
Expand Down
Loading