NTP WG                                                   J. Burbank, Ed.
Internet-Draft                                                   JHU/APL
Obsoletes: RFC 4330 (if approved)                         J. Martin, Ed.
Expires: September 2, 2006
Intended status: Standards Track                             Netzwert AG
Expires: April 26, 2007                                         D. Mills
                                                                 U. Del.

       The
                                                        October 23, 2006

   Network Time Protocol Version 4 Protocol Specification
                     draft-ietf-ntp-ntpv4-proto-02 Reference and Implementation Guide
                     draft-ietf-ntp-ntpv4-proto-03

Status of this Memo

   By submitting this Internet-Draft, each author represents that any
   applicable patent or other IPR claims of which he or she is aware
   have been or will be disclosed, and any of which he or she becomes
   aware will be disclosed, in accordance with Section 6 of BCP 79.

   Internet-Drafts are working documents of the Internet Engineering
   Task Force (IETF), its areas, and its working groups.  Note that
   other groups may also distribute working documents as Internet-
   Drafts.

   Internet-Drafts are draft documents valid for a maximum of six months
   and may be updated, replaced, or obsoleted by other documents at any
   time.  It is inappropriate to use Internet-Drafts as reference
   material or to cite them other than as "work in progress."

   The list of current Internet-Drafts can be accessed at
   http://www.ietf.org/ietf/1id-abstracts.txt.

   The list of Internet-Draft Shadow Directories can be accessed at
   http://www.ietf.org/shadow.html.

   This Internet-Draft will expire on September 2, 2006. April 26, 2007.

Copyright Notice

   Copyright (C) The Internet Society (2006).

Abstract

   The Network Time Protocol (NTP) is widely used to synchronize
   computer clocks in the Internet.  This memorandum describes Version 4
   of the NTP (NTPv4), introducing several changes from Version 3 of NTP
   (NTPv3) described in RFC 1305, including the introduction of a
   modified protocol header to accomodate Internet Protocol Version 6.

   NTPv4 also includes optional extensions to the NTPv3
   protocol,including a dynamic server discovery mechanism.

Table of Contents

   1.  Introduction  . . . . . . . . . . . . . . . . . . . . . . . . .   3
     1.1.  Requirements Notation . . . . . . . . . . . . . . . . . .   4
   2.  NTP Timestamp  . . .  Modes of Operation  . . . . . . . . . . . . . . . . . . . . .   4
   3.  NTP Message Formats  Definitions . . . . . . . . . . . . . . . . . . . . .  6
     3.1.  Leap Indicator (LI) . . . .   6
   4.  Implementation Model  . . . . . . . . . . . . . . .  7
     3.2.  Version (VN) . . . . .   9
   5.  Data Types  . . . . . . . . . . . . . . . . . .  8
     3.3.  Mode . . . . . . .  12
   6.  Data Structures . . . . . . . . . . . . . . . . . . . .  8
     3.4.  Stratum (Strat) . . .  15
     6.1.  Structure Conventions . . . . . . . . . . . . . . . . . .  9
     3.5.  Poll Interval (Poll)  16
     6.2.  Global Parameters . . . . . . . . . . . . . . . . . . .  9
     3.6.  Precision (Prec) .  16
     6.3.  Packet Header Variables . . . . . . . . . . . . . . . . .  18
       6.3.1.  The Kiss-o'-Death Packet  . . .  9
     3.7.  Root Delay . . . . . . . . . . .  22
       6.3.2.  NTP Extension Field Format  . . . . . . . . . . . . .  9
     3.8.  Root Dispersion  23
   7.  On Wire Protocol  . . . . . . . . . . . . . . . . . . . . . 10
     3.9.  Reference Identifier .  25
   8.  Peer Process  . . . . . . . . . . . . . . . . . . 10
     3.10. Reference Timestamp . . . . . .  29
     8.1.  Peer Process Variables  . . . . . . . . . . . . . 11
     3.11. Originate Timestamp . . . .  30
     8.2.  Peer Process Operations . . . . . . . . . . . . . . . 11
     3.12. Receive Timestamp . .  32
   9.  Clock Filter Algorithm  . . . . . . . . . . . . . . . . . . 11
     3.13. Transmit Timestamp .  39
   10. System Process  . . . . . . . . . . . . . . . . . . . 11
     3.14. NTPv4 Extension Fields . . . .  42
     10.1. System Process Variables  . . . . . . . . . . . . . . 12
     3.15. Authentication (optional) . .  42
     10.2. System Process Operations . . . . . . . . . . . . . . 13
   4.  NTP Protocol Operation . .  43
       10.2.1. Selection Algorithm . . . . . . . . . . . . . . . . .  44
       10.2.2. Clustering Algorithm  . 14
   5.  SNTP Protocol Operation . . . . . . . . . . . . . . .  46
       10.2.3. Combining Algorithm . . . . 17
   6.  NTP Server Operations . . . . . . . . . . . . .  48
       10.2.4. Clock Discipline Algorithm  . . . . . . . 18
   7.  NTP Client Operations . . . . . .  52
     10.3. Clock Adjust Process  . . . . . . . . . . . . . . . 20
   8.  NTP Symmetric Peer Operations . . .  60
   11. Poll Process  . . . . . . . . . . . . . 22
   9.  Dynamic Server Discovery . . . . . . . . . . .  61
     11.1. Poll Process Variables and Parameters . . . . . . . . 22
   10. The Kiss-o'-Death Packet . .  61
     11.2. Poll Process Operations . . . . . . . . . . . . . . . . . 23
   11.  62
   12. Security Considerations . . . . . . . . . . . . . . . . . . . 24
   12.  63
   13. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 25
   13.  63
   14. Acknowledgements  . . . . . . . . . . . . . . . . . . . . . . . 25
   14.  64
   15. References  . . . . . . . . . . . . . . . . . . . . . . . . . . 25
     14.1.  64
     15.1. Normative References  . . . . . . . . . . . . . . . . . . . 25
     14.2.  64
     15.2. Informative References  . . . . . . . . . . . . . . . . . . 25  64
   Appendix A.  NTP Control Messages  . . . . . . . . . . . . . . . . 27
     A.1.  NTP Control Message Format . . . . . . . . . . . . . . . . 28
     A.2.  Status Words . . . . . . . . . . .  Code Skeleton  . . . . . . . . . . . . 30
       A.2.1.  System Status Word . . . . . . .  65
     A.1.  Global Definitions  . . . . . . . . . . . 31
       A.2.2.  Peer Status Word . . . . . . . .  65
     A.2.  Definitions, Constants, Parameters  . . . . . . . . . . . 33
       A.2.3.  Clock Status Word  65
     A.3.  Packet Data Structures  . . . . . . . . . . . . . . . . .  69
   Authors' Addresses  . 34
       A.2.4.  Error Status Word . . . . . . . . . . . . . . . . . . 35
     A.3.  Commands . . . . 109
   Intellectual Property and Copyright Statements  . . . . . . . . . . . . . . . . . . . . . 36
   Authors' Addresses . . . . . . . . . . . . . . . . . . . . . . . . 39
   Intellectual Property and Copyright Statements . . . . . . . . . . 40 110

1.  Introduction

   The

   This document is a reference and implementation guide for the Network
   Time Protocol Version 3 (NTPv3) [1] has been 4 (NTPv4), which is widely used to synchronize computer clocks in the global Internet.  It provides
   comprehensive mechanisms to access national time and frequency
   dissemination services, organize the NTP subnet of servers and
   clients and adjust
   the system clock in each participant.  In most
   places on the Internet of today, NTP provides accuracies of 1-50 ms,
   depending on the characteristics of the synchronization source and
   network paths.

   NTP is designed for use by clients and servers with clocks among a wide range set of
   capabilities.  Thus, the Simple Network Time Protocol Version 4
   (SNTPv4) as described in [2] was developed for platforms that cannot
   afford the size distributed time servers and complexity of NTP as a whole.

   Since the standardization of NTPv3, there has been significant
   development which has led to Version 4 of
   clients.  This document defines the Network Time Protocol
   (NTPv4). core architecture, protocol,
   state machines, data structures and algorithms.  This document
   describes NTPv4, which introduces new functionality to NTPv3 as
   described in RFC 1305, [1], and functionality expanded from that of SNTPv4 as
   described in RFC 4330 [2] (SNTPv4 is a subset of NTPv4).  This document
   obsoletes RFC 1305 and RFC 4330.

   When operating with current  While certain minor changes have
   been made in some protocol header fields, these do not affect the
   interoperability between NTPv4 and previous versions of versions.

   The NTP and SNTP,
   NTPv4 requires no changes to the protocol or implementations now
   running subnet model includes a number of widely accessible primary
   time servers synchronized by wire or likely radio to be implemented specifically for future NTP or
   SNTP versions. national standards.
   The purpose of the NTP protocol is to convey timekeeping information
   from these primary servers to secondary time servers and SNTP packet formats are the same clients via
   both private networks and the
   arithmetic operations to calculate the client time, clock offset public Internet.  Crafted algorithms
   mitigate errors that may result from network disruptions, server
   failures and
   round trip delay are the same.  To a NTP or SNTP server, NTP possible hostile action.  Servers and SNTP clients are indistinguishable; to a NTP or SNTP client, NTP and SNTP
   configured such that values flow from the primary servers are indistinguishable.

   An important provision in this memo is at the interpretation of certain
   NTP header fields which provide for IPv6 [3]and OSI [4] addressing. root
   via branching secondary servers toward clients.

   The only NTPv4 design overcomes significant difference between shortcomings in the NTPv3
   design, corrects certain bugs and NTPv4 header
   formats is incorporates new features.  In
   particular, expanded NTP timestamp definitions encourage the four-octet Reference Identifier field, use of
   floating double data types throughout any implementation.  The time
   resolution is better than one nanosecond and frequency resolution
   better than one nanosecond per second.  Additional improvements
   include a new clock discipline algorithm which is used
   primarily more responsive to detect and avoid synchronization loops.  In all NTP and
   SNTP versions providing IPv4 addressing,
   system clock hardware frequency fluctuations.  Typical primary
   servers use using modern machines are precise within a four-
   character ASCII reference clock identifier in this field, while few tens of
   microseconds.  Typical secondary servers use the 32-bit IPv4 address of the synchronization
   source.  In NTPv4 providing IPv6 and OSI addressing, primary servers
   use clients on fast LANs are
   within a few hundred microseconds with poll intervals up to 1024
   seconds, which was the same clock identifier, but secondary maximum with NTPv3.  With NTPv4, servers use the first 32
   bits of the MD5 hash of the IPv6 or NSAP address and
   clients are within a few tens of the
   synchronization source.  A further use milliseconds with poll intervals up
   to 36 hours.

   The main body of this field document describes only the core protocol and
   data structures necessary to interoperate between conforming
   implementations.  Additional detail is when provided in the
   server sends form of a kiss-o'-death message documented later in this
   document.

   In
   skeleton program included as an appendix.  This program includes data
   structures and code segments for the case of OSI, core algorithms and in addition
   the Connectionless Transport Service (CLTS) is mitigation algorithms used as to enhance reliability and accuracy.
   While the skeleton and other descriptions in [5].  Each NTP packet is transmitted this document apply to a
   particular implementation, they are not intended as the TS- Userdata
   parameter of a T-UNITDATA Request primitive.  Alternately, only way the header
   required functions can be encapsulated implemented.  While the NTPv3 symmetric key
   authentication scheme described in a TPDU which itself this document carries over from
   NTPv3, the Autokey public key authentication scheme new to NTPv4 is transported using UDP,
   as
   described in [6].  It is not advised that [3].

   The NTP be operated at protocol includes the
   upper layers modes of the OSI stack, such as might be inferred from [7], as
   this could seriously degrade accuracy.  With the header formats
   defined in this memo, it is, operation described in principle, possible to interwork
   between servers and clients of one protocol family and another,
   although the practical difficulties may make this inadvisable.

   This document is organized as follows. Section
   2 describes using the NTP
   timestamp format and data types described in Section 3 5 and the NTP message format. data structures
   in Section 6.  The implementation model described in Section 4
   provides general NTP is
   based on a multiple-process, threaded architecture, although other
   architectures could be used as well.  The on-wire protocol details, with the subset SNTP described
   in Section 5.  This 7 is followed by specific sections based on Server
   (Section 6), Client(Section 7), a returnable-time design which depends only
   on measured clock offsets, but does not require reliable message
   delivery.  The synchronization subnet is a self-organizing,
   hierarchical, master-slave network with synchronization paths
   determined by a shortest-path spanning tree and Symmetric Peer(Section 8) modes
   of operation.  Section 9 defines the new mechanism defined metric.
   While multiple masters (primary servers) may exist, there is no
   requirement for server
   discovery. describes an election protocol.

   The remaining sections of this document define the control data structures
   and management mechanism algorithms suitable for NTP.
   Section 10 describes the kiss-o'-death message, whose functionality
   is similar to the ICMP Source Quench and ICMP Destination Unreachable
   messages.  Section 11 presents a fully featured NTPv4 security considerations and
   Section 12 discusses IANA Considerations.Appendix implementation.
   Appendix A presents optional
   NTP control messages.

   NTPv4 is hereafter referred contains the code skeleton with definitions, structures
   and code segments that represent the basic structure of the reference
   implementation.

   The remainder of this document contains numerous variables and
   mathematical expressions.  Those variables take the form of Greek
   characters.  Those Greek characters are spelled out by their full
   name, with the "cap" prefix added to simply as NTP, unless explicitly
   noted. variables referring to the
   corresponding upper case Greek character.  For example capdelta
   refers to the uppercase Greek character, where delta refers to the
   lowercase Greek character.  Furthermore, subscripts are denoted with
   a '_' separating the variable name and the subscript.  For example
   'theta_i' refers to the variable lowercase Greek character theta with
   subscript i, or phonetically 'theta sub i.'

1.1.  Requirements Notation

   The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
   "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this
   document are to be interpreted as described in RFC 2119 [8]. [4].

2.  Modes of Operation

   An NTP Timestamp

   There are three NTP formats used implementation operates as a primary server, secondary server
   or client.  A primary server is synchronized directly to represent time values: a 128-bit
   date format, reference
   clock, such as a 64-bit timestamp format, GPS receiver or telephone modem service.  A client
   is synchronized to one or more upstream servers, but does not provide
   synchronization to dependent clients.  A secondary server has one or
   more upstream servers and a 32-bit short format.
   NTP data are specified as integer one or fixed-point quantities, with
   bits numbered in big-endian fashion from 0 starting at the left more downstream servers or
   most significant end.  Unless specified otherwise, all quantities are
   unsigned clients.
   All servers and may occupy the clients claiming full field width with an implied 0
   preceding bit 0.  Note that dates cannot be produced by NTP, but can
   rather be obtained from external means and conveyed via NTPv4 compliance must implement
   the protocol.
   Date values are represented entire suite of algorithms described in twos compliment arithmetic relative this document.  In order
   to
   the base date maintain stability in large NTP subnets, secondary servers must be
   fully NTPv4 compliant.

   Primary servers and clients complying with a subset of 0628:16h 7 February 2036 UTC (when all 128 bits are
   zero).  Values greater than zero represent times after the base date;
   values less than zero represent times before NTP, called
   the base date.  Dates
   are signed values.  Timestamps are signed values.  A value of zero Simple Network Time Protocol (SNTPv4) [2], do not need to
   implement all algorithms.  SNTP is intended for primary servers
   equipped with a special case representing unknown single reference clock, as well as clients with a
   single upstream server and no dependent clients.  The fully developed
   NTPv4 implementation is intended for secondary servers with multiple
   upstream servers and multiple downstream servers or unsynchronized time.

   Figure 1 illustrates the three clients.  Other
   than these considerations, NTP time formats.

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ and SNTP servers and clients are
   completely interoperable and can be mixed and matched in NTP subnets.

            +-------------------+--------------+-------------+
            |          Seconds  Association Mode |           Fraction Assoc.  Mode |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                            NTP Short Format

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Packet Mode |                            Seconds
            +-------------------+--------------+-------------+
            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+  Symmetric Active |                            Fraction       1      |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                          NTP Timestamp Format

    0 1 or 2                   3
    0 1      |
            | Symmetric Passive |       2 3 4 5 6 7 8 9 0      | 1 2           |
            |       Client      |       3      | 4 5 6 7 8 9 0 1 2 3           |
            |       Server      |       4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+      |                           Era Number 3           |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
            |                           Era Offset  Broadcast Server |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+       5      | 5           |
            |                           Fraction  Broadcast Client |       6      | N/A         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                           NTP Date Format

   Figure
            +-------------------+--------------+-------------+

                   Table 1: Association and Packet Modes

   There are three NTP Timestamp Format

   Note that, since some time protocol variants, symmetric, client/server and
   broadcast.  Each is associated with an association mode as shown in 1968 (second 2,147,483,648)
   Table 1.  In the most
   significant bit (bit 0 of client/server variant a client association sends
   mode-3 (client) packets to a server, which returns mode-4 (server)
   packets.  Servers provide synchronization to one or more clients, but
   do not accept synchronization from them.  A server can also be a
   reference clock which obtains time directly from a standard source
   such as a GPS receiver or telephone modem service.  We say that
   clients pull synchronization from servers.

   In the integer part) has been set symmetric variant a peer operates as both a server and that client
   using either a symmetric-active or symmetric-passive association.  A
   symmetric-active association sends mode-1 (symmetric-active) packets
   to a symmetric-active peer association.  Alternatively, a symmetric-
   passive association can be mobilized upon arrival of a mode-1 packet.
   That association sends mode-2 (symmetric-passive) packets and
   persists until error or timeout.  Peers both push and pull
   synchronization to and from each other.  For the
   64-bit field will overflow some time in 2036 (second 4,294,967,296).
   There will exist purposes of this
   document, a 232-picosecond interval, henceforth ignored, every
   136 years when peer operates like a client, so a reference to client
   implies peer as well.

   In the 64-bit field will be 0, broadcast variant a broadcast server association sends
   periodic mode-5 (broadcast) packets which are received by convention multiple
   mode-6 (broadcast client) associations.  It is
   interpreted as useful to provide an invalid or unavailable timestamp.

   If bit 0 is set,
   initial volley where the UTC time is client operating in mode 3 exchanges several
   packets with the range 1968-2036 and UTC time
   is reckoned from 0h 0m 0s UTC on 1 January 1900.  If bit 0 is not
   set, the time is server in order to calibrate the range 2036-2104 propagation delay
   and UTC time is calculated
   from 6h 28m 16s UTC on 7 February 2036.  Note to run the Autokey security protocol, after which the client
   reverts to mode 6.  We say that when calculating broadcast servers push
   synchronization to willing consumers.

   Following conventions established by the telephone industry, the
   level of each server in the correspondence, 2000 hierarchy is defined by a leap year and leap seconds are not
   included in number called
   the reckoning.

