Skip to main content

Crate ntpsec_rs

Crate ntpsec_rs 

Source

Modules§

binio
control_client
counting_alloc
daemon_engine
gpstolfp
ieee754io
leap_query
ntp_assert
ntp_auth
ntp_calendar
ntp_config
ntp_control
ntp_debug
ntp_dns
ntp_endian
ntp_filegen
ntp_fp
ntp_io
ntp_leapsec
ntp_lists
ntp_loopfilter
ntp_malloc
ntp_monitor
ntp_net
ntp_packetstamp
ntp_peer
ntp_proto
ntp_recvbuff
ntp_refclock
ntp_restrict
ntp_sandbox
ntp_scanner
ntp_signd
ntp_stdlib
ntp_syscall
ntp_syslog
ntp_timer
ntp_types
ntp_util
ntpdig_proto
nts
nts_client
nts_cookie
nts_extens
nts_server
parse
refclock_arbiter
refclock_generic
refclock_gpsd
refclock_hpgps
refclock_jjy
refclock_local
refclock_modem
refclock_nmea
refclock_oncore
refclock_pps
refclock_pps_api
refclock_shm
refclock_spectracom
refclock_trimble
refclock_truetime
refclock_zyfer
timespecops

Macros§

ntp_assert
NTPsec-style assertion.
ntp_debug
Debug trace macro (matches ntpsec’s DPRINTF).
ntp_invariant
NTPsec-style invariant assertion.
ntp_require
NTPsec-style require (precondition check).

Structs§

