Documentation
¶
Overview ¶
Package ntp provides an implementation of a Simple NTP (SNTP) client capable of querying the current time from a remote NTP server. See RFC 5905 (https://tools.ietf.org/html/rfc5905) for more details.
This approach grew out of a go-nuts post by Michael Hofmann: https://groups.google.com/forum/?fromgroups#!topic/golang-nuts/FlcdMU5fkLQ
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrAuthFailed = errors.New("authentication MAC verification failed") ErrAuthNAK = errors.New("authentication NAK received") ErrExtensionsNotSupported = errors.New("NTPV3 does not support extension fields") ErrInvalidAuthKey = errors.New("invalid authentication key") ErrInvalidDispersion = errors.New("invalid dispersion in response") ErrInvalidLeapSecond = errors.New("invalid leap second in response") ErrInvalidMode = errors.New("invalid mode in response") ErrInvalidProtocolVersion = errors.New("invalid protocol version requested") ErrInvalidStratum = errors.New("invalid stratum in response") ErrInvalidTime = errors.New("invalid time reported") ErrInvalidTransmitTime = errors.New("invalid transmit time in response") ErrKissOfDeath = errors.New("kiss of death received") ErrServerClockFreshness = errors.New("server clock not fresh") ErrServerNotSynchronized = errors.New("NTPv5 server not synchronized") ErrServerResponseMismatch = errors.New("server response didn't match request") ErrServerTickedBackwards = errors.New("server clock ticked backwards") )
var ( ErrInvalidDraftID = errors.New("invalid draft ID value in response") ErrInvalidExtensionField = errors.New("invalid extension field in response") ErrInvalidReferenceRequest = errors.New("invalid reference ID request") ErrUnexpectedCorrectionField = errors.New("unexpected correction extension field in response") )
NTPv5 errors. Will move to ntp.go once NTPv5 is finalized.
var DelayUnrepresentable = time.Duration(math.MinInt64)
DelayUnrepresentable is a sentinel value used to indicate that a delay correction value (i.e., OriginDelay or ReturnDelay) is not representable. This occurs when a correction exceeds the maximum value representable by NTP's correction timestamp format.
Functions ¶
func Time ¶
Time returns the current, corrected local time using information returned from the remote NTPv4 server. On error, Time returns the uncorrected local system time.
The server address is of the form "host", "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port". The host may contain an IPv4, IPv6 or domain name address. When specifying both a port and an IPv6 address, one of the bracket formats must be used. If no port is included, NTP default port 123 is used.
Types ¶
type AuthOptions ¶ added in v1.2.0
type AuthOptions struct {
// Type determines the cryptographic hash algorithm used to compute the
// authentication code.
Type AuthType
// The cryptographic key used by the client to perform authentication. The
// key may be hex-encoded or ascii-encoded. To use a hex-encoded key,
// prefix it by "HEX:". To use an ascii-encoded key, prefix it by
// "ASCII:". For example, "HEX:6931564b4a5a5045766c55356b30656c7666316c"
// or "ASCII:cvuZyN4C8HX8hNcAWDWp".
Key string
// The identifier used by the NTP server to identify which key to use
// for authentication purposes.
KeyID uint32
}
AuthOptions contains fields used to configure symmetric key authentication for an NTP query.
type AuthType ¶ added in v1.2.0
type AuthType int
AuthType specifies the cryptographic hash algorithm used to generate a symmetric key authentication code for an NTP message. Please note that MD5 and SHA1 are no longer considered secure and have been deprecated for use with NTP; they appear here solely for compatibility with older NTP server implementations. In general, the AES-128-CMAC algorithm should be used if the server supports it (see RFC 8573).
type Correction ¶ added in v1.6.0
type Correction struct {
// OriginDelay is the total delay correction accumulated by the request
// packet on its way from the originating client to the server.
OriginDelay time.Duration
// OriginPathID is the path identifier calculated by intermediate nodes on
// the request packet's path from the originating client to the server.
OriginPathID uint16
// ReturnDelay is the total delay correction accumulated by the response
// packet on its return from the server to the client.
ReturnDelay time.Duration
// ReturnPathID is the path identifier calculated by intermediate nodes on
// the response packet's return from the server to the client. This may be
// compared to the OriginPathID to determine if the request and response
// packets traversed the same network path.
ReturnPathID uint16
}
The Correction struct contains delay correction information provided by network switches and routers along the path between the client and the server. Used only in NTPv5.
type Extension ¶ added in v1.2.0
type Extension interface {
// ProcessQuery is called when the client is about to send a query to the
// NTP server. The buffer contains the NTP message and any extension
// fields generated by this package (excluding the NTPv5 MAC and
// correction extension fields). It may also contain extension fields
// added by other extensions processed prior to this one.
ProcessQuery(buf *bytes.Buffer) error
// ProcessResponse is called after the client has received the server's
// NTP response. The buffer contains the entire message returned by the
// server. It is owned by the package and is valid only for the duration
// of the call.
ProcessResponse(buf []byte) error
}
An Extension adds custom behaviors capable of modifying NTP packets before being sent to the server and processing packets after being received by the server.
type LeapIndicator ¶
type LeapIndicator uint8
The LeapIndicator is used to warn if a leap second should be inserted or deleted in the last minute of the current month.
const ( // LeapNoWarning indicates that no leap second will be inserted in the // near future (within the next 14 days for NTPv5). It is also used when // responding to an NTPv5 leap-smeared timescale request. LeapNoWarning LeapIndicator = 0 + iota // LeapAddSecond indicates that, in the near future (within 14 days for // NTPv5), a leap second will be inserted at the end of the current month. LeapAddSecond // LeapDelSecond indicates that, in the near future (within 14 days for // NTPv5), a leap second will be deleted at the end of the current month. LeapDelSecond // LeapNotInSync indicates that the server has no time source or other // source providing information about leap seconds (often due to an // unsynchronized server clock). LeapNotInSync )
type ProtocolTimestamps ¶ added in v1.6.0
type ProtocolTimestamps struct {
// ClientXmit is the timestamp recorded by the client when it transmitted
// the request.
ClientXmit time.Time
// ServerRecv is the timestamp recorded by the server when it received the
// request.
ServerRecv time.Time
// ServerXmit is the timestamp recorded by the server when it transmitted
// the response.
ServerXmit time.Time
// ClientRecv is the timestamp recorded by the client when it received the
// response.
ClientRecv time.Time
}
ProtocolTimestamps contains the four timestamps used by the NTP protocol to calculate clock offset and round-trip delay.
type QueryOptions ¶
type QueryOptions struct {
// Timeout determines how long the client waits for a response from the
// server before failing with a timeout error. Defaults to 5 seconds.
Timeout time.Duration
// Version of the NTP protocol to use. Defaults to 4. Allowed values
// include 3, 4, and 5.
//
// The IETF has not finalized version 5 of the NTP protocol, so version 5
// support is considered experimental and should not be used in
// production. This package currently supports only NTPv5 draft version
// "draft-ietf-ntp-ntpv5-09".
Version int
// LocalAddress contains the local IP address to use when creating a
// connection to the remote NTP server. This may be useful when the local
// system has more than one IP address. This address should not contain
// a port number.
LocalAddress string
// TTL specifies the maximum number of IP hops before the query datagram
// is dropped by the network. Defaults to the local system's default value.
TTL int
// Timescale is used to request timestamps from the server that are
// measured according to a specific timescale reference (UTC, TAI, UT1, or
// leap-smeared UTC). Defaults to TimescaleUTC. Used only in NTPv5.
Timescale Timescale
// AdditionalTimescales requests additional timestamps using the specified
// timescales, allowing the client to determine the offsets between the
// primary timescale (specified in the Timescale field) and each of the
// additional timescales. If the server supports this feature, offsets
// will be reported in the response's TimescaleOffsets field. Used only in
// NTPv5.
AdditionalTimescales []Timescale
// ServerCookie contains the server cookie returned by a prior server
// response when operating in interleaved mode. Used only in NTPv5.
ServerCookie uint64
// Auth contains the options used to configure symmetric key
// authentication. See RFC 5905 for further details. For NTPv3 and NTPv4,
// this results in a MAC or digest being appended to the end of the NTP
// message. For NTPv5, this results in a message authentication extension
// field being added to the NTP message. Defaults to no symmetric key
// authentication.
Auth AuthOptions
// Extensions may be provided in order to (a) modify NTP queries before
// they are transmitted and (b) process NTP responses after they arrive.
// When building an NTP request, these extensions are processed in the
// order listed. When processing a server response, they are processed in
// reverse order. An example of an extension is one that implements
// Network Time Security (NTS). See: https://github.com/beevik/nts.
Extensions []Extension
// GetSystemTime is a callback used to override the default method of
// obtaining the local system time during time synchronization. If not
// specified, the most precise system clock offered by the platform is
// used. Specifying this callback disables the use of kernel timestamps
// on platforms that would otherwise support them.
GetSystemTime func() time.Time
// RequestReferenceID is a struct used to request reference ID bloom
// filter values, which are returned in the ReferenceIDFilterValues field
// of the response. Used only in NTPv5.
RequestReferenceID ReferenceIDRequest
// RequestSupportedVersions indicates whether to request the versions of
// the NTP protocol supported by the server. When used with NTPv5, the
// response will list all supported versions. When used with NTPv3 or
// NTPv4, the response's ReferenceTime value will be invalid, and the
// supported version list will include the version used in the query as
// well as 5 if the server supports it.
RequestSupportedVersions bool
// RequestCorrection indicates whether to request delay corrections from
// network switches and routers along the path between the client and the
// server. If available, such delay corrections will be applied to the
// response's ClockOffset, making it more accurate. Used only in NTPv5.
RequestCorrection bool
// RequestReferenceTime indicates whether to request that the server
// include a reference timestamp in its response. Used only in NTPv5.
RequestReferenceTime bool
// RequestMonotonic indicates whether to request a second receive
// timestamp from the server using an independent monotonic clock without
// phase correction. This second timestamp is intended to be used by the
// client to reduce clock drift by adjusting the frequency of its local
// system clock. Used only in NTPv5.
RequestMonotonic bool
// RequestInterleavedMode indicates whether to use interleaved mode for
// the NTPv5 query. Used in conjunction with the ServerCookie field. Used
// only in NTPv5.
RequestInterleavedMode bool
// Dialer is a callback used to override the default UDP network dialer.
// The localAddress is directly copied from the LocalAddress field
// specified in QueryOptions. It may be the empty string or a host address
// (without port number). The remoteAddress is the "host:port" string
// derived from the first parameter to QueryWithOptions. The remoteAddress
// is guaranteed to include a port number.
Dialer func(localAddress, remoteAddress string) (net.Conn, error)
// DEPRECATED. Use Dialer instead.
Dial func(laddr string, lport int, raddr string, rport int) (net.Conn, error)
// DEPRECATED. Embed the port number in the query address string instead.
Port int
}
QueryOptions contains configurable options used by the QueryWithOptions function.
type ReferenceIDRequest ¶ added in v1.6.0
type ReferenceIDRequest struct {
// The octet offset of the reference ID filter chunk to request. Must be
// less than or equal to 512.
ChunkOffset uint16
// The number of octets in the requested reference ID filter chunk. The
// sum of ChunkOffset and ChunkSize must be less than or equal to 512.
ChunkSize uint16
}
The ReferenceIDRequest struct is included in QueryOptions to request a chunk of reference ID bloom filter values. Used only in NTPv5. See IETF draft-ietf-ntp-ntpv5 section 7.4 for futher details.
type Response ¶
type Response struct {
// ClockOffset is the estimated offset of the local system clock relative
// to the server's clock. Add this value to subsequent local system clock
// times in order to obtain a time that is synchronized to the server's
// clock.
ClockOffset time.Duration
// RTT is the measured round-trip-time delay estimate between the client
// and the server.
RTT time.Duration
// Timestamps contains the four NTP protocol timestamps used to calculate
// ClockOffset and RTT.
Timestamps ProtocolTimestamps
// Precision is the reported precision of the server's clock.
Precision time.Duration
// Version is the NTP protocol version number reported by the server.
// Supported values include 3, 4, and 5.
Version int
// Stratum is the "stratum level" of the server. The smaller the number,
// the closer the server is to the reference clock. Stratum 1 servers are
// attached directly to the reference clock. For NTPv3 and NTPv4, a
// stratum value of 0 indicates the "kiss of death," which typically
// occurs when the client issues too many requests to the server in a
// short period of time.
Stratum uint8
// Timescale reports the timescale used by the server to timestamp
// messages it sent and received. Always TimescaleUTC for NTPv3 and NTPv4.
Timescale Timescale
// TimescaleOffsets contains the time offsets of any requested additional
// timescales relative to the primary timescale. Used only in NTPv5.
TimescaleOffsets []TimescaleOffset
// Era is the NTP era number returned by the server. Era 0 spans
// 1900-2036, Era 1 spans 2036-2172, etc.
Era uint8
// ReferenceID is a 32-bit integer used to help identify which server or
// reference clock generated the reported time. For stratum 1 servers,
// this is typically a meaningful zero-padded ASCII-encoded string
// assigned to the clock. For stratum 2+ servers, this is a reference
// identifier for the server and is either the server's IPv4 address or a
// hash of its IPv6 address. For kiss-of-death responses (stratum 0), this
// is the ASCII-encoded "kiss code". Used only in NTPv3 and NTPv4.
ReferenceID uint32
// ReferenceIDFilterValues contains the requested chunk of reference ID
// bloom filter values. The size and offset of this chunk are determined
// by the ReferenceIDRequest field in QueryOptions. Used only in NTPv5.
ReferenceIDFilterValues []byte
// ReferenceTime is the time the server last updated its local clock. In
// NTPv3 and NTPv4, this value is always returned by the server. In NTPv5,
// it is returned only when requested via the RequestReferenceTime field
// in QueryOptions.
ReferenceTime time.Time
// MonotonicOffset contains the offset of the server's monotonic clock
// relative to its primary clock. It is calculated by taking the
// difference between the monotonic receive timestamp and the primary
// receive timestamp contained in the response packet. Returned only when
// requested via the RequestMonotonic field in QueryOptions. Used only in
// NTPv5.
MonotonicOffset time.Duration
// MonotonicEpochID is the an identifier associated with the
// MonotonicOffset value. Whenever this value changes, the server's
// monotonic clock has been phase-corrected, and any frequency adjustment
// algorithms running on the client must be reset. Returned only when
// requested via the RequestMonotonic field in QueryOptions. Used only in
// NTPv5.
MonotonicEpochID uint32
// Correction contains delay correction information provided by network
// switches and routers along the path between the client and the server.
// Populated only when supported by the network equipment along the path
// and when requested via the QueryOptions RequestCorrection field. Used
// only in NTPv5.
Correction Correction
// SupportedVersions contains an array of NTP protocol version numbers
// supported by the server. Populated if requested by the
// RequestSupportedVersions field in QueryOptions. Used only in NTPv5.
SupportedVersions []int
// RootDelay is the server's estimated aggregate round-trip-time delay to
// the stratum 1 server.
RootDelay time.Duration
// RootDispersion is the server's estimated maximum measurement error
// relative to the stratum 1 server.
RootDispersion time.Duration
// RootDistance is an estimate of the total synchronization distance
// between the client and the stratum 1 server.
RootDistance time.Duration
// Leap indicates whether a leap second should be added or removed from
// the current month's last minute.
Leap LeapIndicator
// MinError is a lower bound on the "causality violation" between the
// client and server clocks when they are not yet synchronized.
MinError time.Duration
// KissCode is a 4-character string describing the reason for a "kiss of
// death" response (stratum=0). Used only in NTPv3 and NTPv4. For a list
// of standard kiss codes, see:
// https://tools.ietf.org/html/rfc5905#section-7.4.
KissCode string
// Poll is the maximum interval between successive NTP query messages to
// the server.
Poll time.Duration
// Flags reported by the server.
Flags ResponseFlags
// ServerCookie is the cookie returned by an NTPv5 server. In interleaved
// mode, this cookie should be passed to the server in the next query.
// Used only in NTPv5.
ServerCookie uint64
// DEPRECATED. Use Timestamps.ServerXmit instead.
Time time.Time
// contains filtered or unexported fields
}
A Response contains time data, some of which is returned by the NTP server and some of which is calculated by the client.
func Query ¶
Query requests time data from a remote NTPv4 server. The response contains information from which a more accurate local time can be inferred.
The server address is of the form "host", "host:port", "host%zone:port", "[host]:port" or "[host%zone]:port". The host may contain an IPv4, IPv6 or domain name address. When specifying both a port and an IPv6 address, one of the bracket formats must be used. If no port is included, NTP default port 123 is used.
func QueryWithOptions ¶
func QueryWithOptions(remoteAddress string, opt QueryOptions) (*Response, error)
QueryWithOptions performs the same function as Query but allows for the customization of certain query behaviors. See the comments for Query and QueryOptions for further details.
func (*Response) IsKissOfDeath ¶ added in v1.2.0
IsKissOfDeath returns true if the response is a "kiss of death" from the remote server. If this function returns true, you may examine the response's KissCode value to determine the reason for the kiss of death. Valid only for NTPv3 and NTPv4.
func (*Response) Log ¶ added in v1.6.0
Log outputs a human-readable representation of the NTP response to the provided io.Writer. Meant for debugging purposes.
func (*Response) ReferenceString ¶ added in v1.3.0
ReferenceString returns the response's ReferenceID value formatted as a string. If the response's stratum is zero, then the "kiss o' death" string is returned. If stratum is one, then the server is a reference clock and the reference clock's name is returned. If stratum is two or greater, then the ID is either an IPv4 address or an MD5 hash of the IPv6 address; in either case the reference string is reported as 4 dot-separated decimal-based integers. Valid only for NTPv3 and NTPv4.
type ResponseFlags ¶ added in v1.6.0
type ResponseFlags uint32
ResponseFlags are flag bits reported by an NTPv5 server in its response.
const ( // FlagSynchronized indicates whether the server is currently synchronized // to a reference clock. For NTPv3 and NTPv4, this flag is set when the // returned stratum is valid. For NTPv5, it is set only when the server // explicitly indicates synchronization. FlagSynchronized ResponseFlags = 1 << iota // FlagInterleaved indicates whether the server reported its response in // interleaved mode. Only used in NTPv5. FlagInterleaved )
type Timescale ¶ added in v1.6.0
type Timescale uint8
Timescale represents the time reference system used by an NTPv5 server.
const ( // TimescaleUTC indicates Coordinated Universal Time (UTC) with leap // seconds. TimescaleUTC Timescale = 0 // TimescaleTAI indicates International Atomic Time. TimescaleTAI Timescale = 1 // TimescaleUT1 indicates Universal Time based on Earth's rotation. TimescaleUT1 Timescale = 2 // TimescaleUTCSmeared indicates UTC with time-smeared leap seconds. TimescaleUTCSmeared Timescale = 3 )
type TimescaleOffset ¶ added in v1.6.0
type TimescaleOffset struct {
// The Timescale to which this offset pertains.
Timescale Timescale
// The offset of the timescale relative to the request's primary
// timescale. This value may be added to the response's ClockOffset to
// obtain a time synchronized to the associated timescale.
Offset time.Duration
}
The TimescaleOffset struct contains a timescale identifier and its corresponding offset relative to the primary timescale specified in the QueryOptions Timescale field. Used only in NTPv5.