3.  NTP Message Formats

   Both NTP stratum, with the primary servers assigned stratum one and SNTP are layered above the User Datagram Protocol (UDP)
   [9], which itself is layered on
   secondary servers at each level assigned one greater than the Internet Protocol (IP) [10] [3].
   The structure of
   preceding level.  As the IP stratum increases from one, the accuracies
   achievable degrade somewhat depending on the particular network path
   and UDP headers system clock stability.  It is described useful to assume that mean errors,
   and thus a metric called the synchronization distance, increase
   approximately in proportion to the cited
   specification documents stratum and will not be detailed further here.  The
   UDP port number assigned measured roundtrip
   delay.  It is important to note that NTP stratum is 123, which MUST be used in both
   the Source Port only loosely
   modeled after telecommunications stratum.  The NTP stratum numbers
   and Destination Port fields in telecommunications stratum numbers do not correlate with one
   another.  Telecommunications stratum numbers are rigorously defined
   by international standards that are not covered within this document.

   Drawing from the UDP header.  The
   remaining UDP header fields experience of the telephone industry, which learned
   such lessons at considerable cost, the subnet topology should be set as described in
   organized to produce the
   specification.

   Figure 2 provides lowest synchronization distances, but must
   never be allowed to form a description of loop.  In NTP the NTPv4 message format.  This
   format subnet topology is identical to that described in RFC 1305, with the exception
   determined using a variant of the contents Bellman-Ford distributed routing
   algorithm, which computes the shortest-distance spanning tree rooted
   on the primary servers.  As a result of this design, the reference identifier field algorithm
   automatically reorganizes the subnet to produce the most accurate and optional
   extension fields.  The header fields are defined in Figure 2.

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |LI | VN  |Mode |     Strat     |     Poll      |     Prec      |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Root Delay                            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Root Dispersion                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Reference ID                         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                       Reference Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Origin Timestamp                       +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Receive Timestamp                      +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Transmit Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field 1 (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field 2 (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                          Authentication                       .
   .                       (Optional) (160 bits)                   .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

   Figure 2: NTPv4 Message Format

3.1.  Leap Indicator (LI)

   This
   reliable time, even when one or more primary or secondary servers or
   the network paths.

3.  Definitions

   A number of terms used throughout this document have a precise
   technical definition.  A timescale is a two-bit field indicating an impending leap second to be
   inserted in the NTP timescale.  The bits are set before 23:59 on the
   day frame of insertion and reset after 00:00 on the following day.  This
   causes reference where time
   is expressed as the value of a monotonic-increasing binary counter
   with an indefinite number of bits.  It counts in seconds (rollover interval) and fraction
   with the decimal point somewhere in the day of
   insertion to be increased or decreased middle.  The Coordinated
   Universal Time (UTC) timescale represents mean solar time as
   disseminated by one.  A leap second national standards laboratories.  The system time is
   inserted or deleted in
   represented by the timescale on system clock maintained by the last day of June or
   December. operating system
   kernel.  The possible values goal of the LI field, NTP algorithms is to minimize both the time
   difference and frequency difference between UTC and corresponding
   meanings, are given in Table 1.

            +----+--------------------------------------------+
            | LI |                   Meaning                  |
            +----+--------------------------------------------+
            |  0 |                 no warning                 |
            |  1 |    last minute of the day has 61 seconds   |
            |  2 |    last minute of system clock.
   When these differences have been reduced below nominal tolerances,
   the day has 59 seconds   |
            |  3 | alarm condition (clock never synchronized) |
            +----+--------------------------------------------+

                  Table 1: Length Indicator Field Values

   On startup, servers set this field to 3 (clock not synchronized) and
   set this field system clock is said to some other value when be synchronized to UTC.

   The date of an event is the primary
   reference clock.  Once set to other than 3, the field UTC time at which it takes place.  Dates
   are ephemeral values which always increase in step with reality and
   are designated with upper case T in this document.  It is never set convenient
   to define another timescale coincident with the running time of the
   NTP program that value again, even if all provides the synchronization sources become
   unreachable or defective.

3.2.  Version (VN) function.  This is a three-bit integer indicating the NTP/SNTP version number,
   set
   convenient in order to 4 determine intervals for NTPv4.  If necessary to distinguish between IPv4, IPv6
   and OSI, the encapsulating context must various repetitive
   functions like poll events.  Running time is usually designated with
   lower case t.

   A timestamp T(t) represents either the UTC date or time offset from
   UTC at running time t.  Which meaning is intended should be inspected.

3.3.  Mode

   This clear
   from the context.  Let T(t) be the time offset, R(t) the frequency
   offset, D(t) the ageing rate (first derivative of R(t) with respect
   to t).  Then, if T(t_0) is a three-bit number indicating the protocol mode.  The values
   are defined UTC time offset determined at t=t_0,
   the UTC time offset after some interval is:

   T(t+t_0) = T(t_0) + R(t_0)(t+t_0)+(1/2)*D(t_0)(t+t_0)^2 + e,

   where e is a stochastic error term discussed later in Table 2.

                    +------+--------------------------+
                    | Mode |          Meaning         |
                    +------+--------------------------+
                    |   0  |         reserved         |
                    |   1  |     symmetric active     |
                    |   2  |     symmetric passive    |
                    |   3  |          client          |
                    |   4  |          server          |
                    |   5  |         broadcast        |
                    |   6  |    NTP control message   |
                    |   7  | reserved for private use |
                    +------+--------------------------+

                        Table 2: Mode Field Values
   Mode 0 this document.
   While the D(t) term is reserved.  Modes 1 and 2 are intended important when characterizing precision
   oscillators, it is ordinarily neglected for use by symmetric
   peers who set computer oscillators.  In
   this mode document all time values are in seconds (s) and all frequency
   values are in seconds-per-second (s/s).  It is sometimes convenient
   to express frequency offsets in parts-per-million (PPM), where 1 or 2 depending on whether it PPM
   is active
   or passive mode.  In unicast mode or discovery mode, equal to 1*10^(-6) seconds.

   It is important in computer timekeeping applications to assess the
   performance of the timekeeping function.  The NTP performance model
   includes four statistics which are updated each time a client sets
   this field makes a
   measurement with a server.  The offset theta represents the maximum
   likelihood time offset of the server clock relative to 3 (client) in the request system
   clock.  The delay del represents the roundtrip delay between the
   client and server.  The dispersion epsilon represents the server sets it maximum
   error inherent in the measurement.  It increases at a rate equal to 4
   (server)
   the maximum disciplined system clock frequency tolerance phi,
   typically 15 PPM.  The jitter varphi, defined as the root-mean-square
   (RMS) average of the most recent time offset differences, represents
   the nominal error in estimating theta.

   While the reply.  In broadcast mode, theta, del, epsilon, and psi statistics represent
   measurements of the system clock relative to the each server sets this field clock
   separately, the NTP protocol includes mechanisms to 5 (broadcast).  A mode type combine the
   statistics of 6 is reserved several servers to more accurately discipline and
   calibrate the system clock.  The system offset captheta represents
   the maximum-likelihood offset estimate for NTP control
   messages.  Mode 7 is reserved for private usage.

3.4.  Stratum (Strat)

   This is a eight-bit unsigned integer indicating the stratum.  This
   field is significant only in SNTP server messages, where population.
   The system jitter vartheta represents the values nominal error in estimating
   captheta.  The del and epsilon statistics are defined accumulated at each
   stratum level from the reference clocks to produce the root delay
   delta and root dispersion E statistics.  The synchronization distance
   gamma=E+delta/2 represents the maximum error due all causes.  The
   detailed formulations of these statistics are given later in Table 3.

    +---------+-------------------------------------------------------+ this
   document.  They are available to the dependent applications in order
   to assess the performance of the synchronization function.

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |LI | Stratum VN  |Mode |                        Meaning     Strat     |
    +---------+-------------------------------------------------------+     Poll      |    0     Prec      |                 kiss-o'-death message
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Root Delay                            |    1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   | primary reference (e.g., synchronized by radio clock)                         Root Dispersion                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Reference ID                         |  2-255
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |   secondary reference (synchronized by NTP or SNTP)                                                               |
    +---------+-------------------------------------------------------+

                       Table 3: Stratum
   +                       Reference Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Origin Timestamp                       +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Receive Timestamp                      +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Transmit Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field Values

3.5.  Poll Interval (Poll)

   This is an eight-bit unsigned integer indicating the maximum interval
   between successive messages, in log2 seconds.  A client SHOULD NOT
   use a poll interval less than 15 seconds, except at initial startup
   when it MAY send a sequence of 8 packets at 1 second intervals to
   provide initial synchronization of the clients with each server.  A
   client SHOULD increase the poll interval as performance permits (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field 2 (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                          Authentication                       .
   .                       (Optional) (160 bits)                   .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                      Figure 1: NTPv4 Message Format

4.  Implementation Model

   Figure 1 shows two processes dedicated to each server, a peer process
   to receive messages from the server or reference clock and
   especially if a poll
   process to transmit messages to the server does not respond within or reference clock. .

   ..........................................................
   . Remote   ..   Peer/Poll   ..              System       .
   . Servers  ..   Processes   ..              Process      .
   .          ..               ..                           .
   .----------..-------------..--------------               .
   .|        |->|           |..|            |               .
   .|Server 1|..|Peer/Poll 1|->|            |               .
   .|        |<-|           |..|            |               ............
   .----------..-------------..|            |               .   Clock  .
                                                            .Discipline.
   .          ..       ^     ..|            |               .. Process .
   .          ..       |     ..|            |               ..         .
   .----------..-------------..|            |  |-----------|..         .
   .|        |->|           |..| Selection  |->|            ..-------- .
   .|Server 2|..|Peer/Poll 2|->|    and     |  | Combining |->| Loop | .
   .|        |<-|           |..| Clustering |  | Algorithm |..|Filter| .
   .----------..-------------..| Algorithms |->|           |.-----------
   .          ..       ^     ..|            |  |-----------|.     |
   .          ..       |     ..|            |               .     |
   .----------..-------------..|            |               .     |
   .|        |->|           |..|            |               .     |
   .|Server 3|..|Peer/Poll 3|->|            |               .     |
   .|        |<-|           |..|            |               .     |
   .----------..-------------..|------------|               .     |
   ....................^.....................................     |
                       |                                          |
                       |                                         \|/
                       |                                ...............
                       |                                .   /-----\   .
                       '----------------------------------<-| VFO |-<-.
                                                        .   \-----/   .
                                                        . Clock Adjust.
                                                        .   Process   .
                                                        ...............

                    Figure 1 NTPv4 Algorithm Interactions

                  Figure 2: NTPv4 Algorithm Interactions

   These processes operate on a reasonable time.

3.6.  Precision (Prec)

   This is common data structure called an eight-bit signed integer indicating
   association, which contains the precision of statistics described above along with
   various other data described later.  A client sends an NTP packet to
   one or more servers and processes the
   system clock replies as received.  The
   server interchanges addresses and ports, overwrites certain fields in log2 seconds.  Precision is normally determined when
   the service packet and returns it immediately (client/ server mode) or at
   some time later (symmetric modes).  As each NTP message is established as received,
   the minimum number of iterations of offset theta between the
   time to read peer clock and the system clock.  As an example, a value of -18
   corresponds to a precision of about one microsecond.

3.7.  Root Delay

   This clock is a 32-bit signed fixed-point number indicating the total
   roundtrip delay to
   computed along with the primary reference source, in 32-bit NTP short
   format.  Note that this variable can take on both positive associated statistics del, epsilon, and
   negative values, depending on
   varphi.

   The system process includes the relative time selection, clustering and frequency
   offsets.  This field is significant only in server messages, where combining
   algorithms which mitigate among the values range from negative values of a few milliseconds various servers and reference
   clocks to
   positive values of several hundred milliseconds.

3.8.  Root Dispersion

   This is a 32-bit unsigned fixed-point number indicating determine the nominal
   error relative most accurate and reliable candidates to
   synchronize the primary reference source in seconds, in 32-bit
   NTP short format.

3.9.  Reference Identifier

   This is a 32-bit bitstring identifying the particular reference
   source. system clock.  The interpretation of this field depends on selection algorithm uses Byzantine
   principles to remote the value in falsetickers from the
   stratum field.  For stratum 0, this incident population,
   leaving only truechimers.  A 'truechimer' is a four-character ASCII string,
   referred clock that maintains
   timekeeping accuracy to as a 'kiss code' and is used for debugging and monitoring
   purposes.  For stratum 1, this is previously published (and trusted)
   standard, while a four-octet, left-justified, zero-
   padded ASCII string assigned to the reference source.  Above stratum
   1 (secondary servers and clients), this 'falseticker' is the reference identifier a clock that does not maintain
   that level of timekeeping accuracy.  The clustering algorithm uses
   statistical principles to sift the server.  If employing IPv4, most accurate truechimers leaving
   the value is survivors as result.  The combining algorithm develops the 32-bit IPv4
   address final
   clock offset as a statistical average of the synchronization source.  For IPv6 and OSI, the value survivors.

   The clock discipline process, which is the first 32 bits actually part of the MD5 hash of system
   process, includes engineered algorithms to control the IPv6 or NSAP address time and
   frequency of the synchronization source.  The fASCII identifiers that are
   currently defined are given in Table 4.

   Primary (stratum 1) servers set this field to system clock, here represented as a code identifying variable
   frequency oscillator (VFO).  Timestamps struck from the
   external reference source according to Table 4.

      +-------+----------------------------------------------------+
      | Code  | External Reference Source                          |
      +-------+----------------------------------------------------+
      | GOES  | Geosynchronous Orbit Environment Satellite         |
      | GPS   | Global Position System                             |
      | PPS   | Generic pulse-per-second                           |
      | IRIG  | Inter-Range Instrumentation Group                  |
      | WWVB  | LF Radio WWVB Ft.  Collins, CO 60 kHz              |
      | DCF77 | LF Radio DCF77 Mainflingen, DE 77.5 kHz            |
      | HBG   | LF Radio HBG Prangins, HB 75 kHz                   |
      | MSF   | LF Radio MSF Rugby, UK 60 kHz                      |
      | JJY   | LF Radio JJY Fukushima, JP 40 kHz, Saga, JP 60 kHz |
      | LORC  | MF Radio LORAN C 100 kHz                           |
      | TDF   | MF Radio Allouis, FR 162 kHz                       |
      | CHU   | HF Radio CHU Ottawa, Ontario                       |
      | WWV   | HF Radio WWV Ft.  Collins, CO                      |
      | WWVH  | HF Radio WWVH Kauai, HI                            |
      | NIST  | NIST telephone modem                               |
      | USNO  | USNO telephone modem                               |
      | PTB   | European telephone modem                           |
      +-------+----------------------------------------------------+

             Table 4: Currently-defined Reference Identifiers

   If the external reference is one of those listed, the associated code
   should be used.  Codes for sources not listed can be created as
   appropriate (see IANA Considerations section of this document).

3.10.  Reference Timestamp

   This is a 64 bit signed integer indicating VFO close the time when
   feedback loop which maintains the system clock was last set or correctetd, in 64-bit NTP timestamp format.

3.11.  Originate Timestamp

   This time.  Associated with
   the clock discipline process is the time at clock adjust process, which runs
   once each second to inject a computed time offset and maintain
   constant frequency.  The RMS average of past time offset differences
   represents the request departed the client for nominal error or system jitter vartheta.  The RMS
   average of past frequency offset differences represents the
   server, in 64-bit NTP timestamp format.

3.12.  Receive Timestamp

   This
   oscillator frequency stability or frequency wander cappsi.

   A client sends messages to each server with a poll interval of 2^tau
   seconds, as determined by the poll exponent tau.  In NTPv4 tau ranges
   from 4 (16 s) through 17 (36 h).  The value of tau is determined by
   the time at which clock discipline algorithm to match the request arrived loop time constant T_c =
   2^tau.  A server responds with messages at an update interval of mu
   seconds.  For stateless servers, mu = T_c, since the server or responds
   immediately.  However, in symmetric modes each of two peers manages
   the
   reply arrived at time constant as a function of current system offset and system
   jitter, so may not agree with the client, same tau.  It is important that the
   dynamic behavior of the clock discipline algorithms be carefully
   controlled in 64-bit order to maintain stability in the NTP timestamp format.

3.13.  Transmit Timestamp subnet at large.
   This requires that the peers agree on a common tau equal to the
   minimum poll exponent of both peers.  The NTP protocol includes
   provisions to properly negotiate this value.

   While not shown in the figure, the implementation model includes some
   means to set and adjust the system clock.  The operating system is
   assumed to provide two functions, one to set the time at which directly, for
   example the request departed Unix settimeofday() function, and another to adjust the client
   time in small increments advancing or retarding the
   reply departed time by a
   designated amount, for example the server, in 64-bit NTP timestamp format.

3.14.  NTPv4 Extension Fields

   NTPv4 defines new extension field formats.  The minimum extension
   field length Unix adjtime()1 function
   (parentheses following a name indicate reference to a function rather
   than a simple variable).  In the intended design the clock discipline
   process uses the adjtime() function if the adjustment is 8 octets. less than a
   designated threshold, and the settimeofday() function if above the
   threshold.  The format manner in which this is done and the value of the NTP extension field
   threshold is
   given in Figure Figure 3.

    0                   1                   2 described later.

5.  Data Types

   All NTP time values are represented in twos-complement format, with
   bits numbered in big-endian (as described in Appendix A of [5])
   fashion from zero starting at the left, or high-order, position.
   There are three NTP time formats, a 128-bit date format, a 64-bit
   timestamp format and a 32-bit short format, as shown in Figure 3.
   The 128-bit date format is used where sufficient storage and word
   size are available.  It includes a 64-bit signed seconds field
   spanning 584 billion years and a 64-bit fraction field resolving .05
   attosecond (i.e. 0.5e-18).  For convenience in mapping between
   formats, the seconds field is divided into a 32-bit era field and a
   32-bit timestamp field.  Eras cannot be produced by NTP directly, nor
   is there need to do so.  When necessary, they can be derived from
   external means, such as the filesystem or dedicated hardware.

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |          Field Type          Seconds              |            Length           Fraction            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                            NTP Short Format

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Association ID                            Seconds                            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                           Timestamp                            Fraction                           |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                          NTP Timestamp Format

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                           Filestamp                           Era Number                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Value Length                           Era Offset                          |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                             Value                             .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                        Signature Length                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                           Signature                           .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                       Padding (as needed)                           Fraction                            |
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
                           NTP Date Format

                         Figure 3: NTP Extension Field Time Format

   The Field Type field 64-bit timestamp format is used in packet headers and other
   places with limited word size.  It includes a 16-bit integer which indicates the type of
   extension message contained within the extension field.

   The Length 32-bit unsigned seconds
   field is spanning 136 years and a 16-bit integer indicates the length of the
   entire extension 32-bit fraction field in octets, including the Length and Padding
   fields. resolving 232
   picoseconds.  The 32-bit Association ID field short format is set by clients to the value
   previously received from used in delay and dispersion
   header fields where the server or 0 otherwise.  The server sets full resolution and range of the Association ID field when sending other
   formats are not justified.  It includes a response as 16-bit unsigned seconds
   field and a handle for
   subsequent exchanges.  If 16-bit fraction field.

   In the association ID value in a request does
   not match date format the association ID prime epoch, or base date of any association, the server returns
   the request with the first two era 0, is 0 h 1
   January 1900 UTC, when all bits are zero.  It should be noted that
   strictly speaking, UTC did not exist prior to 1 January 1972, but it
   is convenient to assume it has existed for all eternity, even if all
   knowledge of the Field Type field set historic leap seconds has been lost.  Dates are relative
   to 1.

   The Timestamp the prime epoch; values greater than zero represent times after
   that date; values less than zero represent times before it.

   Timestamps are unsigned values and Filestamp 32-bit fields carry operations on them produce a
   result in the seconds field of
   an NTP timestamp.  The Timestamp field establishes same or adjacent eras.  Era 0 includes dates from the signature
   prime epoch of the data field to some time in 2036, when the message, while the filestamp
   establishes the generation epoch of timestamp field wraps
   around and the file that ultimately produced
   the data.

   The 32-bit Value Length field indicates the length of the Value field
   in octets.  The minimum length of the Value field base date for era 1 is 0.

   The 32-bit Signature Length field indicates the length established.  In either format
   a value of the
   Signature field in octets.

   Zero padding zero is applied, as necessary, to extend the extension field
   to a word (4-octet) boundary.  If multiple extension fields are
   present, the last extension field is zero-padded to special case representing unknown or
   unsynchronized time.  Figure 4 shows a double-word (8
   octet) boundary.

3.15.  Authentication (optional)

   NTPv4 provides an optional 160-bit Authentication field.  When
   implemented, the 32-bit Key Identifier and 128-bit Message Digest
   fields contain the Message Authentication Code (MAC) information
   which uses an MD5 cryptosum number of historic NTP header plus extension fields.  The
   authentication field format is shown in Figure Figure 4.
   0 dates
   together with their corresponding Modified Julian Day (MJD), NTP era
   and NTP timestamp.
   Year         MJD         NTP Era NTP Timestamp  Epoch
   1 Jan -4712  -2,400,001  -49     1,795,583,104  1st day Julian
   1 Jan -1     -679,306    -14     139,775,744    2                   3 BCE
   1 Jan 0      -678,491    -14     171,311,744    1 2 3 BCE
   1 Jan 1      -678,575    -14     202,939,144    1 CE
   4 5 6 7 8 9 Oct 1582   -100,851    -3      2,873,647,488  Last day Julian
   15 Oct 1582  -100,840    -3      2,874,597,888  1st day Gregorian
   31 Dec 1899  15019       -1      4,294,880,896  Last d NTPEra-1
   1 Jan 1900   15020       0       0              First d NTPEra0
   1 2 3 4 5 6 7 8 9 Jan 1970   40,587      0       2,208,988,800  First day UNIX
   1 2 3 4 5 6 7 8 9 Jan 1972   41,317      0       2,272,060,800  First day UTC
   31 Dec 1999  51,543      0       3,155,587,200  Last d 20th Cent
   8 Feb 2036   64,731      1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Key Identifier                        |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                                                               +
   |                                                               |
   +                         Message Digest                        +
   |                                                               |
   +                                                               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+       63,104         1st day NTPEra1

                 Figure 4: Interesting Historic NTP Authentication Field Dates

   Let p be the number of significant bits in the second fraction.  The 32-bit Key Identifier
   clock resolution is defined 2p, in seconds.  In order to minimize
   bias and help make timestamps unpredictable to an integer identifying intruder, the 128-bit
   private key used non-
   significant bits should be set to generate the MAC. an unbiased random bit string.  The Message Digest field
   contains
   clock precision is defined as the MD5 Message Digest.  In NTPv4, running time to read the presence of one system
   clock, in seconds.  Note that the precision defined in this way can
   be larger or
   more extension fields requires smaller than the presence of an authentication
   field. resolution.  The presence of term rho, representing
   the Authentication field and extension fields precision used in this document, is determined from the Length field. larger of the two.

   The Key Identifier only operation permitted with dates and timestamps is initialized to zero at twos-
   complement subtraction, yielding a 127-bit or 63-bit signed result.
   It is critical that the start of an
   association.  The type of association then determines first-order differences between two dates
   preserve the key
   identifier.  If full 128-bit precision and the association is active (modes 1, 3, 5) first-order differences
   between two timestamps preserve the key is
   determined from full 64-bit precision.  However,
   the system key identifier.  If differences are ordinarily small compared to the association seconds span, so
   they can be converted to floating double format for further
   processing and without compromising the precision.

   It is
   passive (modes 2, 4) important to note that twos-complement arithmetic does not know
   the key difference between signed and unsigned values; only the
   conditional branch instructions.  Thus, although the distinction is determined from
   made between signed dates and unsigned timestamps, they are processed
   the peer key
   identifier, same way.  A perceived hazard with 64-bit timestamp calculations
   spanning an era, such as possible in 2036, might result in incorrect
   values.  In point of fact, if the authentic bit client is set (see [1]), or as within 68 years of
   the server before the default
   key (zero) otherwise.

4.  NTP Protocol Operation

   The NTP protocol defines three operational roles, Client, Server, is started, correct values are
   obtained even if the client and
   Symmetric Peer.  Clients request or receive time from Servers
   (solicited or unsolicited).  Servers respond to requests or send
   periodic server are in adjacent eras.

   Some time updates to Clients.  Symmetric Peers exchange values are represented in exponent format, including the
   precision, time data
   bidirectionally.  A given NTPv4 implementation can operate constant and poll interval values.  These are in any or
   all of these modes.

   NTP messages make use of two different communication modes, one to
   one and one to many, commonly referred
   8-bit signed integer format in log2 (log to as unicast the base 2) seconds.

   The only operations permitted on them are increment and broadcast. decrement.
   For the purposes purpose of this document, document and to simplify the term broadcast is interpreted presentation, a
   reference to mean any available one to many mechanism.  For IPv4 this equates
   to either IPv4 broadcast or IPv4 multicast.  For IPv6 this equates to
   IPv6 multicast.  For this purpose, IANA has allocated of these state variables by name means the IPv4
   multicast address 224.0.1.1 and
   exponentiated value, e.g., the IPv6 multicast address ending
   :101, with prefix determined poll interval is 1024 s, while
   reference by scoping rules.

   Except name and exponent means the actual value, e.g., the poll
   exponent is 10.

   To convert system time in broadcast mode, an any format to NTP association is formed when two peers
   exchange messages and one or both of them create date and maintain an
   instantiation timestamp
   formats requires that the number of seconds s from the protocol machine, called an association. prime epoch to
   the system time be determined.  The
   association can operate in one of five modes as indicated by era is the
   host- mode variable (peer.mode) (see [1] integer quotient and
   the timestamp the integer remainder as in:

   era = s / 2^(32) and timestamp = s - era*2^(32)

   which works for a description positive and negative dates.  To convert from NTP era
   and timestamp to system time requires the calculation

   s = era*2^(32) + timestamp

   to determine the number of seconds since the prime epoch.  Converting
   between NTP
   variables): symmetric active, symmetric passive, client, server and
   broadcast, which are defined as follows:

   Symmetric Active (1): A host operating in this mode sends periodic
   messages regardless of system time can be a little messy, but beyond the reachability state or stratum
   scope of its peer.
   By operating in this mode document.  Note that the host announces its willingness to
   synchronize and be synchronized by the peer.

   Symmetric Passive (2): This type number of association days in era 0 is ordinarily created
   upon arrival one
   more than the number of a message from a peer operating days in the symmetric
   active mode most other eras and persists only as long as this won't happen
   again until the peer is reachable and
   operating at a stratum level less than or equal year 2400 in era 3.

   In the description of state variables to follow, explicit reference
   to integer type implies a 32-bit unsigned integer.  This simplifies
   bounds checks, since only the host;
   otherwise, upper limit needs to be defined.
   Without explicit reference, the association default type is dissolved.  However, the association 64-bit floating
   double.  Exceptions will always persist until at least one message has been sent be noted as necessary.

6.  Data Structures

   The NTP protocol state machines described in
   reply.  By operating following sections are
   defined using state variables and flow chart fragments.  State
   variables are separated into classes according to their function in this mode
   packet headers, peer and poll processes, the host announces its willingness
   to synchronize system process and be synchronized by the peer.

   Client (3): A host operating
   clock discipline process.  Packet variables represent the NTP header
   values in this mode sends periodic messages
   regardless transmitted and received packets.  Peer and poll variables
   represent the contents of the reachability association for each server separately.
   System variables represent the state or stratum of its peer.  By
   operating in this mode the host announces server as seen by its willingness to be
   synchronized by, but not to synchronize
   dependent clients.  Clock discipline variables represent the peer.

   Server (4): This type of association is ordinarily created upon
   arrival internal
   workings of a client request message the clock discipline algorithm.  Additional constant and exists only
   variable classes are defined in Appendix A..

6.1.  Structure Conventions

   In order to reply
   to that request, after which distinguish between different variables of the association is dissolved.  By
   operating same name
   but used in this mode different processes, the host announces its willingness to
   synchronize, but not to be synchronized by the peer.

   Broadcast (5): A host operating in this mode sends periodic messages
   regardless of the reachability state or stratum of the peers.  By
   operating naming convention summarized in this mode the host announces its willingness to
   synchronize all
   Table 2 is employed.  A receive packet variable v is a member of the peers, but not to be synchronized by any of
   them.

   NTP messages are layered on top of UDP.  All messages MUST be sent
   packet structure r with fully qualified name r.v.  In a destination port of 123, similar
   manner x.v is a transmit packet variable, p.v is a peer variable, s.v
   is a system variable and SHOULD be sent with c.v is a source port clock discipline variable.  There
   is a set of 123.

   The on-wire protocol uses four timestamps numbered T1 through T4 and
   three state peer variables org, rec, for each association; there is only one
   set of system and xmt, as shown in Figure Figure 5,
   where T1 corresponds to clock variables.  Most flow chart fragments begin
   with a statement label and end with a named go-to or exit.  A
   subroutine call includes a dummy () following the Reference Timestamp T2 corresponds to name and return at
   the
   Originate Timestamp, T3 corresponds to end.to the Receive Timestamp, and T4
   corresponds to point following the Transmit Timestamp.

              t2            t3           t6            t7
         +---------+   +---------+   +---------+   +---------+
     T1  |    0    |   |    t2   |   |   t4    |   |    t6   |
         +---------+   +---------+   +---------+   +---------+
     T2  |    0    |   |    t1   |   |   t3    |   |    t5   |  Packet
         +---------+   +---------+   +---------+   +---------+ Variables
     T3  |t2=clock |   |    t2 call.

                +------+---------------------------------+
                |   |t6=clock Name | Description                     |    t6
                +------+---------------------------------+
                |
         +---------+   +---------+   +---------+   +---------+
     T4 r.   |   t1 receive packet header variable  |   |t3=clock
                | x.   |   t5 transmit packet header variable |   |t7=clock
                |
         +---------+   +---------+   +---------+   +---------+
                                                                Peer B
         +---------+   +---------+   +---------+   +---------+
    org p.   |   t1 peer/poll variable              |
                |    t1 s.   | system variable                 | T3<>t1?
                | c.   |    t5 clock discipline variable       |
         +---------+   +---------+   +---------+   +---------+   State
                +------+---------------------------------+

                     Table 2: Name Prefix Conventions

6.2.  Global Parameters

   In addition to the variable classes a number of global parameters are
   defined in this document, including those shown with values in
   Figure 5
   Name      Value       Description
   PORT      123         NTP port number
   VERSION   4           version number
   TOLERANCE 15e-6       frequency tolerance  (s/s)
   MINPOLL   4           minimum poll exponent (16 s)
   MAXPOLL   17          maximum poll exponent (36 h)
   MAXDISP   16          maximum dispersion (s)
   MINDISP   .005        minimum dispersion increment (s)
   MAXDIST   1           distance threshold (s)
   MAXSTRAT  16          maximum stratum number

                        Figure 5: Global Parameters

   .  While these are the only parameters needed in this document, a
   larger collection is necessary in the skeleton and larger still for
   any implementation.  Section B.1 contains those used by the skeleton
   for the mitigation algorithms, clock discipline algorithm and related
   implementation-dependent functions.  Some of these parameter values
   are cast in stone, like the NTP port number assigned by the IANA and
   the version number assigned NTPv4 itself.  Others like the frequency
   tolerance, involve an assumption about the worst case behavior of a
   system clock once synchronized and then allowed to drift when its
   sources have become unreachable.  The minimum and maximum parameters
   define the limits of state variables as described in later sections.

   While shown with fixed values in this document, some implementations
   may make them variables adjustable by configuration commands.  For
   instance, the reference implementation computes the value of
   PRECISION as log2 of the minimum time in several iterations to read
   the system clock.

   Name       Formula Description
   leap       leap    leap indicator (LI)
   version    version version number (VN)
   mode       mode    mode
   stratum    stratum stratum
   poll       poll    poll exponent
   precision rho     precision exponent
   rootdelay  delta   root delay
   rootdisp   E       root dispersion
   refid     refid    reference ID
   reftime   reftime  reference timestamp
   org       T1       origin timestamp
   rec       T2       receive timestamp
   xmt       T3       transmit timestamp
   dst       T4       destination timestamp
   keyid     keyid    key ID
   digest    digest   message digest

                     Figure 6: Packet Header Variables

6.3.  Packet Header Variables

   The most important state variables from an external point of view are
   the packet header variables described below.  The NTP packet consists
   of a number of 32-bit (4 octet) words in network byte order.  The
   packet format consists of three components, the header itself, one or
   more optional extension fields and an optional message authentication
   code (MAC).  The header component is identical to the NTPv3 header
   and previous versions.  The optional extension fields are used by the
   Autokey public key cryptographic algorithms described in [3].  The
   optional MAC is used by both Autokey and the symmetric key
   cryptographic algorithms described in the main body of this report.

   The NTP packet header follows the UDP and IP headers and the physical
   header specific to the underlying transport network.  It consists of
   a number of 32-bit (4-octet) words, although some fields use multiple
   words and others are packed in smaller fields within a word.  The NTP
   packet header shown in Appendix A has 12 words followed by optional
   extension fields and finally an optional message authentication code
   (MAC) consisting of the key identifier and message digest fields.

   The optional extension fields described in this section are used by
   the Autokey security protocol [3], which is not described here.  The
   MAC is used by both Autokey and the symmetric key authentication
   scheme described in Appendix A.  As is the convention in other
   Internet protocols, all fields are in network byte order, commonly
   called big-endian.

   A list of the packet header variables is shown in Figure 6 and
   described in detail below.  The packet header fields apply to both
   transmitted (x prefix) and received packets (r prefix).  The NTP
   header is shown in Figure 7

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |LI | VN  |Mode |     Strat     |     Poll      |     Prec      |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Root Delay                            |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                         Root Dispersion                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Reference ID                         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                       Reference Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Origin Timestamp                       +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Receive Timestamp                      +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                        Transmit Timestamp                     +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field 1 (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                                                               |
   +                    Extension Field 2 (Optional)               +
   |                                                               |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                          Authentication                       .
   .                       (Optional) (160 bits)                   .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                      Figure 7: NTPv4 Message Format
   , where the size of some multiple-word fields is shown in bits if not
   the default 32 bits.  The header extends from the beginning of the
   packet to the end of the Transmit Timestamp field.  The
   interpretation of the header fields is shown in the main body of this
   report.  When using the IPv4 address family these fields are
   backwards compatible with NTPv3.  When using the IPv6 address family
   on an NTPv4 server with a NTPv3 client, the Reference Identifier
   field appears to be a random value and a timing loop might not be
   detected.  The message authentication code (MAC) consists of a 32-bit
   Key Identifier followed by a 128bit Message Digest.  The message
   digest, or cryptosum, is calculated as in [6] over all header and
   optional extension fields.

   The variables are interpreted as follows:
   leap:  2-bit integer warning of an impending leap second to be
   inserted or deleted in the last minute of the current month,
   coded as follows:

       0 no warning
       1 last minute of the day has 61 seconds
       2 last minute of the day has 59 seconds
       3 alarm condition (the clock is not synchronized)

   version:
    3-bit integer representing the NTP version number, currently 4.

   mode:  3-bit integer representing the mode, with values defined
   as follows:

        0 reserved
        1 symmetric active
        2 symmetric passive
        3 client
        4 server
        5 broadcast
        6 NTP control message
        7 reserved for private use

   stratum:   8-bit integer representing the stratum, with values
   defined as follows:

        0 unspecified or invalid
        1 primary server (e.g., equipped with a GPS receiver)
        2-15 secondary server (via NTP)
        16 client-only
        17-255 undefined

   It is customary to map the stratum value 0 in received packets to
   MAXSTRAT (16) in the peer variable p.stratum and to map
   p.stratum values of MAXSTRAT or greater to 0 in transmitted
   packets. This allows reference clocks, which normally appear at
   stratum 0, to be conveniently mitigated using the same algorithms
   used for external sources.

   poll: 8-bit signed integer representing the maximum interval
   between successive messages, in log2 seconds. Suggested default
   limits for minimum and maximum poll intervals are 6 and 10, '
   respectively.

   precision:  8-bit signed integer representing the precision of
   the system clock, in log2 seconds. For instance a value of -18
   corresponds to a precision of about one microsecond. The
   precision can be determined when the service first starts up as
   the minimum time of several iterations to read the system clock.

   rootdelay:  Total roundtrip delay to the reference clock, in NTP
   short format.

   rootdisp:  Total dispersion to the reference clock, in NTP short
   format.

   refid:  32-bit code identifying the particular server or
   referenceclock. The interpretation depends on the value in the
   stratum field.  For packet stratum 0 (unspecified or invalid)
   this is a four-character ASCII string, called the kiss code,
   used for debugging and monitoring purposes. For stratum 1
   (reference clock) this is a four-octet, left-justified,
   zero-padded ASCII string assigned to the radio clock. While not
   specifically enumerated in this document, the following have
   been used as ASCII identifiers:

        GOES Geosynchronous Orbit Environment Satellite
        GPS Global Position System
        PPS Generic pulse-per-second
        IRIG Inter-Range Instrumentation Group
        WWVB LF Radio WWVB Ft. Collins, CO 60 kHz
        DCF LF Radio DCF77 Mainflingen, DE 77.5 kHz
        HBG LF Radio HBG Prangins, HB 75 kHz
        MSF LF Radio MSF Rugby, UK 60 kHz
        JJY LF Radio JJY Fukushima, JP 40 kHz, Saga, JP 60 kHz
        LORC MF Radio LORAN C 100 kHz
        TDF MF Radio Allouis, FR 162 kHz
        CHU HF Radio CHU Ottawa, Ontario
        WWV HF Radio WWV Ft. Collins, CO
        WWVH HF Radio WWVH Kaui, HI
        NIST NIST telephone modem
        USNO USNO telephone modem
        PTB etc. European telephone modem

   Above stratum 1 (secondary servers and clients) this is the
   reference identifier of the server. If using the IPv4 address
   family, the identifier is the four-octet IPv4 address. If using
   the IPv6 address family, it is the first four octets of the MD5
   hash of the IPv6 address.

   reftime: Time when the system clock was last set or corrected,
   in NTP timestamp format.

   org:  Time at the client when the request departed for the
   server, in NTP timestamp format.

   rec:  Time at the server when the request arrived from the
   client, in NTP timestamp format.

   xmt:  Time at the server when the response left for the
   client, in NTP timestamp format.

   dst:  Time at the client when the reply arrived from the
   server, in NTP timestamp format. Note: This value is not
   included in a header field; it is determined upon arrival
   of the packet and made available in the packet buffer data
   structure.

   keyid: 32-bit unsigned integer used by the client and server to
   designate a secret 128-bit MD5 key. Together, the keyid and
   digest fields collectively are called message authentication
   code (MAC).

   digest: 128-bit bitstring computed by the keyed MD5 message
   digest algorithm described in Appendix A.

6.3.1.  The Kiss-o'-Death Packet

   If the Stratum field is 0, which is an 'unspecified' Stratum field
   value, the Reference Identifier field can be used to convey messages
   useful for status reporting and access control.  In NTPv4 and SNTPv4,
   packets of this kind are called Kiss-o'-Death (KoD) packets and the
   ASCII messages they convey are called kiss codes.  The KoD packets
   got their name because an early use was to tell clients to stop
   sending packets that violate server access controls.  The kiss codes
   can provide useful information for an intelligent client.  These
   codes are encoded in four-character ASCII strings left justified and
   zero filled.  The strings are designed for character displays and log
   files.  A list of the currently-defined kiss codes is given below:

   +------+------------------------------------------------------------+
   | Code |                           Meaning                          |
   +------+------------------------------------------------------------+
   | ACST |         The association belongs to a unicast server        |
   | AUTH |                Server authentication failed                |
   | AUTO |                   Autokey sequence failed                  |
   | BCST |        The association belongs to a broadcast server       |
   | CRYP |    Cryptographic authentication or identification failed   |
   | DENY |               Access denied by remote server               |
   | DROP |                 Lost peer in symmetric mode                |
   | RSTR |              Access denied due to local policy             |
   | INIT |   The association has not yet synchronized for the first   |
   |      |                            time                            |
   | MCST | The association belongs to a dynamically discovered server |
   | NKEY |   No key found.  Either the key was never installed or is  |
   |      |                         not trusted                        |
   | RATE |  Rate exceeded.  The server has temporarily denied access  |
   |      |       because the client exceeded the rate threshold       |
   | RMOT |    Alteration of association from a remote host running    |
   |      |                           ntpdc.                           |
   | STEP |     A step change in system time has occurred, but the     |
   |      |           association has not yet resynchronized           |
   +------+------------------------------------------------------------+

                Figure 9: Currently-defined NTP Kiss Codes

6.3.2.  NTP Extension Field Format

   In NTPv4 one or more extension fields can be inserted after the
   header and before the MAC, which is always present when extension
   fields are present.  The extension fields can occur in any order;
   however, in some cases there is a preferred order which improves the
   protocol efficiency.

   An extension field contains a request or response message in the
   format shown in Figure 10
    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |          Field Type           |            Length             |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Association ID                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                           Timestamp                           |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                           Filestamp                           |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                          Value Length                         |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                             Value                             .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                        Signature Length                       |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   .                                                               .
   .                           Signature                           .
   .                                                               .
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
   |                       Padding (as needed)                     |
   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

                   Figure 10: NTP Extension Field Format

   .  All extension fields are zero-padded to a word (4 octets)
   boundary.  The Length field covers the entire extension field,
   including the Length and Padding fields.  While the minimum field
   length is 4 words (16 octets), a maximum field length remains to be
   established.

   The RE, VN, and Code fields together form a Field Type field, a 16-
   bit integer which indicates the type of extension message contained
   within the extension field.

   The Length field is a 16-bit integer indicates the length of the
   entire extension field in octets, including the Length and Padding
   fields.

   The 32-bit Association ID field is set by clients to the value
   previously received from the server or 0 otherwise.  The server sets
   the Association ID field when sending a response as a handle for
   subsequent exchanges.  If the association ID value in a request does
   not match the association ID of any association, the server returns
   the request with the first two bits of the Field Type field set to 1.

   The Timestamp and Filestamp 32-bit fields carry the seconds field of
   an NTP timestamp.  The Timestamp field establishes the signature
   epoch of the data field in the message, while the filestamp
   establishes the generation epoch of the file that ultimately produced
   the data.

   The 32-bit Value Length field indicates the length of the Value field
   in octets.  The minimum length of the Value field is 0.

   The 32-bit Value Length field indicates the length of the Value field
   in octets.  The minimum length of the Value field is 0.

   Zero padding is applied, as necessary, to extend the extension field
   to a word (4-octet) boundary.  If multiple extension fields are
   present, the last extension field is zero-padded to a double-word (8
   octet) boundary.

   The presence of the MAC and extension fields in the packet is
   determined from the length of the remaining area after the header to
   the end of the packet.  The parser initializes a pointer just after
   the header.  If the Length field is not a multiple of 4, a format
   error has occurred and the packet is discarded.  The following cases
   are possible based on the remaining length in words.
   0        The packet is not authenticated.
   1        The packet is an error report or crypto-NAK.
   2, 3, 4  The packet is discarded with a format error.
   5        The remainder of the packet is the MAC.
   >5       One or more extension fields are present.

   If an extension field is present, the parser examines the Length
   field.  If the length is less than 4 or not a multiple of 4, a format
   error has occurred and the packet is discarded; otherwise, the parser
   increments the pointer by this value.  The parser now uses the same
   rules as above to determine whether a MAC is present and/or another
   extension field.  An additional implementation dependent test is
   necessary to ensure the pointer does not stray outside the buffer
   space occupied by the packet.

7.  On Wire Protocol
              t2            t3           t6            t7
         +---------+   +---------+   +---------+   +---------+
     T1  |    0    |   |    t2   |   |   t4    |   |    t6   |
         +---------+   +---------+   +---------+   +---------+
     T2  |    0    |   |    t1   |   |   t3    |   |    t5   |  Packet
         +---------+   +---------+   +---------+   +---------+ Variables
     T3  |t2=clock |   |    t2   |   |t6=clock |   |    t6   |
         +---------+   +---------+   +---------+   +---------+
     T4  |   t1    |   |t3=clock |   |   t5    |   |t7=clock |
         +---------+   +---------+   +---------+   +---------+
                                                                Peer B
         +---------+   +---------+   +---------+   +---------+
    org  |   t1    |   |    t1   |   | T3<>t1? |   |    t5   |
         +---------+   +---------+   +---------+   +---------+   State
    rec  |   t2    |   |    t2   |   |   t6    |   |    t6   | Variables
         +---------+   +---------+   +---------+   +---------+
    xmt  |    0    |   |    t3   |   | T1<>t3? |   |    t7   |
         +---------+   +---------+   +---------+   +---------+

                   t2      t3                 t6          t7
         ---------------------------------------------------------
                  /\         \                 /\            \
                  /           \                /              \
                 /             \              /                \
                /               \/           /                 \/
         ---------------------------------------------------------
              t1                t4         t5                  t8

             t1            t4            t5             t8
         +---------+   +---------+   +---------+   +---------+
     T1  |    0    |   |    t2   |   |   t4    |   |    t6   |
         +---------+   +---------+   +---------+   +---------+
     T2  |    0    |   |    t1   |   |   t3    |   |    t5   |  Packet
         +---------+   +---------+   +---------+   +---------+ Variables
     T3  |    0    |   |t4=clock |   |   t4    |   |t8=clock |
         +---------+   +---------+   +---------+   +---------+
     T4  |t1=clock |   |    t3   |   |t5=clock |   |    t7   |
         +---------+   +---------+   +---------+   +---------+
                                                                Peer A
         +---------+   +---------+   +---------+   +---------+
    org  |    0    |   |  T3<>0? |   |   t3    |   | T3<>t3? |
         +---------+   +---------+   +---------+   +---------+   State
    rec  |    0    |   |    t4   |   |   t4    |   |    t8   | Variables
         +---------+   +---------+   +---------+   +---------+
    xmt  |   t1    |   |  T1=t1? |   |   t5    |   | T1<>t5? |
         +---------+   +---------+   +---------+   +---------+

                        Figure 12: On-Wire Protocol
   The NTP on-wire protocol is the core mechanism to exchange time
   values between servers, peers and clients.  It is inherently
   resistant to lost or duplicate data packets.  Data integrity is
   provided by the IP and UDP checksums.  No flow-control or
   retransmission facilities are provided or necessary.  The protocol
   uses timestamps, either extracted from packet headers or struck from
   the system clock upon the arrival or departure of a packet.
   Timestamps are precision data and should be restruck in case of link
   level retransmission and corrected for the time to compute a MAC on
   transmit.

   NTP messages make use of two different communication modes, one to
   one and one to many, commonly referred to as unicast and broadcast.
   For the purposes of this document, the term broadcast is interpreted
   to mean any available one to many mechanism.  For IPv4 this equates
   to either IPv4 broadcast or IPv4 multicast.  For IPv6 this equates to
   IPv6 multicast.  For this purpose, IANA has allocated the IPv4
   multicast address 224.0.1.1 and the IPv6 multicast address ending
   :101, with prefix determined by scoping rules.

   The on-wire protocol uses four timestamps numbered T_1 through T_4
   and three state variables org, rec and xmt, as shown in Figure 12.
   This figure shows the most general case where each of two peers, A
   and B, independently measure the offset and delay relative to the
   other.  For purposes of illustration the individual timestamp values
   are shown in lower case with subscripts indicating the order of
   transmission and reception.

   In the figure the first packet transmitted by A containing only the
   transmit timestamp T3 with value t1.  B receives the packet at t2 and
   saves the origin timestamp T1 with value t1 in state variable org and
   the destination timestamp T4 with value t2 in state variable rec.  At
   this time or some time later B sends a packet to A containing the org
   and rec state variables in T1 and T2, respectively and in addition
   the transmit timestamp T3 with value t3, which is saved in the xmt
   state variable.  When this packet arrives at A the packet header
   variables T1, T2, T3 and destination timestamp T4 represent the four
   timestamps necessary to compute the offset and delay of B relative to
   A, as described later.

   Before the A state variables are updated, two sanity checks are
   performed in order to protect against duplicate or bogus packets.  A
   packet is a duplicate if the transmit timestamp T3 in the packet
   matches the xmt state variable.  A packet is bogus if the origin
   timestamp T1 in the packet does not match the org state variable.  In
   either of these cases the state variables are updated, but the packet
   is discarded.

   The four most recent timestamps, T1 through T4, are used to compute
   the offset of B relative to A

   theta = T(B) - T(A) = 1/2*(T_2-T_1)+(T_3-T_4)

   and the roundtrip delay

   del = T(ABA)- = (T_4-T_1)-(T_3-T_2)

   Note that the quantities within parentheses are computed from 64-bit
   unsigned timestamps and result in signed values with 63 significant
   bits plus sign.  These values can represent dates from 68 years in
   the past to 68 years in the future.  However, the offset and delay
   are computed as the sum and difference of these values, which contain
   62 significant bits and two sign bits, so can represent unambiguous
   values from 34 years in the past to 34 years in the future.  In other
   words, the time of the client must be set within 34 years of the
   server before the service is started.  This is a fundamental
   limitation with 64-bit integer arithmetic..

   In implementations where floating double arithmetic is available, the
   first-order differences can be converted to floating double and the
   second-order sums and differences computed in that arithmetic.  Since
   the second-order terms are typically very small relative to the
   timestamps themselves, there is no loss in significance, yet the
   unambiguous range is increased from 34 years to 68 years.

   In some scenarios where the frequency offset between the client and
   server is relatively large and the actual propagation time small, it
   is possible that the delay computation becomes negative.  For
   instance, if the frequency difference is 100 PPM and the interval T_4
   - T_1 is 64 s, the apparent delay is -6.4 ms.  Since negative values
   are misleading in subsequent computations, the value of del should be
   clamped not less than the system precision s.precision rho defined
   below.

   The discussion above assumes the most general case where two
   symmetric peers independently measure the offsets and delays between
   them.  In the case of a stateless server, the protocol can be
   simplified.  A stateless server copies T_3 and T_4 from the client
   packet to T_1 and T_2 of the server packet and tacks on the transmit
   timestamp T_3 before sending it to the client.  Additional details
   for filling in the remaining protocol fields are given in the next
   section and in Appendix A.

   A SNTP primary server implementing the on-wire protocol has no
   upstream servers except a single reference clock In principle, it is
   indistinguishable from an NTP primary server which has the mitigation
   algorithms, presumably to mitigate between multiple reference clocks.
   Upon receiving a client request, a SNTP primary server constructs and
   sends the reply packet as shown in Figure 5 below.  Note that the
   dispersion field in the packet header must be calculated in the same
   way as in the NTP case.

   A SNTP client using the on-wire protocol has a single server and no
   downstream clients.  It can operate with any subset of the NTP on-
   wire protocol, the simplest using only the transmit timestamp of the
   server packet and ignoring all other fields.  However, the additional
   complexity to implement the full on-wire protocol is minimal and is
   encouraged.

8.  Peer Process

   The peer process is called upon arrival of a server packet.  It runs
   the on-wire protocol to determine the clock offset and roundtrip
   delay and in addition computes statistics used by the system and poll
   processes.  Peer variables are instantiated in the association data
   structure when the structure is initialized and updated by arriving
   packets.  There is a peer process, poll process and association for
   each server.

   The discussion in this section covers only the variables and routines
   necessary for a conforming NTPv4 implementation.  Additional
   implementation details are in Section B.5.

8.1.  Peer Process Variables
   Name       Formula       Description
   Configuration Variables
   srcaddr    srcaddr       source address
   srcport    srcport       source port
   dstaddr    dstaddr       destination address
   dstport    destport      destination port
   keyid      keyid         key identifier key ID
   Packet Variables
   leap       leap          leap indicator
   version    version       version number
   mode       mode          mode
   stratum    stratum       stratum
   ppoll      ppoll         peer poll exponent
   rootdelay  delta         root delay
   rootdisp   E             root dispersion
   refid     refid          reference ID
   reftime   reftime        reference timestamp
   Timestamp Variables
   t         t              epoch
   org       T1             origin timestamp
   rec       T2             receive timestamp
   xmt       T3             transmit timestamp
   Statistics Variables
   offset    theta          clock offset
   delay     del            roundtrip delay
   disp      epsilon        dispersion
   jitter    varphi         jitter

                     Figure 13: Peer Process Variables

   Figure 13 summarizes the common names, formula names and a short
   description of each peer variable, all of which have prefix p.  The
   following configuration variables are normally initialized when the
   association is mobilized, either from a configuration file or upon
   arrival of the first packet for an ephemeral association.

   p.srcadr: IP address of the remote server or reference clock.  This
   becomes the destination IP address in packets sent from this
   association.

   p.srcport: UDP port number of the server or reference clock.  This
   becomes the destination port number in packets sent from this
   association.  When operating in symmetric modes (1 and 2) this field
   must contain the NTP port number PORT (123) assigned by the IANA.  In
   other modes it can contain any number consistent with local policy.

   p.dstadr: IP address of the client.  This becomes the source IP
   address in packets sent from this association.

   p.dstport: UDP port number of the client, ordinarily the NTP port
   number PORT (123) assigned by the IANA.  This becomes the source port
   number in packets sent from this association.

   p.keyid: Symmetric key ID for the 128-bit MD5 key used to generate
   and verify the MAC.  The client and server or peer can use different
   values, but they must map to the same key.

   The variables defined below are updated from the packet header as
   each packet arrives.  They are interpreted in the same way as the as
   the packet variables of the same names.
   ------------------
   |    receive     |
   ------------------
          \| /
   ------------------ no------------------
   |    format OK?  |-->| format error   |
   ------------------   ------------------
          \| /  yes
   ------------------ no------------------
   |    access OK?  |-->| access error   |
   ------------------   ------------------
          \| /  yes
   ------------------yes------------------
   |    mode = 3?   |-->| client_packet  |
   ------------------   ------------------
          \| /  no
   ------------------yes------------------
   |    auth OK?    |-->| auth error     |
   ------------------   ------------------
          \| /  yes
   ------------------
   |    match_assoc |
   ------------------

                       Figure 14: Receive Processing

   p.leap, p.version, p.mode, p.stratum, p.ppoll, p.rootdelay,
   p.rootdisp, p.refid, p.reftime

   It is convenient for later processing to convert the NTP short format
   packet values p.rootdelay and p.rootdisp to floating doubles as peer
   variables.

   The p.org, p.rec, p.xmt variables represent the timestamps computed
   by the on-wire protocol described previously.  The p.offset, p.delay,
   p.disp, p.jitter variables represent the current time values and
   statistics produced by the clock filter algorithm.  The offset and
   delay are computed by the on-wire protocol; the dispersion and jitter
   are calculated as described below.  Strictly speaking, the epoch p.t
   is not a timestamp; it records the system timer upon arrival of the
   latest packet selected by the clock filter algorithm.

8.2.  Peer Process Operations

   Figure 14 shows the peer process code flow upon the arrival of a
   packet.  There is no specific method required for access control,
   although it is recommended that implementations include a match-and-
   mask scheme similar to many others now in widespread use.  Format
   checks require correct field length and alignment, acceptable version
   number (1-4) and correct extension field syntax, if present.  There
   is no specific requirement for authentication; however, if
   authentication is implemented, the symmetric key scheme described in
   Section 6 must be included among the supported.  This scheme uses the
   MD5 keyed hash algorithm Section A.2.  For the most vulnerable
   applications the Autokey public key scheme described in [3] is
   recommended.

   Next, the association table is searched for matching source address
   and source port using the find_assoc() routine in Section A.5.  The
   dispatch table near the beginning of that section is indexed by the
   packet mode and association mode (0 if no matching association) to
   determine the dispatch code and thus the case target.  The
   significant cases are FXMT, NEWPS and NEWBC.
   -----------------
   | client_packet |
   -----------------
         \ | /
   -----------------
   | copy header   |
   -----------------
         \ | /
   -----------------
   | copy T_1,T_2  |
   -----------------
         \ | /
   -----------------
   | T_3 = clock   |
   -----------------
         \ | /
   -----------------yes-----------------
   | copy header   |-->| MD5 digest    |-\
   -----------------   ----------------- |
           | no                          |
         \ | /                           |
   -----------------                     |
   | NAK digest    |                     |
   -----------------                     |
           |-----------------------------/
         \ | /
   -----------------
   | fast_xmit()   |
   -----------------
         \ | /
   -----------------
   | xmt = T_3     |
   -----------------
         \ | /
   -----------------
   | return        |
   -----------------

   Packet Variable <-- Variable
   x.leap <-- s.leap
   x.version <-- r.version
   x.mode <-- 4
   x.stratum <-- s.stratum
   x.poll <-- r.poll
   x.precision <-- s.precision
   x.rootdelay <-- s.rootdelay
   x.rootdisp <-- s.rootdisp
   x.refid <-- s.refid
   x.reftime <-- s.reftime
   x.org <-- r.xmt
   x.rec <-- r.dst
   x.xmt <-- clock
   x.keyid <-- r.keyid
   x.digest <-- md5 digest

                    Figure 15: Client Packet Processing

   FXMIT.  This is a client (mode 3) packet matching no association.
   The server constructs a server (mode 4) packet and returns it to the
   client without retaining state.  The server packet is constructed as
   in Figure 15 and the fast_xmit() routine in Section B.5.  If the
   s.rootdelay and s.rootdisp system variables are stored in floating
   double, they must be converted to NTP short format first.  Note that,
   if authentication fails, the server returns a special message called
   a crypto-NAK.  This message includes the normal NTP header data shown
   in the figure, but with a MAC consisting of four octets of zeros.
   The client is free to accept or reject the data in the message.

   NEWBC.  This is a broadcast (mode 5) packet matching no association.
   The client mobilizes a client (mode 3) association as shown in the
   mobilize() and clear() routines in Section A.2.  Implementations
   supporting authentication first perform the necessary steps to run
   the Autokey or other protocol, and determine the propagation delay,
   then continues in listen-only (mode 6) to receive further packets.
   Note the distinction between a mode-6 packet, which is reserved for
   the NTP monitor and control functions, and a mode-6 association.

   NEWPS.  This is a symmetric active (1) packet matching no
   association.  The client mobilizes a symmetric passive (mode 2)
   association as shown in the mobilize() and clear() routines in
   Section A.2.  Code flow continues to the match_assoc() fragment
   described below.  In other cases the packet matches an existing
   association and code flows to the match_assoc fragment in Figure 16.
   The packet timestamps are carefully checked to avoid invalid,
   duplicate or bogus packets, as shown in the figure.  Note that a
   crypto-NAK is considered valid only if it survives these tests.
   Next, the peer variables are copied from the packet header variables
   as shown in Figure 17 and the packet() routine in Section A.5.
   Implementations must include a number of data range checks as shown
   in Table 3 and discard the packet if the ranges are exceeded;
   however, the header fields are copied even if errors occur, since
   they are necessary in symmetric modes to construct the subsequent
   poll message.

   ------------------
   | match assoc  |
   ----------------
        \ | /
   ----------------yes----------------
   | T_3 = 0?     |-->| format error |
   ----------------   ----------------
        \ | / no
   ----------------yes----------------
   | T_3 = xmt?   |-->| duplicate    |
   ----------------   ----------------
        \ | / no
   ----------------no ----------------yes
   | mode = 5?    |-->|T_1 or T2 = 0?|--\
   ----------------   ----------------  |
          | yes             \ | / no    |
        \ | /<-----\  ----------------  |
          |         \-| T_1 = xmt?   |  |
   ----------------   ----------------  |
   | auth = NAK?  |      no  \ | /<-----/
   ----------------            |
   yes\|/     no\|/   ----------------
   --------- ------   |  org = T_3   |
   |org=T_3| |auth|   | rec = T_4    |
   |rec=T_4| |err |   ----------------
   --------- ------         \ | /
     \|/              ----------------
   ---------          | return       |
   |packet |          ----------------
   ---------

                      Figure 16: Timestamp Processing
   ----------------
   | packet       |
   ----------------
        \ | /
   ----------------
   | copy header  |
   ----------------
        \ | /
   ----------------bad----------------
   | header?      |-->|header error  |
   ----------------   ----------------
        \ | /
   ----------------
   | reach |= 1   |
   ----------------
        \ | /
   ----------------
   | poll update  |
   ----------------
        \ | /
   ----------------------------------------
   | theta = 1/2*(T_2-T_1)+(T_3-T_4)      |
   | del = (T_4-T_1)-(T_3-T_2)            |
   | epsilon = rho_r+rho+capphi*((T_4-T_1)|
   ----------------------------------------
        \ | /
   ----------------
   | clock filter |
   ----------------

   Peer Variables <-- Packet Variables
   p.leap <-- r.leap
   p.mode <-- r.mode
   p.stratum <-- r.stratum
   p.ppoll <-- r.ppoll
   p.rootdelay <-- r.rootdelay
   p.rootdisp <-- r.rootdisp
   p.refid <-- r.refid
   p.reftime <-- r.reftime

                       Figure 17: Packet Processing
   +----------------+--------------------------------------------------+
   | Packet Type    | Description                                      |
   +----------------+--------------------------------------------------+
   | 1 duplicate    | The packet is at best an old duplicate or at     |
   | packet         | worst a replay by a hacker.  This can happen in  |
   |                | symmetric modes if the poll intervals are        |
   |                | uneven.                                          |
   | 2 bogus packet |                                                  |
   | 3 invalid      | One or more timestamp fields are invalid.  This  |
   |                | normally happens in symmetric modes when one     |
   |                | peer sends the first packet to the other and     |
   |                | before the other has received its first reply.   |
   | 4 access       | The access controls have black                   |
   | denied         |                                                  |
   | 5              | The cryptographic message digest does not match  |
   | authentication | the MAC.                                         |
   | failure        |                                                  |
   | 6              | The server is not synchronized to a valid        |
   | unsynchronized | source.                                          |
   | 7 bad header   | One or more header fields are invalid.           |
   | data           |                                                  |
   | 8 autokey      | Public key cryptography has failed to            |
   | error          | authenticate the packet.                         |
   | 9 crypto error | Mismatched or missing cryptographic keys or      |
   |                | certificates.                                    |
   +----------------+--------------------------------------------------+

                       Table 3: Packet Error Checks

   The 8-bit p.reach shift register in the poll process described later
   is used to determine whether the server is reachable or not and
   provide information useful to insure the server is reachable and the
   data are fresh.  The register is shifted left by one bit when a
   packet is sent and the rightmost bit is set to zero.  As valid
   packets arrive, the rightmost bit is set to one.  If the register
   contains any nonzero bits, the server is considered reachable;
   otherwise, it is unreachable.  Since the peer poll interval might
   have changed since the last packet, the poll_update() routine in
   Section A.8 is called to re-determine the host poll interval.

   The on-wire protocol calculates the clock offset theta and roundtrip
   delay del from the four most recent timestamps as shown in Figure 12.
   While it is in principle possible to do all calculations except the
   first-order timestamp differences in fixed-point arithmetic, it is
   much easier to convert the first-order differences to floating
   doubles and do the remaining calculations in that arithmetic, and
   this will be assumed in the following description.  The dispersion
   statistic epsilon(t) represents the maximum error due to the
   frequency tolerance and time since the last measurement.  It is
   initialized

   epsilon(t_o) = rho_r + rho +cappsi(T_4-T_1)

   when the measurement is made at t _0.  Here rho_r is the peer
   precision in the packet header r.precision and rho the system
   precision s.precision, both expressed in seconds.  These terms are
   necessary to account for the uncertainty in reading the system clock
   in both the server and the client.  The dispersion then grows at
   constant rate TOLERANCE (cappsi); in other words, at time t,
   epsilon(t) = epsilon(t_0) + cappsi(t-t_0).  With the default value
   cappsi = 15 PPM, this amounts to about 1.3 s per day.  With this
   understanding, the argument t will be dropped and the dispersion
   represented simply as epsilon.  The remaining statistics are computed
   by the clock filter algorithm described in the next section.

9.  Clock Filter Algorithm
   -----------------------
   | clock filter        |
   -----------------------
            \ | /
   -----------------------
   | shift sample theta, |
   | del, epsilon, and t |
   | filter shift registr|
   -----------------------
            \ | /
   -----------------------
   | copy filter to a    |
   | temporary list. sort|
   | list by increasing  |
   | del.  Let theta_i   |
   | del_i, epsilon_i,   |
   | t_i be the ith entry|
   | on the sorted list. |
   -----------------------
            \ | /
   -----------------------   no
   |     t_0 > t?        |----\
   -----------------------    |
            \ | / yes         |
   -----------------------    |
   | theta = theta_0     |    |
   | del = del_0         |    |
   | epsilon             |    |
   | = sum(epsilon_i)    |    |
   |       ----------    |    |
   |        2^(i+1)      |    |
   | varphi              |    |
   | = sqrt(1/7* ...     |    |
   |    ... sum( ...     |    |
   | (theta_0-theta_i)^2 |    |
   | t = t_0             |    |
   -----------------------    |
            \ | /             |
   -----------------------    |
   | clock_select()      |    |
   -----------------------    |
            \ | /<------------/
   -----------------------
   | return              |
   -----------------------

                    Figure 18: Clock Filter Processing
   The clock filter algorithm grooms the stream of on-wire data to
   select the samples most likely to represent the correct time.  The
   algorithm produces the p.offset theta, p.delay del, p.dispersion
   epsilon, p.jitter varphi, and time of arrival p.t t used by the
   mitigation algorithms to determine the best and final offset used to
   discipline the system clock.  They are also used to determine the
   server health and whether it is suitable for synchronization.  The
   core processing steps of this algorithm are shown in Figure 18 with
   more detail in the clock_filter() routine in Section A.5.

   The clock filter algorithm saves the most recent sample tuples
   (theta, del, epsilon, t) in an 8-stage shift register in the order
   that packets arrive.  Here t is the system timer, not the peer
   variable of the same name.  The following scheme is used to insure
   sufficient samples are in the register and that old stale data are
   discarded.  Initially, the tuples of all stages are set to the dummy
   tuple (0,MAXDISP, MAXDISP, t).  As valid packets arrive, the (theta,
   del, epsilon, t) tuples are shifted into the register causing old
   samples to be discarded, so eventually only valid samples remain.  If
   the three low order bits of the reach register are zero, indicating
   three poll intervals have expired with no valid packets received, the
   poll process calls the clock filter algorithm with the dummy tuple
   just as if the tuple had arrived from the network.  If this persists
   for eight poll intervals, the register returns to the initial
   condition.

   In the next step the shift register stages are copied to a temporary
   list and the list sorted by increasing del.  Let j index the stages
   starting with the lowest del.  If the sample epoch t_0 is not later
   than the last valid sample epoch p.t, the routine exits without
   affecting the current peer variables.  Otherwise, let epsilon_j be
   the dispersion of the jth entry, then
         i=n-1
         ---     e_i
   e=    \     --------
         /        (i+1)
         ---     2
         i=0

   is the peer dispersion p.disp.  Note the overload of epsilon, whether
   input to the clock filter or output, the meaning should be clear from
   context.

   The observer should note (a) if all stages contain the dummy tuple
   with dispersion MAXDISP, the computed dispersion is a little less
   than 16 s, (b) each time a valid tuple is shifted into the register,
   the dispersion drops by a little less than half, depending on the
   valid tuples dispersion, (c) after the fourth valid packet the
   dispersion is usually a little less than 1 s, which is the assumed
   value of the MAXDIST parameter used by the selection algorithm to
   determine whether the peer variables are acceptable or not.

   Let the first stage offset in the sorted list be theta_0; then, for
   the other stages in any order, the jitter is the RMS average
              +-----                                    -----+
              |                                        1/2   |
              |            +-----                 -----+     |
              |            |  n-1                      |     |
              |            |  ---                      |     |
              |    1       |  \                     2  |     |
   varphi   = | -------- * |  /    (theta_0-theta_j)   |     |
              |  (n-1)     |  ---                      |     |
              |            |  j=1                      |     |
              |            +-----                 -----+     |
              |                                              |
              +-----                                    -----+

   where n is the number of valid tuples in the register.  In order to
   insure consistency and avoid divide exceptions in other computations,
   the varphi is bounded from below by the system precision rho
   expressed in seconds.  While not in general considered a major factor
   in ranking server quality, jitter is a valuable indicator of
   fundamental timekeeping performance and network congestion state.

   Of particular importance to the mitigation algorithms is the peer
   synchronization distance, which is computed from the root delay and
   root dispersion.  The root delay is

   del ' = delta_r + del

   and the root dispersion is

   epsilon ' = E_r + epsilon + varphi

   Note that epsilon and therefore increase at rate capphi.  The peer
   synchronization distance is defined

   lambda = (del ' / 2) + epsilon

   and recalculated as necessary.  The lambda is a component of the root
   synchronization distance caplambda used by the mitigation algorithms
   as a metric to evaluate the quality of time available from each
   server.  Note that there is no state variable for lambda, as it
   depends on the time since the last update.

10.  System Process

   As each new sample (theta, delta, epsilon, t) is produced by the
   clock filter algorithm, the sample is processed by the mitigation
   algorithms consisting of the selection, clustering, combining and
   clock discipline algorithms in the system process.  The selection
   algorithm scans all associations and casts off the falsetickers,
   which have demonstrably incorrect time, leaving the truechimers as
   result.  In a series of rounds the clustering algorithm discards the
   association statistically furthest from the centroid until a minimum
   number of survivors remain.  The combining algorithm produces the
   best and final offset on a weighted average basis and selects one of
   the associations as the system peer providing the best statistics for
   performance evaluation.  The final offset is passed to the clock
   discipline algorithm to steer the system clock to the correct time.
   The statistics (theta, delta, epsilon, t) associated with the system
   peer are used to construct the system variables inherited by
   dependent servers and clients and made available to other
   applications running on the same machine.

   The discussion in following sections covers only the basic variables
   and routines necessary for a conforming NTPv4 implementation.
   Additional implementation details are in Section B.6.  An interface
   that might be considered in a formal specification is represented by
   the function prototypes in Section B.1.

10.1.  System Process Variables

   The variables and parameters associated with the system process are
   summarized in Figure 21, which gives the variable name, formula name
   and short description.  Unless noted otherwise, all variables have
   assumed prefix s.
   Name/Formula/Description
   t/t/epoch
   leap/leap/leap indicator
   stratum/stratum/stratum
   precision/rho/precision
   p/p/system peer pointer
   offset/captheta/combined offset
   jitter/varsigma/combined jitter
   rootdelay/capdelta/root delay
   rootdisp/E/root dispersion
   refid/refid/reference ID
   reftime/reftime/reference time
   NMIN/3/minimum survivors
   CMIN/1/minimum candidates

            Figure 21: System Process Variables and Parameters
   All the variables except s.t and s.p have the same format and
   interpretation as the peer variables of the same name.  The remaining
   variables are defined below.

   s.t: Integer representing the value of the system timer at the last
   update.

   s.p: System peer association pointer.

   s.precision: 8-bit signed integer representing the precision of the
   system clock, in log2 seconds.

   s.offset: Offset computed by the combining algorithm.

   s.jitter: Jitter computed by the cluster and combining algorithms.

   The variables defined below are updated from the system peer process
   as described later.  They are interpreted in the same way as the as
   the peer variables of the same names.

   s.leap, s.stratum, s.rootdelay, s.rootdisp, s.refid, s.reftime

   Initially, all variables are cleared to zero, then the s.leap is set
   to 3 (unsynchronized) and s.stratum is set to MAXSTRAT (16).  The
   remaining statistics are determined as described below.

10.2.  System Process Operations

   The system process implements the selection, clustering, combining
   and clock discipline algorithms.  The clock_select() routine in
   Figure 22 includes the selection algorithm of Section 9.2.1 that
   produces a majority clique of truechimers based on agreement
   principles.  The clustering algorithm of Section 9.2.2 discards the
   outliers of the clique to produce the survivors used by the combining
   algorithm in Section 9.2.3, which in turn provides the final offset
   for the clock discipline algorithm in Section 9.2.4.  If the
   selection algorithm cannot produce a majority clique, or if the
   clustering algorithm cannot produce at least CMIN survivors, the
   system process terminates with no further processing.  If successful,
   the clustering algorithm selects the statistically best candidate as
   the system peer and its variables are inherited as the system
   variables.  The selection and clustering algorithms are described
   below separately, but combined in the code skeleton.

                            -------------------------
                            |   t2 clock_select()        |
                            -------------------------
                                     \|/
   -----------------------------------|---------------
   |    t2              ----------- ---------------------- |
   |   t6          /---| accept? | |    t6  scan candidates   | Variables
         +---------+   +---------+   +---------+   +---------+
    xmt |    0
   |          |    t3   ----------- |                    | T1<>t3? |
   |    t7          |
         +---------+   +---------+   +---------+   +---------+

                   t2      t3                 t6          t7
         ---------------------------------------------------------
                  /\         \                 /\            \
                  /           \                /              \
                 /             \              /                \
                /               \/ yes       no| |                    | |
   |     -----------      |   |                    | |
   |     | add peer|      |   |                    | |
   |     -----------      |   |                    | |
   |          |          \|/  |                    | |
   |          \-------->----->|                    | |
   |                          |                    | |
   |  selection algorithm     ---------------------- |
   |                                  \|/            |
   ------------------------------------|--------------
                  no          -----------------------
               /--------------| survivors?          |
               |              -----------------------
               |                      \|/ yes
               |              -----------------------
               |              | clustering algorithm|
               |              -----------------------
               |                      \|/
               |              -----------------------
               |<---------yes-| n < CMIN?           |
              \|/             -----------------------
   -------------------------          \|/ no
   | s.p = NULL            |  -----------------------
   -------------------------  | s.p = vo.p          |
              \|/             -----------------------
   -------------------------          \|/
   | return (UNSYNC)       |  -----------------------
   -------------------------  | return (SYNC)       |
                              -----------------------

                     Figure 22: clock_select() routine

10.2.1.  Selection Algorithm

   The selection algorithm operates to find the truechimers using
   Byzantine agreement principles originally proposed by Marzullo [7],
   but modified to improve accuracy.  An overview of the algorithm is
   listed below and the first half of the clock_select() routine in
   Section A.6.1.  First, those servers which are unusable according to
   the rules of the protocol are detected and discarded by the accept()
   routine in Figure 23 and Section B.6.3.  Next, a set of tuples {p,
   type, edge} is generated for the remaining servers, where p is an
   association pointer, type and edge identifies the upper (+1), middle
   (0) and lower (-1) endpoint of a correctness interval [theta -
   lambda, theta + lambda], where lambda is the root distance.

   1.  1.  For each of m associations, construct a correctness interval
       [(theta - rootdist()), (theta + rootdist())].

   2.  2.  Select the lowpoint, midpoint and highpoint of these
       intervals.  Sort these values in a list from lowest to highest.
       Set the number of falsetickers f = 0.

   3.  3.  Set the number of midpoints d = 0.  Set c = 0.  Scan from
       lowest endpoint to highest.  Add one to c for every lowpoint,
       subtract one for every highpoint, add one to d for every
       midpoint.  If c >= m - f, stop; set l = current lowpoint

   4.  4.  Set c = 0.  Scan from highest endpoint to lowest.  Add one to
       c for every highpoint, subtract one for every lowpoint, add one
       to d for every midpoint.  If c >= m - f, stop; set u = current
       highpoint.

   5.  5.  Is d = f and l < u?

   6.  if yes, then follow step 5y, else, follow step 5n.

   7.  5y.  Success: the intersection interval is [l, u].

   8.  5n.  Add one to f.  Is f < (m /                 \/
         ---------------------------------------------------------
              t1                t4         t5                  t8

             t1            t4            t5             t8
         +---------+   +---------+   +---------+   +---------+
     T1  |    0    |   |    t2   |   |   t4    |   |    t6   |
         +---------+   +---------+   +---------+   +---------+
     T2  |    0    |   |    t1   |   |   t3    |   |    t5   |  Packet
         +---------+   +---------+   +---------+   +---------+ Variables
     T3  |    0    |   |t4=clock |   |   t4    |   |t8=clock |
         +---------+   +---------+   +---------+   +---------+
     T4  |t1=clock | 2)?  If yes, then go to step 3
       again.  If no, then go to step 6.

   9.  6.  Failure; a majority clique could not be found.  Stop
       algorithm.

   The tuples are placed on a list and sorted by edge.  The list is
   processed from the lowest to the highest, then from highest to lowest
   as described in detail in [8].  The algorithm starts with the
   assumption that there are no falsetickers (f = 0) and attempts to
   find a nonempty intersection interval containing the midpoints of all
   correct servers, i.e., truechimers.  If a nonempty interval cannot be
   found, it increases the number of assumed falsetickers by one and
   tries again.  If a nonempty interval is found and the number of
   falsetickers is less than the number of truechimers, a majority
   clique has been found and the midpoints (offsets) represent the
   survivors available for the clustering algorithm.  Otherwise, there
   are no suitable candidates to synchronize the system clock.

   --------------------
   |    t3 accept()         |   |t5=clock
   --------------------
           \|/
   --------------------
   | leap = 11?       |    t7
   |
         +---------+   +---------+   +---------+   +---------+
                                                                Peer A
         +---------+   +---------+   +---------+   +---------+
    org stratum >=       |--any yes---\ server not
   |    0 MAXSTRAT?        |            |  T3<>0? synchronized
   --------------------            |
           \|/ all no              |   t3
   --------------------            |
   | T3<>t3? reach = 0?       |---yes----->| server not
   --------------------            |
         +---------+   +---------+   +---------+   +---------+   State
    rec reachable
           \|/ no                  |    0
   --------------------            |
   |    t4 root_dist() >=   |            |   t4
   | MAXDIST?         |---yes----->| root distance
   --------------------            |    t8 exceeded
           \|/ no                  | Variables
         +---------+   +---------+   +---------+   +---------+
    xmt
   --------------------            |   t1
   | refid = addr?    |---yes----->| server/client
   --------------------            | sync loop
           \|/ no                  |  T1=t1?
   --------------------            |
   |   t5 return (YES)     | -----------------------
   -------------------- | T1<>t5? return (NO)         |
         +---------+   +---------+   +---------+   +---------+
                        -----------------------

                        Figure 5: NTPState
   This figure shows the most general case, where each 23: accept() routine

10.2.2.  Clustering Algorithm

   The members of two peers, A
   and B, independently measure the offset and delay relative to the
   other.  For illustrative purposes, the individual timestamp values majority clique are shown in lower case with subscripts indicating placed on the order of
   transmission survivor list,
   and reception.  In the figure, the sorted first packet
   transmitted by A contains only the transmit timestamp T4 with value
   t1.  B receives stratum, then by root distance lambda.  The
   sorted list is processed by the packet at t2 clustering algorithm below and saves the originate timestamp T2
   with value t1 in state variable org and
   second half of the receive timestamp T3 with
   value t2 clock_select() algorithm in state variable rec.  Afterwards, B sends Section B.6.1.

      1.  Let (theta, phi, Lambda) represent a packet to A
   containing the org and rec state variables in T2 and T1 respectively
   and additionally the transmit timestamp T4 candidate peer with value t3, which is
   saved in
      offset theta, jitter j and a weight factor Lambda = stratum *
      MAXDIST + rootdist().

      2.  Sort the xmt state variable.  When this packet arrives at A candidates by increasing Lambda.  Let n be the
   packet header variables T1, T2, T3, number
      of candidates and T4 represent NMIN the four
   timestampes necessary to minimum number of survivors.

      3.  For each candidate compute the selection jitter jsubS (RMS
      peer offset differences between this and delay of B relative
   to A.

   Before all other candidates).

      4.  Select j_max as the A state variables candidate with maximum j_S.

      5.  Select j_min as the candidate with minimum j_S.

      If yes, go to step 6y.  If no, go to step 6n.

      6y.  Done.  The remaining cluster survivors are updated, two sanity checks correct.  The
      survivors are
   performed in order to protect against duplicate or invalid packets.
   A packet is a duplicate if the transmit timestamp T4 in v. structure sorted by Lambda.

      6n.  Delete the packet
   matches outlyer candidate with j_max; reduce n by one, and
      go back to step 3.

   It operates in a series of rounds where each round discards the xmt state variable.  A packet
   furthest statistical outlier until a specified minimum number of
   survivors NMIN (3) are left or until no further improvement is invalid if
   possible.  In each round let n be the origin
   timestamp T2 in number of survivors and s index
   the packet does not match survivor list.  Assume jp is the org state variable.  In
   either peer jitter of these cases the state variables are updated, but s survivor.
   Compute
              +-----                                    -----+
              |                                        1/2   |
              |            +-----                 -----+     |
              |            |  n-1                      |     |
              |            |  ---                      |     |
              |    1       |  \                     2  |     |
   varphi_s = | -------- * |  /    (theta_s-theta_j)   |     |
              |  (n-1)     |  ---                      |     |
              |            |  j=1                      |     |
              |            +-----                 -----+     |
              |                                              |
              +-----                                    -----+

   as the packet selection jitter.  Then choose varphi_max = max  (varphi) and
   varphi_min = min (varphi).  If varphi_max < varphi_min or n < NMIN,
   no further reduction in selection jitter is discarded.

   The general rules that govern possible, so the updating of state variables
   algorithm terminates and
   packet variables the remaining survivors are given in Figure 6.
   +-------------------------------------------------------+ processed by the
   combining algorithm.  Otherwise, the algorithm case off the
   varphi_max survivor, reduces n by one and makes another round.

10.2.3.  Combining Algorithm
   ---------------------
   |        Receive clock_combine()   |        Transmit
   ---------------------
           \|/
   ---------------------
   |
   +-------------------------------------------------------+ y = z = w = 0     |   org=T4
   ---------------------
           \|/
   ---------------------
   |   org=unchanged scan cluster      |   ------------------
   |   rec=Time of Receipt survivors         |-->| x = rootdist() |   rec=unchanged
   |                   |   xmt=unchanged   ------------------
   |   xmt=Time of transmission                   |          \|/
   |                   |   ------------------
   |                   |<--| y+= 1/x        |   T1=Received T3
   |   T1=rcv                   |   |   T2=Received T2 z+=theta_i/x   |
   |   T2=org                   |   |   T3=rec w+=(theta_i -  |   T3=unchanged
   |                   |   T4=Received T4   |   T4=xmt theta_o)^2     |
   ---------------------   ------------------
           \|/ done
   -----------------------
   | captheta = z/y      |
   | vartheta = sqrt(w/y)|
   -----------------------
           \|/
   -----------------------
   | return              |
   +-------------------------------------------------------+
   -----------------------

   Variable/Process/Description
   captheta/system/combined clock offset
   vartheta_p/system/combined jitter
   theta_0/survivor list/first survivor offset
   theta_i/survivor list/ith survivor offset
   x,y,z,w/ /temporaries

                    Figure 6: Relationship between NTP State 25: clock_combine() routine
                         --------------------
                         | clock_update()   |
                         --------------------
                                 \|/
                         --------------------
            /----no----->| p.t > s.t        |
            |            --------------------
            |                    \|/ yes
            |            --------------------
            |            | s.t = p.t        |
            |            --------------------
            |                    \|/
            |            --------------------
            |            | local_clock()    |
            |            --------------------
            |                    \|/
            |<--------------------+-----------------\
            | panic\|/            | adj        step\|/
            | -------------       |       -------------------
            | | panic exit|       |       | clear all assoc.|
            | -------------       |       -------------------
            |             -----------------        \|/
            |             |*update system | -----------------
            |             | variables     | | leap = 3      |
            |             ----------------- | quamtum =     |
            |                    \|/        | MAXSTRAT      |
            |                     |         -----------------
            \---------------------+----------------/
                                  |
                          ---------------
                          | return      |
                          ---------------

   System Variables and NTP Packet <-- System Peer Variables

5.  SNTP Protocol Operation

   SNTP operates using
   leap <-- leap
   stratum <-- stratum + 1
   refid <-- refid
   reftime <-- reftime
   capdelta <-- capdelta_r + del
   E <-- E_r+epsilon+cappsi*mu+varphi+|captheta|
   * update system variables

                     Figure 26: clock_update() routine

   The remaining survivors are processed by the same message formats, addresses, and ports as
   NTP.  However, it is stateless, operating only clock_combine() routine
   in the client or
   server roles.  Thus it is compatible with, and a subset of, NTP.

6.  NTP Server Operations

   Fundamentally, the NTP Server role consists of listening for client
   requests, and providing time and associated details as a response.
   Additionally, a server can provide time Figure 25 and associated details
   periodically via a broadcast mechanism.

   An NTP server can communicate via unicast, broadcast, or both.  A
   server receiving a unicast request (NTP mode 3), modifies fields in Section A.6.4 to produce the NTP header as described below, best and sends a reply (NTP mode 4),
   possibly using final data for
   the same message buffer as clock discipline algorithm.  The routine processes the request.  When
   operating in a broadcast mode, unsolicited messages (NTP mode 5) with
   field values as described below are normally sent at intervals
   ranging from 64 s peer
   offset theta and jitter varphi to 1024 s, depending on the expected frequency
   tolerance of produce the client clocks system offset captheta
   and the required accuracy.

   A broadcast system peer jitter vartheta_p, where each server may or may not send messages if not synchronized
   to a correctly operating source, but the preferred option is to
   transmit, since this allows reachability to be determined regardless
   of synchronization state.

   The Leap Indicator (LI) statistic is set to 3 (unsynchronized) if the server
   has never synchronized to a reference source.  Once synchronized,
   weighted by the
   LI field is set to one reciprocal of the other three values root distance and remains at the
   last value set even if the reference source becomes unreachable or
   turns faulty.

   The Version (VN) is copied from the request packet, if responding to
   a unicast request.  For broadcast, this is set to 4. result
   normalized.  The Mode system peer jitter vartheta_p is set to Server (4) if in response to a unicast request.
   For broadcast, this is set to Broadcast (5). component of the
   system jitter described later.

   The Stratum field is set system statistics are passed to the server's current stratum, if
   synchronized. clock_update() routine in
   Figure 26 and Section A.6.4.  If synchronized to a primary reference source the
   Stratum field there is set only one survivor, the
   offset passed to 1.  If unsynchronized this field the clock discipline algorithm is set to 0.

   The Poll field captheta = theta
   and the system peer jitter is coppied from vartheta=varphi.  Otherwise, the request, if responding to a
   unicast request.  For broadcast, this
   selection jitter vartheta_s is set to computed as in (8), where theta_0
   represents the nearest integer
   log2 offset of the poll interval. system peer and j ranges over the
   survivors.
   Peer Variables         Client        System Variables
   ----------------                     -----------------
   | theta = 1/2* |-------------------->| captheta =    |
   | [(T_2 - T_1)+|                     | (combine      |
   | (T_3 - T_4)] |                     | (theta_j))    |
   ----------------                     -----------------
   | del = [(T_4 -|--sum--------------->| capdelta=     |
   | T_1) - (T_3 -|  /|\                | capdelta_r +  |
   | T_2)]        |   |                 | del           |
   ----------------   |                 -----------------
   | epsilon =    |   |                 | E = E_r +     |
   | rho_r + rho +|   |                 | epsilon +     |
   | captheta*(   |   |                 | vartheta +    |
   | T_4 - T_1)   |------------sum----->| absolutevalue(|
   ----------------   |        /|\      | theta)        |
   | varphi =     |   |         |       -----------------
   | sqrt((1/n)-1)*|  |         |       | varphi_s =    |
   | (sum(theta_0)|   |         |       | sqrt(1/(m-1)* |
   | -theta_i)^2))|---|---\     |       | sum(theta_0-  |
   ----------------   |   |     |       | theta_j)^2)   |
         /|\          |   |     |       -----------------
          |           |   |     |             \|/
          |           |   \------------------>sum
    server|           |         |              |
   ----------------   |         |             \|/
   |    rho_r     |   |         |              |
   ----------------   |         |       -----------------
   |  capdelta_r  |>--/         |       | vartheta =    |
   ----------------             |       | sqrt(         |
   |     E_r      |>------------/       | (vartheta_p)^2|
   ----------------                     | +             |
                                        | (vartheta_s)^2|
                                        -----------------

                  Figure 27: System Variables Processing
   The Precision field is set to reflect first survivor on the maximum reading error of survivor list is selected as the system clock.  The Root Delay and Root Dispersion fields are set
   to 0 for a primary server; optionally,
   peer, here represented by the Root Dispersion field can statistics (theta, del, epsilon,
   varphi).  By rule, an update is discarded if its time of arrival p.t
   is not strictly later than the last update used s.t.  Let mu = p.t -
   s.t be set to a value corresponding to the maximum error of time since the radio
   clock itself. last update or update interval.  If the server
   update interval is synchronized less than or equal to a reference source, zero, the value of update is
   discarded.  Otherwise, the
   Reference ID system variables are updated from the
   system peer variables as shown in Figure 26.  Note that s.stratum is
   set to a four-character ASCII string identifying the
   source, left justified p.stratum plus one.

   The arrows labeled IGNOR, PANIC, ADJ and zero padded STEP refer to 32bits.  For IPv4 secondary
   servers,the value is return codes
   from the 32-bit IPv4 address of local_clock() routine described in the synchronization
   source.  For IPv6 and OSI secondary servers, next section.  IGNORE
   means the value update has been ignored as an outlier.  PANIC means the
   offset is greater than the first
   32 bits of panic threshold PANICT (1000 s) and
   normally causes the MD5 hash of program to exit with a diagnostic message to the IPv6 or NSAP address of
   system log.  STEP means the
   synchronization source.  If unsynchronized, it offset is set to an ASCII
   error identifier.

   The timestamp fields in less than the server message are set as follows.  If panic threshold,
   but greater than the server is unsynchronized or first coming up, step threshold STEPT (125 ms).  Since this means
   all timestamp fields peer data have been invalidated, all associations are set to zero with one exception.  If reset and
   the server client begins as at initial start.  ADJ means the offset is synchronized, less
   than the Transmit Timestamp field of step threshold and thus a valid update for the request local_clock()
   routine described later.  In this case the system variables are
   updated as shown in Figure 26.

   There is copied unchanged to one exception not shown.  The dispersion increment is
   bounded from below by MINDISP.  In subnets with very fast processors
   and networks and very small dispersion and delay this forces a
   monotone-definite increase in , which avoids loops between peers
   operating at the same stratum.

   Figure 27 shows how the Originate Timestamp field of error budget grows from the reply.

   If packet variables,
   on-wire protocol and system peer process to produce the server system
   variables that are passed to dependent applications and clients.  The
   system jitter is synchronized, the Reference Timestamp defined

   vartheta = sqrt((vartheta_p)^2+(vartheta_s)^2)

   where vartheta_s is set to the
   time the last update was received from selection jitter relative to the reference source. system peer.
   The
   Originate Timestamp field system jitter is set passed to dependent applications programs as in the unsynchronized case above.
   nominal error statistic.  The Transmit Timestamp field is set root delay capdelta and root dispersion
   E statistics are relative to the time of day when primary server reference clock and
   thus inherited by each server along the
   message path.  The system
   synchronization distance is sent.  In broadcast messages the Receive Timestamp field defined

   caplambda = capdelta/2 + E

   which is set passed to zero and copied from the Transmit Timestamp field in other
   messages.

   Table 5 summarizes these actions.

   +---------------+-----------+-------------------+-------------------+
   |   Field Name  |  Unicast  |   Unicast Reply   |     Broadcast     |
   |               |  Request  |                   |                   |
   +---------------+-----------+-------------------+-------------------+
   |       LI      |   ignore  |     as needed     | dependent application programs as needed     |
   |       VN      |    1-4    |    copied from    |         4         |
   |               |           |      request      |                   |
   |      Mode     |   1 or 3  |       2 or 4      |         5         |
   |    Stratum    |   ignore  |         1         |         1         |
   |      Poll     |   ignore  |    copied from    |     log2 poll     |
   |               |           |      request      |      interval     |
   |   Precision   |   ignore  |    -log2 server   |    -log2 server   |
   |               |           |  significant bits |  significant bits |
   |   Root Delay  |   ignore  |         0         |         0         |
   |      Root     |   ignore  |         0         |         0         |
   |   Dispersion  |           |                   |                   |
   |   Reference the maximum
   error statistic.

10.2.4.  Clock Discipline Algorithm
                        ---------
             thetar +  |   ignore         \        +----------------+
         NTP --------->|  Phase   \  V_d  |    source ident                |    source ident  V_s
             thetac -  | Detector  ------>|  Clock Filter  |-----+
             +-------->|          /       |   Identifier                |     |
             |         |         /        +----------------+     |   Reference
             |   ignore          ---------                                | time of last src.
             | time of last src.                                                   |
           -----                                                 |   Timestamp
          /     \                                                |
          |       update VFO |       update                                                |
          \     /                                                |   Originate
           -----    +-------------------------------------+      |   ignore
             ^      |  copied from xmit            Loop Filter              |         0      |
             |   Timestamp      |                                     |     timestamp      |
             |      |    Receive +---------+   x  +-------------+    |   ignore      |    time of day
             |         0      | |   Timestamp         |<-----|             |    |      |
             +------|-|  Clock  |   y  |    Transmit Phase/Freq  |<---|------+
                    |    (see |    time of day Adjust  |<-----| Prediction  |    time of day    |
                    |   Timestamp |   text)         |      |             |    | Authenticator
                    |  optional +---------+      +-------------+    |      optional
                    |      optional                                     |
   +---------------+-----------+-------------------+-------------------+

               Table 5: NTP Server Message Field Population

      Broadcast servers should respond to client unicast requests, as
      well as send unsolicited broadcast messages.  Broadcast clients
      may send unicast requests in order
                    +-------------------------------------+

                 Figure 28: Clock Discipline Feedback Loop

   The NTPv4 clock discipline algorithm, shortened to measure the network
      propagation delay between the server and client and then continue
      operation discipline in listen-only mode.  However, broadcast servers may
      choose not to respond to unicast requests, so unicast clients
      should be prepared to abandon the measurement and assume
   following, functions as a default
      value for the delay.

7.  NTP Client Operations

   The role combination of an NTP client is two philosophically quite
   different feedback control systems.  In a phase-locked loop (PLL)
   design, periodic phase updates at update intervals m are used
   directly to determine minimize the current time (and
   associated information) from an NTP server.  This can be done
   actively, by sending error and indirectly the frequency
   error.  In a unicast request frequency-locked loop (FLL) design, periodic frequency
   updates at intervals mu are used directly to minimize the frequency
   error and indirectly the time error.  As shown in [8], a configured server, or
   passively by listening on PLL usually
   works better when network jitter dominates, while a known address for periodic server
   messages. FLL works better
   when oscillator wander dominates.  This section contains an outline
   of how the NTPv4 design works.  An NTP client can operate in unicast or broadcast modes.  In unicast
   mode in-depth discussion of the client sends a request (NTP mode 3) to a designated unicast
   server and expects design
   principles is provided in [8], which also includes a reply (NTP mode 4) from that server.  In
   broadcast client mode it sends no request performance
   analysis.

   The clock discipline and waits for a broadcast
   (NTP mode 5) from one or more broadcast servers.

   A unicast client initializes clock adjust processes interact with the NTP message header, sends
   other algorithms in NTPv4.  The output of the
   request combining algorithm
   represents the best estimate of the system clock offset relative to
   the server and strips the time of day from ensemble.  The discipline adjusts the Transmit
   Timestamp field frequency of the reply.  For VFO
   to minimize this purpose, all of offset.  Finally, the NTP
   header fields shown in Section 3 timestamps of each server are set
   compared to 0, except the Mode, VN
   and optional Transmit Timestamp fields.

   NTP and SNTP clients set the mode field to 3 (client) for unicast
   requests.  They set timestamps derived from the VN field VFO in order to any version number supported by calculate
   the server selected by configuration or discovery and can
   interoperate with all previous version NTP offsets and SNTP servers.  Servers
   reply with close the same version feedback loop.

   The discipline is implemented as the request, so feedback control system shown in
   Figure 28.  The variable theta_r represents the VN field of combining algorithm
   offset (reference phase) and theta_c the
   request also specifies VFO offset (control phase).
   Each update produces a signal Vd representing the VN field of instantaneous phase
   difference theta_r - theta_c.  The clock filter for each server
   functions as a tapped delay line, with the reply.  An NTP client can
   specify output taken at the earliest acceptable version on tap
   selected by the expectation that any
   server of that or later version will respond.  NTPv4 servers are
   backwards compatible clock filter algorithm.  The selection, clustering
   and combining algorithms combine the data from multiple filters to
   produce the signal Vs.  The loop filter, with NTPv3 as defined in RFC 1305, NTPv2 as
   defined in [11], impulse response F(t),
   produces the signal Vc which controls the VFO frequency omega_c and NTPv1 as defined in [12].  NTPv0 defined in [13]
   thus its phase theta_c = integral (omega_c, dt) which closes the
   loop.  The Vc signal is not supported.

   In unicast mode, generated by the Transmit Timestamp field clock adjust process in the request SHOULD
   be set to the time
   Section 9.3.  The characteristic behavior of day according to this model, which is
   determined by F(t) and the client clock various gain factors given in NTP
   timestamp format.  This allows for Section
   A.6.6.

   The transient behavior of the PLL/FLL feedback loop is determined by
   the determination impulse response of the
   propagation delay between the server and client and to align the
   system clock relative loop filter F(t).  The loop filter shown
   in Figure 29 predicts a phase adjustment x as a function of Vs.  The
   PLL predicts a frequency adjustment yFLL as an integral of Vs*mu with
   repsect to t, while the server.  In addition, this provides FLL predicts an adjustment yPLL as a
   simple method function
   of Vs /mu.  The two adjustments are combined to verify that correct the server reply is frequency
   y as shown in fact a legitimate
   response Figure 29.  The x and y are then used by the
   clock_adjust()routine to control the specific client request and avoid replays.  Note VFO frequency.  The detailed
   equations that implement these functions are best presented in broadcast mode, the client cannot necessarily calculate the
   propagation delay or determine the validity
   routines of Sections A.6.6 and A.7.1.
                     x <------(Phase Correction)<--.
                                                   |
                           y_FLL                   |
                            .-(FLL Predict)<-------+<--V_s
                            |                      |
                           \|/                     |
                     y <--(Sum)                    |
                            ^                      |
                            |                      |
                            '-(PLL Predict)<-------'
                           y_PLL

                  Figure 29: Clock Discipline Loop Filter

   Ordinarily, the server.

   There pseudo-linear feedback loop described above operates
   to discipline the system clock.  However, there are cases where a
   nonlinear algorithm offers considerable improvement.  One case is some latitude on
   when the part discipline starts without knowledge of most clients to forgive invalid
   timestamps, such as might occur when first coming up or during
   periods when the reference source is inoperative. intrinsic clock
   frequency.  The pseudo-linear loop takes several hours to develop an
   accurate measurement and during most important
   indicator of an unhealthy server is that time the Stratum field, poll interval
   cannot be increased.  The nonlinear loop described below does this in which a
   value
   15 minutes.  Another case is when occasional bursts of large jitter
   are present due to congested network links.  The state machine
   described below resists error bursts lasting less than 15 minutes.

   The remainder of 0 indicates an unsynchronized condition.  When this value is
   displayed, clients should discard section describes how the server message, regardless discipline works.
   Figure 30 contains a summary of the contents of other fields.

   Table 6 summarizes variables and parameters
   including the required NTP client operations in unicast program name, formula name and
   broadcast modes

   +-------------------+---------------+-------------------+-----------+ short description.
   Unless noted otherwisse, all variables have assumed prefix c.  The
   variables c.t, c.tc, c.state, and c.count are integers; the memainder
   are floating doubles.  The function of each will be explained in the
   algorithm descriptions below.

   Name     Formula     Description
   ----     -------     -----------
   t        timer       seconds counter
   offset   captheta    combined offset
   resid    captheta_r  residual offset
   freq     phi         clock frequency
   jitter   varphi      clock jitter
   wander   cappsi      frequency wander
   tc       tau         time constant(log2)
   state    state       state
   adj      adj         frequency adjustment
   count    count       hysteresis counter
   STEPT    125         step threshold (.125 s)
   WATCH    900         stepout thresh(s)
   PANICT   1000        panic threshold(1000 s)
   LIMIT    30          hysteresis limit
   PGATE    4           hysteresis gate
   TC       16          time constant scale
   AVG      8           averaging constant

                                 Figure 30
   =====================================================================
   |     Field Name State |    Unicast  captheta < STEP  | captheta > STEP   |   Unicast Reply    Comments       | Broadcast
   ---------------------------------------------------------------------
   | NSET  | > FREQ; adjust    |    Request > FREQ; step      | no frequency      |
   |
   +-------------------+---------------+-------------------+-----------+       |         LI time              |       0 time              |        0-3 file              |    0-3
   ---------------------------------------------------------------------
   | FSET  |         VN > SYNC; adjust    |      1-4 > SYNC; step      |    copied from frequency file    |    1-4
   |       | time              | time              |      request                   |
   ---------------------------------------------------------------------
   | SPIK  |        Mode > SYNC; adjust    |     1 or 3 if (<900 s)>SPIK  |       2 or 4 outlier detected  |     5
   |       |      Stratum freq, adjust time |       0 else SYNC; step   |        0-15                   |    0-15
   |       |        Poll                   |       0 freq; step time   |       ignore                   |   ignore
   ---------------------------------------------------------------------
   | FREQ  |     Precision if (<900 s)> FREQ |       0 if (<900 s)>FREQ  |       ignore initial frequency |   ignore
   |       |     Root Delay else >SYNC; step  |       0 else >SYNC; step  |                   |
   |       | freq, adjust time | freq, adjust time |                   |
   ---------------------------------------------------------------------
   | SYNC  | >SYNC; adjust freq| if (<900 s)>SPIK  | normal operation  |
   |       | adjust time       | else >SYNC; step  |                   |
   |       |                   | freq; step time   |                   |
   ---------------------------------------------------------------------

                                 Figure 31

   The discipline is implemented by the local_clock() routine, which is
   called from the clock_update() routine.  The local_clock() routine
   pseudo code in Section B.6.6 has two parts; first the state machine
   shown in Figure 32 and second the algorithm that determines the time
   constant and thus the poll interval in Figure 33.  The state
   transition function in Figure 32 is implemented by the rst() function
   shown at the lower left of the figure.  The local_clock() routine
   exits immediately if the offset is greater than the panic threshold.
                               ---
                              | A |
                               ---
                                ||
                                \/
                               --- yes ---
                              | B |-->| C |
                               ---     ---
                             no ||
                                \/
                               ---
                              | D |
                               ---
                                ||
                                \/
                       --- no  ---  yes    SYNC         SPIK FREQ
                      | E |<--| F |----------------------------------
                       ---     ---         ||             ||
           SYNC         ||                 \/             \/
           SPIKE  FSET  \/ FREQ    NSET   ---            ---
            -------------------------    | G |          | H |
           ||     ||        ||      ||    ---            ---
           ||     ||        \/      \/     ||      yes  ||  ||  no
           ||     ||       ---     ---     ||           ||  \/
           ||    ---      | H |   | I |    ||           ||  ---
           \/   | I |      ---     ---     ||           || | J |
          ---    ---   no || ||yes  ||     ||           ||  ---
         | K |    ||      || ||     \/     ||           || ||  || yes
          ---     ||      \/ ||    ---     ||           || ||  \/
           ||     ||     --- ||   | L |    ||           || ||  ---
           ||     ||    | M |||    ---     ||           || || | M |
           ||     ||     --- ||     ||     ||           || ||  ---
           ||     ||      || \/     \/     \/           \/ ||   ||
           ||     ||      ||  ------------>\/<-----------  \/   \/
           ||     ||      ||              ---               --->\/<-----
           ||     ||      ||             | N |                 ---
           ||     ||      ||              ---                 | O |
           ||     ||      ||                                   ---
           ||     ||      ||                                    ||
           ||     ||      ||                                    \/
           ||     ||      ||    ---                ---         ---
            ----->-------->----| P |----><--------| Q |<------| R |
                                ---     ||         ---         ---
         ---                            \/                      ||
        | S |                          ---                      \/
         ---                          | T |                    ---
          ||                           ---                    | U |
          \/                                                   ---
         ---                                                    ||
        | V |                                                   \/
         ---                                                   ---
          ||                                                  | W |
          \/                                                   ---
         ---
        | X |
         ---

   A: local_clock()
   B: |captheta|>PANICT?
   C: return(PANIC)
   D: freq=0
      rval=IGNOR
   E:
   F: |captheta|>STEPT?
   G: state=SPIK
   H: mu<WATCH
   I: captheta_g=captheta
   J: FREQ?
   K: Calculate new freq adjustment from captheta, tau, and mu using
   hybrid PLL and FLL
   L: rst(FREQ,0)
   M: freq=((captheta-captheta_B-captheta_R)/mu)
   N: return(rval)
   O: step_time(captheta)
      rval=STEP
   P: rval=ADJ
   Q: rst(SYNC,0)
   R: state=NSET?
   S: rst(new,off)
   T: tc
   U: rst(FREQ,0)
   V: state=new
      captheta_B=off-captheta_R
      captheta_R=off
   W: return(rval)
   X: return

                 Figure 32: local_clock() routine (1 of 2)

   -----
   |       ignore A |   ignore
   -----
    \|/
   -----
   | B |  Root Dispersion
   -----
    \|/
   -----
   |       0 C |-no-----\
   -----        |       ignore
    \|/yes      |   ignore
   -----      -----
   | D |     Reference      |       0 E |       ignore
   -----      -----
    \|/        \|/
   -----      -----
   |   ignore F |no\   | G |no\
   -----  |     Identifier   -----  |
    \|/yes|    \|/yes|
     |    |     |    |     Reference
   -----  |       0   -----  |       ignore
   |   ignore H |  |     Timestamp   | I |  |
   -----  |   -----  |     Originate
   |       0 J |     (see text)  |   ignore   | K |     Timestamp  |
   -----  |   -----  |
   |y  no-><-no  y|  |
   ----   | Receive Timestamp    ----  |       0
   |     (see text) L|   |   ignore    | M|  |      Transmit
   -------><---------/
         \|/
        -----
        |   (see text) N |      nonzero
        -----
         \|/
        -----
        |  nonzero O |
        -----
         \|/
        -----
        |     Timestamp P |
        -----

   A: tc
   B: state=SYNC
   C: |captheta_g| > PGATE?
   D: count -= 2*tau
   E: count += tau
   F: count <= -LIMIT?
   G: count >= LIMIT?
   H: count = 0
   I: count = 0
   J: tau>MINPOLL
   K: tau<MAXPOLL
   L: tau--
   M: tau++
   N: phi += freq
   O: cappsi = sqrt(expectationvalue(phi^2))
   P: return(rval)

                 Figure 33: local_clock() routine (2 of 2)

   The remaining portion of the local_clock() routine is shown in
   Figure 33.  The time constant tau is determined by comparing the
   clock jitter varphi with the magnitude of the current residual offset
   captheata_R. produced by the clock adjust routine in the next
   section.  If the residual offset is greater than PGATE (4) times the
   clock jitter, be hysteresis counter is reduced by two; otherwise, it
   is increased by one.  If the hysteresis counter increases to the
   upper limit LIMIT (30), the time constant is increased by one; if it
   decreases to the lower limit -LIMIT (-30), the time constant is
   decreased by one.  Normally, the time constant hovers near MAXPOLL,
   but quickly decreases it frequency surges due to a temperature spike,
   for example.

   The clock jitter statistic vartheta and the clock wander statistic
   cappsi are implemented as exponential averages of RMS offset
   differences and RMS frequency differences, respectively.  Let x_i be
   a measurement at time i of either vartheta or cappsi,y_i = x_i -
   x_(i-1) the first-order sample difference and y_i_HAT the exponential
   average.  Then,

   y_(i+1)_HAT = sqrt((y_i_HAT)^2+[(y_i)^2-(y_i_HAT)^2)/AVG])

   where AVG (4) is the averaging parameter in Figure 30, is the
   exponential average at time i + 1.  The clock jitter statistic is
   used by the poll-adjust algorithm above; the clock wander statistic
   issued only for performance monitoring.

10.3.  Clock Adjust Process
   -----
   | A |
   -----
    \|/
   -----
   | B |   Authenticator
   -----
    \|/
   -----
   |    optional C |      optional
   -----
    \|/
   -----
   | D |
   -----
    \|/
   -----
   |  optional E |
   +-------------------+---------------+-------------------+-----------+

               Table 6: NTP Client Message Field Population

8.  NTP Symmetric Peer Operations

   NTP Symmetric Peer mode
   -----
    \|/
   -----
   | F |-----no----\
   -----           |
    \|/yes        \|/
   -----         -----
   | H |<--------| G |
   -----         -----

   A: clock_adjust()
   B: E += captheta
   C: tmp = captheta_r/TC(tau)
   D: captheta_R -= tmp
   E: adjust_time(phi + tmp)
   F: next < timer?
   G: poll()
   H: return

                     Figure 34: clock_adjust() Routine

   The actual clock adjustment is intended for configurations where performed by the clock_adjust()
   routine shown in Figure 34 and Section B.7.1.  It runs at one-second
   intervals to add the frequency offset in Figure 33 and a set fixed
   percentage of
   low-stratum peers operate as mutual backups the residual offset captheta_R. The captheta_R is in
   effect the exponential decay of the captheta value produced by the
   loop filter at each update.  The TC parameter scales the time
   constant to match the poll interval for convenience.  Note that the
   dispersion E increases by capphi at each other.  Each
   peer normally operates with one or more sources, such as a reference
   clock, or second.

   The clock adjust process includes a subset of primary or secondry servers known to be
   reliable or authentic.

   Symmetric Peer mode timer interrupt facility driving
   the system timer c.t.  It begins at zero when the service starts and
   increments once each second.  At each interrupt the clock_adjust()
   routine is exclusive called to incorporate the NTP protocol clock discipline time and
   frequency adjustments, then the associations are scanned to determine
   if the system timer equals or exceeds the p.next state variable
   defined in the next section.  If so, the poll process is
   specifically excluded from SNTP operation.  For called to
   send a packet and compute the purposes of next p.next value.

11.  Poll Process

   Each association supports a poll process that runs at regular
   intervals to construct and send packets in symmetric, client and
   broadcast server associations.  It runs continuously, whether or not
   servers are reachable.  The discussion in this
   document, an NTP peer operates like section covers only
   the variables and routines necessary for a client.

9.  Dynamic Server Discovery conforming NTPv4 provides a mechanism, commonly known as "Manycast",
   implementation.  Additional implementation details are in Section
   B.8.  Further details and rationale for the engineering design are
   discussed in [8].

   Name     Formula    Description
   ----     -------    -----------
   hpoll    hpoll      host poll exponent
   last     last       last poll time
   next     next       next poll time
   reach    reach      reach register
   unreach  unreach    unreach counter
   UNREACH  24         unreach limit
   BCOUNT   8          burst count
   BURST    flag       burst enable
   IBURST   flag       iburst enable

                                 Figure 35

11.1.  Poll Process Variables and Parameters

   The poll process variables are allocated in the association data
   structure along with the peer process variables.  Figure 35 shows the
   names, formula names and short definition for each one.  Following is
   a detailed description of the variables, all of which carry the p
   prefix.

   p.hpoll: Signed integer representing the poll exponent, in log2
   seconds.

   p.last: Integer representing the system timer value when the most
   recent packet was sent.

   p.next: Integer representing the system timer value when the next
   packet is to be sent.

   p.reach: 8-bit integer shift register.  When a
   client to dynamically discover packet is sent, the existance of one or more servers
   with no a-priori knowledge.  Once servers are discovered, they are
   then treated as any other unicast server.

   A client employing server discovery
   register is configured shifted left one bit, with MinServers, zero entering from the minimum number of desired servers right
   and MaxServers, overflow bits discarded.

   p.unreach: Integer representing the maximum number of desired servers.  The discovery mechanism is a simple
   expanding ring search, using IP multicast with increasing TTLs or Hop
   Counts.  The multicast address used MUST be scoped to seconds the local site,
   as defined by [14].

   The client initiates server has
   been unreachable.

11.2.  Poll Process Operations

   As described previously, once each second the discovery process by sending an NTP message
   to clock_adjust() routine
   is called.  This routine calls the configured multicast address (224.0.1.1 poll() routine in Section B.8.1
   for IPv4 and a
   multicast address ending :101 each association in turn.  If the time for IPv6 with proper scoping.) with an
   IP TTL or Hop Count of 1.  This the next poll message has all of
   is greater than the NTP header
   fields set to 0, except system timer, the Mode, VN and optional Transmit Timestamp
   fields.  The Mode is set to 3.  It then starts routine returns immediately.  A
   mode-5 (broadcast server) association always sends a retry timer
   (Default: 64 seconds) packet, but a
   mode-6 (broadcast client) association never sends a packet, but runs
   the routine to update the p.reach and listens for unicast responses from servers. p.unreach variables.  The source address of any server responses are treated as newly
   configured unicast servers, up
   poll() routine calls the peer_xmit() routine in Section B.8.3 to send
   a limit of MaxServers. packet.  If the
   number of discovered servers in a burst (p.burst > 0), nothing further is less than MinServers when done
   except call the retry
   timer expires, an identical NTP message is sent with an increased
   TTL/Hop Count, and poll_update() routine to set the retry timer is restarted.  This continues
   until either MinServers servers have been discovered or a configured
   maximum TTL/Hop Count is reached. next poll interval.

   If not in a burst, the configured maximum TTL/Hop
   Count p.reach variable is reached, packets continue to be periodically sent at shifted left by one bit,
   with zero replacing the
   maximum TTL/Hop Count. rightmost bit.  If at some subsequent time, the number of
   valid servers drops below MinServers, server has not been
   heard for the process restarts at last three poll intervals, the
   initial state.

   A server configured clock_filter() routine
   is called to provide server discovery will listen on increase the
   specified multicast address for discovery messages from clients. dispersion as described in Section 8.3.  If
   the server BURST flag is in scope of the current TTL lit and the server is itself synchronized
   to reachable and a valid source it replies to the discovery message from
   of synchronization is available, the client
   with an ordinary unicast server message as described in Section 6

10.  The Kiss-o'-Death Packet

   According sends a burst of BCOUNT
   (8) packets at each poll interval.  This is useful to accurately
   measure jitter with long poll intervals.  If the NTPv3 specification [1], if IBURST flag is lit
   and this is the Stratum field in first packet sent when the
   NTP header is 1, indicating server becomes
   unreachable, the client sends a primary server, burst.  This is useful to quickly
   reduce the Reference
   Identifier field contains an ASCII string identifying synchronization distance below the particular
   reference clock type.  However, in [1] nothing is said about distance threshold and
   synchronize the
   Reference Identifier field if clock.  The figure also shows the Stratum field is 0, mechanism which is called
   out as "unspecified".  However,
   backs off the poll interval if the Stratum field server becomes unreachable.  If
   p.reach is 0, nonzero, the
   Reference Identifier field can be used server is reachable and p.unreach is set to convey messages useful
   zero; otherwise, p.unreach is incremented by one for
   status reporting and access control.  In NTPv4 and SNTPv4, packets of
   this kind are called Kiss-o'-Death (KoD) packets and the ASCII
   messages they convey are called kiss codes.  The KoD packets got
   their name because an early use was each poll to tell clients the
   maximum UNREACH (24).  Thereafter for each poll p.hpoll is increased
   by one, which doubles the poll interval up to stop sending
   packets that violate the maximum MAXPOLL
   determined by the poll_update() routine.  When the server access controls.

   The kiss codes can provide useful information for again
   becomes reachable, p.unreach is set to zero, p.hpoll is reset to tau
   and operation resumes normally.

   When a packet is sent from an intelligent
   client.  These codes association, some header values are encoded in four-character ASCII strings
   copied from the peer variables left
   justified by a previous packet and zero filled.  The strings others
   from the system variables. includes a flow diagram and a table
   showing which values are designed copied to each header field.  In those
   implementations using floating double data types for character
   displays root delay and log files.  A list of the currently-defined kiss codes
   is given in Table 7.

   +------+------------------------------------------------------------+
   | Code |                           Meaning                          |
   +------+------------------------------------------------------------+
   | ACST |         The association belongs
   root dispersion, these must be converted to NTP short format.  All
   other fields are either copied intact from peer and system variables
   or struck as a unicast server        |
   | AUTH |                Server authentication failed                |
   | AUTO |                   Autokey sequence failed                  |
   | BCST | timestamp from the system clock.

   The association belongs to poll_update() routine shown in Section B.8.2 is called when a broadcast server       |
   | CRYP |    Cryptographic authentication or identification failed   |
   | DENY |               Access denied by remote server               |
   | DROP |                 Lost peer
   valid packet is received and immediately after a poll message is
   sent.  If in symmetric mode                |
   | RSTR |              Access denied due a burst, the poll interval is fixed at 2 s; otherwise,
   the host poll exponent is set to local policy             |
   | INIT |   The association has the minimum of p.poll from the last
   packet received and p.hpoll from the poll() routine, but not yet synchronized for less
   than MINPOLL nor greater than MAXPOLL.  Thus the first   |
   |      |                            time                            |
   | MCST | The association belongs clock discipline can
   be oversampled, but not undersampled.  This is necessary to a dynamically discovered server |
   | NKEY |   No key found.  Either preserve
   subnet dynamic behavior and protect against protocol errors.
   Finally, the key was never installed or poll exponent is  |
   |      |                         not trusted                        |
   | RATE |  Rate exceeded.  The server has temporarily denied access  |
   |      |       because converted to an interval which
   establishes the client exceeded time at the rate threshold       |
   | RMOT |    Alteration of association next poll p.next.

12.  Security Considerations

   NTPv4 provides an optional authentication field that utilizes the MD5
   algorithm.  MD5, as the case for SHA-1, is derived from a remote host running    |
   |      |                           ntpdc.                           |
   | STEP | MD4, which
   has long been known to be weak.  In 2004, techniques for efficiently
   finding collisions in MD5 were announced.  A step change summary of the weakness
   of MD5 can be found in system time has occurred, but [9].

   In the     |
   |      |           association has not yet resynchronized           |
   +------+------------------------------------------------------------+

                 Table 7: Currently-defined case of NTP Kiss Codes

   In general, an as specified herein, NTP broadcast clients are
   vulnerable to disruption by misbehaving or hostile SNTP or NTP
   broadcast servers elsewhere in the Internet.  Access controls and/or
   cryptographic authentication means should be provided for additional
   security in such cases.

13.  IANA Considerations

   UDP/TCP Port 123 was previously assigned by IANA for this protocol.
   The IANA has assigned the IPv4 multicast group address 224.0.1.1 and
   the IPv6 multicast address ending :101 for NTP.  This document
   introduces NTP client should stop sending extension fields allowing for the development of
   future extensions to the protocol, where a particular server
   if that server returns a reply with a Stratum field of 0, regardless
   of kiss code, and an alternate server is available.  If no alternate
   server extension is available, the client SHOULD increase the poll interval as
   performance permits.

11.  Security Considerations

   NTPv4 provides an optional authentication field that utilizes to
   be identified by the MD5
   algorithm.  MD5, as Field Type sub-field within the case for SHA-1, extension field.
   IANA is derived from MD4, which
   has long been known requested to be weak.  In 2004, techniques establish and maintain a registry for efficiently
   finding collisions Extension
   Field Types associated with this protocol, populating this registry
   with no initial entries.  As future needs arise, new Extension Field
   Types may be defined.  Following the policies outlined in MD5 were announced.  A summary [10], new
   values are to be defined by IETF Consensus.

14.  Acknowledgements

   This authors would like to thank Brian Haberman, Greg Dowd, Mark
   Elliot, and Harlan Stenn for technical reviews of the weakness this document.

15.  References

15.1.  Normative References

   [1]  Mills, D., "Network Time Protocol (Version 3) Specification,
        Implementation", RFC 1305, March 1992.

15.2.  Informative References

   [2]   Mills, D., "Simple Network Time Protocol (SNTP) Version 4 for
         IPv4, IPv6 and OSI", RFC 4330, January 2006.

   [3]   University of Delaware, "The Autokey security architecture,
         protocol and algorithms. Electrical and Com puter Engineering
         Technical Report 06-1-1", NDSS , January 2006.

   [4]   Bradner, S., "Key words for use in RFCs to Indicate Requirement
         Levels", BCP 14, RFC 2119, March 1997.

   [5]   Postel, J., "Internet Protocol", STD 5, RFC 791,
         September 1981.

   [6]   Rivest, R., "The MD5 can be found Message-Digest Algorithm", RFC 1321,
         April 1992.

   [7]   Marzullo and S. Owicki, "Maintaining the time in [15].

   In a distributed
         system.", ACM Operating Systems Review 19 , July 1985.

   [8]   Mills, D. L., "Computer Network Time Synchronization - the case
         Network Time Protocol. CRC Press, 304pp.", 2006.

   [9]   Bellovin, S. and E. Rescorla, Proceedings of NTP as specified herein, there is a vulnerability that
   NTP broadcast clients can be disrupted by misbehaving or hostile SNTP
   or NTP broadcast servers elsewhere in the Internet.  Access controls
   and/or cryptographic authentication means should be provided 13th annual
         ISOC Network and Distributed System Security Symposium,
         "Deploying a new Hash Algorithm", February 2006.

   [10]  Narten, T. and H. Alvestrand, "Guidelines for
   additional security Writing an IANA
         Considerations Section in such cases.

   While not required RFCs", BCP 26, RFC 2434,
         October 1998.

Appendix A.  Code Skeleton

   This appendix is intended to describe the protocol and algorithms of
   an implementation in a conforming NTP client implementation, there
   are general way using what is called a variety code
   skeleton program.  This consists of recommended checks that an NTP client can perform
   that are designed to avoid various types a set of abuse that might happen
   as definitions, structures
   and code segments which illustrate the result protocol operations without
   the complexities of server an actual implementation errors or malicious attack.
   These recommended checks are as follows:

      When of the IP source protocol.  This
   program is not an executable and destination addresses are available for the
      client request, they should match the interchanged addresses is not designed to run in the server reply.

      When the UDP source
   ordinary sense.  It is designed to be compiled only in order to
   verify consistent variable and destination ports are available for type usage.  The program is not
   intended to be fast or compact, just to demonstrate the
      client request, algorithms
   with sufficient fidelity to understand how they should match the interchanged ports in the
      server reply. work.  Reword or
   remove The Originate Timestamp in the server reply should match the
      Transmit Timestamp used in code skeleton consists of five segments, a header segment
   included by each of the client request.

      A client can check other segments, plus a code segment for the Root Delay
   main program and Root Dispersion fields peer, system, clock_adjust and poll processes.
   These are
      each greater than or equal presented in order below along with definitions and
   variables specific to 0 each process.

A.1.  Global Definitions

   Following are definitions and less than infinity, where
      infinity is other data shared by all programs.
   These values are defined in a header file ntp4.h which is on the order of 15-20 seconds.  This check included in
   all files.

A.2.  Definitions, Constants, Parameters
   #include <math.h> s/* avoids
      using a server whose synchronization source has expired for a very
      long time.

12.  IANA Considerations

   UDP/TCP Port 123 was previously assigned by IANA complaints about sqrt() */
   #include <sys/time.h> /* for this protocol.
   The IANA has assigned the IPv4 multicast group address 224.0.1.1 gettimeofday() and
   the IPv6 multicast address ending :101 friends */
   #include <stdlib.h> /* for NTP.

   This document identifies the set of defined 4-character (ASCII)
   Reference Identifier values.  This document also defines the set of
   defined Kiss Codes. malloc() and friends */

   /*
   * Data types
   *
   * This document also introduces NTP extension
   fields allowing for program assumes the development of future extensions to int data type is 32 bitsand
    the
   protocol, where a particular extension long data
   * type is 64 bits. The native data
    type used in most calculations is
   * floating double. The data types used
   in some packet header fields
   * require conversion to be identified and from this
    representation. Some header
   * fields involve partitioning an octet, here
    represented by individual
   * octets.
   *
   * The 64-bit NTP timestamp format used in
    timestamp calculations is
   * unsigned seconds and fraction with the
   Field Type sub-field within
    decimal point to the extension field.

   IANA left of
   * bit 32. The only operation permitted
    with these values is requested to establish and maintain
   * subtraction, yielding a registry for Reference
   Identifiers, Kiss codes, signed 31-bit
    difference. The 32-bit NTP
   * short format used in delay and Extension Field Types associated dispersion
   calculations is seconds and
   * fraction with
   this protocol, populating this registry from the Reference
   Identifiers given in Section 3.9 decimal point to the
    left of bit 16. The only
   * operations permitted with these values
    are addition and Kiss Codes given in Section 11
   * multiplication by a constant.
   *
   * The IPv4 address is 32 bits, while the
    IPv6 address is 128 bits. The
   * message digest field is 128 bits as
    constructed by the initial entries. MD5 algorithm.
   * The Extension Field Types registry will have
   no initial entries.  As future needs arise, new Reference
   Identifiers, Kiss Codes, precision and Extension Field Types may be defined.
   Following the policies outlined in [16], new values poll interval fields
    are signed log2 seconds.
   */

   typedef unsigned long tstamp;
   typedef unsigned int tdist;
   typedef unsigned long ipaddr;
   typedef unsinged int ipport;
   typedef unsigned long digest;
   typedef signed char s_char;

   /*
   * Arithmetic conversion macroni
   */

   /* NTP timestamp format */
   /* NTP short format */
   /* IPv4 or IPv6 address */
   /* IP port number */
   /* md5 digest */
   /* precision and poll interval (log2) */

   #define LOG2D(a) ((a) < 0 ? 1. / (1L << -(a)) : \

   1L << (a)) /* poll, etc. */

   #define LFP2D(a) ((double)(a) / 0x100000000L) /* NTP timestamp */

   #define D2LFP(a) ((tstamp)((a) * 0x100000000L))

   #define FP2D(a) (double)(a) / 0x10000L)  /* NTP short */
   #define D2FP(a) ((tdist)((a) * 0x10000L))
   #define SQUARE(x) (x * x)
   #define SQRT(x) (sqrt(x))

   /*
   * Global constants. Some of these might be
    converted to variables
   * which can be defined tinkered by IETF Consensus.

13.  Acknowledgements

   This document has drawn material configuration
    or computed on-fly. For
   * instance, PRECISION could be calculated
    on-fly and
   * provide performance tuning for the defines
    marked with % below.
   */
   #define VERSION 4 /* version number */
   #define PORT 123 /* NTP poert number */
   #define MINDISP .01 /* % minimum dispersion (s) */
   #define MAXDISP 16 /* % maximum dispersion (s) */
   #define MAXDIST 1 /* % distance threshold (s) */
   #define NOSYNC 3 /* leap unsync */
   #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
   #define MINPOLL 4 /* % minimum poll interval (16 s)*/
   #define MAXPOLL 17 /* % maximum poll interval (36.4 h) */
   #define PHI 15e-6 /* % frequency tolerance (15 PPM) */
   #define NSTAGE 8 /* clock register stages */
   #define NMAX 50 /* % maximum number of peers */
   #define NSANE 1 /* % minimum intersection survivors */
   #define NMIN 3 /* % minimum cluster survivors */

   /*
   * Global return values
   */
   #define TRUE 1 /* boolean true */
   #define FALSE 0 /* boolean false */
   #define NULL 0 /* empty pointer */

   /*
   * Local clock process return codes
   */
   #define IGNORE 0 /* ignore */
   #define SLEW 1 /* slew adjustment */
   #define STEP 2 /* step adjustment */
   #define PANIC 3 /* panic - no adjustment */

   /*
   * System flags
   */
   #define S_FLAGS 0 /* any system flags */
   #define S_BCSTENAB 0x1 /* enable broadcast client */
   /*
   * Peer flags
   */
   #define P_FLAGS 0 /* any peer flags */
   #define P_EPHEM 0x01 /* association is ephemeral */
   #define P_BURST 0x02 /* burst enable */
   #define P_IBURST 0x04 /* intial burst enable */
   #define P_NOTRUST 0x08 /* authenticated access */
   #define P_NOPEER 0x10 /* authenticated mobilization */

   /*
   * Authentication codes
   */
   #define A_NONE 0 /* no authentication */
   #define A_OK 1 /* authentication OK */
   #define A_ERROR 2 /* authentication error */
   #define A_CRYPTO 3 /* crypto-NAK */

   /*
   * Association state codes
   */
   #define X_INIT 0 /* initialization */
   #define X_STALE 1 /* timeout */
   #define X_STEP 2 /* time step */
   #define X_ERROR 3 /* authentication error */
   #define X_CRYPTO 4 /* crypto-NAK received */
   #define X_NKEY 5 /* untrusted key */

   /*
   * Protocol mode definitionss
   */
   #define M_RSVD 0 /* reserved */
   #define M_SACT 1 /* symmetric active */
   #define M_PASV 2 /* symmetric passive */
   #define M_CLNT 3 /* client */
   #define M_SERV 4 /* server */
   #define M_BCST 5 /* broadcast server */
   #define M_BCLN 6 /* broadcast client */
   /*
   * Clock state definitions
   */
   #define NSET 0 /* clock never set */
   #define FSET 1 /* frequency set from RFC 4330, "Simple Network Time
   Protocol (SNTP) Version file */
   #define SPIK 2 /* spike detected */
   #define FREQ 3 /* frequency mode */
   #define SYNC 4 for IPv4, IPv6 /* clock synchronized */

A.3.  Packet Data Structures
   /*
   * The receive and OSI."  As transmit packets may
   contain an optional message
   * authentication code (MAC) consisting of a result,
   key identifier (keyid) and * message digest (mac).
   NTPv4 supports optional extension fields which * are
    inserted after the
   authors would like to acknowledge D. Plonka of the University of
   Wisconsin header and J. Montgomery of Netgear, who were contributors.  The
   authors would also like to thank B. Haberman for providing rigorous
   reviews before the MAC,
    but these are * not described here.
   *

   * Receive packet
   *
   * Note the dst timestamp is not part of this document.

14.  References

14.1.  Normative References

   [1]  Mills, D., "Network Time Protocol (Version 3) Specification,
        Implementation", RFC 1305, March 1992.

14.2.  Informative References

   [2]   Mills, D., "Simple Network Time Protocol (SNTP) Version 4 for
         IPv4, IPv6 and OSI", RFC 4330, January 2006.

   [3]   Deering, S. and R. Hinden, "Internet Protocol, Version 6 (IPv6)
         Specification", RFC 2460, December 1998.

   [4]   Colella, R., Callon, R., Gardner, E., the packet
    itself. It is
   * captured upon arrival and Y. Rekhter,
         "Guidelines for OSI NSAP Allocation returned in the Internet", RFC 1629,
         May 1994.

   [5]   International Standards Organization, "International Standards
         8602 - Information Processing Systems - OSI: Connectionless
         Transport Protocol Specification.", NDSS , December 1986.

   [6]   Shue, C., Haggerty, W., and K. Dobbins, "OSI connectionless
         transport services on top
    receive buffer along with
   * the buffer length and data. Note that some
    of UDP: Version 1", RFC 1240,
         June 1991.

   [7]   Furniss, P., "Octet Sequences for Upper-Layer OSI to Support
         Basic Communications Applications", RFC 1698, October 1994.

   [8]   Bradner, S., "Key words for use the char fields are
   * packed in the actual header, but the
    details are omited here.
   */
   struct r {
   ipaddr  srcaddr;  /* source (remote) address */
   ipaddr  dstaddr;  /* destination (local) address */
   char  version;  /* version number */
   char  leap;  /* leap indicator */
   char  mode;  /* mode */
   char  stratum;  /* stratum */
   char  poll;  /* poll interval */
   s_char  precision;  /* precision */
   tdist  rootdelay;  /* root delay */
   tdist  rootdisp;  /* root dispersion */
   char  refid;  /* reference ID */
   tstamp  reftime;  /* reference time */
   tstamp  org;  /* origin timestamp */
   tstamp  rec;  /* receive timestamp */
   tstamp  xmt;  /* transmit timestamp */
   int  keyid;  /* key ID */
   digest  digest;  /* message digest */
   tstamp  dst;  /* destination timestamp */
   } r;

   /*
   * Transmit packet
   */
   struct x {
   ipaddr  dstaddr;  /* source (local) address */
   ipaddr  srcaddr;  /* destination (remote) address */
   char  version;  /* version number */
   char  leap;  /* leap indicator */
   char  mode;  /* mode */
   char  stratum;  /* stratum */
   char  poll;  /* poll interval */
   s_char  precision;  /* precision */
   tdist  rootdelay;  /* root delay */
   tdist  rootdisp;  /* root dispersion */
   char  refid;  /* reference ID */
   tstamp  reftime;  /* reference time */
   tstamp  org;  /* origin timestamp */
   tstamp  rec;  /* receive timestamp */
   tstamp  xmt;  /* transmit timestamp */
   int keyid; /* key ID */
   digest digest; /* message digest */
   } x;

   A.1.3 Association Data Structures

   /*
   * Filter stage structure. Note the t member in RFCs to Indicate Requirement
         Levels", BCP 14, RFC 2119, March 1997.

   [9]   Postel, J., "User Datagram Protocol", STD 6, RFC 768,
         August 1980.

   [10]  Postel, J., "Internet Protocol", STD 5, RFC 791,
         September 1981.

   [11]  Mills, D., "Network Time Protocol (version 2) specification and
         implementation", STD 12, RFC 1119, September 1989.

   [12]  Mills, D., "Network Time Protocol (version 1) specification and
         implementation", RFC 1059, July 1988.

   [13]  Postel, J. and J. Reynolds, "File Transfer Protocol", STD 9,
         RFC 959, October 1985.

   [14]  Meyer, D., "Administratively Scoped IP Multicast", BCP 23,
         RFC 2365, July 1998.

   [15]  Bellovin, S. this and E. Rescorla, "Deploying a New Hash Algorithm",
         Proceedings other
   * structures refers to process time, not real time. Process time
   * increments by one second for every elapsed second of real time.
   */
   struct f {
   tstamp   t;   /* update time */
   double   offset;   /* clock ofset */
   double   delay;   /* roundtrip delay */
   double   disp;   /* dispersion */
   } f;

   /*
   * Association structure. This is shared between the 13th Annual ISOC Network
    peer process and Distributed * poll process.
   */
   struct p {

   /*
   * Variables set by configuration
   */
   ipaddr   srcaddr;   /* source (remote) address */
   ipport   srcport;   /* source port number *.
   ipaddr   dstaddr;   /* destination (local) address */
   ipport   dstport;   /* destination port number */
   char   version;   /* version number */
   char   mode;   /* mode */
   int   keyid;   /* key identifier */
   int   flags;   /* option flags */
   /*
   * Variables set by received packet
   */
   char   leap;   /* leap indicator */
   char   mode;   /* mode */
   char   stratum;   /* stratum */
   char   ppoll;   /* peer poll interval */
   double   rootdelay;   /* root delay */
   double   rootdisp;   /* root dispersion */
   char   refid;   /* reference ID */
   tstamp   reftime;   /* reference time */
   #define   begin_clear org   /* beginning of clear area */
   tstamp   org;   /* originate timestamp */
   tstamp   rec;   /* receive timestamp */
   tstamp   xmt;   /* transmit timestamp */

   /*
   * Computed data
   */
   double   t;   /* update time */
   struct f f[NSTAGE];   /* clock filter */
   double   offset;   /* peer offset */
   double   delay;   /* peer delay */
   double   disp;   /* peer dispersion */
   double   jitter;   /* RMS jitter */

   /*
   * Poll process variables
   */
   char   hpoll;   /* host poll interval */
   int   burst;   /* burst counter */
   int   reach;   /* reach register */
   #define   end_clear unreach   /* end of clear area */
   int   unreach;   /* unreach counter */
   int   last;   /* last poll time */
   int   next;   /* next poll time */
   } p;
   A.1.4 System Security Symposium (NDSS) , February 2006.

   [16]  Narten, T. and H. Alvestrand, "Guidelines Data Structures

   /*
   * Chime list. This is used by the intersection algorithm.
   */
   struct m {   /* m is for Writing an IANA
         Considerations Section in RFCs", BCP 26, RFC 2434,
         October 1998.

Appendix A.  NTP Control Messages

   In Marzullo */
   struct p *p;   /* peer structure pointer */
   int   type;   /* high +1, mid 0, low -1 */
   double   edge;   /* correctness interval edge */
   } m;
   /*
   * Survivor list. This is used by the clustering algorithm.
   */
   struct v {
   struct p *p;   /* peer structure pointer */
   double   metric;   /* sort metric */
   } v;
   /*
   * System structure
   */
   struct s {
   tstamp   t;   /* update time */
   char   leap;   /* leap indicator */
   char   stratum;   /* stratum */
   char   poll;   /* poll interval */
   char   precision;   /* precision */
   double   rootdelay;   /* root delay */
   double   rootdisp;   /* root dispersion */
   char   refid;   /* reference ID */
   tstamp   reftime;   /* reference time */
   struct m m[NMAX];   /* chime list */
   struct v v[NMAX];   /* survivor list */
   struct p *p;   /* association ID */
   double   offset;   /* combined offset */
   double   jitter;   /* combined jitter */
   int   flags;   /* option flags */
   } s;
   A.1.5 Local Clock Data Structure

   /*
   * Local clock structure
   */
   struct c {
   tstamp   t;   /* update time */
   int   state;   /* current state */
   double   offset;   /* current offset */
   double   base;   /* base offset */
   double   last;   /* previous offset */
   int   count;   /* jiggle counter */
   double   freq;   /* frequency */
   double   jitter;   /* RMS jitter */
   double   wander;   /* RMS wander */
   } c;
   A.1.6 Function Prototypes

   /*
   * Peer process
   */
   void   receive(struct r *);   /* receive packet */
   void   fast_xmit(struct r *, int, int);
   /* transmit a comprehensive network-management environment, facilities are
   presumed available to perform routine NTP control and monitoring
   functions, such as setting reply packet */
   struct p *find_assoc(struct r *);
   /* search the leap-indicator bits at association table */
   void   packet(struct p *, struct r *);
   /* process packet */
   void   clock_filter(struct p *, double, double, double);
   /* filter */
   int   accept(struct p *);
   /* determine fitness of server */
   int   access(struct r *);
   /* determine access restrictions */

   /*
   * System process
   */
   void   clock_select();   /* find the primary
   servers, adjusting best clocks */
   void   clock_update(struct p *);   /* update the various system parameters and monitoring
   regular operations.  Ordinarily, these functions can be implemented
   using clock */
   void   clock_combine();   /* combine the offsets */
   double   root_dist(struct p *);   /* calculate root distance */

   /*
   * Clock discipline process
   */
   int   local_clock(struct p *, double); /* clock discipline */
   void   rstclock(int, double, double); /* clock state transition */

   /*
   * Clock adjust process
   */
   void   clock_adjust();   /* one-second timer process */

   /*
   * Poll process
   */
   void   poll(struct p *);   /* poll process */
   void   poll_update(struct p *, int); /* update the poll interval */
   void   peer_xmit(struct p *);   /* transmit a network-management protocol such as SNMP packet */

   /*
   * Main program and suitable
   extensions to the MIB database.  However, in those cases where such
   facilities are not available, these functions can be implemented
   using special NTP control messages described herein.  These messages
   are intended for use only in systems where no other management
   facilities are available or appropriate, such as in dedicated-
   function bus peripherals.  Support utility routines
   */
   int   main();   /* main program */
   struct p *mobilize(ipaddr, ipaddr, int, int, int, int);
    /* mobilize */
   void   clear(struct p *, int);   /* clear association */
   digest   md5(int);   /* generate a message digest */

   /*
   * Kernel I/O Interface
   */
   struct r *recv_packet();   /* wait for these messages is not required
   in order to conform to this specification.

   The packet */
   void   xmit_packet(struct x *);   /* send packet */

   .*
   * Kernel system clock interface
   */
   void   step_time(double);   /* step time */
   void   adjust_time(double);   /* adjust (slew) time */
   tstamp   get_time();   /* read time */
   A.2 Main Program and Utility Routines

   #include "ntp4.h"

   /*
   * Definitions
   */
   #define PRECISION -18   /* precision (log2 s)    */
   #define IPADDR   0   /* any IP address */
   #define MODE   0   /* any NTP Control Message has the value 6 specified in the mode field
   of the first octet of the NTP header */
   #define KEYID   0   /* any key identifier */

   /*
   * main() - main program
   */
   int
   main()
   {
   struct p *p;   /* peer structure pointer */
   struct r *r;   /* receive packet pointer */

   /*
   * Read command line options and is formatted as shown in
   Section 10.1.  The format of initialize system
    variables. * Implementations MAY measure the data field is precision
    specific * to each
   command or response; however, in most cases machine by measuring the format is designed clock
    increments to
   be constructed read the * system clock.
   */
   memset(&s, sizeof(s), 0);
   s.leap = NOSYNC;
   s.stratum = MAXSTRAT;
   s.poll = MINPOLL;
   s.precision = PRECISION;
   s.p = NULL;
   /*
   * Initialize local clock variables
   */
   memset(&c, sizeof(c), 0);
   if (/* frequency file */ 0) {
      c.freq = /* freq */ 0;
      rstclock(FSET, 0, 0);
    } else {
   rstclock(NSET, 0, 0);
   }
   c.jitter = LOG2D(s.precision);

   /*
   * Read the configuration file and viewed by humans mobilize persistent
   * associations with spcified addresses, version, mode,
    key ID * and so is coded in free-form
   ASCII.  This facilitates flags.
   */
   while (/* mobilize configurated associations */ 0) {
      p = mobilize(IPADDR, IPADDR, VERSION, MODE, KEYID,
      P_FLAGS);
   }

   /*
   * Start the specification system timer, which ticks once per second. Then
   * read packets as they arrive, strike receive timestamp and implementation of
   simple management tools in the absence of fully evolved network-
   management facilities.  As in ordinary NTP messages, the
   authenticator field follows the data field.  If the authenticator is
   used
   * call the data field receive() routine.
   */
   while (0) {
   r = recv_packet(); r->dst = get_time(); receive(r);
   }
   }

   /*
   * mobilize() - mobilize and initialize an association
   */
   struct p
   *mobilize(
   ipaddr   srcaddr,   /* IP source address */
   ipaddr   dstaddr,   /* IP destination address */
   int   version,   /* version */
   int   mode,   /* host mode */
   int   keyid,   /* key identifier */
   int   flags   /* peer flags */
   )
   {
   struct p *p;   /* peer process pointer */

   /*
   * Allocate and initialize association memory
   */
   p = malloc(sizeof(struct p));
   p->srcaddr = srcaddr;
   p->srcport = PORT;
   p->dstaddr = dstaddr;
   p->dstport = PORT;
   p->version = version;
   p->mode = mode;
   p->keyid = keyid;
   p->hpoll = MINPOLL;
   clear(p, X_INIT);
   p->flags == flags;
   return (p);
   }

   /*
   * clear() - reinitialize for persistent association,
    demobilize * for ephemeral association.
   */
   void
   clear(
   struct p *p,   /* peer structure pointer */
   int   kiss   /* kiss code */
   )
   {
   int i;

   /*
   * The first thing to do is zero-padded return all resources to a 32-bit boundary, but
    the
   padding bits bank. * Typical resources are not considered part of the data field detailed here
   , but they include * dynamically allocated structures
    for keys, certificates, etc. * If an ephemeral
    association and are not
   included in initialization, return * the field count.

   IP hosts are not required to reassemble datagrams larger than 576
   octets; however, some commands or responses may involve more data
   than will fit into a single datagram.  Accordingly, a simple
   reassembly feature is included in which each octet of association
    memory as well.
   */
   /* return resources */
   if (s.p == p)
   s.p = NULL;
   if (kiss != X_INIT && (p->flags & P_EPHEM)) {
      free(p);
   return;
   }

   /*
   * Initialize the message
   data is numbered starting with zero.  As each fragment is transmitted association fields for general reset.
   */
   memset(BEGIN_CLEAR(p), LEN_CLEAR, 0); p->leap = NOSYNC;
   p->stratum = MAXSTRAT;
   p->ppoll = MAXPOLL;
   p->hpoll = MINPOLL;
   p->disp = MAXDISP;
   p->jitter = LOG2D(s.precision); p->refid = kiss;
   for (i = 0; i < NSTAGE; i++)
      p->f[i].disp = MAXDISP;

   /*
   * Randomize the number of its first octet is inserted poll just in the offset field and the
   number case thousands
   of broadcast * clients have just been stirred up after
    a long absence of octets is inserted in the count field. * broadcast server.
   */
   p->last = p->t = c.t;
   p->next = p->last + (random() & ((1 << MINPOLL) - 1));
   }

   /*
   * md5() - compute message digest
   */
   digest
   md5(
   int   keyid   /* key identifier */
   )
   {
   /*
   * Compute a keyed cryptographic message digest.
   The more-data (M)
   bit key
   * identifier is set associated with a key in all fragments except the last.

   Most control functions involve sending a command and receiving a
   response, perhaps involving several fragments. local
    key cache.
    * The sender chooses a
   distinct, nonzero sequence number and sets key is prepended to the status field packet header and R
   extension fieds * and
   E bits to zero.  The responder interprets the opcode and additional
   information result hashed by the MD5
    algorithm as described in * RFC-1321. Return a MAC
    consisting of the data field, updates 32-bit key ID
   * concatenated with the status field, sets 128-bit digest.
   */
   return (/* MD5 digest */ 0);
   }
   A.3 Kernel Input/Output Interface

   /*
   * Kernel interface to transmit and receive packets. Details are
   * deliberately vague and depend on the R
   bit operating system.
   *
   * recv_packet - receive packet from network
   */
   struct r   /* receive packet pointer*/
   *recv_packet() {
   return (/* receive packet r */ 0);
   }

   /*
   * xmit_packet - transmit packet to one network
   */
   void
   xmit_packet(
   struct x *x   /* transmit packet pointer */
   )
   {
   /* send packet x */
   }
   A.4 Kernel System Clock Interface

   *
   * There are three time formats: native (Unix),
   NTP and floating double.
   * The get_time() routine returns the three time in NTP long
    format. The Unix
   * routines expect arguments as a structure of two
    signed 32-bit words of the header along
   with additional information
   * in the data field.  In case of invalid
   message format seconds and microseconds (timeval) or contents the responder inserts a code
    nanoseconds (timespec). The
   * step_time() and adjust_time() routines ex
   pect signed arguments in the status
   field, sets the R
   * floating double. The simplified code shown
   here is for illustration
   * only and E bits to one and, optionally, inserts a
   diagnostic message has not been verified.
   */
   #define JAN_1970   2208988800UL   /* 1970 - 1900 in the data field.

   Some commands seconds */

   /*
   * get_time - read or write system variables time and peer variables for
   an association identified convert to NTP format
   */
   tstamp
   get_time()
   {
   struct timeval unix_time;

   /*
   * There are only two calls on this routine in the command.  Others read or write
   variables associated with a radio clock or other device directly
   connected to program. One
   * when a source of primary synchronization information.  To
   identify which type of variable packet arrives from the network and association a 16-bit association
   identifier is used.  System variables are indicated by the identifier
   zero.  As each association is mobilized other when a unique, nonzero identifier
   * packet is created for it.  These identifiers are used in a cyclic fashion,
   so that placed on the chance of using an old identifier which matches a newly
   created association is remote.  A management entity can request a
   list send queue. Call the kernel time of current identifiers
   * day routine (such as gettimeofday()) and subsequently use them convert to read NTP
   * format.
   */
   gettimeofday(&unix_time, NULL);
   return ((unix_time.tv_sec + JAN_1970) * 0x100000000L +
      (unix_time.tv_usec * 0x100000000L) / 1000000);
    }

   /*
   * step_time() - step system time to given offset valuet
   */
   void
   step_time(
   double   offset   /* clock offset */
   )
   {
   struct timeval unix_time;
   tstamp   ntp_time;

   /*
   * Convert from double to native format (signed) and
   write variables for each association.  An attempt add to use an expired
   identifier results in an exception response, following which the list
   can be requested again.

   Some exception events, such as when a peer becomes reachable
   * current time. Note the addition is done in native format to
   * avoid overflow or
   unreachable, occur spontaneously loss of precision.
   */
   ntp_time = D2LFP(offset); gettimeofday(&unix_time, NULL);
   unix_time.tv_sec += ntp_time / 0x100000000L;
   unix_time.tv_usec += ntp_time % 0x100000000L;
   unix_time.tv_sec += unix_time.tv_usec / 1000000;
   unix_time.tv_usec %= 1000000;
   settimeofday(&unix_time, NULL);
   }

   /*
   * adjust_time() - slew system clock to given offset value
   */
   void
   adjust_time(
   double   offset   /* clock offset */
   )
   {
   struct timeval unix_time;
   tstamp   ntp_time;

   /*
   * Convert from double to native format (signed) and are not necessarily associated
   with a command.  An implementation may elect add to save the event
   information for later retrieval or to send an asynchronous response
   (called
   * current time.
   */
   ntp_time = D2LFP(offset);
   unix_time.tv_sec = ntp_time / 0x100000000L;
   unix_time.tv_usec = ntp_time % 0x100000000L;
   unix_time.tv_sec += unix_time.tv_usec / 1000000;
   unix_time.tv_usec %= 1000000;
   adjtime(&unix_time, NULL);
   }
   A.5 Peer Process

   #include "ntp4.h"

   /*
   * A crypto-NAK packet includes the NTP header followed
    by a trap) or both.  In case MAC
   * consisting only of a trap the IP address and port
   number is determined by key identifier with value zero.
    It tells the
   * receiver that a previous command prior request could not be properly
    authenticated,
   * but the NTP header fields are correct.
   *
   * A kiss-o'-death packet has an NTP header with leap 3
    (NOSYNC) and
   * stratum 0. It tells the sequence field is
   set receiver that something drastic
   * has happened, as described below.  Current status and summary information for revealled by the latest exception event is returned in all normal responses.  Bits kiss code in the status field indicate whether an exception has occurred since
    refid field. The
   * NTP header fields may or may not be correct.
   */
   /*
   * Definitions
   */
   #define SGATE   3   /* spike gate (clock filter */
   #define BDELAY   .004   /* broadcast delay (s) */

   /*
   * Dispatch codes
   */
   #define ERR   -1   /* error */
   #define DSCRD   0   /* discard packet */
   #define PROC   1   /* process packet */
   #define BCST   2   /* broadcast packet */
   #define FXMIT   3   /* client packet */
   #define NEWPS   4   /* new symmetric passive client */
   #define NEWBC   5   /* new broadcast client */

   /*
   * Dispatch matrix
   *   active passv client server bcast */
   int table[7][5] = {
   /* nopeer    */{ NEWPS, DSCRD, FXMIT, DSCRD, NEWBC },
   /* active    */{ PROC, PROC, DSCRD, DSCRD, DSCRD },
   /* passv    */{ PROC, ERR, DSCRD, DSCRD, DSCRD },
   /* client    */{ DSCRD, DSCRD, DSCRD, PROC, DSCRD },
   /* server    */{ DSCRD, DSCRD, DSCRD, DSCRD, DSCRD },
   /* bcast    */{ DSCRD, DSCRD, DSCRD, DSCRD, DSCRD },
   /* bclient */{ DSCRD, DSCRD, DSCRD, DSCRD, PROC}
   };

   /*
   * Miscellaneous macroni
   *
   * This macro defines the last response authentication state. If x is 0,
   * authentication is optional, othewise it is required.
   */
   #define AUTH(x, y)((x) ? (y) == A_OK : (y) == A_OK || \
      (y) == A_NONE)

   /*
   * These are used by the clear() routine
   */
   #define BEGIN_CLEAR(p)   ((char *)&((p)->begin_clear))
   #define END_CLEAR(p)   ((char *)&((p)->end_clear))
   #define LEN_CLEAR (END_CLEAR ((struct p *)0) - \
      BEGIN_CLEAR((struct p *)0))
   A.5.1 receive()

   /*
   * receive() - receive packet and decode modes
   */
   void
   receive(
   struct r *r   /* receive packet pointer */
   )
   {
   struct p *p;   /* peer structure pointer
   int   auth;   /* authentication code */
   int   has_mac;   /* size of MAC */
   int   synch;   /* synchronized switch */
   int   auth;   /* authentication code */

   /*
   * Check access control lists. The intent here is to implement a
   * whitelist of those IP addresses specifically accepted and/or
   * a blacklist of those IP addresses specifically rejected.
   * There could be different lists for authenticated clients and whether more than one exception has occurred.

   Commands need
   * unauthenticated clients.
   */
   if (!access(r))
   return;   /* access denied */

   /*
   * The version must not necessarily be sent by an NTP peer, so ordinary
   access-control procedures may not apply; however, the optional mask/
   match mechanism suggested elsewhere in this document provides the
   capability to control access future. Format checks include
   * packet length, MAC length and extension field lengths, if
   * present.
   */
   if (r->version > VERSION /* or format error */)
   return;   /* format error */

   /*
   * Authentication is conditioned by mode number, so this could two switches which can be used to
   limit
   * specified on a per-client basis.
   *
   * P_NOPEER   do not mobilize an association unless
   *   authenticated
   * P_NOTRUST   do not allow access for control messages (mode 6) to selected address
   ranges.

A.1.  NTP Control Message Format

   The format of unless authenticated
   *   (implies P_NOPEER)*
   * There are four outcomes:
   *
   * A_NONE the NTP Control Message header, which immediately
   follows packet has no MAC
   * A_OK   the UDP header, packet has a MAC and authentication
   *   succeeds
   * A_ERROR   the packet has a MAC and authentication fails
   * A_CRYPTO   crypto-NAK. the MAC has four octets only.
   *
   * Note: The AUTH(x, y) macro is shown in Figure 7.  Following used to filter outcomes. If x
   * is a
   description zero, acceptable outcomes of its fields.  Bit positions marked as zero y are reserved NONE and should always be transmitted as zero.

     0                   1                   2                   3
     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |00 | VN  |  6  | REM |    Op   |           Sequence            |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |            Status             |         Association ID        |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |            Offset             |             Count             |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    .                                                               .
    .                     Data (468 Octets Max)                     .
    .                                                               .
    |                               |         Padding (zeros)       |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                   Authenticator (optional)(96)                |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

   Figure 7: NTP Control Message Format

   Version Number (VN): This OK. If x is
   * one, the only acceptable outcome of y is OK.
   */
   has_mac = /* length of MAC field */ 0; if (has_mac == 0) {
   auth = A_NONE;   /* not required */
   } else if (has_mac == 4) {
   auth == A_CRYPTO;   /* crypto-NAK */
   } else {
   if (r->mac != md5(r->keyid))
   auth = A_ERROR;   /* auth error */
   else
   auth = A_OK;   /* auth OK */
   }

   /*
   * Find association and dispatch code. If there is a three-bit integer indicating no
   * association to match, the NTP
   version number, currently four (4)

   Mode: This value of p->mode is assumed NULL.
   */
   p = find_assoc(r);
   switch(table[p->mode][r->mode]) {

   /*
   * Client packet. Send server reply (no association). If
   * authentication fails, send a three-bit integer indicating crypto-NAK packet.
   */
   case FXMIT:
   if (AUTH(p->flags & P_NOTRUST, auth))
      fast_xmit(r, M_SERV, auth);
   else if (auth == A_ERROR)
      fast_xmit(r, M_SERV, A_CRYPTO);
   return;   /* M_SERV packet sent */

   /*
   * New symmetric passive client (ephemeral association). It is
   * mobilized in the mode. same version as in the packet. If
   * authentication fails, send a crypto-NAK packet. If restrict
   * no-moblize, send a symmetric active packet instead.
   */
   case NEWPS:
   if (!AUTH(p->flags & P_NOTRUST, auth)) {
      if (auth == A_ERROR)
   fast_xmit(r, M_SACT, A_CRYPTO);
   return;   /* crypto-NAK packet sent */
   }
   if (!AUTH(p->flags & P_NOPEER, auth)) {
      fast_xmit(r, M_SACT, auth);
   return;   /* M_SACT packet sent */
   }
   p = mobilize(r->srcaddr, r->dstaddr, r->version, M_PASV,
      r->keyid, P_EPHEM);
   break;

   /*
   * New broadcast client (ephemeral association). It must have is mobilized
   * in the value 6, indicating an NTP control message.

   Response Bit (R): Set to zero for commands, one for responses.

   Error Bit (E): Set to zero for normal response, one for same version as in the packet. If authentication
   * error, ignore the packet.
   */
   case NEWBC:
   if (!AUTH(p->flags & (P_NOTRUST | P_NOPEER), auth))
   return;   /* authentication error
   response.

   More Bit (M): Set to zero for last fragment, one for all others.

   Operation Code (Op): This */

   if (!(s.flags & S_BCSTENAB))
   return;   /* broadcast not enabled */

   p = mobilize(r->srcaddr, r->dstaddr, r->version, M_BCLN,
      r->keyid, P_EPHEM);
   break;   /* processing continues */

   /*
   * Process packet. Placeholdler only.
   */
   case PROC:
   break;   /* processing continues */
   /*
   * Invalid mode combination. We get here only in case of
   * ephemeral associations, so the correct action is simply to
   * toss it.
   */
   case ERR:
   clear(p, X_ERROR);
   return;   /* invalid mode combination */

   /*
   * No match; just discard the packet.
   */
   case DSCRD:
   return;   /* orphan abandoned */
   }

   /*
   * Next comes a five-bit integer specifying rigorous schedule of timestamp checking. If the
   command function.  Values currently defined are given in Table 8.

            +-------+----------------------------------------+
            | Value |                 Meaning                |
            +-------+----------------------------------------+
            |   0   |                reserved                |
            |   1   |      read status command/response      |
            |   2   |     read variables command/response    |
            |   3   |    write variables command/response    |
            |   4   |  read clock variables command/response |
            |   5   | write clock variables command/response |
            |   6   | set trap address/port command/response |
            |   7   |              trap response             |
            |  8-31 |                reserved                |
            +-------+----------------------------------------+

                Table 8: Currently-defined Operation Codes

   Sequence: This
   * transmit timestamp is a 16-bit integer indicating zero, the sequence number of server is horribly broken.
   */
   if (r->xmt == 0)
   return;   /* invalid timestamp */

   /*
   * If the command or response.

   Status: This transmit timestamp duplicates a previous one, the
   * packet is a replay.
   */
   if (r->xmt == p->xmt)
   return;   /* duplicate packet */

   /*
   * If this is a 16-bit code indicating broadcast mode packet, skip further checking.
   * If the current status of origin timestamp is zero, the
   system, peer or clock, with values coded as described in following
   sections.

   Association ID: This sender has not yet heard
   * from us. Otherwise, if the origin timestamp does not match
   * the transmit timestamp, the packet is a 16-bit integer identifying a bogus.
   */
   synch = TRUE;
   if (r->mode != M_BCST) {
      if (r->org == 0)
   synch = FALSE;/* unsynchronized */

   else if (r->org != p->xmt)
   synch = FALSE;/* bogus packet */
   }

   /*
   * Update the origin and destination timestamps. If
   * unsynchronized or bogus, abandon ship.

   */
   p->org = r->xmt;
   p->rec = r->dst;
   if (!synch)
   return;   /* unsynch */

   /*
   * The timestamps are valid
   association.

   Offset: This and the receive packet matches the
   * last one sent. If the packet is a 16-bit integer indicating crypto-NAK, the offset, in octets, of server
   * might have just changed keys. We demobilize the first octet in association
   * and wait for better times.
   */
   if (auth == A_CRYPTO) {
      clear(p, X_CRYPTO);
   return;   /* crypto-NAK */
   }

   /*
   * If the data area.

   Count: association is authenticated, the key ID is nonzero
   * and received packets must be authenticated. This is designed *
    to avoid a 16-bit integer indicating the length of the data
   field, bait-and-switch attack, which was possible in octets.

   Data: This contains past
   * versions.
   */
   if (!AUTH(p->keyid || (p->flags & P_NOTRUST), auth))
   return;   /* bad auth */

   /*
   * Everything possible has been done to validate the message data for timestamps
   * and prevent bad guys from disrupting the command protocol or response.
   The maximum number of data octets is 468.

   Authenticator (optional): When
   * injecting bogus data. Earn some revenue.
   */
   packet(p, r);
   }

   /*
   * find_assoc() - find a matching association
   */
   struct p   /* peer structure pointer or NULL */
   *find_assoc(
   struct r *r   /* receive packet pointer */
   )
   {
   struct p *p;   /* dummy peer structure pointer */

   /*
   * Search association table for matching source * address and
    source port.
   */
   while (/* all associations */ 0) {
   if (r->srcaddr == p->srcaddr && r->port == p->port)
      return(p);
   }
   return (NULL);
   }
   A.5.2 packet()

   /*
   * packet() - process packet and compute offset, delay and
   * dispersion.
   */
   void
   packet(
   struct p *p,   /* peer structure pointer */
   struct r *r   /* receive packet pointer */
   )
   {
   double   offset;   /* sample offsset */
   double   delay;   /* sample delay */
   double   disp;   /* sample dispersion */

   /*
   * By golly the NTP authentication mechanism packet is
   implemented, this contains valid. Light up the authenticator information.

A.2.  Status Words

   Status words indicate remaining header
   * fields. Note that we map stratum 0 (unspecified) to MAXSTRAT
   * to make stratum comparisons simpler and to provide a natural
   * interface for radio clock drivers that operate for
   * convenience at stratum 0.
   */
   p->leap = r->leap;
   if (r->stratum == 0)
      p->stratum = MAXSTRAT; else
   p->stratum = r->stratum; p->mode = r->mode;
   p->ppoll = r->poll;
   p->rootdelay = FP2D(r->rootdelay); p->rootdisp = FP2D(r->rootdisp);
   p->refid = r->refid;
   p->reftime = r->reftime;

   /*
   * Verify the present status of server is synchronized with valid stratum and
   * reference time not later than the system, associations transmit time.
   */
   if (p->leap == NOSYNC || p->stratum >= MAXSTRAT)
   return;   /* unsynchronized */

   /*
   * Verify valid root distance.
   */
   if (r->rootdelay / 2 + r->rootdisp >= MAXDISP || p->reftime >
      r->xmt)
   return;   /* invalid header values */

   poll_update(p, p->hpoll);
   p->reach |= 1;

   /*
   * Calculate offset, delay and clock.  They are designed dispersion, then pass to be interpreted by network-monitoring
   programs and are the
   * clock filter. Note carefully the implied processing. The
   * first-order difference is done directly in one of four 16-bit formats described 64-bit arithmetic,
   * then the result is converted to floating double. All further
   * processing is in this
   section.  System and peer status words are associated floating double arithmetic with responses
   for all commands except rounding
   * done by the read clock variables, write clock
   variables hardware. This is necessary in order to avoid
   * overflow and set trap address/port commands. preseve precision.
   *
   * The association
   identifier zero specifies the system status word, while a nonzero
   identifier specifies delay calculation is a particular peer association.  The status word
   returned in response to read clock variables special case. In cases where the
   * server and write clock
   variables commands indicates client clocks are running at different rates and
   * with very fast networks, the state delay can appear negative. In
   * order to avoid violating the Principle of Least Astonishment,
   * the clock hardware and
   decoding software.  A special error status word delay is used to report
   malformed command fields or invalid values.

A.2.1.  System Status Word

   The clamped not less than the system status word appears in precision.
   */
   if (p->mode == M_BCST) {
   offset = LFP2D(r->xmt - r->dst); delay = BDELAY;
   disp = LOG2D(r->precision) + LOG2D(s.precision) + PHI *
      2 * BDELAY;
   } else {
   offset = (LFP2D(r->rec - r->org) + LFP2D(r->dst
      r->xmt)) / 2;
   delay = max(LFP2D(r->dst - r->org) - LFP2D(r->rec
      r->xmt), LOG2D(s.precision));
   disp = LOG2D(r->precision) + LOG2D(s.precision) + PHI *
      LFP2D(r->dst - r->org);
   }
   clock_filter(p, offset, delay, disp);
   }
   A.5.3 clock_filter()

   /*
   * clock_filter(p, offset, delay, dispersion) - select the status field of best
    from the response to
   a read status or read variables command with a zero association
   identifier. * latest eight delay/offset samples.
   */
   void
   clock_filter(
   struct p *p,   /* peer structure pointer */
   double   offset,   /* clock offset */
   double   delay,   /* roundtrip delay */
   double   disp   /* dispersion */
   )
   {
   struct f f[NSTAGE];/* sorted list */
   double   dtemp;
   int   i;

   /*
   * The format clock filter contents consist of eight tuples (offset,
   * delay, dispersion, time). Shift each tuple to the system status word is given in
   Figure 8.
     0                                       1
     0   1   2   3   4   5   6   7   8   9   0   1   2   3   4   5
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
   |  LI   |     Clock Source      |     Count     |     Code      |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

   Figure 8: System Status Word Format

   Leap Indicator (LI): This left,
   * discarding the leftmost one. As each tuple is shifted,
   * increase the dispersion since the last filter update. At the
   * same time, copy each tuple to a two-bit code warning temporary list. After this,
   * place the (offset, delay, disp, time) in the vacated
   * rightmost tuple.
   */
   for (i = 1; i < NSTAGE; i++) {
      p->f[i] = p->f[i - 1];
   p->f[i].disp += PHI * (c.t - p->t); f[i] = p->f[i];
   }
   p->f[0].t = c.t;
   p->f[0].offset = offset;
   p->f[0].delay = delay;
   p->f[0].disp = disp;
   f[0] = p->f[0];

   /*
   * Sort the temporary list of an impending
   leap second to tuples by increasing f[].delay. *
    The first entry on the sorted list represents the best * sample,
    but it might be inserted/deleted in old.
   */
   dtemp = p->offset;
   p->offset = f[0].offset;
   p->delay = f[0].delay;
   for (i = 0; i < NSTAGE; i++) {
      p->disp += f[i].disp / (2 ^ (i + 1));
      p->jitter += SQUARE(f[i].offset - f[0].offset);
    }
   p->jitter = max(SQRT(p->jitter), LOG2D(s.precision));

   /*
   * Prime directive: use a sample only once and never a sample
    * older than the latest one, but anything goes before first
    * synchronized.
   */
   if (f[0].t - p->t <= 0 && s.leap != NOSYNC)
      return;

   /*
   * Popcorn spike suppressor. Compare the difference between the
   * last minute of and current offsets to the current
   day, with bit 0 jitter. If greater
   * than SGATE (3) and bit 1, respectively, coded as shown in Table 9.

           +-------+------------------------------------------+
           | Value |                  Meaning                 |
           +-------+------------------------------------------+
           |   00  |                no warning                |
           |   01  |        last minute has 61 seconds        |
           |   10  | if the interval since the last minute has 59 seconds        |
           |   11  | alarm condition (clock not synchronized) |
           +-------+------------------------------------------+

                       Table 9: Leap Indicator Field

   Clock Source: This offset is a six-bit integer indicating
   * less than twice the current
   synchronization source, with values coded as shown system poll interval, dump the spike.
   * Otherwise, and if not in Table 10.

    +-------+---------------------------------------------------------+
    | Value |                         Meaning                         |
    +-------+---------------------------------------------------------+
    |   0   |                  unspecified or unknown                 |
    |   1   |         Calibrated atomic clock (e.g.,, HP 5061)        |
    | a burst, shake out the truechimers.
   */
   if (fabs(p->offset - dtemp) > SGATE * p->jitter && (f[0].t
      p->t) < 2   | VLF (band 4) or LF (band 5) radio (e.g.,, OMEGA,, WWVB) |
    |   3   |       HF (band 7) radio (e.g.,, CHU,, MSF,, WWV/H)      |
    |   4   |        UHF (band 9) satellite (e.g.,, GOES,, GPS)       |
    |   5   |            local net (e.g.,, DCN,, TSP,, DTS)           |
    |   6   |                         UDP/NTP                         |
    |   7   |                         UDP/TIME                        |
    |   8   |                        wall time                        |
    |   9   |               telephone modem (e.g.  NIST)              |
    | 10-31 |                         reserved                        |
    |   32  |                        PPS signal                       |
    | 33-63 |                         reserved                        |
    +-------+---------------------------------------------------------+

                    Table 10: Clock Source Field Values

   System Event Counter: * s.poll)
   return;

   p->t = f[0].t;
   if (p->burst == 0)
      clock_select();
   return;
   }
   A.5.4 fast_xmit()

   /*
   * fast_xmit() - transmit a reply packet for receive packet r
   */
   void
   fast_xmit(
   struct r *r,   /* receive packet pointer */
   int   mode,   /* association mode */
   int   auth   /* authentication code */
   )
   {
   struct x x;

   /*
   * Initialize header and transmit timestamp. Note that
   the * transmit version is copied from the receive version.
    This is a four-bit integer indicating * for backward compatibility.
   */
   x.version = r->version;
   x.srcaddr = r->dstaddr;
   x.dstaddr = r->srcaddr;
   x.leap = s.leap;
   x.mode = mode;
   if (s.stratum == MAXSTRAT)
      x.stratum = 0;
   else
   x.stratum = s.stratum; x.poll = r->poll;
   x.precision = s.precision;
   x.rootdelay = D2FP(s.rootdelay); x.rootdisp = D2FP(s.rootdisp);
    x.refid = s.refid;
   x.reftime = s.reftime;
   x.org = r->xmt;
   x.rec = r->dst;
   x.xmt = get_time();

   /*
   * If the
   number of system exception events occurring since authentication code is A.NONE, include only the last time
   * header; if A.CRYPTO, send a crypto-NAK; if A.OK, send a valid
   * MAC. Use the
   system status word was returned key ID in a response or included the received packet and the key in a trap
   message. the
   * local key cache.
   */
   if (auth != A_NONE) {
      if (auth == A_CRYPTO) {
      x.keyid = 0;
   } else {
   x.keyid = r->keyid;
   x.digest = md5(x.keyid);
   }
   }
   xmit_packet(&x);
   }
   A.5.5 access()

   /*
   * access() - determine access restrictions
   */
   int
   access(
   struct r *r   /* receive packet pointer */
   )
   {
   /*
   * The counter access control list is cleared when returned in the status field an ordered set of
   a response tuples
   * consisting of an address, mask and freezes when it reaches the value 15.

   System Event Code: This restrict word containing
   * defined bits. The list is a four-bit integer identifying searched for the latest
   system exception event, with new values overwriting previous values, first match on the
   * source address (r->srcaddr) and coded as shown in Table 11.

   +-------+-----------------------------------------------------------+
   | Value |                          Meaning                          |
   +-------+-----------------------------------------------------------+
   |   0   |                        unspecified                        |
   |   1   |                       system restart                      |
   |   2   |                  system or hardware fault                 |
   |   3   |    system new status the associated restrict word (leap
   * is returned.
   */
   return (/* access bits or synchronization   |
   |       |                          change)                          |
   |   4   | system new synchronization source or stratum (sys.peer or |
   |       |                    sys.stratum) change                    |
   |   5   |  system clock reset (offset correction exceeds CLOCK.MAX) |
   |   6   |                system invalid time or date                |
   |   7   |   system clock exception (see system clock status word)   |
   |  8-15 |                          reserved                         |
   +-------+-----------------------------------------------------------+

                    Table 11: */ 0);
   }
   A.6 System Event Code Values

A.2.2.  Peer Status Word

   A Process

   #include "ntp4.h"

   A.6.1 clock_select()

   /*
   * clock_select() - find the best clocks
   */
   void
   clock_select() {
   struct p *p, *osys;   /* peer status word is returned in structure pointers */
   double   low, high;   /* correctness interval extents */
   int   allow, found, chime; /* used by intersecion algorithm */
   int   n, i, j;

   /*
   * We first cull the status field of a response to a
   read status, read variables or write variables command and appears
   also in falsetickers from the list of association identifiers and status words returned
   by a read status command with a zero server population,
   * leaving only the truechimers. The correctness interval for
   * association identifier. p is the interval from offset - root_dist() to
   * offset + root_dist(). The
   format object of a peer status word is shown in Figure 9.
     0                                       1
     0   1   2   3   4   5   6   7   8   9   0   1   2   3   4   5
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
   |    Peer Status    |    Sel    |     Count     |     Code      |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
   Peer Status Word

   Figure 9: Peer Status Word Format

   Peer Status: This the game is to find a five-bit code indicating the status
   * majority clique; that is, an intersection of correctness
   * intervals numbering more than half the
   peer determined by server population.
   *
   * First construct the packet procedure, with bits assigned chime list of tuples (p, type, edge) as
   * shown
   in Table 12.

           +-------+------------------------------------------+
           | Value |                  Meaning                 |
           +-------+------------------------------------------+
           |   0   |         configured (peer.config)         |
           |   1   | authentication enabled (peer.authenable) |
           |   2   |   authentication okay (peer.authentic)   |
           |   3   |      reachability okay (peer.reach)      |
           |   4   |                 reserved                 |
           +-------+------------------------------------------+

                       Table 12: Peer Status Values

   Peer Selection (Sel): This below, then sort the list by edge from lowest to
   * highest.
   */
   osys = s.p;
   s.p = NULL;
   n = 0;
   while (accept(p)) {
      s.m[n].p = p;
   s.m[n].type = +1;
   s.m[n].edge = p->offset + root_dist(p);
   n++;
   s.m[n].p = p;
   s.m[n].type = 0;
   s.m[n].edge = p->offset;
   n++;
   s.m[n].p = p;
   s.m[n].type = -1;
   s.m[n].edge = p->offset - root_dist(p);
   n++;
   }

   /*
   * Find the largest contiguous intersection of correctness
   * intervals. Allow is a three-bit integer indicating the
   status number of allowed falsetickers; found
   * is the peer determined by number of midpoints. Note that the clock-selection procedure, with edge values coded as shown in Table 13.

   +-------+-----------------------------------------------------------+
   | Value |                          Meaning                          |
   +-------+-----------------------------------------------------------+
   |   0   |                          rejected                         |
   |   1   |                    passed sanity checks                   |
   | are
   * limited to the range +-(2 ^ 30) < +-2e9 by the timestamp
   * calculations.
   */
   low = 2e9; high = -2e9;
   for (allow = 0; 2   |                 passed correctness checks                 |
   |   3   |    passed candidate checks (if limit check implemented)   |
   |   4   |                   passed outlyer checks                   |
   |   5   | current synchronization source; max distance exceeded (if |
   |       |                  limit check implemented)                 |
   |   6   |     current synchronization source; max distance okay     |
   |   7   |                          reserved                         |
   +-------+-----------------------------------------------------------+

                   Table 13: Peer Selection Field Values

   Peer Event Counter: This is a four-bit integer indicating * allow < n; allow++) {
   /*
   * Scan the chime list from lowest to highest to find
   * the lower endpoint.

   */
   found = 0;
   chime = 0;
   for (i = 0; i < n; i++) {
      chime -= s.m[i].type;
      if (chime >= n - found) {
      low = s.m[i].edge;
   break;
   }
   if (s.m[i].type == 0)
      found++;
   }

   /*
   * Scan the chime list from highest to lowest to find
   * the upper endpoint.
   */
   chime = 0;
   for (i = n - 1; i >= 0; i--) {
      chime += s.m[i].type;
   if (chime >= n - found) {
      high = s.m[i].edge;
      break;
   }
   if (s.m[i].type == 0)
      found++;
   }

   /*
   * If the number of peer exception events that occurred since midpoints is greater than the last time number
   * of allowed falsetickers, the peer
   status word was returned in a response or included in a trap message.
   The counter is cleared when returned in intersection contains at
   * least one truechimer with no midpoint. If so,
   * increment the status field number of a
   response allowed falsetickers and go
   * around again. If not and freezes when it reaches the value 15.

   Peer Event Code: This intersection is
   * nonempty, declare success.
   */
   if (found > allow)
      continue;

   if (high > low)
      break;
   }

   /*
   * Clustering algorithm. Construct a four-bit integer identifying list of survivors
   (p, * metric) from the latest
   peer exception event, with new values overwriting previous values, chime list, where metric is dominated
    first * by stratum and coded as shown in Table 14.

   +-------+-----------------------------------------------------------+
   | Value |                          Meaning                          |
   +-------+-----------------------------------------------------------+
   |   0   |                        unspecified                        |
   |   1   |                       peer IP error                       |
   |   2   |  peer authentication failure (peer.authentic bit was one  |
   |       |                         now zero)                         |
   |   3   |     peer unreachable (peer.reach was nonzero now zero)    |
   |   4   |      peer reachable (peer.reach was zero now nonzero)     |
   |   5   |     peer clock exception (see peer clock status word)     |
   |  6-15 |                          reserved                         |
   +-------+-----------------------------------------------------------+

                        Table 14: Peer Event Codes

A.2.3.  Clock Status Word then by root distance. All other
    things being * equal, this is the order of preference.

   */
   n = 0;
   for (i = 0; i < n; i++) {
   if (s.m[i].edge < low || s.m[i].edge > high)
      continue;

   p = s.m[i].p;
   s.v[n].p = p;
   s.v[n].metric = MAXDIST * p->stratum + root_dist(p);
   n++;
   }

   /*
   * There are two ways a reference clock can must be attached at least NSANE survivors to a NTP service
   host, satisfy the
   * correctness assertions. Ordinarily, the Byzantine criteria
   * require four, susrvivors, but for the demonstration here, one
   * is acceptable.
   */
   if (n == NSANE)
      return;

   /*
   * For each association p in turn, calculate the selection
   * jitter p->sjitter as an dedicated device managed by the operating system and square root of the sum of squares
   * (p->offset - q->offset) over all q associations. The idea is
   * to repeatedly discard the survivor with maximum selection
   * jitter until a termination condition is met.
   */
   while (1) {
   struct p *p, *q, *qmax;/* peer structure pointers */
   double   max, min, dtemp;

   max = -2e9; min = 2e9; for (i = 0; i < n; i++) {
      p = s.v[i].p;
   if (p->jitter < min)
      min = p->jitter;
   dtemp = 0;
   for (j = 0; j < n; j++) {
      q = s.v[j].p;
   dtemp += SQUARE(p->offset - q->offset);
   }
   dtemp = SQRT(dtemp); if (dtemp > max) {
      max = dtemp;
   qmax = q;
   }
   }

   /*
   * If the maximum selection jitter is less than the
   * minimum peer jitter, then tossing out more survivors
   * will not lower the minimum peer jitter, so we might
   * as well stop. To make sure a
   synthetic peer managed by NTP.  As in few survivors are left
   * for the read status command, clustering algorithm to chew on, we also stop
   * if the
   association identifier number of survivors is used less than or equal to identify which one, zero for
   * NMIN (3).
   */
   if (max < min || n <= NMIN)
      break;

   /*
   * Delete survivor qmax from the
   system clock list and nonzero for a peer go around * again.
   */
   n--;
   }

   /*
   * Pick the best clock.  Only one system clock is
   supported by If the protocol, although many peer clocks can be
   supported.  A old system or peer clock status word appears in is on the status
   field of list
   * and at the response to same stratum as the first survivor on the list,
   * then don't do a read clock variables or write clock
   variables command.  This word can be considered an extension of hop. Otherwise, select the
   system status word or first
   * survivor on the peer status word list as appropriate. the new system peer.
   */
   if (osys->stratum == s.v[0].p->stratum)
      s.p = osys;
   else
   s.p = s.v[0].p;
   clock_update(s.p);
   }
   A.6.2 root_dist()

   /*
   * root_dist() - calculate root distance
   */
   double
   root_dist(
   struct p *p   /* peer structure pointer */
   )
   {
   /*
   * The
   format root synchronization distance is the maximum error due to
   * all causes of the local clock status word relative to the primary server.
   * It is shown in Figure 10.
     0                                       1
     0   1   2   3   4   5   6   7   8   9   0   1 defined as half the total delay plus total dispersion
   * plus peer jitter.
   */
   return (max(MINDISP, p->rootdelay + p->delay) / 2   3   4   5
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
   |          Clock Status         |            Code               |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

   Figure 10: Clock Status Word Format

   Clock Status: This +
      p->rootdisp + p->disp + PHI * (c.t - p->t) + p->jitter);
    }
   A.6.3 accept()

   /*
   * accept() - test if association p is acceptable for
    synchronization
   */
   int
   accept(
   struct p *p   /* peer structure pointer */
   )
   {
   /*
   * A stratum error occurs if (1) the server has never been
   * synchronized, (2) the server stratum is invalid.
   */
   if (p->leap == NOSYNC || p->stratum >= MAXSTRAT)
      return (FALSE);

   /*
   * A distance error occurs if the root distance exceeds the
   * distance threshold plus an increment equal to one poll
   * interval.
   */
   if (root_dist(p) > MAXDIST + PHI * LOG2D(s.poll))
      return (FALSE);

   /*
   * A loop error occurs if the remote peer is synchronized to the
   * local peer or the remote peer is an eight-bit integer indicating synchronized to the current
   * system peer. Note this is the behavior for IPv4; for IPv6 the
   * MD5 hash is used instead.
   */
   if (p->refid == p->dstaddr || p->refid == s.refid)
      return (FALSE);

   /*
   * An unreachable error occurs if the server is unreachable.
   */
   if (p->reach == 0)
      return (FALSE);

   return (TRUE);
   }
   A.6.4 clock_update()

   /*
   * clock_update() - update the system clock status, with values coded
   */
   void
   clock_update(
   struct p *p   /* peer structure pointer */
   )
   {
   double dtemp;

   /*
   * If this is an old update, for instance as shown in Table 15.

                  +-------+----------------------------+
                  | Value |           Meaning          |
                  +-------+----------------------------+
                  |   0   |  clock nominally operating |
                  |   1   |        reply timeout       |
                  |   2   |      bad reply format      |
                  |   3   | hardware the result of a
   * system peer change, avoid it. We never use an old sample or software fault |
                  |   4   |     propagation failure    |
                  |   5   |  bad date format
   * the same sample twice.
   *
   if (s.t >= p->t)
   return;

   /*
   * Combine the survivor offsets and update the system clock; the
   * local_clock() routine will tell us the good or value  |
                  |   6   | bad time format or value  |
                  | 7-255 |          reserved          |
                  +-------+----------------------------+

                       Table 15: Clock Status Values

   Clock Event Code: This news.
   */
   s.t = p->t;
   clock_combine();
   switch (local_clock(p, s.offset)) {

   /*
   * The offset is an eight-bit integer identifying too large and probably bogus. Complain to the
   * system log and order the operator to set the latest clock exception event, with new values overwriting previous values.
   When manually
   * within PANIC range. An implementation MAY include a change
   * command line option to any nonzero value occurs in disable this check and to change the radio status field,
   * panic threshold from the radio status field default 1000 s as required.
   */
   case PANIC:
   exit (0);

   /*
   * The offset is copied to more than the clock event code field and step threshold (0.125 s by
   * default). After a
   system or peer step, all associations now have
   * inconsistent time valurs, so they are reset and started
   * fresh. The step threshold MAY be changed in an
   * implementation in order to lessen the chance the clock exception event is declared as appropriate.

A.2.4.  Error Status Word

   An error status word might
   * be stepped backwards. However, there may be serious
   * consequences.
   */
   case STEP:
   while (/* all associations */ 0)
   clear(p, X_STEP);
   s.stratum = MAXSTRAT;
   s.poll = MINPOLL;
   break;
   /*
   * The offset was less than the step threshold, which is returned in the status field of an error
   response as
   * normal case. Update the result of invalid message format or contents.  Its
   presence system variables from the peer
   * variables. The lower clamp on the dispersion increase is indicated to
   * avoid timing loops and clockhopping when highly precise
   * sources are in play. The clamp MAY be changed from the E (error) bit
   * suggested default of .01 s.
   */
   case SLEW:
   s.leap = p->leap;
   s.stratum = p->stratum + 1; s.refid = p->refid;
   s.reftime = p->reftime;
   s.rootdelay = p->rootdelay + p->delay;
   dtemp = SQRT(SQUARE(p->jitter) + SQUARE(s.jitter));
   dtemp += max(p->disp + PHI * (c.t - p->t) +
   fabs(p->offset), MINDISP);
   s.rootdisp = p->rootdisp + dtemp; break;

   /*
   * Some samples are discarded while, for instance, a direct
   * frequency measurement is set along being made.
   */
   case IGNORE:
   break;
   }
   }
   A.6.5 clock_combine()

   /*
   * clock_combine() - combine offsets
   */
   void
   clock_combine()
   {
   struct p *p;/* peer structure pointer */
   double x, y, z, w;
   int i;

   /*
   * Combine the offsets of the clustering algorithm survivors
   * using a weighted average with weight determined by the
   response (R) bit in the response.  It consists of an eight-bit
   integer coded root
   * distance. Compute the selection jitter as shown in Figure 11.

     0                                       1
     0   1   2   3   4   5   6   7   8   9   0   1   2   3   4   5
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
   |          Error Code           |           Reserved            |
   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

   Figure 11: Error Status Word Format

   Currently-defined error codes are given in Table 16.

               +-------+----------------------------------+
               | Value |              Meaning             |
               +-------+----------------------------------+
               |   0   |            unspecified           |
               |   1   |      authentication failure      |
               |   2   | invalid message length or format |
               |   3   |          invalid opcode          |
               |   4   |  unknown association identifier  |
               |   5   |       unknown variable name      |
               |   6   |      invalid variable value      |
               |   7   |    administratively prohibited   |
               | 8-255 |             reserved             |
               +-------+----------------------------------+

                        Table 16: Error Code Values

A.3.  Commands

   Commands consist of the header weighted RMS
   * difference between the first survivor and optional data field of the Status
   Word.  When present, remaining
   * survivors. In some cases the data field contains a list of identifiers or
   assignments in inherent clock jitter can be
   * reduced by not using this algorithm, especially when frequent
   * clockhopping is involved.
   */
   y = z = w = 0;
   for (i = 0; s.v[i].p != NULL; i++) {
   p = s.v[i].p;
   x = root_dist(p);
   y += 1 / x;
   z += p->offset / x;
   w += SQUARE(p->offset - s.v[0].p->offset) / x;
   }
   s.offset = z / y;
   s.jitter = SQRT(w / y);
   }
   A.6.6 local_clock()

   #include "ntp4.h"

   /*
   * Constants
   */
   #define STEPT.128/* step threshold (s) */
   #define WATCH900/* stepout threshold (s) */
   #define PANICT1000/* panic threshold (s) */
   #define PLL65536/* PLL loop gain */
   #define FLLMAXPOLL + 1/* FLL loop gain */
   #define AVG 4/* parameter averaging constant */
   #define ALLAN1500/* compromise Allan intercept (s) */
   #define LIMIT  30  /* poll-adjust threshold */
   #define MAXFREQ  500e-6
    /* maximum frequency tolerance (s/s) */
   #define PGATE  4  /* poll-adjust gate */

   /*
   * local_clock() - discipline the local clock
   */
   int  /* return code */
   local_clock(
   struct p *p,  /* peer structure pointer */
   double  offset  /* clock offset from combine() */
   )
   {
   int  state;  /* clock discipline state */
   double  freq;  /* frequency */
   double  mu;  /* interval since last update */
   int  rval;
   double  etemp, dtemp;

   /*
   * If the form

   <<identifier>>[=<<value>>],<<identifier>>[=<<value>>],... offset is too large, give up and go home.
   */
   if (fabs(offset) > PANICT)
     return (PANIC);

   /*
   * Clock state machine transition function. This is where <<identifier>> the
   * action is and defines how the ASCII name of a system or peer variable
   specified in Table 2 or Table 3 of [1] reacts to large time
   * and <<value>> is expressed as
   a decimal, hexadecimal or string constant in frequency errors. There are two main regimes: when the syntax of
   * offset exceeds the C
   programming language.  Where no ambiguity exists, step threshold and when it does not.
   */
   rval = SLEW;
   mu = p->t - s.t;
   freq = 0;
   if (fabs(offset) > STEPT) {
     switch (c.state) {

   /*
   * In S_SYNC state we ignore the <169>sys.<170>
   or <169>peer.<170> prefixes shown in Table 2 or Table 4 of [1] can be
   suppressed.  Whitespace (ASCII nonprinting format effectors) can be
   added first outlyer amd
   * switch to improve readability for simple monitoring programs that do
   not reformat S_SPIK state.
   */
   case SYNC:
     state = SPIK;
     return (rval);
   /*
   * In S_FREQ state we ignore outlyers and inlyers. At
   * the data field.  Internet addresses are represented as
   four octets in first outlyer after the form [n.n.n.n], where n is in decimal notation and stepout threshold,
   * compute the brackets are optional.  Timestamps, including reference,
   originate, receive apparent frequency correction and transmit values, as well as step
   * the logical clock,
   are represented time.
   */
   case FREQ:
   if (mu < WATCH)
     return (IGNORE);

   freq = (offset - c.base - c.offset) / mu;
   /* fall through to S_SPIK */

   /*
   * In S_SPIK state we ignore succeeding outlyers until
   * either an inlyer is found or the stepout threshold is
   * exceeded.
   */
   case SPIK:
   if (mu < WATCH)
     return (IGNORE);

   /* fall through to default */

   /*
   * We get here by default in units of seconds S_NSET and fractions, preferably in
   hexadecimal notation, while delay, offset, dispersion S_FSET states
   * and distance
   values are represented from above in units of milliseconds S_FREQ state. Step the time and fractions,
   preferably in decimal notation.All other values are represented
   as-is, preferably in decimal notation.

   Implementations may define variables other than those listed in Table
   2 or Table 3 of [1].  Called extramural variables, these are
   distinguished by
   * clamp down the poll interval.
   *
   * In S_NSET state an initial frequency correction is
   * not available, usually because the frequency file has
   * not yet been written. Since the time is outside the
   * capture range, the clock is stepped. The frequency
   * will be set directly following the stepout interval.
   *
   * In S_FSET state the initial frequency has been set
   * from the inclusion of some character type other than
   alphanumeric or <169>.<170> in frequency file. Since the name.  For those commands that
   return a list of assignments in time is outside
   * the response data field, if capture range, the
   command data field clock is empty, stepped immediately,
   * rather than after the stepout interval. Guys get
   * nervous if it takes 17 minutes to set the clock for
   * the first time.
   *
   * In S_SPIK state the stepout threshold has expired and
   * the phase is expected still above the step threshold. Note
   * that all available
   variables defined in Table 3 or Table 4 of [1] will be included in a single spike greater than the response.  For step threshold
   * is always suppressed, even at the read commands, longer poll
   * intervals.
   */
   default:

   /*
   * This is the kernel set time function, usually
   * implemented by the Unix settimeofday() system
   * call.
   */
   step_time(offset); c.count = 0;
   rval = STEP;
   if (state == NSET) {
     rstclock(FREQ, p->t, 0);
     return (rval);
   }
   break;
   }
   rstclock(SYNC, p->t, 0);
   } else {

   /*
   * Compute the command data field is
   nonempty, an implementation may choose to process this field to
   individually select which variables are to be returned.

   Commands are interpreted clock jitter as follows:

   Read Status (1): The command data field is empty or contains a list the RMS of identifiers separated exponentially
   * weighted offset differences. This is used by commas.  The command operates in two ways
   depending on the value of
   * poll-adjust code.
   */
   etemp = SQUARE(c.jitter);
   dtemp = SQUARE(max(fabs(offset - c.last),
     LOG2D(s.precision)));
   c.jitter = SQRT(etemp + (dtemp - etemp) / AVG);
   switch (c.state) {

   /*
   * In S_NSET state this is the association identifier.  If first update received and
   * the frequency has not been initialized. The first
   * thing to do is directly measure the oscillator
   * frequency.
   */
   case NSET:
   c.offset = offset;
   rstclock(FREQ, p->t, offset); return (IGNORE);

   /*
   * In S_FSET state this
   identifier is nonzero, the response includes first update and the peer identifier
   * frequency has been initialized. Adjust the phase, but
   * don't adjust the frequency until the next update.
   */
   case FSET:
   c.offset = offset; break;

   /*
   * In S_FREQ state ignore updates until the stepout
   * threshold. After that, correct the phase and
   status word.  Optionally,
   * frequency and switch to S_SYNC state.
   */
   case FREQ:
   if (c.t - s.t < WATCH)
     return (IGNORE);

   freq = (offset - c.base - c.offset) / mu;
   break;

   /*
   * We get here by default in S_SYNC and S_SPIK states.
   * Here we compute the response data field may contain other
   information, such as described frequency update due to PLL and
   * FLL contributions.
   */
   default:

   /*
   * The FLL and PLL frequency gain constants
   * depend on the poll interval and Allan
   * intercept. The FLL is not used below one-half
   * the Allan intercept. Above that the loop gain
   * increases in steps to 1 / AVG.
   */
   if (LOG2D(s.poll) > ALLAN / 2) {
     etemp = FLL - s.poll;
   if (etemp < AVG)
     etemp = AVG;
   freq += (offset - c.offset) / (max(mu,
     ALLAN) * etemp);
   }

   /*
   * For the Read Variables command.  If PLL the
   association identifier integration interval
   * (numerator) is zero, the response includes minimum of the system
   identifier (0) update
   * interval and status word, while poll interval. This allows
   * oversampling, but not undersampling.
   */
   etemp = min(mu, LOG2D(s.poll));
   dtemp = 4 * PLL * LOG2D(s.poll);
   freq += offset * etemp / (dtemp * dtemp);
   break;
   }
   rstclock(SYNC, p->t, offset);
   }

   /*
   * Calculate the data field contains a list new frequency and frequency stability (wander).
   * Compute the clock wander as the RMS of binary-coded pairs

   <<association identifier>> <<status word>>,

   one for each currently defined association.

   Read Variables (2): The command data field exponentially weighted
   * frequency differences. This is empty or contains not used directly, but can,
   * along withthe jitter, be a
   list of identifiers separated highly useful monitoring and
   * debugging tool
   */
   freq += c.freq;
   c.freq = max(min(MAXFREQ, freq), -MAXFREQ);
   etemp = SQUARE(c.wander);
   dtemp = SQUARE(freq);
   c.wander = SQRT(etemp + (dtemp - etemp) / AVG);

   /*
   * Here we adjust the poll interval by commas. comparing the current
   * offset with the clock jitter. If the association
   identifier offset is nonzero, less than the response includes
   * clock jitter times a constant, then the requested peer
   identifier averaging interval is
   * increased, otherwise it is decreased. A bit of hysteresis
   * helps calm the dance. Works best using burst mode.
   */
   if (fabs(c.offset) < PGATE * c.jitter) {
     c.count += s.poll;
   if (c.count > LIMIT) {
     c.count = LIMIT;
   if (s.poll < MAXPOLL) {
     c.count = 0;
   s.poll++;
   }
   }
   } else {
   c.count -= s.poll << 1; if (c.count < -LIMIT) {
     c.count = -LIMIT;
   if (s.poll > MINPOLL) {
     c.count = 0;
   s.poll--;
   }
   }
   }
   return (rval);
   }
   A.6.7 rstclock()

   /*
   * rstclock() - clock state machine
   */
   void
   rstclock(
   int  state,  /* new state */
   double  offset,  /* new offset */
   double  t  /* new update time */
   )
   {
   /*
   * Enter new state and status word, while set state variables. Note we use the data field contains a list
   time
   * of
   peer variables and values as described above.  If the association
   identifier is zero, last clock filter sample, which must be
   earlier than
   * the data field contains a list of system
   variables and values.  If a peer has been selected as current time.
   */
   c.state = state;
   c.base = offset - c.offset;
   c.last = c.offset = offset;
   s.t = t;
   }

   A.7 Clock Adjust Process

   A.7.1 clock_adjust()

   /*
   * clock_adjust() - runs at one-second intervals
   */
   void
   clock_adjust() {
   double  dtemp;
   /*
   * Update the
   synchronization source, process time c.t. Also increase the response includes dispersion
   * since the peer identifier and
   status word; otherwise, last update. In contrast to NTPv3, NTPv4 does not
   * declare unsynchronized after one day, since the response includes dispersion
   * threshold serves this function. When the system identifier
   (0) and status word.

   Write Variables (3): The command data field contains a list of
   assignments as described above.  The variables are updated as
   indicated.  The response dispersion exceeds
   * MAXDIST (1 s), the server is as described considered unaccept for
   * synchroniztion.
   */
   c.t++;
   s.rootdisp += PHI;

   /*
   * Implement the Read Variables
   command.

   Read Clock Variables (4): phase and frequency adjustments. The command data field gain
   * factor (denominator) is empty or contains
   a list of identifiers separated not allowed to increase beyond the
   * Allan intercept. It doesn't make sense to average phase noise
   * beyond this point and it helps to damp residual offset at the
   * longer poll intervals.
   */
   dtemp = c.offset / (PLL * min(LOG2D(s.poll), ALLAN));
   c.offset -= dtemp;

   /*
   * This is the kernel adjust time function, usually implemented
   * by commas.  The association
   identifier selects the Unix adjtime() system clock variables or call.
   */
   adjust_time(c.freq + dtemp);

   /*
   * Peer timer. Call the poll() routine when the poll timer
   * expires.
   */
   while (/* all associations */ 0) {
   struct p *p;/* dummy peer structure pointer */

   if (c.t >= p->next)
   poll(p);
   }

   /*
   * Once per hour write the clock variables frequency to a file
   */
   if (c.t % 3600 == 3599)
   /* write c.freq to file */ 0;
   }
   A.8 Poll Process

   #include "ntp4.h"
   /*
   * Constants
   */
   #define UNREACH  12  /* unreach counter threshold */
   #define BCOUNT  8  /* packets in a burst */
   #define BTIME  2  /* burst interval (s) */
   A.8.1 poll()

   /*
   * poll() - determine when to send a packet for association p->
   */
   void
   poll(
   struct p *p  /* peer structure pointer */
   )
   {
   int  hpoll;
   int  oreach;

   /*
   * This routine is called when the same way as in current time c.t catches up
   * to the Read Variables command. next poll time p->next. The response
   includes value p->last is
   * the requested clock identifier and status word and last time this routine was executed. The poll_update()
   * routine determines the data
   field contains next execution time p->next.
   *
   * If broadcasting, just do it, but only if we are synchronized.
   */
   hpoll = p->hpoll;
   if (p->mode == M_BCST) {
     p->last = c.t;
   if (s.p != NULL)
     peer_xmit(p);
   poll_update(p, hpoll); return;
   }
   if (p->burst == 0) {

   /*
   * We are not in a list of clock variables and values, including burst. Shift the
   last timecode message received from reachability
   * register to the clock.

   Write Clock Variables (5): The command data field contains left. Hopefully, some time before the
   * next poll a list of
   assignments as described above. packet will arrive and set the rightmost
   * bit.
   */
   p->last = c.t;
   oreach = p->reach;
   p->reach << 1;
   if (!p->reach) {

   /*
   * The clock variables are updated as
   indicated. server is unreachable, so bump the
   * unreach counter. If the unreach threshold has
   * been reached, double the poll interval to
   * minimize wasted network traffic.
   */
   if (p->flags & P_IBURST && p->unreach == 0) {
     p->burst = BCOUNT;
   } else if (p->unreach < UNREACH)
     p->unreach++;
   else
   hpoll++;
   p->unreach++;
   } else {

   /*
   * The response server is as described reachable. However, if has not
   * been heard for three consecutive poll
   * intervals, stuff the Read Clock Variables
   command.

   Set Trap Address/Port (6): The command association identifier, status
   and data fields are ignored.  The address clock register to
   * increase the peer dispersion. This makes old
   * servers less desirable and port number for
   subsequent trap messages are taken from eventually boots
   * them off the island.
   */
   p->unreach = 0;
   if (!(p->reach & 0x7))
   clock_filter(p, 0, 0, MAXDISP); hpoll = s.poll;
   if (p->flags & P_BURST && accept(p))
     p->burst = BCOUNT;
   }
   } else {

   /*
   * If in a burst, count it down. When the source address and port
   of reply comes
   * back the control message itself.  The initial trap counter for trap
   response messages is taken from clock_filter() routine will call
   * clock_select() to process the sequence field results of the command.
   The response association identifier, status and data fields are burst.
   */
   p->burst--;
   }

   /*
   * Do not
   significant.  Implementations should include sanity timeouts which
   prevent trap transmissions transmit if in broadcast client mode.
   */
   if (p->mode != M_BCLN)
     peer_xmit(p);
   poll_update(p, hpoll);
   }
   A.8.2 poll_update()

   /*
   * poll_update() - update the monitoring program does not renew
   this information after a lengthy interval.

   Trap Response (7): poll interval for association p
   *
   * Note: This message routine is sent called by both the packet() and
    poll() routine.
   * Since the packet() routine is executed when a system, network
    packet arrives
   * and the poll() routine is executed as the result of
    timeout, a
   * potential race can occur, possibly causing an incorrect
    interval for
   * the next poll. This is considered so unlikely as to
    be negligible.
   */
   void
   poll_update(
   struct p *p,  /* peer or clock
   exception event occurs.  The opcode field structure pointer */
   int  hpoll  /* poll interval (log2 s) */
   )
   {
   int  poll;

   /*
   * This routine is 7 called by both the poll() and packet()
   * routines to determine the R bit next poll time. If within a burst
   * the poll interval is set.
   The trap counter two seconds. Otherwise, it is incremented the
   * minimum of the host poll interval and peer poll interval, but
   * not greater than MAXPOLL and not less than MINPOLL. The
   * design insures that a longer interval can be preempted by a
   * shorter one if required for each trap sent and rapid response.
   */
   p->hpoll = min(MAXPOLL, max(MINPOLL, hpoll)); if (p->burst != 0) {
   if(c.t != p->next)
     return;

   p->next += BTIME;
   } else {
   poll = min(p->hpoll, max(MINPOLL, ppoll));
   }
   /*
   * While not shown here, an implementation
   * SHOULD randomize the
   sequence field set to poll interval by a small factor.
   */
   p->next = p->last + (1 << poll);
   }

   /*
   * It might happen that value.  The trap message is sent using the
   IP address and port fields established by due time has already passed. If so,
   * make it one second in the set trap address/port
   command. future.

   */
   if (p->next <= c.t)
   p->next = c.t + 1;
   }
   A.8.3 transmit()

   /*
   * transmit() - transmit a packet for association p
   */
   void
   peer_xmit(
   struct p *p/* peer structure pointer */
   )
   {
   struct x x;/* transmit packet */

   /*
   * Initialize header and transmit timestamp
   */
   x.srcaddr = p->dstaddr;
   x.dstaddr = p->srcaddr;
   x.leap = s.leap;
   x.version = VERSION;
   x.mode = p->mode;
   if (s.stratum == MAXSTRAT)
     x.stratum = 0;
   else
   x.stratum = s.stratum; x.poll = p->hpoll;
   x.precision = s.precision;
   x.rootdelay = D2FP(s.rootdelay); x.rootdisp = D2FP(s.rootdisp);
    x.refid = s.refid;
   x.reftime = s.reftime;
   x.org = p->org;
   x.rec = p->rec;
   x.xmt = get_time();
   p->xmt = x.xmt;

   /*
   * If the key ID is nonzero, send a system trap valid MAC using the key ID
   * of the association identifier field is set to
   zero and the status field contains key in the system status word. local key cache. If
   * something breaks, like a peer
   trap missing trusted key, don't send the
   * packet; just reset the association identifier field is set to that peer and stop until the
   status field contains the peer status word.  Optional ASCII-coded
   information can be included in the data field. problem
   * is fixed.
   */
   if (p->keyid)
   if (/* p->keyid invalid */ 0) {
     clear(p, X_NKEY);
   return;
   }
   x.digest = md5(p->keyid); xmit_packet(&x);
   }

Authors' Addresses

   Jack Burbank (editor)
   The Johns Hopkins University Applied Physics Laboratory
   11100 Johns Hopkins Road
   Laurel, MD  20723-6099
   US

   Phone: +1 443 778 7127
   Email: jack.burbank@jhuapl.edu

   Jim Martin (editor)
   Netzwert AG
   An den Treptowers 1
   Berlin  12435
   Germany

   Phone: +49.30/5 900 80-1180
   Email: jim@netzwert.ag

   Dr. David L. Mills
   University of Delaware
   Newark, DE  19716
   US

   Phone: +1 302 831 8247
   Email: mills@udel.edu

Full Copyright Statement

   Copyright (C) The Internet Society (2006).

   This document is subject to the rights, licenses and restrictions
   contained in BCP 78, and except as set forth therein, the authors
   retain all their rights.

   This document and the information contained herein are provided on an
   "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
   OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
   ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
   INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Intellectual Property Statement

   The IETF takes no position regarding the validity or scope of any
   Intellectual Property Rights or other rights that might be claimed to
   pertain to the implementation or use of the technology described in
   this document or the extent to which any license under such rights
   might or might not be available; nor does it represent that it has
   made any independent effort to identify any such rights.  Information
   on the procedures with respect to rights in RFC documents can be
   found in BCP 78 and BCP 79.

   Copies of IPR disclosures made to the IETF Secretariat and any
   assurances of licenses to be made available, or the result of an
   attempt made to obtain a general license or permission for the use of
   such proprietary rights by implementers or users of this
   specification can be obtained from the IETF on-line IPR repository at
   http://www.ietf.org/ipr.

   The IETF invites any interested party to bring to its attention any
   copyrights, patents or patent applications, or other proprietary
   rights that may cover technology that may be required to implement
   this standard.  Please address the information to the IETF at
   ietf-ipr@ietf.org.

Disclaimer of Validity

   This document and the information contained herein are provided on an
   "AS IS" basis and THE CONTRIBUTOR, THE ORGANIZATION HE/SHE REPRESENTS
   OR IS SPONSORED BY (IF ANY), THE INTERNET SOCIETY AND THE INTERNET
   ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED,
   INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
   INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED
   WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

Copyright Statement

   Copyright (C) The Internet Society (2006).  This document is subject
   to the rights, licenses and restrictions contained in BCP 78, and
   except as set forth therein, the authors retain all their rights.

Acknowledgment

   Funding for the RFC Editor function is currently provided by the
   Internet Society. IETF
   Administrative Support Activity (IASA).