1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
//! Rust SNTP client
//!
//! # Overview
//!
//! This crate provides a method for sending requests to NTP servers
//! and process responses, extracting received timestamp. Supported SNTP protocol
//! versions:
//! - [SNTPv4](https://datatracker.ietf.org/doc/html/rfc4330)
//!
//! # Usage
//!
//! Put this in your `Cargo.toml`:
//! ```cargo
//! [dependencies]
//! sntpc = "0.3.7"
//! ```
//!
//! ## Features
//!
//! Sntpc supports several features:
//! - `std`: includes functionality that depends on the standard library
//! - `utils`: includes functionality that mostly OS specific and allows system time sync
//! - `log`: enables library debug output during execution
//! - `async`: enables asynchronous feature support
//!
//! <div class="example-wrap" style="display:inline-block"><pre class="compile_fail" style="white-space:normal;font:inherit;">
//!
//! **Warning**: `utils` feature is not stable and may change in the future.
//! </pre></div>
//!
//! # Details
//!
//! There are multiple approaches how the library can be used:
//! - under environments where a networking stuff is hidden in system/RTOS kernel, [`get_time`] can
//! be used since it encapsulates network I/O
//! - under environments where TCP/IP stack requires to call some helper functions like `poll`,
//! `wait`, etc. and/or there are no options to perform I/O operations within a single call,
//! [`sntp_send_request`] and [`sntp_process_response`] can be used
//!
//! As `sntpc` supports `no_std` environment as well, it was
//! decided to provide a set of traits to implement for a network object (`UdpSocket`)
//! and timestamp generator:
//! - [`NtpUdpSocket`] trait should be implemented for `UdpSocket`-like objects for the
//! library to be able to send and receive data from NTP servers
//! - [`NtpTimestampGenerator`] trait should be implemented for timestamp generator objects to
//! provide the library with system related timestamps
//!
//! ## Logging support
//!
//! Library debug logs can be enabled in executables by enabling `log` feature. Server
//! addresses, response payload will be printed.
//!
//! # Example
//!
//! ```rust
//! # #[cfg(not(feature = "std"))]
//! # use no_std_net::{SocketAddr, ToSocketAddrs, IpAddr, Ipv4Addr};
//! # #[cfg(feature = "std")]
//! use std::net::UdpSocket;
//! use std::time::Duration;
//!
//! # #[cfg(not(feature = "std"))]
//! # #[derive(Debug)]
//! # struct UdpSocket;
//! # #[cfg(not(feature = "std"))]
//! # impl UdpSocket {
//! # fn bind(addr: &str) -> sntpc::Result<Self> {
//! # Ok(UdpSocket)
//! # }
//! # fn send_to<T: ToSocketAddrs>(&self, buf: &[u8], dest: T) -> sntpc::Result<usize> {
//! # Ok(0usize)
//! # }
//! # fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
//! # Ok((0usize, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)))
//! # }
//! # fn set_read_timeout<T>(&self, _arg: T) -> sntpc::Result<()> {
//! # Ok(())
//! # }
//! # }
//!
//! fn main() {
//! let socket =
//! UdpSocket::bind("0.0.0.0:0").expect("Unable to crate UDP socket");
//! socket
//! .set_read_timeout(Some(Duration::from_secs(2)))
//! .expect("Unable to set UDP socket read timeout");
//! # #[cfg(all(feature = "std", feature = "sup"))]
//! let result = sntpc::simple_get_time("time.google.com:123", socket);
//! # #[cfg(all(feature = "std", feature = "sup"))]
//! match result {
//! Ok(time) => {
//! println!("Got time: {}.{}", time.sec(), sntpc::fraction_to_milliseconds(time.sec_fraction()));
//! }
//! Err(err) => println!("Err: {:?}", err),
//! }
//! }
//! ```
//!
//! For more complex example with custom timestamp generator and UDP socket implementation, see
//! `examples/smoltcp_request.rs`.
//!
//! For usage SNTP-client in an asynchronous environment, see `examples/tokio.rs`
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "utils")]
pub mod utils;
mod types;
pub use crate::types::*;
#[cfg(feature = "async")]
pub mod async_impl;
use core::fmt::Debug;
use core::iter::Iterator;
use core::marker::Copy;
use core::mem;
pub(crate) mod net {
#[cfg(not(feature = "std"))]
pub use no_std_net::{SocketAddr, ToSocketAddrs};
#[cfg(feature = "std")]
pub use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
}
#[cfg(feature = "log")]
use log::debug;
/// Send request to a NTP server with the given address and process the response in a single call
///
/// May be useful under an environment with `std` networking implementation, where all
/// network stuff is hidden within system's kernel. For environment with custom
/// Uses [`NtpUdpSocket`] and [`NtpTimestampGenerator`] trait bounds to allow generic specification
/// of objects that can be used with the library
/// **Args:**
/// - `pool_addrs` - Server's name or IP address with port specification as a string
/// - `socket` - UDP socket object that will be used during NTP request-response
/// communication
/// - `context` - SNTP client context to provide timestamp generation feature
///
/// # Example
///
/// ```rust
/// use sntpc::{self, NtpContext, NtpTimestampGenerator, Result};
/// use std::time::Duration;
/// # #[cfg(not(feature = "std"))]
/// # use no_std_net::{SocketAddr, ToSocketAddrs, IpAddr, Ipv4Addr};
/// # #[cfg(feature = "std")]
/// # use std::net::{SocketAddr, ToSocketAddrs, UdpSocket, IpAddr, Ipv4Addr};
/// # #[cfg(not(feature = "std"))]
/// # #[derive(Debug)]
/// # struct UdpSocket;
/// # #[cfg(not(feature = "std"))]
/// # impl UdpSocket {
/// # fn bind(addr: &str) -> Result<Self> {
/// # Ok(UdpSocket)
/// # }
/// # fn send_to<T: ToSocketAddrs>(&self, buf: &[u8], dest: T) -> Result<usize> {
/// # Ok(0usize)
/// # }
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # Ok((0usize, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)))
/// # }
/// # }
/// // implement required trait on network objects
/// # #[derive(Debug)]
/// # struct UdpSocketWrapper(UdpSocket);
/// #
/// # impl sntpc::NtpUdpSocket for UdpSocketWrapper {
/// # fn send_to<T: ToSocketAddrs>(
/// # &self,
/// # buf: &[u8],
/// # addr: T,
/// # ) -> Result<usize> {
/// # match self.0.send_to(buf, addr) {
/// # Ok(usize) => Ok(usize),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// #
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # match self.0.recv_from(buf) {
/// # Ok((size, addr)) => Ok((size, addr)),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// # }
/// // implement required trait on the timestamp generator object
/// #[derive(Copy, Clone, Default)]
/// struct StdTimestampGen {
/// duration: Duration,
/// }
///
/// impl NtpTimestampGenerator for StdTimestampGen {
/// fn init(&mut self) {
/// self.duration = std::time::SystemTime::now()
/// .duration_since(std::time::SystemTime::UNIX_EPOCH)
/// .unwrap();
/// }
///
/// fn timestamp_sec(&self) -> u64 {
/// self.duration.as_secs()
/// }
///
/// fn timestamp_subsec_micros(&self) -> u32 {
/// self.duration.subsec_micros()
/// }
/// }
///
/// let ntp_context = NtpContext::new(StdTimestampGen::default());
/// let socket = UdpSocketWrapper(UdpSocket::bind("0.0.0.0:0").expect("something"));
/// # #[cfg(feature = "std")]
/// let result = sntpc::get_time("time.google.com:123", socket, ntp_context);
/// // OR
/// // let result = sntpc::get_time("83.168.200.199:123", socket, context);
///
/// // .. process the result
/// ```
pub fn get_time<A, U, T>(
pool_addrs: A,
socket: U,
context: NtpContext<T>,
) -> Result<NtpResult>
where
A: net::ToSocketAddrs + Copy + Debug,
U: NtpUdpSocket + Debug,
T: NtpTimestampGenerator + Copy,
{
let result = sntp_send_request(pool_addrs, &socket, context)?;
sntp_process_response(pool_addrs, &socket, context, result)
}
#[cfg(feature = "std")]
/// Supplementary `get_time` alternative that wraps provided UDP socket into a wrapper type
/// that implements necessary traits for SNTP client proper operation
pub fn simple_get_time<A>(
pool_addrs: A,
socket: net::UdpSocket,
) -> Result<NtpResult>
where
A: net::ToSocketAddrs + Copy + Debug,
{
let ntp_context = NtpContext::new(StdTimestampGen::default());
get_time(pool_addrs, socket, ntp_context)
}
/// Send SNTP request to a server
///
/// That function along with the [`sntp_process_response`] is required under an environment(s)
/// where you need to call TCP/IP stack helpers (like `poll`, `wait`, etc.)
/// *Args*:
/// - `dest` - Initial NTP server's address to validate response against
/// - `socket` - Socket reference to use for receiving a NTP response
/// - `context` - SNTP client context
///
/// # Example
///
/// ```
/// use sntpc::{self, NtpContext, NtpTimestampGenerator, Result};
/// # use std::time::Duration;
/// # use std::str::FromStr;
/// # #[cfg(not(feature = "std"))]
/// # use no_std_net::{SocketAddr, ToSocketAddrs, IpAddr, Ipv4Addr};
/// # #[cfg(feature = "std")]
/// # use std::net::{SocketAddr, ToSocketAddrs, UdpSocket, IpAddr, Ipv4Addr};
/// # #[cfg(not(feature = "std"))]
/// # #[derive(Debug)]
/// # struct UdpSocket(u8);
/// # #[cfg(not(feature = "std"))]
/// # impl UdpSocket {
/// # fn bind(addr: &str) -> Result<Self> {
/// # Ok(UdpSocket(0))
/// # }
/// # fn send_to<T: ToSocketAddrs>(&self, buf: &[u8], dest: T) -> Result<usize> {
/// # Ok(0usize)
/// # }
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # Ok((0usize, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)))
/// # }
/// # }
/// // implement required trait on network objects
/// # #[derive(Debug)]
/// # struct UdpSocketWrapper(UdpSocket);
///
/// # impl sntpc::NtpUdpSocket for UdpSocketWrapper {
/// # fn send_to<T: ToSocketAddrs>(
/// # &self,
/// # buf: &[u8],
/// # addr: T,
/// # ) -> Result<usize> {
/// # match self.0.send_to(buf, addr) {
/// # Ok(usize) => Ok(usize),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// #
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # match self.0.recv_from(buf) {
/// # Ok((size, addr)) => Ok((size, addr)),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// # }
/// // implement required trait on the timestamp generator object
/// # #[derive(Copy, Clone, Default)]
/// # struct StdTimestampGen {
/// # duration: Duration,
/// # }
/// #
/// # impl NtpTimestampGenerator for StdTimestampGen {
/// # fn init(&mut self) {
/// # self.duration = std::time::SystemTime::now()
/// # .duration_since(std::time::SystemTime::UNIX_EPOCH)
/// # .unwrap();
/// # }
/// #
/// # fn timestamp_sec(&self) -> u64 {
/// # self.duration.as_secs()
/// # }
/// #
/// # fn timestamp_subsec_micros(&self) -> u32 {
/// # self.duration.subsec_micros()
/// # }
/// # }
/// #
/// # let ntp_context = NtpContext::new(StdTimestampGen::default());
/// # let socket = UdpSocketWrapper(UdpSocket::bind("0.0.0.0:0").expect("something"));
/// // "time.google.com:123" string here used for the sake of simplicity. In the real app
/// // you would want to fix destination address, since string hostname may resolve to
/// // different IP addresses
/// # #[cfg(feature = "std")]
/// let result = sntpc::sntp_send_request("time.google.com:123", &socket, ntp_context);
/// ```
pub fn sntp_send_request<A, U, T>(
dest: A,
socket: &U,
context: NtpContext<T>,
) -> Result<SendRequestResult>
where
A: net::ToSocketAddrs + Debug,
U: NtpUdpSocket + Debug,
T: NtpTimestampGenerator + Copy,
{
#[cfg(feature = "log")]
debug!("Address: {:?}, Socket: {:?}", dest, *socket);
let request = NtpPacket::new(context.timestamp_gen);
send_request(dest, &request, socket)?;
Ok(SendRequestResult::from(request))
}
/// Process SNTP response from a server
///
/// That function along with the [`sntp_send_request`] is required under an environment(s)
/// where you need to call TCP/IP stack helpers (like `poll`, `wait`, etc.)
/// *Args*:
/// - `dest` - NTP server's address to send request to
/// - `socket` - Socket reference to use for sending a NTP request
/// - `context` - SNTP client context
/// - `send_req_result` - send request result that obtained after [`sntp_send_request`] call
///
/// # Example
/// ```
/// use sntpc::{self, NtpContext, NtpTimestampGenerator, Result};
/// # use std::time::Duration;
/// # use std::str::FromStr;
/// # #[cfg(not(feature = "std"))]
/// # use no_std_net::{SocketAddr, ToSocketAddrs, IpAddr, Ipv4Addr};
/// # #[cfg(feature = "std")]
/// # use std::net::{SocketAddr, ToSocketAddrs, UdpSocket, IpAddr, Ipv4Addr};
/// # #[cfg(not(feature = "std"))]
/// # #[derive(Debug, Clone)]
/// # struct UdpSocket(u8);
/// # #[cfg(not(feature = "std"))]
/// # impl UdpSocket {
/// # fn bind(addr: &str) -> Result<Self> {
/// # Ok(UdpSocket(0))
/// # }
/// # fn send_to<T: ToSocketAddrs>(&self, buf: &[u8], dest: T) -> Result<usize> {
/// # Ok(0usize)
/// # }
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # Ok((0usize, SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0)))
/// # }
/// # }
/// // implement required trait on network objects
/// # #[derive(Debug)]
/// # struct UdpSocketWrapper(UdpSocket);
/// #
/// # impl sntpc::NtpUdpSocket for UdpSocketWrapper {
/// # fn send_to<T: ToSocketAddrs>(
/// # &self,
/// # buf: &[u8],
/// # addr: T,
/// # ) -> Result<usize> {
/// # match self.0.send_to(buf, addr) {
/// # Ok(usize) => Ok(usize),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// #
/// # fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
/// # match self.0.recv_from(buf) {
/// # Ok((size, addr)) => Ok((size, addr)),
/// # Err(_) => Err(sntpc::Error::Network),
/// # }
/// # }
/// # }
/// // implement required trait on the timestamp generator object
/// # #[derive(Copy, Clone, Default)]
/// # struct StdTimestampGen {
/// # duration: Duration,
/// # }
/// #
/// # impl NtpTimestampGenerator for StdTimestampGen {
/// # fn init(&mut self) {
/// # self.duration = std::time::SystemTime::now()
/// # .duration_since(std::time::SystemTime::UNIX_EPOCH)
/// # .unwrap();
/// # }
/// #
/// # fn timestamp_sec(&self) -> u64 {
/// # self.duration.as_secs()
/// # }
/// #
/// # fn timestamp_subsec_micros(&self) -> u32 {
/// # self.duration.subsec_micros()
/// # }
/// # }
/// #
/// # let ntp_context = NtpContext::new(StdTimestampGen::default());
/// # let socket = UdpSocketWrapper(UdpSocket::bind("0.0.0.0:0").expect("something"));
/// // "time.google.com:123" string here used for the sake of simplicity. In the real app
/// // you would want to fix destination address, since string hostname may resolve to
/// // different IP addresses
/// # #[cfg(feature = "std")]
/// if let Ok(result) = sntpc::sntp_send_request("time.google.com:123", &socket, ntp_context) {
/// let time = sntpc::sntp_process_response("time.google.com:123", &socket, ntp_context, result);
/// }
/// ```
pub fn sntp_process_response<A, U, T>(
dest: A,
socket: &U,
mut context: NtpContext<T>,
send_req_result: SendRequestResult,
) -> Result<NtpResult>
where
A: net::ToSocketAddrs + Debug,
U: NtpUdpSocket + Debug,
T: NtpTimestampGenerator + Copy,
{
let mut response_buf = RawNtpPacket::default();
let (response, src) = socket.recv_from(response_buf.0.as_mut())?;
context.timestamp_gen.init();
let recv_timestamp = get_ntp_timestamp(context.timestamp_gen);
#[cfg(feature = "log")]
debug!("Response: {}", response);
match dest.to_socket_addrs() {
Err(_) => return Err(Error::AddressResolve),
Ok(mut it) => {
if !it.any(|addr| addr == src) {
return Err(Error::ResponseAddressMismatch);
}
}
}
if response != mem::size_of::<NtpPacket>() {
return Err(Error::IncorrectPayload);
}
let result =
process_response(send_req_result, response_buf, recv_timestamp);
if let Ok(_r) = &result {
#[cfg(feature = "log")]
debug!("{:?}", _r);
}
result
}
fn send_request<A: net::ToSocketAddrs, U: NtpUdpSocket>(
dest: A,
req: &NtpPacket,
socket: &U,
) -> core::result::Result<(), Error> {
let buf = RawNtpPacket::from(req);
match socket.send_to(&buf.0, dest) {
Ok(size) => {
if size == buf.0.len() {
Ok(())
} else {
Err(Error::Network)
}
}
Err(_) => Err(Error::Network),
}
}
fn process_response(
send_req_result: SendRequestResult,
resp: RawNtpPacket,
recv_timestamp: u64,
) -> Result<NtpResult> {
const SNTP_UNICAST: u8 = 4;
const SNTP_BROADCAST: u8 = 5;
const LI_MAX_VALUE: u8 = 3;
let mut packet = NtpPacket::from(resp);
convert_from_network(&mut packet);
#[cfg(feature = "log")]
debug_ntp_packet(&packet, recv_timestamp);
if send_req_result.originate_timestamp != packet.origin_timestamp {
return Err(Error::IncorrectOriginTimestamp);
}
// Shift is 0
let mode = shifter(packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);
let resp_version = shifter(packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
let req_version =
shifter(send_req_result.version, VERSION_MASK, VERSION_SHIFT);
if mode != SNTP_UNICAST && mode != SNTP_BROADCAST {
return Err(Error::IncorrectMode);
}
if li > LI_MAX_VALUE {
return Err(Error::IncorrectLeapIndicator);
}
if req_version != resp_version {
return Err(Error::IncorrectResponseVersion);
}
if packet.stratum == 0 {
return Err(Error::IncorrectStratumHeaders);
}
// System clock offset:
// theta = T(B) - T(A) = 1/2 * [(T2-T1) + (T3-T4)]
// Round-trip delay:
// delta = T(ABA) = (T4-T1) - (T3-T2).
// where:
// - T1 = client's TX timestamp
// - T2 = server's RX timestamp
// - T3 = server's TX timestamp
// - T4 = client's RX timestamp
let t1 = packet.origin_timestamp;
let t2 = packet.recv_timestamp;
let t3 = packet.tx_timestamp;
let t4 = recv_timestamp;
let units = Units::Microseconds;
let roundtrip = roundtrip_calculate(t1, t2, t3, t4, units);
let offset = offset_calculate(t1, t2, t3, t4, units);
let timestamp = NtpTimestamp::from(packet.tx_timestamp);
#[cfg(feature = "log")]
debug!(
"Roundtrip delay: {} {}. Offset: {} {}",
roundtrip, units, offset, units
);
Ok(NtpResult::new(
timestamp.seconds as u32,
timestamp.seconds_fraction as u32,
roundtrip,
offset,
packet.stratum,
packet.precision,
))
}
fn shifter(val: u8, mask: u8, shift: u8) -> u8 {
(val & mask) >> shift
}
fn convert_from_network(packet: &mut NtpPacket) {
fn ntohl<T: NtpNum>(val: T) -> T::Type {
val.ntohl()
}
packet.root_delay = ntohl(packet.root_delay);
packet.root_dispersion = ntohl(packet.root_dispersion);
packet.ref_id = ntohl(packet.ref_id);
packet.ref_timestamp = ntohl(packet.ref_timestamp);
packet.origin_timestamp = ntohl(packet.origin_timestamp);
packet.recv_timestamp = ntohl(packet.recv_timestamp);
packet.tx_timestamp = ntohl(packet.tx_timestamp);
}
fn convert_delays(sec: u64, fraction: u64, units: u64) -> u64 {
sec * units + fraction * units / u32::MAX as u64
}
fn roundtrip_calculate(
t1: u64,
t2: u64,
t3: u64,
t4: u64,
units: Units,
) -> u64 {
let delta = t4.wrapping_sub(t1).wrapping_sub(t3.wrapping_sub(t2));
let delta_sec = (delta & SECONDS_MASK) >> 32;
let delta_sec_fraction = delta & SECONDS_FRAC_MASK;
match units {
Units::Milliseconds => {
convert_delays(delta_sec, delta_sec_fraction, MSEC_IN_SEC as u64)
}
Units::Microseconds => {
convert_delays(delta_sec, delta_sec_fraction, USEC_IN_SEC as u64)
}
}
}
fn offset_calculate(t1: u64, t2: u64, t3: u64, t4: u64, units: Units) -> i64 {
let theta = (t2.wrapping_sub(t1) as i64)
.wrapping_add(t3.wrapping_sub(t4) as i64)
/ 2;
let theta_sec = (theta.unsigned_abs() & SECONDS_MASK) >> 32;
let theta_sec_fraction = theta.unsigned_abs() & SECONDS_FRAC_MASK;
match units {
Units::Milliseconds => {
convert_delays(theta_sec, theta_sec_fraction, MSEC_IN_SEC as u64)
as i64
* theta.signum()
}
Units::Microseconds => {
convert_delays(theta_sec, theta_sec_fraction, USEC_IN_SEC as u64)
as i64
* theta.signum()
}
}
}
#[cfg(feature = "log")]
fn debug_ntp_packet(packet: &NtpPacket, _recv_timestamp: u64) {
let mode = shifter(packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
let version = shifter(packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);
use core::str;
let delimiter_gen = || unsafe { str::from_utf8_unchecked(&[b'='; 64]) };
debug!("{}", delimiter_gen());
debug!("| Mode:\t\t{}", mode);
debug!("| Version:\t{}", version);
debug!("| Leap:\t\t{}", li);
debug!("| Stratum:\t{}", packet.stratum);
debug!("| Poll:\t\t{}", packet.poll);
debug!("| Precision:\t\t{}", packet.precision);
debug!("| Root delay:\t\t{}", packet.root_delay);
debug!("| Root dispersion:\t{}", packet.root_dispersion);
debug!(
"| Reference ID:\t\t{}",
str::from_utf8(&packet.ref_id.to_be_bytes()).unwrap_or("")
);
debug!(
"| Origin timestamp (client):\t{:>16}",
packet.origin_timestamp
);
debug!(
"| Receive timestamp (server):\t{:>16}",
packet.recv_timestamp
);
debug!(
"| Transmit timestamp (server):\t{:>16}",
packet.tx_timestamp
);
debug!("| Receive timestamp (client):\t{:>16}", _recv_timestamp);
debug!(
"| Reference timestamp (server):\t{:>16}",
packet.ref_timestamp
);
debug!("{}", delimiter_gen());
}
fn get_ntp_timestamp<T: NtpTimestampGenerator>(timestamp_gen: T) -> u64 {
((timestamp_gen.timestamp_sec()
+ (u64::from(NtpPacket::NTP_TIMESTAMP_DELTA)))
<< 32)
+ timestamp_gen.timestamp_subsec_micros() as u64 * u32::MAX as u64
/ USEC_IN_SEC as u64
}
/// Convert second fraction value to milliseconds value
pub fn fraction_to_milliseconds(sec_fraction: u32) -> u32 {
(u64::from(sec_fraction) * u64::from(MSEC_IN_SEC) / u64::from(u32::MAX))
as u32
}
/// Convert second fraction value to microseconds value
pub fn fraction_to_microseconds(sec_fraction: u32) -> u32 {
(u64::from(sec_fraction) * u64::from(USEC_IN_SEC) / u64::from(u32::MAX))
as u32
}
/// Convert second fraction value to nanoseconds value
pub fn fraction_to_nanoseconds(sec_fraction: u32) -> u32 {
(u64::from(sec_fraction) * u64::from(NSEC_IN_SEC) / u64::from(u32::MAX))
as u32
}
/// Convert second fraction value to picoseconds value
pub fn fraction_to_picoseconds(sec_fraction: u32) -> u64 {
(u128::from(sec_fraction) * u128::from(PSEC_IN_SEC) / u128::from(u32::MAX))
as u64
}
#[cfg(test)]
mod sntpc_ntp_result_tests {
use crate::{
fraction_to_microseconds, fraction_to_milliseconds,
fraction_to_nanoseconds, fraction_to_picoseconds, NtpResult,
};
#[test]
fn test_ntp_result() {
let result1 = NtpResult::new(0, 0, 0, 0, 1, -2);
assert_eq!(0, result1.sec());
assert_eq!(0, result1.sec_fraction());
assert_eq!(0, result1.roundtrip());
assert_eq!(0, result1.offset());
assert_eq!(1, result1.stratum());
assert_eq!(-2, result1.precision());
let result2 = NtpResult::new(1, 2, 3, 4, 5, -23);
assert_eq!(1, result2.sec());
assert_eq!(2, result2.sec_fraction());
assert_eq!(3, result2.roundtrip());
assert_eq!(4, result2.offset());
assert_eq!(5, result2.stratum());
assert_eq!(-23, result2.precision());
let result3 =
NtpResult::new(u32::MAX - 1, u32::MAX, u64::MAX, i64::MAX, 1, -127);
assert_eq!(u32::MAX, result3.sec());
assert_eq!(0, result3.sec_fraction());
assert_eq!(u64::MAX, result3.roundtrip());
assert_eq!(i64::MAX, result3.offset());
assert_eq!(-127, result3.precision());
}
#[test]
fn test_ntp_fraction_overflow_result() {
let result = NtpResult::new(0, u32::MAX, 0, 0, 1, -19);
assert_eq!(1, result.sec());
assert_eq!(0, result.sec_fraction());
assert_eq!(0, result.roundtrip());
assert_eq!(0, result.offset());
let result = NtpResult::new(u32::MAX - 1, u32::MAX, 0, 0, 1, -17);
assert_eq!(u32::MAX, result.sec());
assert_eq!(0, result.sec_fraction());
assert_eq!(0, result.roundtrip());
assert_eq!(0, result.offset());
}
#[test]
fn test_conversion_to_ms() {
let result = NtpResult::new(0, u32::MAX - 1, 0, 0, 1, 0);
let milliseconds = fraction_to_milliseconds(result.seconds_fraction);
assert_eq!(999u32, milliseconds);
let result = NtpResult::new(0, 0, 0, 0, 1, 0);
let milliseconds = fraction_to_milliseconds(result.seconds_fraction);
assert_eq!(0u32, milliseconds);
}
#[test]
fn test_conversion_to_us() {
let result = NtpResult::new(0, u32::MAX - 1, 0, 0, 1, 0);
let microseconds = fraction_to_microseconds(result.seconds_fraction);
assert_eq!(999999u32, microseconds);
let result = NtpResult::new(0, 0, 0, 0, 1, 0);
let microseconds = fraction_to_microseconds(result.seconds_fraction);
assert_eq!(0u32, microseconds);
}
#[test]
fn test_conversion_to_ns() {
let result = NtpResult::new(0, u32::MAX - 1, 0, 0, 1, 0);
let nanoseconds = fraction_to_nanoseconds(result.seconds_fraction);
assert_eq!(999999999u32, nanoseconds);
let result = NtpResult::new(0, 0, 0, 0, 1, 0);
let nanoseconds = fraction_to_nanoseconds(result.seconds_fraction);
assert_eq!(0u32, nanoseconds);
}
#[test]
fn test_conversion_to_ps() {
let result = NtpResult::new(0, u32::MAX - 1, 0, 0, 1, 0);
let picoseconds = fraction_to_picoseconds(result.seconds_fraction);
assert_eq!(999999999767u64, picoseconds);
let result = NtpResult::new(0, 1, 0, 0, 1, 0);
let picoseconds = fraction_to_picoseconds(result.seconds_fraction);
assert_eq!(232u64, picoseconds);
let result = NtpResult::new(0, 0, 0, 0, 1, 0);
let picoseconds = fraction_to_picoseconds(result.seconds_fraction);
assert_eq!(0u64, picoseconds);
}
}
#[cfg(all(test, feature = "std"))]
mod sntpc_tests {
use crate::{get_time, Error, NtpContext, StdTimestampGen, Units};
use std::net::UdpSocket;
#[test]
fn test_ntp_request_sntpv4_supported() {
let context = NtpContext::new(StdTimestampGen::default());
let pools = [
"pool.ntp.org:123",
"time.google.com:123",
"time.apple.com:123",
"time.cloudflare.com:123",
"time.facebook.com:123",
];
for pool in &pools {
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket
.set_read_timeout(Some(std::time::Duration::from_secs(2)))
.expect("Unable to set up socket timeout");
let result = get_time(pool, socket, context);
assert!(
result.is_ok(),
"{} is bad - {:?}",
pool,
result.unwrap_err()
);
assert_ne!(result.unwrap().seconds, 0);
}
}
#[test]
fn test_ntp_request_sntpv3_not_supported() {
let context = NtpContext::new(StdTimestampGen::default());
let pools = ["time.nist.gov:123", "time.windows.com:123"];
for pool in &pools {
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket
.set_read_timeout(Some(std::time::Duration::from_secs(2)))
.expect("Unable to set up socket timeout");
let result = get_time(pool, socket, context);
assert!(result.is_err(), "{} is ok", pool);
assert_eq!(result.unwrap_err(), Error::IncorrectResponseVersion);
}
}
#[test]
fn test_invalid_addrs_ntp_request() {
let context = NtpContext::new(StdTimestampGen::default());
let pool = "asdf.asdf.asdf:123";
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket
.set_read_timeout(Some(std::time::Duration::from_secs(2)))
.expect("Unable to set up socket timeout");
let result = get_time(pool, socket, context);
assert!(result.is_err(), "{} is ok", pool);
assert_eq!(result.unwrap_err(), Error::Network);
}
#[test]
fn test_units_str_representation() {
assert_eq!(format!("{}", Units::Milliseconds), "ms");
assert_eq!(format!("{}", Units::Microseconds), "us");
}
}