1use 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
45pub(crate) const NETWORK_POLL_INTERVAL: Duration = Duration::from_secs(10);
48
49pub(crate) const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(60);
51
52pub(crate) const MAXIMUM_RETRY_DELAY: Duration = Duration::from_secs(1800);
54
55pub(crate) const REPEATED_FAILURE_LOG_THRESHOLD: u32 = 3;
58
59pub(crate) const FAILURE_LOG_STRIDE: u32 = 10;
61
62pub(crate) const MAXIMUM_RATE_MULTIPLIER: u32 = 64;
65
66pub(crate) const DNS_CACHE_LIFETIME: Duration = Duration::from_secs(3600);
68
69pub(crate) const FIRST_QUERY_JITTER: Duration = Duration::from_secs(2);
71
72pub(crate) const JITTER_PERCENT: u64 = 12;
75
76pub(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
87fn 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
100fn 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct ServerState {
114 banned: bool,
116 rate_multiplier: u32,
118 kiss_logged: bool,
120 not_before: Option<Duration>,
123}
124
125impl ServerState {
126 fn interval(&self, base: Duration) -> Duration {
129 base.checked_mul(self.rate_multiplier.max(1))
130 .unwrap_or(MAXIMUM_RESYNC_INTERVAL)
131 }
132
133 fn blocked(&self, now: Duration) -> bool {
135 self.banned || self.not_before.is_some_and(|deadline| now < deadline)
136 }
137}
138
139fn 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
150pub(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#[derive(Clone, Debug)]
198pub struct Outcome {
199 pub server: &'static str,
201 pub applied: Applied,
203 pub interval: Duration,
205}
206
207#[derive(Clone, Debug)]
209enum Attempt {
210 Synchronized(Outcome),
211 Failed(Failure),
212 AllBanned,
215 Deferred(Duration),
217 Unconfirmed,
220}
221
222#[derive(Clone, Debug)]
227struct PendingStep {
228 offset_nanos: i128,
229 server: usize,
230 address: Option<IpAddress>,
231 recorded_at: Duration,
232}
233
234fn pending_step_age_limit(configuration: &Configuration) -> Duration {
241 configuration
242 .resync_interval
243 .max(MAXIMUM_RETRY_DELAY)
244 .saturating_mul(2)
245}
246
247fn pending_step_expired(pending: &PendingStep, now: Duration, limit: Duration) -> bool {
249 now.saturating_sub(pending.recorded_at) > limit
250}
251
252struct DnsEntry {
254 name: String,
255 addresses: Vec<IpAddress>,
256 resolved_at: Duration,
257}
258
259async 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
290fn drop_cache_entry(cache: &mut Vec<DnsEntry>, name: &str) {
293 cache.retain(|entry| entry.name != name);
294}
295
296pub 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 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 pub async fn start(self, task: TaskIdentifier) -> Result<TaskIdentifier> {
329 self.start_on(task, None).await
330 }
331
332 pub async fn start_on(
335 self,
336 task: TaskIdentifier,
337 executor: Option<task::SpawnerIdentifier>,
338 ) -> Result<TaskIdentifier> {
339 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
363async 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 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 task::sleep(add_jitter(network, configuration.resync_interval)).await;
418 }
419 Attempt::Deferred(deadline) => {
420 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 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#[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 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 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 _ => *pending_step = None,
552 }
553 match client.apply(&exchange) {
554 Ok(applied) => {
555 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 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 const T0: i128 = 1_800_000_000_000_000_000;
619
620 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 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 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 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 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 #[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 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 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 #[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 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 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 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 #[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 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 #[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 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 #[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 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 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 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 #[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; 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 assert!(deadline - before >= Duration::from_secs(7199));
1163 }
1164 other => panic!("expected a deferred attempt, got {other:?}"),
1165 }
1166 }
1167
1168 #[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 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; 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}