diff --git a/Cargo.lock b/Cargo.lock index 0420139..669f289 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2187,6 +2187,7 @@ dependencies = [ "chrono", "ed25519-dalek", "hex", + "libc", "openssl", "prost", "reqwest", diff --git a/crates/agent-core/Cargo.toml b/crates/agent-core/Cargo.toml index 4153be6..f73c898 100644 --- a/crates/agent-core/Cargo.toml +++ b/crates/agent-core/Cargo.toml @@ -31,3 +31,6 @@ openssl = { workspace = true, optional = true } [target.'cfg(unix)'.dev-dependencies] openssl.workspace = true + +[target.'cfg(target_os = "freebsd")'.dependencies] +libc = "0.2" diff --git a/crates/agent-core/src/freebsd_clock.rs b/crates/agent-core/src/freebsd_clock.rs new file mode 100644 index 0000000..87edf56 --- /dev/null +++ b/crates/agent-core/src/freebsd_clock.rs @@ -0,0 +1,81 @@ +//! Read-only FreeBSD kernel discipline for the signed reconciliation clock. +//! Never adjust the guest clock. No cached qualification across a failed read. +use crate::reconcile::{ClockReading, SyncClock}; +use anyhow::{Context, Result, ensure}; +use chrono::{DateTime, TimeDelta, Utc}; +use std::{mem::MaybeUninit, time::Instant}; + +pub struct NativeClock { + origin: DateTime, + monotonic: Instant, +} + +impl Default for NativeClock { + fn default() -> Self { + Self { + origin: Utc::now(), + monotonic: Instant::now(), + } + } +} + +impl NativeClock { + fn observation(&self) -> Result<(DateTime, TimeDelta)> { + let start = Instant::now(); + let mut raw = MaybeUninit::::zeroed(); + // SAFETY: the read-only syscall writes the platform's ntptimeval. + let result = unsafe { libc::ntp_gettime(raw.as_mut_ptr()) }; + ensure!(result == libc::TIME_OK, "FREEBSD_CLOCK_UNQUALIFIED"); + let sample = unsafe { raw.assume_init() }; + let wall = + DateTime::from_timestamp(sample.time.tv_sec, u32::try_from(sample.time.tv_nsec)?) + .context("FREEBSD_CLOCK_INVALID")?; + let duration = TimeDelta::from_std(start.elapsed())?; + ensure!( + sample.time_state == libc::TIME_OK + && (0..=5_000_000).contains(&sample.maxerror) + && (0..=sample.maxerror).contains(&sample.esterror) + && sample.time.tv_nsec < 1_000_000_000 + && duration <= TimeDelta::milliseconds(100) + && ((wall - self.origin) - TimeDelta::from_std(self.monotonic.elapsed())?) + .num_milliseconds() + .unsigned_abs() + <= 5000, + "FREEBSD_CLOCK_UNQUALIFIED" + ); + Ok((wall, TimeDelta::microseconds(sample.maxerror) + duration)) + } +} + +impl SyncClock for NativeClock { + fn now(&self) -> Result> { + Ok(self.observation()?.0) + } + fn reading(&self) -> Result { + let (wall, error) = self.observation()?; + Ok(ClockReading { + own_wall: wall, + upper: wall + error, + }) + } + fn bounds(&self) -> Result<(DateTime, DateTime)> { + let (wall, error) = self.observation()?; + Ok((wall - error, wall + error)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires a FreeBSD guest synchronized by ntpd"] + fn native_bounds_and_monotonic_fence() -> Result<()> { + let mut clock = NativeClock::default(); + let (low, high) = clock.bounds()?; + ensure!(low <= high && high - low <= TimeDelta::milliseconds(10200)); + clock.origin += TimeDelta::minutes(1); + ensure!(clock.bounds().is_err()); + Ok(()) + } +} diff --git a/crates/agent-core/src/lib.rs b/crates/agent-core/src/lib.rs index 310c85b..6b520a9 100644 --- a/crates/agent-core/src/lib.rs +++ b/crates/agent-core/src/lib.rs @@ -5,6 +5,8 @@ pub mod auth; pub mod customer_transfer; pub mod crypto; +#[cfg(target_os = "freebsd")] +pub mod freebsd_clock; pub mod helper_reconcile; pub mod jobs; pub mod ledger; diff --git a/crates/agent-linux/src/process.rs b/crates/agent-linux/src/process.rs index 0b1a073..c61c402 100644 --- a/crates/agent-linux/src/process.rs +++ b/crates/agent-linux/src/process.rs @@ -114,7 +114,7 @@ pub(crate) fn run_controlled( let state = unsafe { libc::waitid( libc::P_PID, - child.id(), + child.id() as libc::id_t, info.as_mut_ptr(), libc::WEXITED | libc::WNOHANG | libc::WNOWAIT, ) @@ -232,6 +232,7 @@ fn drain( } Ok(false) } +#[cfg(not(target_os = "freebsd"))] fn group_has_no_live_members(pgid: u32) -> bool { let Ok(entries) = std::fs::read_dir("/proc") else { return false; @@ -265,6 +266,48 @@ fn group_has_no_live_members(pgid: u32) -> bool { true } +#[cfg(target_os = "freebsd")] +fn group_has_no_live_members(pgid: u32) -> bool { + // FreeBSD has no Linux /proc//stat. Ask the kernel for this + // process group while its original leader's PID is still reserved. + use std::{mem, ptr}; + let mib = [ + libc::CTL_KERN, + libc::KERN_PROC, + libc::KERN_PROC_PGRP, + pgid as i32, + ]; + let mut size = 0; + let query = |out, n: &mut usize| unsafe { + libc::sysctl(mib.as_ptr(), mib.len() as _, out, n, ptr::null(), 0) + }; + let unit = mem::size_of::(); + if query(ptr::null_mut(), &mut size) != 0 || size == 0 || size > 16 * 1024 * 1024 { + return false; + } + let mut rows = vec![mem::MaybeUninit::::zeroed(); size.div_ceil(unit) + 1]; + size = rows.len() * unit; + if query(rows.as_mut_ptr().cast(), &mut size) != 0 + || !size.is_multiple_of(unit) + || size / unit > rows.len() + { + return false; + } + let mut leader = false; + for row in &rows[..size / unit] { + // A successful MIB read returned this complete aligned record. + let row = unsafe { row.assume_init_ref() }; + if row.ki_structsize as usize != unit + || row.ki_pgid != pgid as i32 + || row.ki_stat != libc::SZOMB + { + return false; + } + leader |= row.ki_pid == pgid as i32; + } + leader +} + #[cfg(test)] mod tests { use super::*;