Skip to main content

network/sntp/
service.rs

1//! The SNTP synchronization service: a task that starts when an interface has
2//! an address, sets UTC from the configured servers through `sntpc`, and
3//! resynchronizes periodically with a bounded exponential backoff on failure.
4//!
5//! Kiss-of-death answers (RFC 5905 section 7.4) get a per-server policy:
6//! `DENY` and `RSTR` ban the server until the next configuration change or
7//! reboot, and `RATE` sets a monotonic `not_before` deadline for that server
8//! (now plus the doubled interval): servers whose deadline has not passed are
9//! skipped, and the service sleeps until the earliest deadline. Each event is
10//! logged once per server. A successful answer resets the server's rate
11//! multiplier.
12//!
13//! After the first network synchronization, a clock step larger than 1000 s is
14//! applied only when a second answer confirms it: the signed offset (candidate
15//! minus the current clock) of the two answers must agree within 5 s. The
16//! servers are tried in order, so a confirming answer from another server or
17//! resolved address is preferred; with a single server, a later exchange of
18//! the same server confirms, which means a single-server setup only resists a
19//! blind off-path attacker. A pending step expires only after twice the larger
20//! of the resynchronization interval and the maximum retry delay (30 min), so
21//! the confirming attempt always comes before the expiry.
22//!
23//! Query times carry a random jitter, as the NTP Pool vendor guidance asks:
24//! 0 to 2 s before the first query, and 0 to 12 percent added to every
25//! resynchronization interval, retry delay and deferred wait. Resolved server
26//! names are cached for one hour, and dropped after a failed exchange.
27
28use alloc::boxed::Box;
29use alloc::string::String;
30use alloc::vec::Vec;
31use core::time::Duration;
32
33use sntpc::{Error as SntpError, KissOfDeathCode};
34use task::{Manager as TaskManager, TaskIdentifier};
35use time::Timestamp;
36
37use crate::{
38    DnsQueryKind, IntoIoErrorKind, IpAddress, Manager, Result,
39    sntp::{
40        client::{self, Applied, Client, Failure, MAXIMUM_CLOCK_STEP, STEP_CONFIRMATION_TOLERANCE},
41        configuration::{self, Configuration, MAXIMUM_RESYNC_INTERVAL},
42    },
43};
44
45/// How often to check that an interface has an address while waiting for the
46/// network to come up.
47pub(crate) const NETWORK_POLL_INTERVAL: Duration = Duration::from_secs(10);
48
49/// The delay before the first retry after a failure.
50pub(crate) const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(60);
51
52/// The largest delay between two attempts after failures.
53pub(crate) const MAXIMUM_RETRY_DELAY: Duration = Duration::from_secs(1800);
54
55/// After this many consecutive failures, and then again every
56/// `FAILURE_LOG_STRIDE`-th failure, a warning is logged.
57pub(crate) const REPEATED_FAILURE_LOG_THRESHOLD: u32 = 3;
58
59/// The stride between two failure warnings once the threshold is reached.
60pub(crate) const FAILURE_LOG_STRIDE: u32 = 10;
61
62/// The largest multiplier a `RATE` kiss of death applies to one server's
63/// resynchronization interval.
64pub(crate) const MAXIMUM_RATE_MULTIPLIER: u32 = 64;
65
66/// How long a resolved server name is reused before resolving it again.
67pub(crate) const DNS_CACHE_LIFETIME: Duration = Duration::from_secs(3600);
68
69/// Random delay before the first query, from zero up to this bound.
70pub(crate) const FIRST_QUERY_JITTER: Duration = Duration::from_secs(2);
71
72/// Random percentage added to every interval, retry delay and deferred wait,
73/// from 0 up to this value.
74pub(crate) const JITTER_PERCENT: u64 = 12;
75
76/// The delay before retrying after `failures` consecutive failures: the
77/// initial delay doubled per failure, capped at the maximum.
78pub(crate) fn retry_delay(failures: u32) -> Duration {
79    let shift = failures.saturating_sub(1).min(16);
80    let factor = 1u64.checked_shl(shift).unwrap_or(u64::MAX);
81    let millis = (INITIAL_RETRY_DELAY.as_millis() as u64)
82        .saturating_mul(factor)
83        .min(MAXIMUM_RETRY_DELAY.as_millis() as u64);
84    Duration::from_millis(millis)
85}
86
87/// A random duration from zero up to `span`, from the network manager's random
88/// device; zero when the device cannot be read.
89fn jitter(network: &Manager, span: Duration) -> Duration {
90    match network.random_u32() {
91        Some(value) => {
92            let nanos =
93                (u128::from(value) * span.as_nanos() / u128::from(u32::MAX)).min(u64::MAX as u128);
94            Duration::from_nanos(nanos as u64)
95        }
96        None => Duration::ZERO,
97    }
98}
99
100/// `base` plus a random 0 to `JITTER_PERCENT` percent.
101fn add_jitter(network: &Manager, base: Duration) -> Duration {
102    let percent = network
103        .random_u32()
104        .map(|value| u64::from(value) % (JITTER_PERCENT + 1))
105        .unwrap_or(0);
106    let nanos = base.as_nanos().saturating_mul(u128::from(100 + percent)) / 100;
107    Duration::from_nanos(nanos.min(u64::MAX as u128) as u64)
108}
109
110/// The per-server state the kiss-of-death policy keeps. It lives in memory
111/// only: a reboot or a new configuration starts every server fresh.
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct ServerState {
114    /// `DENY` or `RSTR`: the server is not queried again.
115    banned: bool,
116    /// How many times a `RATE` kiss of death doubled this server's interval.
117    rate_multiplier: u32,
118    /// Whether the kiss of death was already logged for this server.
119    kiss_logged: bool,
120    /// Monotonic instant before which a `RATE` kiss of death says the server
121    /// must not be queried.
122    not_before: Option<Duration>,
123}
124
125impl ServerState {
126    /// The resynchronization interval of this server: the configured interval
127    /// times the rate multiplier, saturated.
128    fn interval(&self, base: Duration) -> Duration {
129        base.checked_mul(self.rate_multiplier.max(1))
130            .unwrap_or(MAXIMUM_RESYNC_INTERVAL)
131    }
132
133    /// Whether the server may not be queried at the monotonic instant `now`.
134    fn blocked(&self, now: Duration) -> bool {
135        self.banned || self.not_before.is_some_and(|deadline| now < deadline)
136    }
137}
138
139/// The earliest monotonic deadline among the rate-limited servers that are not
140/// yet due, if any.
141fn earliest_deadline(states: &[ServerState], now: Duration) -> Option<Duration> {
142    states
143        .iter()
144        .filter(|state| !state.banned)
145        .filter_map(|state| state.not_before)
146        .filter(|deadline| now < *deadline)
147        .min()
148}
149
150/// Apply a kiss-of-death answer to one server's state and log it once. Returns
151/// whether this call logged it. `now` is the monotonic instant and `base` the
152/// configured resynchronization interval.
153pub(crate) fn handle_kiss_of_death(
154    state: &mut ServerState,
155    code: KissOfDeathCode,
156    server: &str,
157    now: Duration,
158    base: Duration,
159) -> bool {
160    match code {
161        KissOfDeathCode::Deny | KissOfDeathCode::Rstr => {
162            state.banned = true;
163            if state.kiss_logged {
164                return false;
165            }
166            state.kiss_logged = true;
167            log::warning!(
168                "SNTP: server {server} denied access ({}); not used again until the next configuration change or reboot",
169                code.as_str()
170            );
171            true
172        }
173        KissOfDeathCode::Rate => {
174            state.rate_multiplier = state
175                .rate_multiplier
176                .max(1)
177                .saturating_mul(2)
178                .min(MAXIMUM_RATE_MULTIPLIER);
179            let interval = state.interval(base);
180            state.not_before = Some(now.checked_add(interval).unwrap_or(Duration::MAX));
181            if state.kiss_logged {
182                return false;
183            }
184            state.kiss_logged = true;
185            log::warning!(
186                "SNTP: server {server} asked to slow down ({}); next query in {} s",
187                code.as_str(),
188                interval.as_secs()
189            );
190            true
191        }
192        _ => false,
193    }
194}
195
196/// One successful synchronization.
197#[derive(Clone, Debug)]
198pub struct Outcome {
199    /// The server that answered.
200    pub server: &'static str,
201    /// What applying the answer changed.
202    pub applied: Applied,
203    /// How long to wait before resynchronizing with this server.
204    pub interval: Duration,
205}
206
207/// The result of one attempt over the configured servers.
208#[derive(Clone, Debug)]
209enum Attempt {
210    Synchronized(Outcome),
211    Failed(Failure),
212    /// Every configured server denied access: nothing is queried until the
213    /// next configuration change or reboot.
214    AllBanned,
215    /// Every usable server is rate-limited: wait until this monotonic deadline.
216    Deferred(Duration),
217    /// A clock step larger than the bound was seen but no second answer
218    /// confirmed it yet.
219    Unconfirmed,
220}
221
222/// A large clock step waiting for a confirming second answer: the signed
223/// offset in nanoseconds (candidate minus the current clock), the server that
224/// reported it, the address that answered, and the monotonic instant when it
225/// was recorded. It expires after [`pending_step_age_limit`].
226#[derive(Clone, Debug)]
227struct PendingStep {
228    offset_nanos: i128,
229    server: usize,
230    address: Option<IpAddress>,
231    recorded_at: Duration,
232}
233
234/// The age limit of a pending step: the larger of the resynchronization
235/// interval and the maximum retry delay, times two. After an unconfirmed step
236/// the loop waits a retry delay (60 s first, doubling up to 30 min), so the
237/// limit must exceed the longest wait before the confirming attempt: with the
238/// smallest interval (60 s) a limit of one interval expired the step before
239/// the next attempt and a single server could never confirm.
240fn pending_step_age_limit(configuration: &Configuration) -> Duration {
241    configuration
242        .resync_interval
243        .max(MAXIMUM_RETRY_DELAY)
244        .saturating_mul(2)
245}
246
247/// Whether a pending step recorded at `recorded_at` is expired at `now`.
248fn pending_step_expired(pending: &PendingStep, now: Duration, limit: Duration) -> bool {
249    now.saturating_sub(pending.recorded_at) > limit
250}
251
252/// A cached name resolution.
253struct DnsEntry {
254    name: String,
255    addresses: Vec<IpAddress>,
256    resolved_at: Duration,
257}
258
259/// Resolve `name`, reusing the cached addresses while they are younger than
260/// [`DNS_CACHE_LIFETIME`].
261async fn resolve_cached(
262    network: &Manager,
263    cache: &mut Vec<DnsEntry>,
264    name: &str,
265    now: Duration,
266) -> core::result::Result<Vec<IpAddress>, Failure> {
267    if let Some(entry) = cache.iter().find(|entry| entry.name == name)
268        && now.saturating_sub(entry.resolved_at) < DNS_CACHE_LIFETIME
269    {
270        return Ok(entry.addresses.clone());
271    }
272    let addresses = network
273        .resolve(name, DnsQueryKind::A | DnsQueryKind::Aaaa, true, None)
274        .await
275        .map_err(|error| Failure::Io(error.kind()))?;
276    match cache.iter_mut().find(|entry| entry.name == name) {
277        Some(entry) => {
278            entry.addresses = addresses.clone();
279            entry.resolved_at = now;
280        }
281        None => cache.push(DnsEntry {
282            name: String::from(name),
283            addresses: addresses.clone(),
284            resolved_at: now,
285        }),
286    }
287    Ok(addresses)
288}
289
290/// Drop the cached resolution of `name`, for example after a failed exchange:
291/// the next attempt resolves it again.
292fn drop_cache_entry(cache: &mut Vec<DnsEntry>, name: &str) {
293    cache.retain(|entry| entry.name != name);
294}
295
296/// The SNTP service, assembled from the runtime subsystems it needs.
297pub struct Service {
298    task_manager: &'static TaskManager,
299    network: &'static Manager,
300    time: &'static time::Manager<'static>,
301    virtual_file_system: &'static virtual_file_system::VirtualFileSystem,
302    minimum_timestamp: Timestamp,
303}
304
305impl Service {
306    /// `minimum_timestamp` is the platform's floor for UTC, as Unix time in
307    /// UTC: on a device without a battery clock, the build date, for example
308    /// `time::Timestamp::from(core::time::Duration::from_secs(BUILD_EPOCH))`.
309    /// Answers before it are rejected.
310    pub fn new(
311        task_manager: &'static TaskManager,
312        network: &'static Manager,
313        time: &'static time::Manager<'static>,
314        virtual_file_system: &'static virtual_file_system::VirtualFileSystem,
315        minimum_timestamp: Timestamp,
316    ) -> Self {
317        Self {
318            task_manager,
319            network,
320            time,
321            virtual_file_system,
322            minimum_timestamp,
323        }
324    }
325
326    /// Load the configuration and spawn the service task. The task runs until
327    /// the system stops; its identifier is returned.
328    pub async fn start(self, task: TaskIdentifier) -> Result<TaskIdentifier> {
329        self.start_on(task, None).await
330    }
331
332    /// Start the service on a selected executor. With no selection, use the
333    /// executor that calls this method.
334    pub async fn start_on(
335        self,
336        task: TaskIdentifier,
337        executor: Option<task::SpawnerIdentifier>,
338    ) -> Result<TaskIdentifier> {
339        // The configuration is allocated once, outside the task stack.
340        let configuration: &'static Configuration = Box::leak(Box::new(
341            configuration::load(self.virtual_file_system, task).await,
342        ));
343        let network = self.network;
344        let time = self.time;
345        let minimum_timestamp = self.minimum_timestamp;
346        let service = move |_| async move {
347            run(network, time, configuration, minimum_timestamp).await;
348        };
349        let name = "SNTP synchronization";
350        match executor {
351            Some(executor) => {
352                self.task_manager
353                    .spawn_on_executor(task, name, executor, service)
354                    .await
355            }
356            None => self.task_manager.spawn(task, name, None, service).await,
357        }
358        .map(|(_, identifier)| identifier)
359        .map_err(|error| error.into_io_error_kind())
360    }
361}
362
363/// The service loop: wait for the network, synchronize, resynchronize after the
364/// configured interval, and back off exponentially (bounded) on failure.
365async fn run(
366    network: &'static Manager,
367    time: &'static time::Manager<'static>,
368    configuration: &'static Configuration,
369    minimum_timestamp: Timestamp,
370) {
371    let client = Client::new(network, time, Some(minimum_timestamp));
372    let mut adapter: Option<client::SntpUdpSocket> = None;
373    let mut states: Vec<ServerState> = configuration
374        .servers
375        .iter()
376        .map(|_| ServerState::default())
377        .collect();
378    let mut dns_cache: Vec<DnsEntry> = Vec::new();
379    let mut pending_step: Option<PendingStep> = None;
380    let mut failures: u32 = 0;
381    let mut synchronized_once = false;
382    let mut first_query = true;
383
384    loop {
385        // Start when an interface has an address.
386        while !network.has_ip_address(None).await {
387            task::sleep(NETWORK_POLL_INTERVAL).await;
388        }
389        if first_query {
390            first_query = false;
391            task::sleep(jitter(network, FIRST_QUERY_JITTER)).await;
392        }
393
394        match attempt(
395            &client,
396            network,
397            time,
398            configuration,
399            &mut states,
400            &mut adapter,
401            &mut dns_cache,
402            &mut pending_step,
403        )
404        .await
405        {
406            Attempt::Synchronized(outcome) => {
407                if !synchronized_once {
408                    synchronized_once = true;
409                    log_success(&outcome);
410                }
411                failures = 0;
412                task::sleep(add_jitter(network, outcome.interval)).await;
413            }
414            Attempt::AllBanned => {
415                // Nothing is queried until the next configuration change or
416                // reboot; the kiss-of-death was already logged once.
417                task::sleep(add_jitter(network, configuration.resync_interval)).await;
418            }
419            Attempt::Deferred(deadline) => {
420                // Every usable server is rate-limited: wait for the earliest
421                // deadline.
422                let wait = deadline.saturating_sub(time.monotonic_now());
423                task::sleep(add_jitter(network, wait)).await;
424            }
425            Attempt::Unconfirmed => {
426                failures = failures.saturating_add(1);
427                log::warning!(
428                    "SNTP: a clock step larger than {} s is waiting for a confirming second answer",
429                    MAXIMUM_CLOCK_STEP.as_secs()
430                );
431                task::sleep(add_jitter(network, retry_delay(failures))).await;
432            }
433            Attempt::Failed(error) => {
434                failures = failures.saturating_add(1);
435                if let Failure::Io(kind) = error
436                    && client::invalidates_socket(kind)
437                {
438                    // The interface may have changed: rebuild the socket.
439                    adapter = None;
440                }
441                if failures >= REPEATED_FAILURE_LOG_THRESHOLD
442                    && (failures - REPEATED_FAILURE_LOG_THRESHOLD)
443                        .is_multiple_of(FAILURE_LOG_STRIDE)
444                {
445                    log::warning!(
446                        "SNTP: synchronization still failing after {failures} attempts (last error {error:?})"
447                    );
448                }
449                task::sleep(add_jitter(network, retry_delay(failures))).await;
450            }
451        }
452    }
453}
454
455/// Query the configured servers in order and apply the first valid answer.
456/// Servers that are banned or rate-limited are skipped.
457#[allow(clippy::too_many_arguments)]
458async fn attempt(
459    client: &Client<'_>,
460    network: &Manager,
461    time: &time::Manager<'_>,
462    configuration: &'static Configuration,
463    states: &mut [ServerState],
464    adapter: &mut Option<client::SntpUdpSocket>,
465    dns_cache: &mut Vec<DnsEntry>,
466    pending_step: &mut Option<PendingStep>,
467) -> Attempt {
468    let now = time.monotonic_now();
469    // A pending step expires after the age limit, which is always longer than
470    // the wait before the confirming attempt.
471    let age_limit = pending_step_age_limit(configuration);
472    if let Some(pending) = pending_step.as_ref()
473        && pending_step_expired(pending, now, age_limit)
474    {
475        *pending_step = None;
476    }
477    let mut last_error = Failure::Protocol(SntpError::Network);
478    let mut queried = false;
479    let mut unconfirmed = false;
480    for (index, server) in configuration.servers.iter().enumerate() {
481        if states[index].blocked(now) {
482            continue;
483        }
484        queried = true;
485        let addresses = match resolve_cached(network, dns_cache, server, now).await {
486            Ok(addresses) => addresses,
487            Err(error) => {
488                last_error = error;
489                continue;
490            }
491        };
492        let result = match client.ensure_socket(adapter).await {
493            Ok(socket) => client.exchange_addresses(&addresses, socket).await,
494            Err(error) => Err(Failure::Io(error)),
495        };
496        match result {
497            Ok(exchange) => {
498                let candidate = match client.candidate(&exchange) {
499                    Ok(candidate) => candidate,
500                    Err(error) => {
501                        last_error = error;
502                        continue;
503                    }
504                };
505                // After the first network synchronization, a step larger than
506                // the bound is applied only when a second answer confirms it:
507                // the signed offsets of the two answers must agree.
508                let already_network = time
509                    .status()
510                    .synchronization
511                    .is_some_and(|status| status.source == time::ClockSource::Network);
512                let offset_nanos = if already_network {
513                    time.realtime_now()
514                        .ok()
515                        .map(|current| candidate.as_nanos() - current.as_nanos())
516                } else {
517                    None
518                };
519                match offset_nanos {
520                    Some(offset_nanos)
521                        if offset_nanos.abs() > MAXIMUM_CLOCK_STEP.as_nanos() as i128 =>
522                    {
523                        let confirmed = pending_step.as_ref().is_some_and(|pending| {
524                            (offset_nanos - pending.offset_nanos).abs()
525                                <= STEP_CONFIRMATION_TOLERANCE.as_nanos() as i128
526                        });
527                        if confirmed {
528                            if let Some(pending) = pending_step.take()
529                                && (pending.server != index
530                                    || pending.address != Some(exchange.answered_from.clone()))
531                            {
532                                log::information!(
533                                    "SNTP: the large clock step is confirmed by a second server or address"
534                                );
535                            }
536                        } else {
537                            *pending_step = Some(PendingStep {
538                                offset_nanos,
539                                server: index,
540                                address: Some(exchange.answered_from.clone()),
541                                recorded_at: now,
542                            });
543                            unconfirmed = true;
544                            last_error = Failure::Protocol(SntpError::InvalidTimestamp);
545                            continue;
546                        }
547                    }
548                    // Any other answer (in range, or before the first network
549                    // synchronization) clears the pending step, so a stale
550                    // step can never confirm a later answer.
551                    _ => *pending_step = None,
552                }
553                match client.apply(&exchange) {
554                    Ok(applied) => {
555                        // A success clears the rate multiplier of the server
556                        // that answered.
557                        states[index].rate_multiplier = 1;
558                        return Attempt::Synchronized(Outcome {
559                            server: &configuration.servers[index],
560                            applied,
561                            interval: states[index].interval(configuration.resync_interval),
562                        });
563                    }
564                    Err(error) => last_error = error,
565                }
566            }
567            Err(Failure::Protocol(SntpError::KissOfDeath(code))) => {
568                handle_kiss_of_death(
569                    &mut states[index],
570                    code,
571                    server,
572                    time.monotonic_now(),
573                    configuration.resync_interval,
574                );
575                last_error = Failure::Protocol(SntpError::KissOfDeath(code));
576            }
577            Err(error) => {
578                // A failed or timed-out exchange: resolve the name again on
579                // the next attempt.
580                drop_cache_entry(dns_cache, server);
581                last_error = error;
582            }
583        }
584    }
585    if unconfirmed {
586        Attempt::Unconfirmed
587    } else if queried {
588        Attempt::Failed(last_error)
589    } else if let Some(deadline) = earliest_deadline(states, now) {
590        Attempt::Deferred(deadline)
591    } else {
592        Attempt::AllBanned
593    }
594}
595
596fn log_success(outcome: &Outcome) {
597    log::information!(
598        "SNTP: UTC synchronized from {} (offset {:+} ms, round trip {} ms, accuracy {} ms)",
599        outcome.server,
600        outcome.applied.server_offset_micros as f64 / 1_000.0,
601        outcome.applied.round_trip.as_millis(),
602        outcome.applied.accuracy.as_millis()
603    );
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::sntp::support::{
610        TEST_MUTEX, host_time_manager, spawn_scripted_server, valid_answer,
611    };
612    use crate::tests::initialize;
613    use alloc::vec;
614    use core::cell::Cell;
615    use time::{ClockSource, RealtimeSample};
616
617    /// 2027-01-01 00:00:00 UTC, in Unix nanoseconds.
618    const T0: i128 = 1_800_000_000_000_000_000;
619
620    /// A static configuration with the given server names and a one-hour
621    /// resynchronization interval.
622    fn test_configuration(servers: &[&str]) -> &'static Configuration {
623        Box::leak(Box::new(Configuration {
624            servers: servers.iter().map(|name| String::from(*name)).collect(),
625            resync_interval: Duration::from_secs(3600),
626        }))
627    }
628
629    /// Set the clock to `nanos`, claiming a network synchronization.
630    fn set_network_clock(time: &time::Manager<'_>, nanos: i128) {
631        time.set_realtime(RealtimeSample {
632            timestamp: Timestamp::from_nanos(nanos),
633            source: ClockSource::Network,
634            resolution: Duration::from_secs(1),
635            accuracy: None,
636        })
637        .unwrap();
638    }
639
640    #[test]
641    fn retry_delay_doubles_and_is_bounded() {
642        assert_eq!(retry_delay(1), INITIAL_RETRY_DELAY);
643        assert_eq!(retry_delay(2), INITIAL_RETRY_DELAY * 2);
644        assert_eq!(retry_delay(3), INITIAL_RETRY_DELAY * 4);
645        assert_eq!(retry_delay(100), MAXIMUM_RETRY_DELAY);
646        assert_eq!(retry_delay(u32::MAX), MAXIMUM_RETRY_DELAY);
647        assert!(retry_delay(4) < MAXIMUM_RETRY_DELAY);
648    }
649
650    #[test]
651    fn failure_logging_points() {
652        let logged: Vec<u32> = (1..=25u32)
653            .filter(|failures| {
654                *failures >= REPEATED_FAILURE_LOG_THRESHOLD
655                    && (failures - REPEATED_FAILURE_LOG_THRESHOLD)
656                        .is_multiple_of(FAILURE_LOG_STRIDE)
657            })
658            .collect();
659        assert_eq!(logged, vec![3, 13, 23]);
660    }
661
662    #[test]
663    fn deny_and_rstr_ban_the_server_and_log_once() {
664        let base = Duration::from_secs(3600);
665        for code in [KissOfDeathCode::Deny, KissOfDeathCode::Rstr] {
666            let mut state = ServerState::default();
667            assert!(handle_kiss_of_death(
668                &mut state,
669                code,
670                "a",
671                Duration::ZERO,
672                base
673            ));
674            assert!(state.banned);
675            assert_eq!(state.interval(base), base);
676            assert!(state.blocked(Duration::ZERO));
677            assert!(!handle_kiss_of_death(
678                &mut state,
679                code,
680                "a",
681                Duration::ZERO,
682                base
683            ));
684        }
685    }
686
687    #[test]
688    fn rate_sets_a_monotonic_deadline_and_doubles_the_interval_bounded() {
689        let base = Duration::from_secs(3600);
690        let now = Duration::from_secs(1000);
691        let mut state = ServerState::default();
692        assert!(handle_kiss_of_death(
693            &mut state,
694            KissOfDeathCode::Rate,
695            "a",
696            now,
697            base
698        ));
699        // The next query is not before now plus the doubled interval.
700        assert_eq!(state.not_before, Some(now + base * 2));
701        assert_eq!(state.interval(base), base * 2);
702        assert!(state.blocked(now + base * 2 - Duration::from_secs(1)));
703        assert!(!state.blocked(now + base * 2));
704        // A second RATE moves the deadline again but is not logged again.
705        assert!(!handle_kiss_of_death(
706            &mut state,
707            KissOfDeathCode::Rate,
708            "a",
709            now,
710            base
711        ));
712        assert_eq!(state.not_before, Some(now + base * 4));
713        assert_eq!(state.interval(base), base * 4);
714        for _ in 0..10 {
715            handle_kiss_of_death(&mut state, KissOfDeathCode::Rate, "a", now, base);
716        }
717        assert_eq!(state.interval(base), base * MAXIMUM_RATE_MULTIPLIER);
718        assert_eq!(state.not_before, Some(now + base * MAXIMUM_RATE_MULTIPLIER));
719        assert!(!state.banned);
720    }
721
722    #[test]
723    fn with_two_servers_only_the_rate_limited_one_is_skipped() {
724        let base = Duration::from_secs(3600);
725        let now = Duration::from_secs(1000);
726        let mut states = vec![ServerState::default(), ServerState::default()];
727        assert!(handle_kiss_of_death(
728            &mut states[0],
729            KissOfDeathCode::Rate,
730            "a",
731            now,
732            base
733        ));
734        assert!(states[0].blocked(now), "server 0 waits for its deadline");
735        assert!(!states[1].blocked(now), "server 1 is still queried");
736        assert_eq!(earliest_deadline(&states, now), Some(now + base * 2));
737        // Once both are limited, the earliest deadline wins.
738        let later = now + base * 2;
739        assert!(handle_kiss_of_death(
740            &mut states[1],
741            KissOfDeathCode::Rate,
742            "b",
743            later,
744            base
745        ));
746        assert_eq!(earliest_deadline(&states, later), Some(later + base * 2));
747        assert_eq!(earliest_deadline(&states, later + base * 2), None);
748    }
749
750    #[test]
751    fn other_kiss_codes_change_nothing() {
752        let mut state = ServerState::default();
753        assert!(!handle_kiss_of_death(
754            &mut state,
755            KissOfDeathCode::Init,
756            "a",
757            Duration::ZERO,
758            Duration::from_secs(3600)
759        ));
760        assert_eq!(state, ServerState::default());
761    }
762
763    /// An honest server that is 2000 s ahead of the (network-synchronized but
764    /// wrong) local clock: its two answers carry the same signed offset, so
765    /// the second one confirms the large step and applies it.
766    #[task::test]
767    async fn an_honest_large_step_is_confirmed_by_a_second_answer() {
768        let _lock = TEST_MUTEX.lock().await;
769        let network = initialize().await;
770        let time_manager = host_time_manager();
771        set_network_clock(time_manager, T0);
772        let client = Client::new(network, time_manager, None);
773
774        // The honest server answers "now plus 2000 s" at answer time.
775        let (ready, server_task) = spawn_scripted_server(
776            [127, 0, 0, 1],
777            move |request| {
778                let now = time_manager.realtime_now().unwrap().as_nanos();
779                alloc::vec![valid_answer(now + 2_000_000_000_000)(request)]
780            },
781            2,
782        )
783        .await;
784        ready.wait().await;
785
786        let configuration = test_configuration(&["127.0.0.1"]);
787        let mut states = vec![ServerState::default()];
788        let mut adapter = None;
789        let mut dns_cache: Vec<DnsEntry> = Vec::new();
790        let mut pending_step: Option<PendingStep> = None;
791
792        let first = attempt(
793            &client,
794            network,
795            time_manager,
796            configuration,
797            &mut states,
798            &mut adapter,
799            &mut dns_cache,
800            &mut pending_step,
801        )
802        .await;
803        assert!(
804            matches!(first, Attempt::Unconfirmed),
805            "the first answer alone does not apply a 2000 s step: {first:?}"
806        );
807        let pending = pending_step.as_ref().expect("a step is pending");
808        assert!(
809            (pending.offset_nanos - 2_000_000_000_000).abs() < 1_000_000_000,
810            "the pending step is the signed offset: {}",
811            pending.offset_nanos
812        );
813
814        // Ten seconds pass: the local clock advances and the honest server
815        // follows it, so the offset stays the same.
816        set_network_clock(time_manager, T0 + 10_000_000_000);
817        let second = attempt(
818            &client,
819            network,
820            time_manager,
821            configuration,
822            &mut states,
823            &mut adapter,
824            &mut dns_cache,
825            &mut pending_step,
826        )
827        .await;
828        assert!(
829            matches!(second, Attempt::Synchronized(_)),
830            "the second answer confirms the step: {second:?}"
831        );
832        assert!(pending_step.is_none());
833        server_task.join().await;
834    }
835
836    /// A server repeating one constant wrong time: the signed offset moves
837    /// with the local clock, so the second answer does not confirm it.
838    #[task::test]
839    async fn a_constant_wrong_time_is_not_confirmed() {
840        let _lock = TEST_MUTEX.lock().await;
841        let network = initialize().await;
842        let time_manager = host_time_manager();
843        set_network_clock(time_manager, T0);
844        let client = Client::new(network, time_manager, None);
845
846        // The attacker always answers the same frozen time, 5000 s ahead.
847        let constant = T0 + 5_000_000_000_000;
848        let (ready, server_task) = spawn_scripted_server(
849            [127, 0, 0, 1],
850            move |request| alloc::vec![valid_answer(constant)(request)],
851            2,
852        )
853        .await;
854        ready.wait().await;
855
856        let configuration = test_configuration(&["127.0.0.1"]);
857        let mut states = vec![ServerState::default()];
858        let mut adapter = None;
859        let mut dns_cache: Vec<DnsEntry> = Vec::new();
860        let mut pending_step: Option<PendingStep> = None;
861
862        let first = attempt(
863            &client,
864            network,
865            time_manager,
866            configuration,
867            &mut states,
868            &mut adapter,
869            &mut dns_cache,
870            &mut pending_step,
871        )
872        .await;
873        assert!(matches!(first, Attempt::Unconfirmed), "{first:?}");
874
875        // Ten seconds pass: the constant answer is now 10 s further from the
876        // local clock, outside the confirmation tolerance.
877        set_network_clock(time_manager, T0 + 10_000_000_000);
878        let second = attempt(
879            &client,
880            network,
881            time_manager,
882            configuration,
883            &mut states,
884            &mut adapter,
885            &mut dns_cache,
886            &mut pending_step,
887        )
888        .await;
889        assert!(
890            matches!(second, Attempt::Unconfirmed),
891            "a constant wrong time never confirms: {second:?}"
892        );
893        // The clock was not set to the wrong time.
894        let realtime = time_manager.realtime_now().unwrap().as_nanos();
895        assert!(
896            (realtime - (T0 + 10_000_000_000)).abs() < 1_000_000_000,
897            "the clock kept its own time: {realtime}"
898        );
899        server_task.join().await;
900    }
901
902    /// An in-range answer applies and clears the pending step, so a single
903    /// later large answer does not confirm at once.
904    #[task::test]
905    async fn an_in_range_answer_clears_the_pending_step() {
906        let _lock = TEST_MUTEX.lock().await;
907        let network = initialize().await;
908        let time_manager = host_time_manager();
909        set_network_clock(time_manager, T0);
910        let client = Client::new(network, time_manager, None);
911
912        // The server answers +2000 s, then in range, then +2000 s again.
913        let calls = Cell::new(0usize);
914        let (ready, server_task) = spawn_scripted_server(
915            [127, 0, 0, 1],
916            move |request| {
917                let call = calls.get();
918                calls.set(call + 1);
919                let now = time_manager.realtime_now().unwrap().as_nanos();
920                let offset = if call == 1 { 0 } else { 2000 };
921                alloc::vec![valid_answer(now + offset * 1_000_000_000)(request)]
922            },
923            3,
924        )
925        .await;
926        ready.wait().await;
927
928        let configuration = test_configuration(&["127.0.0.1"]);
929        let mut states = vec![ServerState::default()];
930        let mut adapter = None;
931        let mut dns_cache: Vec<DnsEntry> = Vec::new();
932        let mut pending_step: Option<PendingStep> = None;
933
934        let first = attempt(
935            &client,
936            network,
937            time_manager,
938            configuration,
939            &mut states,
940            &mut adapter,
941            &mut dns_cache,
942            &mut pending_step,
943        )
944        .await;
945        assert!(matches!(first, Attempt::Unconfirmed), "{first:?}");
946        assert!(pending_step.is_some());
947
948        let second = attempt(
949            &client,
950            network,
951            time_manager,
952            configuration,
953            &mut states,
954            &mut adapter,
955            &mut dns_cache,
956            &mut pending_step,
957        )
958        .await;
959        assert!(
960            matches!(second, Attempt::Synchronized(_)),
961            "the in-range answer applies: {second:?}"
962        );
963        assert!(
964            pending_step.is_none(),
965            "the applied answer cleared the pending step"
966        );
967
968        let third = attempt(
969            &client,
970            network,
971            time_manager,
972            configuration,
973            &mut states,
974            &mut adapter,
975            &mut dns_cache,
976            &mut pending_step,
977        )
978        .await;
979        assert!(
980            matches!(third, Attempt::Unconfirmed),
981            "a single later large answer does not confirm without a pending step: {third:?}"
982        );
983        server_task.join().await;
984    }
985
986    /// The pending-step age limit is independent of the retry race: at the
987    /// smallest interval (60 s) it is twice the maximum retry delay, so a step
988    /// recorded one retry delay ago is not expired.
989    #[test]
990    fn the_pending_step_age_limit_beats_the_retry_race() {
991        let minimum = Configuration {
992            servers: vec![String::from("a")],
993            resync_interval: Duration::from_secs(60),
994        };
995        let limit = pending_step_age_limit(&minimum);
996        assert_eq!(limit, MAXIMUM_RETRY_DELAY * 2);
997        assert!(
998            limit > retry_delay(1),
999            "the first retry delay comes before the expiry"
1000        );
1001        assert!(
1002            limit > MAXIMUM_RETRY_DELAY,
1003            "the longest retry delay comes before the expiry"
1004        );
1005        let pending = PendingStep {
1006            offset_nanos: 2_000_000_000_000,
1007            server: 0,
1008            address: None,
1009            recorded_at: Duration::ZERO,
1010        };
1011        assert!(!pending_step_expired(&pending, retry_delay(1), limit));
1012        assert!(!pending_step_expired(&pending, MAXIMUM_RETRY_DELAY, limit));
1013        assert!(!pending_step_expired(&pending, limit, limit));
1014        assert!(pending_step_expired(
1015            &pending,
1016            limit + Duration::from_secs(1),
1017            limit
1018        ));
1019        // At a larger interval the limit follows the interval, saturated.
1020        let large = Configuration {
1021            servers: vec![String::from("a")],
1022            resync_interval: Duration::from_secs(7 * 24 * 3600),
1023        };
1024        assert_eq!(
1025            pending_step_age_limit(&large),
1026            Duration::from_secs(2 * 7 * 24 * 3600)
1027        );
1028    }
1029
1030    /// At the minimum resynchronization interval (60 s), a +2000 s step is
1031    /// confirmed by the next attempt: the age limit (twice the maximum retry
1032    /// delay) is far longer than the wait before that attempt.
1033    #[task::test]
1034    async fn a_large_step_confirms_at_the_minimum_interval() {
1035        let _lock = TEST_MUTEX.lock().await;
1036        let network = initialize().await;
1037        let time_manager = host_time_manager();
1038        set_network_clock(time_manager, T0);
1039        let client = Client::new(network, time_manager, None);
1040
1041        // The server always answers 2000 s ahead of the current clock.
1042        let (ready, server_task) = spawn_scripted_server(
1043            [127, 0, 0, 1],
1044            move |request| {
1045                let now = time_manager.realtime_now().unwrap().as_nanos();
1046                alloc::vec![valid_answer(now + 2_000_000_000_000)(request)]
1047            },
1048            2,
1049        )
1050        .await;
1051        ready.wait().await;
1052
1053        // resync_interval_seconds = 60, the clamped minimum.
1054        let configuration = Box::leak(Box::new(Configuration {
1055            servers: vec![String::from("127.0.0.1")],
1056            resync_interval: Duration::from_secs(60),
1057        }));
1058        let mut states = vec![ServerState::default()];
1059        let mut adapter = None;
1060        let mut dns_cache: Vec<DnsEntry> = Vec::new();
1061        let mut pending_step: Option<PendingStep> = None;
1062
1063        let first = attempt(
1064            &client,
1065            network,
1066            time_manager,
1067            configuration,
1068            &mut states,
1069            &mut adapter,
1070            &mut dns_cache,
1071            &mut pending_step,
1072        )
1073        .await;
1074        assert!(matches!(first, Attempt::Unconfirmed), "{first:?}");
1075        assert!(pending_step.is_some());
1076
1077        // The next attempt (after one retry delay in the real loop) confirms.
1078        let second = attempt(
1079            &client,
1080            network,
1081            time_manager,
1082            configuration,
1083            &mut states,
1084            &mut adapter,
1085            &mut dns_cache,
1086            &mut pending_step,
1087        )
1088        .await;
1089        assert!(
1090            matches!(second, Attempt::Synchronized(_)),
1091            "the step confirms at the minimum interval: {second:?}"
1092        );
1093        assert!(pending_step.is_none());
1094        server_task.join().await;
1095    }
1096
1097    /// A RATE kiss of death defers the next attempt until the deadline.
1098    #[task::test]
1099    async fn a_rate_kiss_defers_the_next_attempt() {
1100        let _lock = TEST_MUTEX.lock().await;
1101        let network = initialize().await;
1102        let time_manager = host_time_manager();
1103        let client = Client::new(network, time_manager, None);
1104
1105        let kod = |request: [u8; 48]| {
1106            let mut response = [0u8; 48];
1107            response[0] = 0x24 | (3 << 6);
1108            response[1] = 0; // stratum 0: kiss of death
1109            response[12..16].copy_from_slice(b"RATE");
1110            response[24..32].copy_from_slice(&request[40..48]);
1111            response[40..48].copy_from_slice(&request[40..48]);
1112            alloc::vec![response]
1113        };
1114        let (ready, server_task) = spawn_scripted_server([127, 0, 0, 1], kod, 1).await;
1115        ready.wait().await;
1116
1117        let configuration = test_configuration(&["127.0.0.1"]);
1118        let mut states = vec![ServerState::default()];
1119        let mut adapter = None;
1120        let mut dns_cache: Vec<DnsEntry> = Vec::new();
1121        let mut pending_step: Option<PendingStep> = None;
1122
1123        let first = attempt(
1124            &client,
1125            network,
1126            time_manager,
1127            configuration,
1128            &mut states,
1129            &mut adapter,
1130            &mut dns_cache,
1131            &mut pending_step,
1132        )
1133        .await;
1134        assert!(
1135            matches!(
1136                first,
1137                Attempt::Failed(Failure::Protocol(SntpError::KissOfDeath(
1138                    KissOfDeathCode::Rate
1139                )))
1140            ),
1141            "{first:?}"
1142        );
1143        server_task.join().await;
1144
1145        let before = time_manager.monotonic_now();
1146        let second = attempt(
1147            &client,
1148            network,
1149            time_manager,
1150            configuration,
1151            &mut states,
1152            &mut adapter,
1153            &mut dns_cache,
1154            &mut pending_step,
1155        )
1156        .await;
1157        match second {
1158            Attempt::Deferred(deadline) => {
1159                assert!(deadline > before, "the deadline is in the future");
1160                assert_eq!(deadline, states[0].not_before.unwrap());
1161                // Roughly the doubled interval from the kiss of death.
1162                assert!(deadline - before >= Duration::from_secs(7199));
1163            }
1164            other => panic!("expected a deferred attempt, got {other:?}"),
1165        }
1166    }
1167
1168    /// A failed exchange drops the cached resolution of the name; a successful
1169    /// one keeps it.
1170    #[task::test]
1171    async fn a_failed_exchange_drops_the_dns_cache_entry() {
1172        let _lock = TEST_MUTEX.lock().await;
1173        let network = initialize().await;
1174        let time_manager = host_time_manager();
1175        let client = Client::new(network, time_manager, None);
1176
1177        // The first answer is garbage (mode 5), the second is valid.
1178        let calls = Cell::new(0usize);
1179        let (ready, server_task) = spawn_scripted_server(
1180            [127, 0, 0, 1],
1181            move |request| {
1182                if calls.get() == 0 {
1183                    calls.set(1);
1184                    let mut response = valid_answer(T0)(request);
1185                    response[0] = 0x25; // mode 5: rejected by sntpc
1186                    alloc::vec![response]
1187                } else {
1188                    alloc::vec![valid_answer(T0)(request)]
1189                }
1190            },
1191            2,
1192        )
1193        .await;
1194        ready.wait().await;
1195
1196        let configuration = test_configuration(&["127.0.0.1"]);
1197        let mut states = vec![ServerState::default()];
1198        let mut adapter = None;
1199        let mut dns_cache: Vec<DnsEntry> = Vec::new();
1200        let mut pending_step: Option<PendingStep> = None;
1201
1202        let first = attempt(
1203            &client,
1204            network,
1205            time_manager,
1206            configuration,
1207            &mut states,
1208            &mut adapter,
1209            &mut dns_cache,
1210            &mut pending_step,
1211        )
1212        .await;
1213        assert!(matches!(first, Attempt::Failed(_)), "{first:?}");
1214        assert!(
1215            dns_cache.is_empty(),
1216            "the failed exchange dropped the cached resolution"
1217        );
1218
1219        let second = attempt(
1220            &client,
1221            network,
1222            time_manager,
1223            configuration,
1224            &mut states,
1225            &mut adapter,
1226            &mut dns_cache,
1227            &mut pending_step,
1228        )
1229        .await;
1230        assert!(matches!(second, Attempt::Synchronized(_)), "{second:?}");
1231        assert_eq!(dns_cache.len(), 1, "the success cached the resolution");
1232        server_task.join().await;
1233    }
1234}