ArbiterRefclock
Arbiter 1088A/B GPS refclock.
AssocOptions
Parse association options into structured form. Parsed association options from a server/peer/pool config line.
AssociationStatus
Parsed association record from READSTAT binary response.
AuthCounters
Authentication statistics counters — tracks auth events across the daemon.
AuthKeyStore
Authentication key store — matches ntpsec’s key database.
ClockFilter
The clock filter (8-sample shift register).
ClockFilterEntry
Clock filter register (8-sample shift register, RFC 5905 §9.2).
CompositeParser
A composite parser that tries multiple parsers in order.
ConfigScanner
ConfigTree
ControlClient
Mode 6 control protocol client with connected UDP, DNS resolution, fragment reassembly, and response validation.
ControlExchange
A parsed control request/response pair.
ControlMessage
Control message header — 12 bytes on wire, all big-endian. Instead of #[repr(packed)] (which caused OOB reads), we use explicit encode/decode with to_be_bytes/from_be_bytes.
ControlOpcode
Control message opcodes (bits: R(1), E(1), M(1), Op(5)).
CookieCipher
CookieKeyIndex
Cookie key index — NTPsec rotates cookie encryption keys.
DaemonEngine
The deterministic daemon state machine.
DaemonInput
A replay-stable, serializable representation of a daemon input event. This is the “recording” format — every DaemonEvent can be converted to a DaemonInput for deterministic replay, log, or differential testing. All fields use only primitive types (no libc types, no heap-allocated compound objects from the protocol layer).
ExtensionField
Extension field parsed from a packet tail.
ExtensionFieldHeader
NTP extension field header (4 bytes).
FileGenEntry
File generation entry.
FileGenRegistry
Open file handles for active file generation entries.
FixedWidthParser
A parser for fixed-width numeric timecode strings.
FlashBits
Peer/test flash bits — each bit indicates a failed test. A peer with any TEST bit set is NOT selectable. Matching ntpsec’s TEST bits exactly.
FragmentCollector
Pure fragment reassembly engine. Collects fragments and validates that the assembled range is contiguous with no holes or overlaps.
GenericRefclock
A generic refclock that uses the parse engine to interpret timecodes.
GpsdFix
A GPS time fix from gpsd.
GpsdRefclock
GPSD refclock driver instance.
HpGpsRefclock
HP GPS receiver refclock.
JjyRefclock
JJY time signal refclock.
LeapEntry
A single leap second entry.
LeapInfo
Leap info structure returned when loading a leap file. Used by daemon_engine to pass loaded leap data to the LeapTable.
LeapTable
Leap second table.
LocalClockDriver
Local clock driver (type 1).
LoopFilter
Clock discipline state — matching ntpsec’s loop_data structure.
MemoryStateStore
An in-memory state store for deterministic lab testing.
ModemRefclock
Modem refclock driver.
MonEntry
A single MRU entry (matches ntpsec’s mon_entry).
MonList
MRU list.
MruEntry
MRU (Most Recently Used) entry from the daemon. Represents a single client entry in the daemon’s MRU list.
NetAddr
Network address abstraction (IPv4 or IPv6 with port).
NmeaParser
A parser for NMEA 0183 timecode sentences: $GPGGA, $GPRMC, $GPZDA (and with any talker ID, e.g. $GNGGA, $GNRMC, $GNZDA).
NmeaRefclock
NMEA refclock driver.
NmeaSample
A single time sample produced by the NMEA refclock.
NonceCache
Nonce cache for MRU queries.
NonceEntry
A single nonce entry in the nonce cache.
NtpAuthKey
An NTP authentication key (matching ntpsec’s symkey struct).
NtpCalendar
NTP calendar date structure.
NtpDigClient
A simple NTP client that queries servers using the on-wire protocol.
NtpPacket
NTP packet header (RFC 5905 §6), 48 bytes big-endian. Use encode_header()/decode_header() for safe wire serialization.
NtpQueryResult
Result of a single NTP query.
NtpShort
NTP short format (32-bit): 16 bits seconds + 16 bits fraction.
NtpStats
Statistics counters matching ntpsec.
NtpStrBuf
Recoverable-allocated string buffer (replaces ntpsec’s lib_strbuf).
NtpTimespec
A timespec with ns precision.
NtpTs
NTP timestamp format (64-bit): 32 bits seconds + 32 bits fraction. The 64-bit signed version used for most computations.
NtpTs64
NTP 64-bit signed timestamp for arithmetic.
NtsAssociation
An NTS association that binds the results of an NTS-KE handshake to an NTP association (Gate 8.1).
NtsAuthResult
NTS authentication result (RFC 8915 §5.4, extension type 0x0106).
NtsAuthenticator
NTS Authenticator payload (RFC 8915 §5.3, extension type 0x0404).
NtsCookie
NTS cookie structure (RFC 8915 §4.2).
NtsKeClient
NTS-KE client using TLS 1.3 with rustls.
NtsKeInFlight
An in-flight NTS-KE handshake worker. Tracked by the engine so late completions can be matched to the correct association generation.
NtsKeJob
An NTS-KE handshake job awaiting execution. Stored in the engine queue and dispatched to the shell for async execution. Tracks lifecycle state for generation-safe completion and retry/backoff.
NtsKeNegotiation
NTS-KE negotiated parameters.
NtsKeProtocolClient
NTS-KE client — manages the NTS-KE state machine and record exchange.
NtsKeRecord
NTS-KE message record.
NtsServerConfig
Configuration for the NTS-KE server (Gate 8.4).
NtsServerSession
NTS server state for a single association.
NtsState
NTS state for a single association.
NtsUniqueKey
NTS unique identifier key (UIK) — used to derive cookie encryption keys.
OncoreRefclock
Motorola Oncore GPS refclock.
PacketStamp
The NTP timestamping namespace.
PacketTimestamp
A received packet timestamp with its type metadata.
PacketTrace
A recorded NTP packet trace for replay and analysis.
ParsedTimecode
A parsed timecode result.
ParsedTimecodeWithLeap
The parsed timecode with an associated NTP leap indicator.
Peer
A peer association (matches ntpsec’s struct peer).
PeerFlags
Peer flags matching ntpsec.
PeerRow
A single peer row for the peers billboard.
PeerTable
Peer association table.
PeerVariables
Typed peer variables parsed from Mode 6 text response.
PendingDns
A hostname-based association awaiting DNS resolution. Stored in the engine until the shell resolves the hostname and feeds back the result as DnsResolved/DnsFailed.
PollInterval
PoolState
State for a pooled DNS entry — tracks resolved addresses and refresh timing.
Ppm
Frequency measured in parts per million (PPM). PPM is dimensionless but physically distinct from raw fractions.
PpsRefclock
PPS refclock driver instance.
PpsStamp
A PPS timestamp with both raw and corrected times.
PpsVersion
PPS kernel API version information.
RateLimit
Reachability
Peer reachability register (8-bit shift register, RFC 5905 §13.1).
ReceivedDatagram
A received NTP datagram with kernel timestamp.
RecvBufPool
Receive buffer pool.
RecvBuffer
A receive buffer (matches ntpsec’s recvbuf).
RecvFlags
RefClockRegistry
Reference clock registry.
RefClockSample
A reference clock sample.
RefclockInstance
A managed refclock instance with its driver and metadata.
RefclockManager
Manages refclock lifecycle — open, poll, close.
ReplayNetwork
A replay network that returns pre-recorded datagrams for deterministic testing. Records all sent packets for transcript assertion.
RestrictEntry
A single restrict entry.
RestrictFlags
Restriction flags matching ntpsec’s restrict flags.
RestrictList
Restriction list.
Seconds
A time interval in seconds, as a newtype for dimensional safety. Prevents accidental mixing of offsets, delays, dispersions, and jitters, all of which are measured in seconds but have different physical meanings.
SelectionPolicy
Selection policy parameters matching ntpsec’s tos and tinker directives. Passed through the selection pipeline so that configuration values are the single source of truth — NOT hardcoded constants in clock_cluster or update_from_peers.
SerialConfig
Serial port configuration parameters.
ServerCounters
Server-side statistics counters — tracks packet handling events.
ShmRefclock
SHM refclock driver instance.
ShmSample
Result of reading a time sample from the SHM segment.
ShmTime
The shared memory structure, matching ntpsec’s struct shmTime.
SigndClient
A client for the Samba NTP signing daemon (samba-dcerpcd or samba-ntp-sign).
SimulatedClock
A simulated system clock for deterministic lab testing. Starts at a fixed NTP time and increments only when explicitly advanced via advance() or step()/slew().
SpectracomRefclock
Spectracom GPS receiver refclock.
SyslogBuffer
A syslog message buffer (used in deterministic testing to capture messages).
SystemEventState
System event state — tracks the last system event and event timer.
SystemState
Global NTP system state — matches ntpsec’s sys_* globals.
SystemVariables
Typed system variables parsed from Mode 6 text response.
TimerEntry
A scheduled timer entry.
TimerQueue
Timer queue — manages scheduled events.
Timex
A safe Rust representation of the Linux struct timex.
TraceEntry
A single traced NTP packet with timestamp and direction.
TrimbleRefclock
Trimble GPS refclock.
TrueTimeRefclock
TrueTime GPS receiver refclock.
ZyferRefclock
Zyfer GPStarplus refclock.

