Files
rust-discovery/crates/time-source-linux/src/tracking.rs
T
2026-11-14 23:39:41 +01:00

205 lines
7.4 KiB
Rust

use anyhow::{Result, ensure};
pub(crate) const PACKET_BYTES: usize = 104;
pub(crate) const MAX_ERROR_NS: u64 = 500_000_000;
pub(crate) const MAX_AGE_NS: u64 = 3_600_000_000_000;
pub(crate) fn request(sequence: u32) -> [u8; PACKET_BYTES] {
let mut out = [0; PACKET_BYTES];
out[0] = 6;
out[1] = 1;
out[4..6].copy_from_slice(&33u16.to_be_bytes());
out[8..12].copy_from_slice(&sequence.to_be_bytes());
out
}
fn u16_at(raw: &[u8], n: usize) -> u16 {
u16::from_be_bytes(raw[n..n + 2].try_into().expect("checked packet size"))
}
fn u32_at(raw: &[u8], n: usize) -> u32 {
u32::from_be_bytes(raw[n..n + 4].try_into().expect("checked packet size"))
}
/// Chrony's wire Float is signed7 exponent + signed25 coefficient, value
/// coefficient * 2^(exponent-25). Convert its magnitude to ns, rounding upward
/// using integer arithmetic; no IEEE conversion or underflow-to-zero.
fn float_ns(raw: u32, allow_negative: bool) -> Result<u64> {
let mut exponent = (raw >> 25) as i32;
if exponent >= 64 {
exponent -= 128;
}
let mut coefficient = (raw & 0x01ff_ffff) as i32;
if coefficient >= 0x0100_0000 {
coefficient -= 0x0200_0000;
}
ensure!(allow_negative || coefficient >= 0, "CHRONY_NEGATIVE_ERROR");
let numerator = u128::from(coefficient.unsigned_abs()) * 1_000_000_000;
let shift = exponent - 25;
let rounded = if shift >= 0 {
numerator
.checked_shl(shift as u32)
.ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))?
} else {
let denominator = 1u128
.checked_shl((-shift) as u32)
.ok_or_else(|| anyhow::anyhow!("CHRONY_FLOAT_OVERFLOW"))?;
numerator.div_ceil(denominator)
};
u64::try_from(rounded).map_err(Into::into)
}
#[derive(Debug)]
pub(crate) struct Tracking {
pub reference_utc_ns: i64,
pub error_ns: u64,
}
pub(crate) fn reply(raw: &[u8], sequence: u32) -> Result<Tracking> {
ensure!(raw.len() == PACKET_BYTES, "CHRONY_PACKET_LENGTH");
ensure!(
raw[0] == 6
&& raw[1] == 2
&& raw[2..4] == [0, 0]
&& u16_at(raw, 4) == 33
&& u16_at(raw, 6) == 5
&& u16_at(raw, 8) == 0
&& raw[10..16] == [0; 6]
&& raw[20..28] == [0; 8]
&& u32_at(raw, 16) == sequence,
"CHRONY_REPLY_BINDING"
);
let reference = u32_at(raw, 28);
let family = u16_at(raw, 48);
// Network peers only. Local/reference-clock fallback is deliberately outside
// this profile; family UNSPEC/ID and loopback identities cannot qualify.
ensure!(
reference != 0
&& reference != 0x4c4f_434c
&& reference >> 24 != 127
&& (family == 1 || family == 2)
&& raw[50..52] == [0, 0],
"CHRONY_REFERENCE_SOURCE"
);
if family == 1 {
ensure!(
raw[32] != 127 && raw[32..36] != [0; 4] && raw[36..48] == [0; 12],
"CHRONY_LOCAL_IPV4"
);
} else {
let address = &raw[32..48];
let mapped = address[..10] == [0; 10] && address[10..12] == [0xff, 0xff];
let compatible = address[..12] == [0; 12];
ensure!(
!((mapped || compatible) && (address[12] == 127 || address[12..16] == [0; 4])),
"CHRONY_LOCAL_EMBEDDED_IPV4"
);
ensure!(
raw[32..48] != [0; 16]
&& raw[32..48] != [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
"CHRONY_LOCAL_IPV6"
);
}
ensure!(
(1..=15).contains(&u16_at(raw, 52)) && u16_at(raw, 54) <= 2,
"CHRONY_UNSYNCHRONIZED"
);
let high = u32_at(raw, 56);
let seconds = if high == 0x7fff_ffff {
u64::from(u32_at(raw, 60))
} else {
(u64::from(high) << 32) | u64::from(u32_at(raw, 60))
};
let nanos = u32_at(raw, 64);
ensure!(
seconds > 0 && nanos < 1_000_000_000,
"CHRONY_REFERENCE_TIME"
);
let reference_utc_ns = i64::try_from(u128::from(seconds) * 1_000_000_000 + u128::from(nanos))?;
let correction = float_ns(u32_at(raw, 68), true)?;
let delay = float_ns(u32_at(raw, 92), false)?;
let dispersion = float_ns(u32_at(raw, 96), false)?;
let error_ns = correction
.checked_add(delay.div_ceil(2))
.and_then(|v| v.checked_add(dispersion))
.ok_or_else(|| anyhow::anyhow!("CHRONY_ERROR_OVERFLOW"))?;
ensure!(error_ns <= MAX_ERROR_NS, "CHRONY_ERROR_LIMIT");
Ok(Tracking {
reference_utc_ns,
error_ns,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn good() -> [u8; PACKET_BYTES] {
let mut b = [0; PACKET_BYTES];
b[0] = 6;
b[1] = 2;
b[4..6].copy_from_slice(&33u16.to_be_bytes());
b[6..8].copy_from_slice(&5u16.to_be_bytes());
b[16..20].copy_from_slice(&7u32.to_be_bytes());
b[28..32].copy_from_slice(&0xc0000201u32.to_be_bytes());
b[32..36].copy_from_slice(&[192, 0, 2, 1]);
b[48..50].copy_from_slice(&1u16.to_be_bytes());
b[52..54].copy_from_slice(&2u16.to_be_bytes());
b[60..64].copy_from_slice(&1_800_000_000u32.to_be_bytes());
b
}
#[test]
fn exact_packet_sequence_and_network_source() {
let b = good();
let t = reply(&b, 7).unwrap();
assert_eq!(t.reference_utc_ns, 1_800_000_000_000_000_000);
assert_eq!(t.error_ns, 0);
assert!(reply(&b, 8).is_err());
assert!(reply(&b[..103], 7).is_err());
for offset in [0, 1, 4, 6, 8, 10, 20, 48, 54] {
let mut bad = b;
bad[offset] ^= 0x40;
assert!(reply(&bad, 7).is_err(), "offset {offset}");
}
let mut bad = b;
bad[48..50].fill(0);
assert!(reply(&bad, 7).is_err());
// IPv4 loopback/unspecified cannot hide inside mapped or compatible
// IPv6. Ordinary IPv6 and mapped network peers remain accepted.
for (mapped, ipv4) in [
(true, [127, 0, 0, 1]),
(true, [0, 0, 0, 0]),
(false, [127, 0, 0, 1]),
(false, [0, 0, 0, 0]),
] {
let mut bad = b;
bad[48..50].copy_from_slice(&2u16.to_be_bytes());
bad[32..48].fill(0);
if mapped {
bad[42..44].fill(0xff);
}
bad[44..48].copy_from_slice(&ipv4);
assert!(reply(&bad, 7).is_err());
}
let mut ipv6 = b;
ipv6[48..50].copy_from_slice(&2u16.to_be_bytes());
ipv6[32..48].fill(0);
ipv6[32..36].copy_from_slice(&[0x20, 0x01, 0x0d, 0xb8]);
ipv6[47] = 1;
assert!(reply(&ipv6, 7).is_ok());
ipv6[32..48].fill(0);
ipv6[42..44].fill(0xff);
ipv6[44..48].copy_from_slice(&[192, 0, 2, 1]);
assert!(reply(&ipv6, 7).is_ok());
assert_eq!(request(7).len(), 104);
assert_eq!(&request(7)[8..12], &7u32.to_be_bytes());
}
#[test]
fn signed_float_ceil_and_overflow_are_conservative() {
// exp=-6, coeff=2^24 -> 1/128 sec, exactly 7_812_500ns.
let positive = (122u32 << 25) | 0x0100_0000; // coeff -2^24
assert_eq!(float_ns(positive, true).unwrap(), 7_812_500);
assert!(float_ns(positive, false).is_err());
assert_eq!(float_ns(64u32 << 25 | 1, true).unwrap(), 1);
assert!(float_ns(63u32 << 25 | 0x00ff_ffff, true).is_err());
let mut b = good();
b[96..100].copy_from_slice(&(63u32 << 25 | 0x00ff_ffff).to_be_bytes());
assert!(reply(&b, 7).is_err());
}
}