//! The time service: in the background, with no window, it sets the time //! of day from the network, so a board with no real-time clock knows it, //! and one whose clock runs wrong is put right. //! //! It asks an NTP server with Network Time Security (NTS, RFC 8915, //! `pinnacle_net::nts`): a key exchange over TLS with `time.cloudflare.com`, //! or the one `/settings/time-server` names (`host` or `host:port`), then //! NTP whose answers count only when sealed with the keys of that exchange, //! so nobody on the path can move the clock. Where no NTS server answers //! (a network that lets no NTS through), it takes the date an https server //! sends (`/settings/time-https`, else `https://pinnacle-os.eu/`). Either //! way TLS checks the server's certificates against the roots with no clock //! to check them by (`pinnacle_rt::net::date`, `nts_keys`), and the time is //! believed only within the life of those certificates. //! //! Once the network is up, then every six hours; a minute after a try //! that found nothing, up to ten. Each setting is written to the log, with //! how it was authenticated and how far the clock was off. #![no_std] #![no_main] extern crate alloc; use alloc::format; use alloc::string::String; use alloc::vec::Vec; use pinnacle_net::nts; use pinnacle_rt::abi::net::ONLINE; use pinnacle_rt::{Received, fs, net, println}; /// The NTS key exchange server asked, when the settings name none. const NTS_SERVER: &str = "time.cloudflare.com"; /// Where a date is fetched when no NTS server answers. const HTTPS_SERVER: &str = "https://pinnacle-os.eu/"; const NTS_SETTING: &str = "system:/settings/time-server"; const HTTPS_SETTING: &str = "system:/settings/time-https"; /// Between settings. const EVERY_MS: u64 = 6 * 3600 * 1000; /// After a try that found nothing, doubling to [`LATEST_MS`]. const SOON_MS: u64 = 60_000; const LATEST_MS: u64 = 10 * 60_000; /// How long the key exchange may wait for a piece. const KE_WAIT_MS: u64 = 10_000; /// How long an NTP answer is waited for, each of [`TRIES`] times. const NTP_WAIT_MS: u64 = 2000; const TRIES: usize = 3; /// A setting's text, trimmed, or `default`. fn setting(path: &str, default: &str) -> String { fs::read_string(path) .map(|s| String::from(s.trim())) .filter(|s| !s.is_empty()) .unwrap_or_else(|| default.into()) } /// Random bytes. fn random() -> [u8; N] { let mut bytes = [0u8; N]; pinnacle_rt::random(&mut bytes); bytes } /// The time from an NTS server, milliseconds since 1970 as it was when /// the answer came: a key exchange with `server` (`host` or /// `host:port`), then NTP to the server it names, a fresh cookie each /// try. Answers not sealed with the exchange's key are refused, and /// waited past. fn ask_nts(server: &str) -> Result { let (host, port) = match server.rsplit_once(':') { Some((host, port)) => (host, port.parse().map_err(|_| format!("no port {port:?}"))?), None => (server, nts::KE_PORT), }; let (keys, agreed, (from, until)) = net::nts_keys(host, port, KE_WAIT_MS).map_err(|e| format!("{host}'s key exchange: {e:?}"))?; let ntp_host = agreed.server.as_deref().unwrap_or(host); let ntp_port = agreed.port.unwrap_or(pinnacle_net::ntp::PORT); // A program's UDP is IPv4 only: on a network without IPv4 the clock // comes from the HTTPS date instead. let ip = match net::resolve(ntp_host) { Some(net::IpAddr::V4(ip)) => ip, Some(net::IpAddr::V6(_)) => return Err(format!("{ntp_host} has only an IPv6 address")), None => return Err(format!("{ntp_host} has no address")), }; let (socket, _) = net::udp_bind(0).ok_or("no UDP socket")?; let mut buffer = [0u8; 1500]; let mut cookies: Vec> = agreed.cookies; for _ in 0..TRIES { // A cookie is used once, so two requests cannot be linked. let Some(cookie) = cookies.pop() else { break }; let transmit = u64::from_be_bytes(random()); let uid: [u8; 32] = random(); let sent = pinnacle_rt::time(); let request = nts::request(transmit, &uid, &cookie, 0, &keys, &random()); net::send_to(&socket, ip, ntp_port, &request); let until_ms = sent + NTP_WAIT_MS; loop { match pinnacle_rt::receive(&[&socket], &mut buffer, Some(until_ms)) { Received::Message { len, .. } => { let Some((_, _, packet)) = net::datagram(&buffer[..len]) else { continue; }; let elapsed = pinnacle_rt::time() - sent; match nts::answer(packet, transmit, &uid, &keys, elapsed) { Ok((ms, _)) => { let seconds = (ms / 1000) as i64; if !(from..=until).contains(&seconds) { return Err(format!("{ntp_host} gave a time outside its certificates' life")); } return Ok(ms); } // Another's answer, or a late one: wait on. Err(nts::Refused::Ntp(pinnacle_net::ntp::Refused::NotOurs)) => continue, // Someone on the path: refused, and the true // answer waited for. Err(nts::Refused::Forged) => { println!("time: refused an answer to {ntp_host} that is not authenticated"); continue; } Err(e) => return Err(format!("{ntp_host} answered {e:?}")), } } Received::Closed { .. } => return Err("the socket closed".into()), Received::Timeout => break, } } } Err(format!("{ntp_host} did not answer")) } /// Sets the clock from the network; how, or why it could not. fn set_from_network() -> Result { let server = setting(NTS_SETTING, NTS_SERVER); let (ms, how) = match ask_nts(&server) { Ok(ms) => (ms, format!("{server} (NTS, authenticated)")), Err(nts) => { let url = setting(HTTPS_SETTING, HTTPS_SERVER); let seconds = net::date(&url, 10_000).map_err(|e| format!("{nts}; {url}: {e:?}"))?; // A date is to the second: half of one is the best guess. ( seconds * 1000 + 500, format!("{url} (its date over TLS, authenticated, as NTS was not answered: {nts})"), ) } }; let (before, _) = pinnacle_rt::clock_ms(); if !pinnacle_rt::set_clock(ms) { return Err("the kernel would not set the clock".into()); } let off = ms as i64 - before as i64; let (date, _) = pinnacle_rt::locale::Zone::utc().civil((ms / 1000) as i64); Ok(format!( "{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC from {how}; the clock was {}", date.year, date.month, date.day, date.hour, date.minute, date.second, if before == 0 { String::from("not set") } else if off.abs() < 1000 { format!("{off} ms off") } else { format!( "{} s {}", off.abs() / 1000, if off > 0 { "behind" } else { "ahead" } ) } )) } #[unsafe(no_mangle)] fn main(_argument: u64) -> u64 { let mut wait = SOON_MS; loop { if net::state() != ONLINE || net::info().is_none() { // Looked at again every few seconds until it is up. pinnacle_rt::sleep(3000); continue; } match set_from_network() { Ok(how) => { println!("time: set to {how}"); wait = SOON_MS; pinnacle_rt::sleep(EVERY_MS); } Err(why) => { println!("time: not set: {why}"); pinnacle_rt::sleep(wait); wait = (wait * 2).min(LATEST_MS); } } } }