Enums§

Adjustment
Clock adjustment type returned by local_clock().
AeadAlgorithm
Strongly-typed AEAD algorithm identifiers (RFC 8915 §4.1.3).
ClockState
Return status codes from adjtimex() / ntp_adjtime().
ConfigOption
ControlError
Mode 6 response/error codes matching ntpsec.
DaemonAction
Actions the daemon engine emits.
DaemonEvent
Events the daemon engine processes.
DaemonInputType
Tag identifying the kind of input event, for serialization stability.
DigestType
Supported digest types for NTP authentication.
DisciplineType
Clock discipline types matching ntpsec.
DnsError
DNS resolution errors.
DnsErrorKind
Specific category of DNS resolution failure.
FileGenType
File generation type (matches ntpsec).
InterfaceAction
Action for the interface directive.
IoError
I/O errors that can occur during daemon operation.
JjyReceiverType
JJY receiver type identifiers (matching C UNITTYPE_* constants)
LeapIndicator
NTP leap indicator.
MacType
MAC computation type.
NmeaSentence
NMEA sentence types we care about.
NmeaSentenceType
The type of NMEA sentence that produced a sample.
NtpAssociationState
NTP association states.
NtpDigError
Errors that can occur during an NTP query.
NtpMode
NTP mode field values.
NtpVersion
NTP version numbers.
NtsErrorCode
NTS warning/error codes (RFC 8915 §4.1.4).
NtsFailureReason
NTS failure reason — distinguishes failure modes for diagnostics (Gate 8.3).
NtsKeJobState
Lifecycle state of an NTS-KE handshake attempt.
NtsKeState
NTS-KE session state.
Parity
Serial parity setting.
ParseError
Error returned when a timecode string cannot be parsed.
PeerEventCode
Peer event codes matching ntpsec’s event_codes enum.
ProcessResult
Process a received NTP packet. This is the main receive path, matching ntpsec’s receive() and process_packet() logic.
QueryError
RefclockDriver
A real refclock driver instance — one variant per supported type.
RestrictAction
Actions the restrict system can take on a packet.
SelectionStatus
Selection status values per RFC 9327 §5.2.2.
ShmMode
NTP_SHM_MODE values — how the time provider writes samples.
SigndError
Errors that can occur during MS-SNTP signing operations.
StopBits
Serial stop bits setting.
SysEvent
System event type (matches ntpsec’s sys_events).
SyslogLevel
Syslog severity levels matching ntpsec.
SystemEventCode
System event codes matching ntpsec’s sys_event_codes enum (Gate 10 exact semantics).
TimecodeSource
Metadata identifying the source format of a parsed timecode.
TimerEvent
Timer event types — matching ntpsec’s timer event system.
TimerId
Timer identifiers for the event loop.
TimestampMode
Timestamping modes supported.
TimestampSource
Provenance of a receive timestamp.
TimestampType
The type of timestamp extracted from CMSG ancillary data.
Token
TraceDirection
Direction of a traced NTP packet.
TrimbleClockType
Clock type identifiers
TrueTimeType
Receiver type identifiers

