ntp-os-clock-1.1.2/.cargo_vcs_info.json0000644000000001520000000000100133440ustar { "git": { "sha1": "6751bef01a2469c0824f1db8710b7a3418b824a8" }, "path_in_vcs": "ntp-os-clock" }ntp-os-clock-1.1.2/COPYING000064400000000000000000000005111046102023000131660ustar 00000000000000Copyright (c) 2022-2023 Tweede Golf and Contributors Except as otherwise noted (below and/or in individual files), ntpd-rs is licensed under the Apache License, Version 2.0 or or the MIT license or , at your option. ntp-os-clock-1.1.2/Cargo.toml0000644000000016600000000000100113470ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.67" name = "ntp-os-clock" version = "1.1.2" publish = true description = "ntpd-rs system clock interfaces" homepage = "https://github.com/pendulum-project/ntpd-rs" readme = "README.md" license = "Apache-2.0 OR MIT" repository = "https://github.com/pendulum-project/ntpd-rs" [dependencies.libc] version = "0.2.145" [dependencies.ntp-proto] version = "1.1.2" features = ["__internal-api"] [dependencies.tracing] version = "0.1.21" ntp-os-clock-1.1.2/Cargo.toml.orig000064400000000000000000000007311046102023000150260ustar 00000000000000[package] name = "ntp-os-clock" description = "ntpd-rs system clock interfaces" readme = "README.md" version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true homepage.workspace = true publish.workspace = true rust-version.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ntp-proto.workspace = true libc.workspace = true tracing.workspace = true ntp-os-clock-1.1.2/LICENSE-APACHE000064400000000000000000000227731046102023000140750ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ntp-os-clock-1.1.2/LICENSE-MIT000064400000000000000000000020651046102023000135750ustar 00000000000000Copyright (c) 2022-2023 Tweede Golf and Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ntp-os-clock-1.1.2/README.md000064400000000000000000000005711046102023000134200ustar 00000000000000# ntp-os-clock This crate contains the system clock interfaces for ntpd-rs and is not intended as a public interface at this time. It follows the same version as the main ntpd-rs crate, but that version is not intended to give any stability guarantee. Use at your own risk. Please visit the [ntpd-rs](https://github.com/pendulum-project/ntpd-rs) project for more information. ntp-os-clock-1.1.2/src/lib.rs000064400000000000000000000033421046102023000140430ustar 00000000000000//! This crate contains the system clock interfaces for ntpd-rs and is not intended //! as a public interface at this time. It follows the same version as the main //! ntpd-rs crate, but that version is not intended to give any stability guarantee. //! Use at your own risk. //! //! Please visit the [ntpd-rs](https://github.com/pendulum-project/ntpd-rs) project //! for more information. mod unix; #[cfg(unix)] pub type DefaultNtpClock = unix::UnixNtpClock; /// Errors that can be thrown by modifying a unix clock #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub enum Error { /// Insufficient permissions to interact with the clock. NoPermission, /// No access to the clock. NoAccess, /// Invalid operation requested Invalid, /// Clock device has gone away NoDevice, /// Clock operation requested is not supported by operating system. NotSupported, } impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { use Error::*; let msg = match self { NoPermission => "Insufficient permissions to interact with the clock.", NoAccess => "No access to the clock.", Invalid => "Invalid operation requested", NoDevice => "Clock device has gone away", NotSupported => "Clock operation requested is not supported by operating system.", }; f.write_str(msg) } } impl std::error::Error for Error {} // Unix uses an epoch located at 1/1/1970-00:00h (UTC) and NTP uses 1/1/1900-00:00h. // This leads to an offset equivalent to 70 years in seconds // there are 17 leap years between the two dates so the offset is pub(crate) const EPOCH_OFFSET: u32 = (70 * 365 + 17) * 86400; ntp-os-clock-1.1.2/src/unix.rs000064400000000000000000000405371046102023000142670ustar 00000000000000// Note on unsafe usage. // // This module uses unsafe code to interact with the system calls that // are used to set/get the current behaviour and time of the clock. It // is constructed in such a way that use of the public functions is // safe regardless of given arguments. use std::{ os::unix::io::{AsRawFd, RawFd}, path::Path, }; use crate::{Error, EPOCH_OFFSET}; use ntp_proto::{NtpClock, NtpDuration, NtpLeapIndicator, NtpTimestamp, PollInterval}; // Libc has no good other way of obtaining this, so let's at least make our functions // more readable. #[cfg(all(target_os = "linux", target_env = "gnu"))] pub(crate) const EMPTY_TIMEX: libc::timex = libc::timex { modes: 0, offset: 0, freq: 0, maxerror: 0, esterror: 0, status: 0, constant: 0, precision: 0, tolerance: 0, time: libc::timeval { tv_sec: 0, tv_usec: 0, }, tick: 0, ppsfreq: 0, jitter: 0, shift: 0, stabil: 0, jitcnt: 0, calcnt: 0, errcnt: 0, stbcnt: 0, tai: 0, __unused1: 0, __unused2: 0, __unused3: 0, __unused4: 0, __unused5: 0, __unused6: 0, __unused7: 0, __unused8: 0, __unused9: 0, __unused10: 0, __unused11: 0, }; #[cfg(all(target_os = "linux", target_env = "musl"))] pub(crate) const EMPTY_TIMEX: libc::timex = libc::timex { modes: 0, offset: 0, freq: 0, maxerror: 0, esterror: 0, status: 0, constant: 0, precision: 0, tolerance: 0, time: libc::timeval { tv_sec: 0, tv_usec: 0, }, tick: 0, ppsfreq: 0, jitter: 0, shift: 0, stabil: 0, jitcnt: 0, calcnt: 0, errcnt: 0, stbcnt: 0, tai: 0, __padding: [0; 11], }; #[cfg(any(target_os = "freebsd", target_os = "macos"))] pub(crate) const EMPTY_TIMEX: libc::timex = libc::timex { modes: 0, offset: 0, freq: 0, maxerror: 0, esterror: 0, status: 0, constant: 0, precision: 0, tolerance: 0, ppsfreq: 0, jitter: 0, shift: 0, stabil: 0, jitcnt: 0, calcnt: 0, errcnt: 0, stbcnt: 0, }; /// NTP Clock that uses the unix NTP KAPI clock functions to get/modify the /// current time. // Implementation note: this is intentionally a bare struct, the NTP Clock defined // in the NTP KAPI is unique and no state is needed to interact with it. #[derive(Debug, Default, Clone, Copy)] pub struct UnixNtpClock { clock: libc::clockid_t, } impl UnixNtpClock { pub fn realtime() -> Self { Self::custom(libc::CLOCK_REALTIME) } pub fn custom(id: libc::clockid_t) -> Self { Self { clock: id } } pub fn from_path(path: &Path) -> Result { match std::fs::File::options().read(true).write(true).open(path) { Err(_) => Err(convert_errno()), Ok(file) => { let fd = file.as_raw_fd(); // never close the file, keep it open so clock steering can use the file descriptor std::mem::forget(file); Ok(Self::from_file_descriptor(fd)) } } } pub fn from_file_descriptor(fd: RawFd) -> Self { // using an invalid clock id is safe. The function that take this value as an argument will // return an EINVAL IO error when the clock id is invalid. let id = ((!(fd as libc::clockid_t)) << 3) | 0b11; Self::custom(id) } #[cfg_attr(target_os = "linux", allow(unused))] fn clock_gettime(&self) -> Result { let mut timespec = libc::timespec { tv_sec: 0, tv_nsec: 0, }; // # Safety // // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL error // https://linux.die.net/man/3/clock_gettime // // The timespec pointer is valid. cerr(unsafe { libc::clock_gettime(self.clock, &mut timespec) })?; Ok(timespec) } #[cfg_attr(target_os = "linux", allow(unused))] fn clock_settime(&self, mut timespec: libc::timespec) -> Result<(), Error> { while timespec.tv_nsec > 1_000_000_000 { timespec.tv_sec += 1; timespec.tv_nsec -= 1_000_000_000; } // # Safety // // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL error // https://linux.die.net/man/3/clock_settime // // The timespec pointer is valid. unsafe { cerr(libc::clock_settime(self.clock, ×pec))? }; Ok(()) } fn clock_adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> { // We don't care about the time status, so the non-error // information in the return value of clock_adjtime can be ignored. // // # Safety // // The clock_adjtime call is safe because the reference always // points to a valid libc::timex. // // using an invalid clock id is safe. `clock_adjtime` will return an EINVAL error // https://man.archlinux.org/man/clock_adjtime.2.en#EINVAL~4 #[cfg(target_os = "linux")] use libc::clock_adjtime as adjtime; #[cfg(any(target_os = "freebsd", target_os = "macos"))] unsafe fn adjtime(clk_id: libc::clockid_t, buf: *mut libc::timex) -> libc::c_int { assert_eq!( clk_id, libc::CLOCK_REALTIME, "only the REALTIME clock is supported" ); libc::ntp_adjtime(buf) } if unsafe { adjtime(self.clock, timex) } == -1 { Err(convert_errno()) } else { Ok(()) } } fn ntp_adjtime(timex: &mut libc::timex) -> Result<(), Error> { #[cfg(any(target_os = "freebsd", target_os = "macos", target_env = "gnu"))] use libc::ntp_adjtime as adjtime; // ntp_adjtime is equivalent to adjtimex for our purposes // // https://man7.org/linux/man-pages/man2/adjtimex.2.html #[cfg(all(target_os = "linux", target_env = "musl"))] use libc::adjtimex as adjtime; // We don't care about the time status, so the non-error // information in the return value of ntp_adjtime can be ignored. // The ntp_adjtime call is safe because the reference always // points to a valid libc::timex. if unsafe { adjtime(timex) } == -1 { Err(convert_errno()) } else { Ok(()) } } pub(crate) fn adjtime(&self, timex: &mut libc::timex) -> Result<(), Error> { if self.clock == libc::CLOCK_REALTIME { Self::ntp_adjtime(timex) } else { self.clock_adjtime(timex) } } #[cfg_attr(target_os = "linux", allow(unused))] fn step_clock_timespec(&self, offset: ntp_proto::NtpDuration) -> Result { let (offset_secs, offset_nanos) = offset.as_seconds_nanos(); let mut timespec = self.clock_gettime()?; // see https://github.com/rust-lang/libc/issues/1848 #[cfg_attr(target_env = "musl", allow(deprecated))] { timespec.tv_sec += offset_secs as libc::time_t; timespec.tv_nsec += offset_nanos as libc::c_long; } self.clock_settime(timespec)?; Ok(current_time_timespec(timespec, Precision::Nano)) } #[cfg(target_os = "linux")] fn step_clock_timex(&self, offset: ntp_proto::NtpDuration) -> Result { let (secs, nanos) = offset.as_seconds_nanos(); let mut timex = libc::timex { modes: libc::ADJ_SETOFFSET | libc::MOD_NANO, time: libc::timeval { tv_sec: secs as _, tv_usec: nanos as libc::suseconds_t, }, ..crate::unix::EMPTY_TIMEX }; self.adjtime(&mut timex)?; self.extract_current_time(&timex) } fn extract_current_time(&self, _timex: &libc::timex) -> Result { #[cfg(target_os = "linux")] // hardware clocks may not report the timestamp if _timex.time.tv_sec != 0 && _timex.time.tv_usec != 0 { // in a timex, the status flag determines precision let precision = match _timex.status & libc::STA_NANO { 0 => Precision::Micro, _ => Precision::Nano, }; return Ok(current_time_timeval(_timex.time, precision)); } // clock_gettime always gives nanoseconds let timespec = self.clock_gettime()?; Ok(current_time_timespec(timespec, Precision::Nano)) } } fn error_number() -> libc::c_int { #[cfg(target_os = "linux")] unsafe { *libc::__errno_location() } #[cfg(not(target_os = "linux"))] unsafe { *libc::__error() } } // Convert those error numbers that can occur for the ntp_gettime and ntp_adjtimex calls fn convert_errno() -> Error { match error_number() { libc::EINVAL => Error::Invalid, // The documentation is a bit unclear if this can happen with // non-dynamic clocks like the ntp kapi clock, however lets // deal with it just in case. libc::ENODEV => Error::NoDevice, libc::EOPNOTSUPP => Error::NotSupported, libc::EPERM => Error::NoPermission, // No other errors should occur (EFAULT is not possible as we always // pass in a proper buffer) other => { let error = std::io::Error::from_raw_os_error(other); unreachable!("error code `{other}` ({error:?}) should not occur") } } } fn cerr(c_int: libc::c_int) -> Result<(), Error> { if c_int == -1 { Err(convert_errno()) } else { Ok(()) } } fn duration_in_nanos(duration: NtpDuration) -> libc::c_long { let (secs, nanos) = duration.as_seconds_nanos(); (secs as libc::c_long) * 1_000_000_000 + (nanos as libc::c_long) } pub(crate) enum Precision { Nano, #[cfg_attr(any(target_os = "freebsd", target_os = "macos"), allow(unused))] Micro, } fn micros_to_nanos(micros: u32) -> u32 { let msg = "microseconds out of range (this can happen when initializing hardware clocks)"; match micros.checked_mul(1000) { Some(v) => v, None => { tracing::debug!(msg); 0 } } } #[cfg_attr(target_os = "linux", allow(unused))] fn current_time_timespec(timespec: libc::timespec, precision: Precision) -> NtpTimestamp { let mut seconds = timespec.tv_sec as u32; let mut nanos = match precision { Precision::Nano => timespec.tv_nsec as u32, Precision::Micro => micros_to_nanos(timespec.tv_nsec as u32), }; // on macOS (at least) we've observed higher nanosecond counts that appear valid while nanos > 1_000_000_000 { seconds = seconds.wrapping_add(1); nanos -= 1_000_000_000; } // Negative eras are completely valid, so any wrapping is perfectly reasonable here. NtpTimestamp::from_seconds_nanos_since_ntp_era(seconds.wrapping_add(EPOCH_OFFSET), nanos) } #[cfg_attr(not(target_os = "linux"), allow(unused))] fn current_time_timeval(timespec: libc::timeval, precision: Precision) -> NtpTimestamp { // Negative eras are completely valid, so any wrapping is perfectly reasonable here. NtpTimestamp::from_seconds_nanos_since_ntp_era( (timespec.tv_sec as u32).wrapping_add(EPOCH_OFFSET), match precision { Precision::Nano => timespec.tv_usec as u32, Precision::Micro => micros_to_nanos(timespec.tv_usec as u32), }, ) } fn ignore_not_supported(res: Result<(), Error>) -> Result<(), Error> { match res { Err(Error::NotSupported) => Ok(()), other => other, } } impl NtpClock for UnixNtpClock { type Error = Error; fn now(&self) -> Result { let mut ntp_kapi_timex = EMPTY_TIMEX; self.adjtime(&mut ntp_kapi_timex)?; self.extract_current_time(&ntp_kapi_timex) } fn set_frequency(&self, freq: f64) -> Result { let mut ntp_kapi_timex = EMPTY_TIMEX; ntp_kapi_timex.modes = libc::MOD_FREQUENCY; // NTP Kapi expects frequency adjustment in units of 2^-16 ppm // but our input is in units of seconds drift per second, so convert. ntp_kapi_timex.freq = (freq * 65536e6) as libc::c_long; ntp_kapi_timex.status = !libc::STA_PLL & !libc::STA_PPSFREQ & !libc::STA_FLL & !libc::STA_PPSTIME; self.adjtime(&mut ntp_kapi_timex)?; self.extract_current_time(&ntp_kapi_timex) } #[cfg(target_os = "linux")] fn step_clock(&self, offset: ntp_proto::NtpDuration) -> Result { self.step_clock_timex(offset) } #[cfg(any(target_os = "freebsd", target_os = "macos"))] fn step_clock(&self, offset: ntp_proto::NtpDuration) -> Result { self.step_clock_timespec(offset) } fn enable_ntp_algorithm(&self) -> Result<(), Self::Error> { let mut timex = EMPTY_TIMEX; self.adjtime(&mut timex)?; timex.modes = libc::MOD_STATUS; // Enable the kernel phase locked loop timex.status |= libc::STA_PLL; // and disable the frequency locked loop, // pps input based time control, and pps // input based frequency control. timex.status &= !libc::STA_FLL & !libc::STA_PPSTIME & !libc::STA_PPSFREQ; self.adjtime(&mut timex) } fn disable_ntp_algorithm(&self) -> Result<(), Self::Error> { let mut timex = EMPTY_TIMEX; self.adjtime(&mut timex)?; timex.modes = libc::MOD_STATUS; // Disable all kernel time control loops (phase lock, frequency lock, pps time and pps frequency). timex.status &= !libc::STA_PLL & !libc::STA_FLL & !libc::STA_PPSTIME & !libc::STA_PPSFREQ; // ignore if we cannot disable the kernel time control loops (e.g. external clocks) ignore_not_supported(self.adjtime(&mut timex)) } fn ntp_algorithm_update( &self, offset: NtpDuration, poll_interval: PollInterval, ) -> Result<(), Self::Error> { let mut timex = EMPTY_TIMEX; timex.modes = libc::MOD_OFFSET | libc::MOD_TIMECONST; timex.offset = duration_in_nanos(offset); timex.constant = poll_interval.as_log() as libc::c_long; ignore_not_supported(self.adjtime(&mut timex)) } fn error_estimate_update( &self, est_error: NtpDuration, max_error: NtpDuration, ) -> Result<(), Self::Error> { let mut timex = EMPTY_TIMEX; timex.modes = libc::MOD_ESTERROR | libc::MOD_MAXERROR; timex.esterror = duration_in_nanos(est_error) / 1000; timex.maxerror = duration_in_nanos(max_error) / 1000; ignore_not_supported(self.adjtime(&mut timex)) } fn status_update(&self, leap_status: NtpLeapIndicator) -> Result<(), Self::Error> { let mut timex = EMPTY_TIMEX; self.adjtime(&mut timex)?; timex.modes = libc::MOD_STATUS; // Clear out the leap seconds and synchronization flags timex.status &= !libc::STA_INS & !libc::STA_DEL & !libc::STA_UNSYNC; // and add back in what is needed. match leap_status { NtpLeapIndicator::NoWarning => {} NtpLeapIndicator::Leap61 => timex.status |= libc::STA_INS, NtpLeapIndicator::Leap59 => timex.status |= libc::STA_DEL, NtpLeapIndicator::Unknown => timex.status |= libc::STA_UNSYNC, } ignore_not_supported(self.adjtime(&mut timex)) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_time_now_does_not_crash() { let clock = UnixNtpClock::realtime(); assert_ne!( clock.now().unwrap(), NtpTimestamp::from_seconds_nanos_since_ntp_era(0, 0) ); } #[test] fn realtime_gettime() { let clock = UnixNtpClock::realtime(); let time = clock.clock_gettime().unwrap(); assert_ne!((time.tv_sec, time.tv_nsec), (0, 0)); } #[test] #[ignore = "requires permissions, useful for testing permissions"] fn ptp0_gettime() { let clock = UnixNtpClock::realtime(); let time = clock.clock_gettime().unwrap(); assert_ne!((time.tv_sec, time.tv_nsec), (0, 0)); } #[test] #[ignore = "requires permissions, useful for testing permissions"] fn step_clock() { UnixNtpClock::realtime() .step_clock(NtpDuration::from_seconds(0.0)) .unwrap(); } }