use std::fmt;
use std::fs::File;
use std::io;
use std::path::Path;
pub const DEFAULT_PATH: &str = "/var/run/clockbound/shm0";
const MAGIC: [u32; 2] = [0x414D_5A4E, 0x4342_0200];
const VERSION: u16 = 2;
const SEGMENT_LEN: usize = 80;
const GRACE_NS: u64 = 5_000_000_000;
const CAUSALITY_BLUR_NS: u64 = 1_000;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClockBoundStatus {
Unknown,
Synchronized,
FreeRunning,
Disrupted,
}
impl ClockBoundStatus {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Unknown => "unknown",
Self::Synchronized => "synchronized",
Self::FreeRunning => "free-running",
Self::Disrupted => "disrupted",
}
}
#[must_use]
pub const fn trusted(self) -> bool {
matches!(self, Self::Synchronized | Self::FreeRunning)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClockBoundReading {
pub bound_ns: u64,
pub status: ClockBoundStatus,
pub age_ns: u64,
pub max_drift_ppb: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClockBoundError {
Io(io::ErrorKind),
Short(usize),
NeverSettled,
Malformed(&'static str),
NoClock,
}
impl fmt::Display for ClockBoundError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{DEFAULT_PATH}: ")?;
match self {
Self::Io(kind) => write!(f, "{kind}"),
Self::Short(n) => write!(f, "{n} bytes, shorter than a ClockBound 2.0 segment"),
Self::NeverSettled => f.write_str("never settled in four reads"),
Self::Malformed(why) => f.write_str(why),
Self::NoClock => f.write_str(
"no CLOCK_MONOTONIC_COARSE reading to judge it against (a tree standing for a \
host: set TimeSyncProbe::clockbound_now_ns)",
),
}
}
}
impl std::error::Error for ClockBoundError {}
fn ne<const N: usize>(bytes: &[u8], at: usize) -> [u8; N] {
let mut b = [0_u8; N];
if let Some(s) = bytes.get(at..at + N) {
b.copy_from_slice(s);
}
b
}
fn timespec_ns(bytes: &[u8], at: usize) -> Option<u64> {
let secs = u64::try_from(i64::from_ne_bytes(ne(bytes, at))).ok()?;
let nanos = u64::try_from(i64::from_ne_bytes(ne(bytes, at + 8))).ok()?;
if nanos >= 1_000_000_000 {
return None;
}
secs.checked_mul(1_000_000_000)?.checked_add(nanos)
}
fn generation(segment: &[u8]) -> u16 {
if segment.len() < 16 {
return 0;
}
u16::from_ne_bytes(ne(segment, 14))
}
pub fn parse(segment: &[u8], now_coarse_ns: u64) -> Result<ClockBoundReading, &'static str> {
if segment.len() < SEGMENT_LEN {
return Err("shorter than a ClockBound 2.0 segment");
}
let magic = [
u32::from_ne_bytes(ne(segment, 0)),
u32::from_ne_bytes(ne(segment, 4)),
];
if magic != MAGIC {
return Err("not ClockBound's magic number");
}
let segsize = u32::from_ne_bytes(ne(segment, 8));
if usize::try_from(segsize).map_or(true, |s| s < SEGMENT_LEN) {
return Err("segment size too small");
}
if u16::from_ne_bytes(ne(segment, 12)) != VERSION {
return Err("not layout version 2");
}
let generation = generation(segment);
if generation == 0 {
return Err("not yet written (generation 0)");
}
if generation % 2 == 1 {
return Err("mid-update (odd generation)");
}
let as_of = timespec_ns(segment, 16).ok_or("as_of out of range")?;
let void_after = timespec_ns(segment, 32).ok_or("void_after out of range")?;
let bound = u64::try_from(i64::from_ne_bytes(ne(segment, 48))).map_err(|_| "negative bound")?;
let max_drift_ppb = u32::from_ne_bytes(ne(segment, 64));
if max_drift_ppb >= 1_000_000_000 {
return Err("drift rate of 100% or more");
}
let status = match i32::from_ne_bytes(ne(segment, 68)) {
0 => ClockBoundStatus::Unknown,
1 => ClockBoundStatus::Synchronized,
2 => ClockBoundStatus::FreeRunning,
3 => ClockBoundStatus::Disrupted,
_ => return Err("unknown clock status"),
};
let age_ns = if now_coarse_ns >= as_of {
now_coarse_ns - as_of
} else if as_of - now_coarse_ns <= CAUSALITY_BLUR_NS {
0
} else {
return Err("as_of after now");
};
let status = match status {
ClockBoundStatus::Synchronized | ClockBoundStatus::FreeRunning => {
if age_ns < GRACE_NS {
status
} else if now_coarse_ns < void_after {
ClockBoundStatus::FreeRunning
} else {
ClockBoundStatus::Unknown
}
}
other => other,
};
let growth = u64::try_from(u128::from(age_ns) * u128::from(max_drift_ppb) / 1_000_000_000)
.unwrap_or(u64::MAX);
Ok(ClockBoundReading {
bound_ns: bound.saturating_add(growth),
status,
age_ns,
max_drift_ppb,
})
}
pub fn read(path: &Path) -> Result<Option<[u8; SEGMENT_LEN]>, ClockBoundError> {
let file = match File::open(path) {
Ok(f) => f,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(ClockBoundError::Io(e.kind())),
};
let read_once = || -> Result<[u8; SEGMENT_LEN], ClockBoundError> {
let mut buf = [0_u8; SEGMENT_LEN];
let filled = crate::quota::read_from_start(&file, &mut buf)
.map_err(|e| ClockBoundError::Io(e.kind()))?;
if filled < SEGMENT_LEN {
return Err(ClockBoundError::Short(filled));
}
Ok(buf)
};
for _ in 0..4 {
let first = read_once()?;
let second = read_once()?;
if first == second && generation(&first).is_multiple_of(2) {
return Ok(Some(first));
}
}
Err(ClockBoundError::NeverSettled)
}
#[cfg(test)]
mod tests {
use super::*;
fn segment(
generation: u16,
as_of: u64,
void_after: u64,
bound: i64,
drift: u32,
status: i32,
) -> [u8; SEGMENT_LEN] {
let mut s = [0_u8; SEGMENT_LEN];
s[0..4].copy_from_slice(&MAGIC[0].to_ne_bytes());
s[4..8].copy_from_slice(&MAGIC[1].to_ne_bytes());
s[8..12].copy_from_slice(&80_u32.to_ne_bytes());
s[12..14].copy_from_slice(&2_u16.to_ne_bytes());
s[14..16].copy_from_slice(&generation.to_ne_bytes());
let ts = |s: &mut [u8; SEGMENT_LEN], at: usize, ns: u64| {
s[at..at + 8]
.copy_from_slice(&i64::try_from(ns / 1_000_000_000).unwrap_or(0).to_ne_bytes());
s[at + 8..at + 16]
.copy_from_slice(&i64::try_from(ns % 1_000_000_000).unwrap_or(0).to_ne_bytes());
};
ts(&mut s, 16, as_of);
ts(&mut s, 32, void_after);
s[48..56].copy_from_slice(&bound.to_ne_bytes());
s[64..68].copy_from_slice(&drift.to_ne_bytes());
s[68..72].copy_from_slice(&status.to_ne_bytes());
s
}
const S: u64 = 1_000_000_000;
#[test]
fn the_bound_grows_by_the_drift_rate_since_it_was_written() -> Result<(), &'static str> {
let s = segment(2, 100 * S, 110 * S, 30_000, 50_000, 1);
let r = parse(&s, 102 * S)?;
assert_eq!(r.bound_ns, 130_000);
assert_eq!(r.age_ns, 2 * S);
assert_eq!(r.status, ClockBoundStatus::Synchronized);
Ok(())
}
#[test]
fn the_status_ages_as_clockbounds_reader_ages_it() -> Result<(), &'static str> {
let s = segment(4, 100 * S, 110 * S, 0, 0, 1);
assert_eq!(parse(&s, 104 * S)?.status, ClockBoundStatus::Synchronized);
assert_eq!(parse(&s, 106 * S)?.status, ClockBoundStatus::FreeRunning);
assert_eq!(parse(&s, 111 * S)?.status, ClockBoundStatus::Unknown);
assert_eq!(
parse(&segment(4, 100 * S, 110 * S, 0, 0, 3), 101 * S)?.status,
ClockBoundStatus::Disrupted
);
Ok(())
}
#[test]
fn malformed_segments_are_refused() {
let good = segment(2, 100 * S, 110 * S, 30_000, 50_000, 1);
assert!(parse(&good, 100 * S).is_ok());
let with = |at: usize, v: u8| {
let mut s = good;
s[at] = v;
s
};
assert_eq!(
parse(&good[..79], 100 * S),
Err("shorter than a ClockBound 2.0 segment")
);
assert_eq!(
parse(&with(0, 0), 100 * S),
Err("not ClockBound's magic number")
);
assert_eq!(parse(&with(12, 3), 100 * S), Err("not layout version 2"));
assert_eq!(
parse(&segment(0, 100 * S, 110 * S, 0, 0, 1), 100 * S),
Err("not yet written (generation 0)")
);
assert_eq!(
parse(&segment(3, 100 * S, 110 * S, 0, 0, 1), 100 * S),
Err("mid-update (odd generation)")
);
assert_eq!(
parse(&segment(2, 100 * S, 110 * S, -1, 0, 1), 100 * S),
Err("negative bound")
);
assert_eq!(
parse(&segment(2, 100 * S, 110 * S, 0, 1_000_000_000, 1), 100 * S),
Err("drift rate of 100% or more")
);
assert_eq!(
parse(&segment(2, 100 * S, 110 * S, 0, 0, 9), 100 * S),
Err("unknown clock status")
);
assert_eq!(parse(&good, 99 * S), Err("as_of after now"));
let mut small = good;
small[8..12].copy_from_slice(&16_u32.to_ne_bytes());
assert_eq!(parse(&small, 100 * S), Err("segment size too small"));
let mut nanos = good;
nanos[24..32].copy_from_slice(&1_000_000_000_i64.to_ne_bytes());
assert_eq!(parse(&nanos, 100 * S), Err("as_of out of range"));
}
#[test]
fn the_segment_is_read_from_its_file() -> Result<(), Box<dyn std::error::Error>> {
let dir =
std::env::temp_dir().join(format!("ergon-tune-clockbound-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
let path = dir.join("shm0");
let _ = std::fs::remove_file(&path);
assert_eq!(read(&path), Ok(None));
let s = segment(2, 100 * S, 110 * S, 30_000, 50_000, 1);
std::fs::write(&path, s)?;
assert_eq!(read(&path), Ok(Some(s)));
std::fs::write(&path, &s[..40])?;
assert_eq!(read(&path), Err(ClockBoundError::Short(40)));
std::fs::remove_dir_all(&dir)?;
Ok(())
}
}