Constants§

AEAD_AES_GCM_128
AEAD_AES_SIV_CMAC_256
AEAD_AES_SIV_CMAC_512
C2S_KEY_SIZE
Client-to-server key size (256 bits).
COOKIE_PLAINTEXT_MIN
Minimum cookie plaintext size: server_id(32) + c2s_key(32) + s2c_key(32) + timestamp_secs(8) + timestamp_frac(4) + aead(2) = 110 bytes.
DAYS_PER_MONTH
Days in each month (non-leap year).
DAYS_PER_MONTH_LEAP
Days in each month (leap year).
DEFAULT_SIGN_SOCKET_PATH
The default path to the Samba NTP signing socket.
DEFAULT_SIGN_TIMEOUT_MS
The default timeout for signing socket I/O operations (milliseconds).
DEF_TC
EVENT_NAMES
Event/state name table matching ntpsec’s event strings.
EXTENSION_FIELD_NTS_AUTHENTICATOR
NTS Authenticator — AEAD encryption result (RFC 8915 §5.3).
EXTENSION_FIELD_NTS_AUTH_RESULT
NTS Authentication Result extension field (RFC 8915 §5.4).
EXTENSION_FIELD_NTS_COOKIE
NTS Cookie extension field (RFC 8915 §5.2).
EXTENSION_FIELD_NTS_COOKIE_PLACEHOLDER
NTS Cookie Placeholder extension field (RFC 8915 §5.2).
EXTENSION_FIELD_UNIQUE_IDENTIFIER
NTS Unique Identifier extension field (RFC 8915 §5.1).
FILEGEN_MAX_BACKUP
Maximum number of rotated backup files to keep.
FILEGEN_MAX_SIZE
Maximum file size before rotation (10MB default).
GPSD_DEFAULT_PORT
Default gpsd port.
GPSD_MIN_VERSION
Minimum GPSD protocol version required.
INITIAL_RECONNECT_BACKOFF
Initial reconnection backoff in seconds.
KEYID_MAX
Maximum key ID value (ntpsec uses u32 max).
KEY_MAX_LEN
Maximum key length in bytes (ntpsec: 64 bytes for SHA1, 16 for MD5).
KISS_DENY
Standard Kiss-o’-Death codes as 4-byte ASCII arrays for use with build_kod_packet(). Each code identifies the reason for the KOD response. Access denied by server.
KISS_RATE
Rate limit exceeded — client should reduce polling rate.
KISS_RSTR
Server restart — client should discard state and re-sync.
KNOWN_DIGEST_LENGTHS
Known valid MAC digest lengths: MD5 (16), SHA-1 (20), AES-128-CMAC (16). Used by split_packet_tail() to validate packet tails.
LEAP_SMEAR_DEFAULT
Default smear interval in seconds (narrow = 2h, wide = 24h).
MAX_KEYS
AES-SIV-CMAC-256 cookie encryption/decryption with key rotation support, a random-nonce envelope format, and bounded key storage.
MAX_RECONNECT_BACKOFF
Maximum reconnection backoff in seconds.
MAX_TC
MAX_TOTAL_SIZE
Maximum total size of extension fields (65535 bytes as per NTP packet format).
MIN_AUTH_PACKET_SIZE
Minimum size for a packet with key ID + MAC.
MIN_MAC_SIZE
Minimum MAC size: 4-byte key ID + 16-byte minimum digest.
MIN_TC
Loop filter time constants (ntpsec defaults).
NTP_EPOCH_OFFSET
Number of seconds between NTP epoch (1900-01-01) and Unix epoch (1970-01-01).
NTP_ERA_LENGTH
NTP era length in seconds: 2^32.
NTP_FRAC_PER_SEC
One second as an NTP fractional unit (2^32).
NTP_HEADER_SIZE
NTP packet header size in bytes (RFC 5905).
NTP_MAXDISPERSE
NTP.MAXDISPERSE — maximum dispersion (16 s) before a peer is considered unreachable. Matches ntpsec’s NTP_MAXDISPERSE.
NTP_MAXDIST
NTP.MAXDIST — maximum select distance (1.5 s). Matches ntpsec’s NTP.MAXDIST / sys_maxdist default.
NTP_MAXPOLL
NTP.MAXPOLL — default maximum poll exponent (10 = 1024 s).
NTP_MAXSTRAT
NTP.MAXSTRAT — maximum stratum (16).
NTP_MAX_PACKET_SIZE
Maximum NTP packet size (RFC 5905).
NTP_MINDIST
NTP.MINDIST — minimum select distance (0.001 s / 1 ms).
NTP_MINPOLL
NTP.MINPOLL — default minimum poll exponent (4 = 16 s).
NTP_MINSANE
Minimum clock-selectable peers.
NTP_SHIFT
Clock filter register depth (RFC 5905 §9.2).
NTP_TO_UNIX_OFFSET
NTP-era offset in seconds from the Unix epoch. This is the classic 2_208_988_800 offset (years 1900→1970).
NTP_WEIGHT
Weight factor for peer jitter in the combine algorithm (ntpsec default).
NTS_COOKIE_MAX_AGE
Maximum age for an NTS cookie in seconds (1 day). Cookies older than this are rejected during decryption.
NTS_KE_DEFAULT_PORT
NTS_KE_EXPORTER_LABEL
NTS_KE_PORT
NTS-KE default port (RFC 8915 §4).
NTS_KE_RECORD_AEAD_ALGORITHM
NTS_KE_RECORD_CRITICAL_BIT
NTS_KE_RECORD_END_OF_MESSAGE
NTS_KE_RECORD_ERROR
NTS_KE_RECORD_NEW_COOKIE
NTS_KE_RECORD_NEXT_PROTOCOL
NTS_KE_RECORD_NTPV4_PORT
NTS_KE_RECORD_NTPV4_SERVER
NTS_KE_RECORD_WARNING
NTS_MAX_COOKIES
Maximum number of cookies per NTS-KE response (ntpsec default).
NTS_MAX_COOKIE_SIZE
Maximum cookie size in bytes.
NTS_VERSION
NTS protocol version.
RECOGNIZED_DIRECTIVES
S2C_KEY_SIZE
Server-to-client key size (256 bits).
SERVER_ID_SIZE
Size of the server identity field in the cookie plaintext.
SHM_SIZE
Size of the shared memory segment (struct shmTime + padding). Must match the layout used by ntpsec’s time providers.
SHM_UNITS
SHM refclock unit number maximum (0-3, matching ntpsec default).

Traits§

NetworkIo
Abstract network I/O — real UDP sockets or replay harness.
RefClockDriver
Reference clock driver interface.
StateStore
Abstract state persistence — real filesystem or memory.
SystemClock
Abstract system clock — real or simulated.
TimecodeParser
A parser that converts a raw timecode string from a reference clock into an NTP timestamp and leap-indicator pair.

Functions§

accept_sample
Accept the peer sample: update clock filter, reachability, and peer variables. Matching ntpsec’s accept().
build_control_fragments
Build multi-datagram Mode 6 control response fragments.
build_error_response
Build a Mode 6 error response given a request header and error code.
build_kod_packet
Build a Kiss-o’-Death packet (RFC 5905 §7.4, §13).
build_nts_request
Build an NTS-protected NTP request by adding the required extension fields to the raw NTP packet (Gate 8.1).
build_request
Build an NTP client request packet. Matching ntpsec’s transmit() for client mode.
build_response
Build an NTP server response packet. Matching ntpsec’s transmit().
clock_cluster
The clustering algorithm (RFC 5905 §11, ntpsec exact parity).
clock_combine
The combining algorithm (RFC 5905 §12). Computes a weighted average of the survivor offsets. The weight for each survivor is inversely proportional to its root synchronization distance (not peer jitter²). This gives more weight to peers with smaller total clock uncertainty.
clock_intersection
The intersection algorithm (RFC 5905 §11.2.1, three-tuple majority clique). Finds the smallest intersection interval that contains at least m = n - allow midpoints (peer offset values), not just overlapping confidence intervals. Peers whose confidence interval does NOT overlap the intersection are falsetickers (marked TEST5).
compute_offsets
Compute the NTP on-wire protocol offsets (RFC 5905 §8). offset = [(T2 − T1) + (T3 − T4)] / 2 delay = (T4 − T1) − (T3 − T2)
configure_serial
Apply serial port configuration using termios.
correct_era
Correct a wire-format NTP timestamp to the current era.
decodenetnum
Decode a network number string into a socket address.
dedup_addrs
Deduplicate a list of socket addresses by IP (ignoring port).
dolfptoa
Format an NTP timestamp as a string, matching ntpsec’s dolfptoa output.
ealloc
Zeroed allocation for a type.
emalloc
Zeroed allocation of size bytes (matches ntpsec’s emalloc_zeroed()).
emalloc_vec
Safe wrapper for ntpsec-style allocation (for use within Rust code).
enable_hardware_timestamps
Enable hardware receive timestamps on a socket.
enable_pktinfo
Enable or disable receiving the packet info (destination address) via IP_PKTINFO / IPV6_PKTINFO. This is often paired with timestamping so the receiver can determine which local address the packet arrived on.
enable_sandbox
Enable the seccomp sandbox.
enable_software_timestamps
Enable software receive timestamps on a socket.
encode_var_list
Encode a list of variables in key=value format (matching ntpq output).
estrdup
Copy a C string (matches ntpsec’s estrdup()).
extract_response_cookie
Extract the NTS cookie from a server response, checking both public extension fields and (if present) inside the authenticator plaintext.
extract_unique_identifier
Extract the NTS Unique Identifier from a packet.
f64_to_ntp_short
Convert a f64 seconds value to NTP short format (16.16 fixed-point).
f64_to_ntp_ts
Convert f64 seconds relative to the NTP epoch to an NtpTs64.
format_associations
Render associations table in ntpq-compatible format.
format_peer_readvar
Render peer READVAR variables in ntpq-compatible format (multi-line, matching real C ntpq).
format_peers
Render peers billboard in ntpq-compatible format.
format_readvar
Render system variables in ntpq-compatible format (matching real C ntpq).
get_f32_be
Decode an IEEE 754 32-bit float from big-endian bytes.
get_f64_be
Decode an IEEE 754 64-bit double from big-endian bytes.
get_peer_variable
Peer variable accessor — retrieves a named peer variable.
get_system_variable
System variable accessor — retrieves a named system variable from the daemon state. Matching ntpsec’s read_sysvars() output format.
get_u16
Read a big-endian u16 from a byte slice.
get_u32
Read a big-endian u32 from a byte slice.
gps_to_ntp
gpsd_fix_to_packet
Construct a synthetic NTP packet from a GPSD fix and a receive timestamp.
hton16
Convert u16 from host to network byte order.
hton32
Convert u32 from host to network byte order.
init_signd_client
Initialize the global signing client with a custom socket path.
is_ip_address
Check if a string looks like an IP address (no DNS needed).
is_leap_year
Is the given year a leap year?
is_recognized_directive
is_sandbox_active
Check if NO_NEW_PRIVS is set.
is_seccomp_active
Check if seccomp filter is installed.
is_signing_available
Check if MS-SNTP signing is configured (sign socket exists).
leap_pending
Check if a leap second is pending (from kernel state).
netaddr_to_sockaddr
Convert a NetAddr to a libc sockaddr_storage for restrict evaluation.
nmea_sample_to_packet
Convert an NmeaSample into a server-mode NtpPacket.
ntoh16
Convert u16 from network to host byte order.
ntoh32
Convert u32 from network to host byte order.
ntp_adjtime
Call adjtimex(2) (a.k.a. ntp_adjtime()) to read or set kernel clock discipline parameters.
ntp_get_esterror
Convenience: return the estimated error in microseconds.
ntp_get_maxerror
Convenience: return the maximum error in microseconds.
ntp_get_tai_offset
Convenience: return the TAI offset from the kernel (if available).
ntp_gettime
Get the current kernel clock discipline status (read-only).
ntp_init
Initialize NTPSEC-specific system state.
ntp_shm_key
Compute the System V IPC key for a SHM refclock unit. NTPsec uses NTP_SHM_KEY (0x4e545030 = “NTP0”) + unit.
ntp_short_to_double
Convert NTP short format to double.
ntp_to_gps
ntp_to_ts
Convert an NTP timestamp (l_fp) to a timespec (seconds + nanoseconds).
ntp_to_tv
Convert an NTP timestamp (l_fp) to a timeval (seconds + microseconds).
ntp_ts64_to_double
Convert NTP 64-bit signed timestamp to double.
ntp_ts64_to_ntpts
Convert an NtpTs64 to an NtpTs, preserving the full 64-bit seconds value. This is the inverse of ntp_ts_to_ntpts and does not truncate to u32; it retains era information for internal use.
ntp_ts64_to_wire
Convert an i64 NTP timestamp to wire format (u32 seconds + u32 fraction). Handles NTP era rollover by wrapping at 2^32 seconds.
ntp_ts_to_double
Convert NTP timestamp to double (seconds).
ntp_ts_to_f64
Convert an NtpTs64 to f64 seconds relative to the NTP epoch.
ntp_ts_to_ntpts
Convert wire-format NtpTs (u32 seconds) to NtpTs64 (i64 seconds). Handles the unsigned-to-signed conversion through NTP era boundaries.
numtoa
Convert an IP address (u32) to a dotted-quad string (IPv4).
parse_config
parse_fixed_width_timecode
Parse a numeric-only timecode string (fixed-width fields).
parse_mode6_vars
Parse Mode 6 key=value text with proper quote handling. Splits on , outside quotes; strips surrounding quotes from values.
parse_nmea_sentence
Parse an NMEA 0183 sentence from a raw line of text.
parse_nmea_timecode
Parse an NMEA 0183 timecode sentence and return the parsed components together with a leap indicator.
parsed_timecode_to_sample
Convert a ParsedTimecode into a RefClockSample.
peer_status
Format the peer status word for Mode 6 READSTAT responses. Matching NTPsec’s peer_status() and RFC 9327 §5.2.
perform_nts_ke
Perform a full NTS-KE handshake and return an NtsAssociation ready for NTP packet protection (Gate 8.1).
perform_nts_ke_with_ca
Perform NTS-KE with optional custom CA certificate (Gate 8.7).
poll_update
Determine the next poll time. Matching ntpsec’s poll_update().
pps_api_available
Check if the kernel PPS API is available on this system.
pps_stamp_to_packet
Build a synthetic NTP packet from a PPS timestamp.
prettydate
Format an NTP timestamp as a human-readable date in ntpsec’s style. Matches ntpsec’s prettydate() output format.
put_f32_be
Encode an f32 as big-endian bytes.
put_f64_be
Encode an f64 as big-endian bytes.
put_u16
Write a big-endian u16 to a mutable byte slice.
put_u32
Write a big-endian u32 to a mutable byte slice.
query_tai_offset
Query the leap second status from system or file. Returns the current TAI offset if available.
read_config_file
recv_timestamp_from_cmsg
Parse ancillary data (CMSG) for receive timestamps.
refid_from_addr
Generate a (hopefully) unique reference ID for a server.
refid_to_string
Convert a reference identifier (refid: u32) to a display string.
reset_reconnect_backoff
Reset the reconnection backoff to its initial value. Useful after a successful long-term connection is established.
resolve_hostname
Resolve a hostname to a list of IP addresses with a timeout.
root_dispersion
Compute root dispersion (RFC 5905 §10.1).
root_distance
Compute root synchronization distance (RFC 5905 §10.1). rootdist = root_delay / 2 + root_dispersion + peer_dispersion + phi * (t - t0) where phi = 15 us/s (NTP clock skew maximum).
rotate_file
Rotate a statistics file when it exceeds FILEGEN_MAX_SIZE.
shm_sample_to_packet
Build a synthetic NTP packet from a SHM sample, suitable for feeding into the daemon engine as a server response.
sign_ms_sntp_response
Sign a response for MS-SNTP using the Samba signing daemon.
sockaddr_to_netaddr
Convert a libc sockaddr_storage to a NetAddr (for daemon_engine peer addressing).
socktoa
Convert a socket address to a string (matches ntpsec’s socktoa()).
split_packet_tail
Parse the tail of an NTP packet: extension fields + optional MAC.
start_nts_ke_server
Start the NTS-KE server on the configured port (Gate 8.4).
swap_u16
Swap bytes in a 16-bit value.
swap_u32
Swap bytes in a 32-bit value.
swap_u64
Swap bytes in a 64-bit value.
system_event_name
Map a system event code to a human-readable name matching ntpsec’s sys_event_names table.
ts_to_ntp
Convert a timespec (seconds + nanoseconds) to an NTP timestamp (l_fp).
tv_to_ntp
Convert a timeval (seconds + microseconds) to an NTP timestamp (l_fp).
unix_seconds_to_hms
Break down Unix seconds into hours/minutes/seconds.
unix_seconds_to_ymd
Break down Unix seconds into Gregorian year/month/day.
validate_extension_fields_total_size
Validate that the total size of a sequence of extension fields does not exceed the maximum allowed by the NTP packet format.
validate_packet
Validate a received NTP packet. Returns a FlashBits mask — set bits indicate which tests failed. Matching ntpsec’s test_free() logic.
verify_nts_response
Verify the NTS authenticator on an NTP response packet (Gate 8.1).
write_stat_file
Open and write to a statistics file.
yd_to_ymd
Convert day-of-year to month/day (1-based).
ymd_to_yd
Convert month/day to day-of-year (1-based).

Type Aliases§

KeyId
Key identifier type (32-bit unsigned, matching ntpsec’s keyid_t).
LFP
Absolute-precision timestamp (l_fp in ntpsec C — “long fixed-point”).
RefClockId
Reference clock type identifier.
RefClockUnit
Reference clock unit number (127.127.X.Y).
SockAddr
SockAddrIn
SockAddrIn6
int32
NTP signed 32-bit integer.
int64
NTP signed 64-bit integer.
ntp_bool
NTP Boolean type.
s_char
NTP signed 8-bit integer.
u_char
NTP unsigned 8-bit integer.
u_int32
NTP unsigned 32-bit integer (network-order).
u_int64
NTP unsigned 64-bit integer.
u_short
NTP unsigned 16-bit integer (network-order).