001    package railo.runtime.net.ntp;
002    
003    import java.text.DecimalFormat;
004    import java.util.Date;
005    
006    import railo.commons.i18n.DateFormatPool;
007    
008    public final class NtpMessage
009    {
010            /**
011             * This is a two-bit code warning of an impending leap second to be
012             * inserted/deleted in the last minute of the current day.  It's values
013             * may be as follows:
014             * 
015             * Value     Meaning
016             * -----     -------
017             * 0         no warning
018             * 1         last minute has 61 seconds
019             * 2         last minute has 59 seconds)
020             * 3         alarm condition (clock not synchronized)
021             */
022            public byte leapIndicator = 0;
023            
024            
025            /**
026             * This value indicates the NTP/SNTP version number.  The version number
027             * is 3 for Version 3 (IPv4 only) and 4 for Version 4 (IPv4, IPv6 and OSI).
028             * If necessary to distinguish between IPv4, IPv6 and OSI, the
029             * encapsulating context must be inspected.
030             */
031            public byte version = 3;
032            
033            
034            /**
035             * This value indicates the mode, with values defined as follows:
036             * 
037             * Mode     Meaning
038             * ----     -------
039             * 0        reserved
040         * 1        symmetric active
041         * 2        symmetric passive
042         * 3        client
043         * 4        server
044         * 5        broadcast
045         * 6        reserved for NTP control message
046         * 7        reserved for private use
047         * 
048         * In unicast and anycast modes, the client sets this field to 3 (client)
049         * in the request and the server sets it to 4 (server) in the reply. In
050         * multicast mode, the server sets this field to 5 (broadcast).
051         */ 
052            public byte mode = 0;
053            
054            
055            /**
056             * This value indicates the stratum level of the local clock, with values
057             * defined as follows:
058         * 
059         * Stratum  Meaning
060         * ----------------------------------------------
061         * 0        unspecified or unavailable
062         * 1        primary reference (e.g., radio clock)
063         * 2-15     secondary reference (via NTP or SNTP)
064         * 16-255   reserved
065             */
066            public short stratum = 0;
067            
068    
069            /**
070             * This value indicates the maximum interval between successive messages,
071             * in seconds to the nearest power of two. The values that can appear in
072             * this field presently range from 4 (16 s) to 14 (16284 s); however, most
073             * applications use only the sub-range 6 (64 s) to 10 (1024 s).
074             */
075            public byte pollInterval = 0;
076            
077            
078            /**
079             * This value indicates the precision of the local clock, in seconds to
080             * the nearest power of two.  The values that normally appear in this field\
081             * range from -6 for mains-frequency clocks to -20 for microsecond clocks
082             * found in some workstations.
083             */
084            public byte precision = 0;
085            
086            
087            /**
088             * This value indicates the total roundtrip delay to the primary reference
089             * source, in seconds.  Note that this variable can take on both positive
090             * and negative values, depending on the relative time and frequency
091             * offsets. The values that normally appear in this field range from
092             * negative values of a few milliseconds to positive values of several
093             * hundred milliseconds.
094             */
095            public double rootDelay = 0;
096            
097            
098            /**
099             * This value indicates the nominal error relative to the primary reference
100             * source, in seconds.  The values  that normally appear in this field
101             * range from 0 to several hundred milliseconds.
102             */     
103            public double rootDispersion = 0;
104            
105            
106            /**
107             * This is a 4-byte array identifying the particular reference source.
108             * In the case of NTP Version 3 or Version 4 stratum-0 (unspecified) or
109             * stratum-1 (primary) servers, this is a four-character ASCII string, left
110             * justified and zero padded to 32 bits. In NTP Version 3 secondary
111             * servers, this is the 32-bit IPv4 address of the reference source. In NTP
112             * Version 4 secondary servers, this is the low order 32 bits of the latest
113             * transmit timestamp of the reference source. NTP primary (stratum 1)
114             * servers should set this field to a code identifying the external
115             * reference source according to the following list. If the external
116             * reference is one of those listed, the associated code should be used.
117             * Codes for sources not listed can be contrived as appropriate.
118             * 
119             * Code     External Reference Source
120             * ----     -------------------------
121         * LOCL     uncalibrated local clock used as a primary reference for
122         *          a subnet without external means of synchronization
123         * PPS      atomic clock or other pulse-per-second source
124         *          individually calibrated to national standards
125         * ACTS     NIST dialup modem service
126         * USNO     USNO modem service
127         * PTB      PTB (Germany) modem service
128         * TDF      Allouis (France) Radio 164 kHz
129         * DCF      Mainflingen (Germany) Radio 77.5 kHz
130         * MSF      Rugby (UK) Radio 60 kHz
131         * WWV      Ft. Collins (US) Radio 2.5, 5, 10, 15, 20 MHz
132         * WWVB     Boulder (US) Radio 60 kHz
133         * WWVH     Kaui Hawaii (US) Radio 2.5, 5, 10, 15 MHz
134         * CHU      Ottawa (Canada) Radio 3330, 7335, 14670 kHz
135         * LORC     LORAN-C radionavigation system
136         * OMEG     OMEGA radionavigation system
137         * GPS      Global Positioning Service
138         * GOES     Geostationary Orbit Environment Satellite
139         */
140            public byte[] referenceIdentifier = {0, 0, 0, 0};
141            
142            
143            /**
144             * This is the time at which the local clock was last set or corrected, in
145             * seconds since 00:00 1-Jan-1900.
146             */
147            public double referenceTimestamp = 0;
148            
149            
150            /**
151             * This is the time at which the request departed the client for the
152             * server, in seconds since 00:00 1-Jan-1900.
153             */
154            public double originateTimestamp = 0;
155            
156            
157            /**
158             * This is the time at which the request arrived at the server, in seconds
159             * since 00:00 1-Jan-1900.
160             */
161            public double receiveTimestamp = 0;
162            
163            
164            /**
165             * This is the time at which the reply departed the server for the client,
166             * in seconds since 00:00 1-Jan-1900.
167             */
168            public double transmitTimestamp = 0;
169            
170            
171            
172            /**
173             * Constructs a new NtpMessage from an array of bytes.
174             * @param array
175             */
176            public NtpMessage(byte[] array)
177            {
178                    // See the packet format diagram in RFC 2030 for details 
179                    leapIndicator = (byte) ((array[0] >> 6) & 0x3);
180                    version = (byte) ((array[0] >> 3) & 0x7);
181                    mode = (byte) (array[0] & 0x7);
182                    stratum = unsignedByteToShort(array[1]);
183                    pollInterval = array[2];
184                    precision = array[3];
185                    
186                    rootDelay = (array[4] * 256.0) + 
187                            unsignedByteToShort(array[5]) +
188                            (unsignedByteToShort(array[6]) / 256.0) +
189                            (unsignedByteToShort(array[7]) / 65536.0);
190                    
191                    rootDispersion = (unsignedByteToShort(array[8]) * 256.0) + 
192                            unsignedByteToShort(array[9]) +
193                            (unsignedByteToShort(array[10]) / 256.0) +
194                            (unsignedByteToShort(array[11]) / 65536.0);
195                    
196                    referenceIdentifier[0] = array[12];
197                    referenceIdentifier[1] = array[13];
198                    referenceIdentifier[2] = array[14];
199                    referenceIdentifier[3] = array[15];
200                    
201                    referenceTimestamp = decodeTimestamp(array, 16);
202                    originateTimestamp = decodeTimestamp(array, 24);
203                    receiveTimestamp = decodeTimestamp(array, 32);
204                    transmitTimestamp = decodeTimestamp(array, 40);
205            }
206            
207            
208            
209            /**
210             * Constructs a new NtpMessage
211             * @param leapIndicator
212             * @param version
213             * @param mode
214             * @param stratum
215             * @param pollInterval
216             * @param precision
217             * @param rootDelay
218             * @param rootDispersion
219             * @param referenceIdentifier
220             * @param referenceTimestamp
221             * @param originateTimestamp
222             * @param receiveTimestamp
223             * @param transmitTimestamp
224             */
225            public NtpMessage(byte leapIndicator,
226                    byte version,
227                    byte mode,
228                    short stratum,
229                    byte pollInterval,
230                    byte precision,
231                    double rootDelay,
232                    double rootDispersion,
233                    byte[] referenceIdentifier,
234                    double referenceTimestamp,
235                    double originateTimestamp,
236                    double receiveTimestamp,
237                    double transmitTimestamp)
238            {
239                    // ToDo: Validity checking
240                    this.leapIndicator = leapIndicator;
241                    this.version = version;
242                    this.mode = mode;
243                    this.stratum = stratum;
244                    this.pollInterval = pollInterval;
245                    this.precision = precision;
246                    this.rootDelay = rootDelay;
247                    this.rootDispersion = rootDispersion;
248                    this.referenceIdentifier = referenceIdentifier;
249                    this.referenceTimestamp = referenceTimestamp;
250                    this.originateTimestamp = originateTimestamp;
251                    this.receiveTimestamp = receiveTimestamp;
252                    this.transmitTimestamp = transmitTimestamp;
253            }
254            
255            
256            
257            /**
258             * Constructs a new NtpMessage in client -> server mode, and sets the
259             * transmit timestamp to the current time.
260             */
261            public NtpMessage()
262            {
263                    // Note that all the other member variables are already set with
264                    // appropriate default values.
265                    this.mode = 3;
266                    this.transmitTimestamp = (System.currentTimeMillis()/1000.0) + 2208988800.0; 
267            }
268            
269            
270            
271            /**
272             * This method constructs the data bytes of a raw NTP packet.
273             * @return
274             */
275            public byte[] toByteArray()
276            {
277                    // All bytes are automatically set to 0
278                    byte[] p = new byte[48];
279    
280                    p[0] = (byte) (leapIndicator << 6 | version << 3 | mode);
281                    p[1] = (byte) stratum;
282                    p[2] = pollInterval;
283                    p[3] = precision;
284                    
285                    // root delay is a signed 16.16-bit FP, in Java an int is 32-bits
286                    int l = (int) (rootDelay * 65536.0);
287                    p[4] = (byte) ((l >> 24) & 0xFF);
288                    p[5] = (byte) ((l >> 16) & 0xFF);
289                    p[6] = (byte) ((l >> 8) & 0xFF);
290                    p[7] = (byte) (l & 0xFF);
291                    
292                    // root dispersion is an unsigned 16.16-bit FP, in Java there are no
293                    // unsigned primitive types, so we use a long which is 64-bits 
294                    long ul = (long) (rootDispersion * 65536.0);
295                    p[8] = (byte) ((ul >> 24) & 0xFF);
296                    p[9] = (byte) ((ul >> 16) & 0xFF);
297                    p[10] = (byte) ((ul >> 8) & 0xFF);
298                    p[11] = (byte) (ul & 0xFF);
299                    
300                    p[12] = referenceIdentifier[0];
301                    p[13] = referenceIdentifier[1];
302                    p[14] = referenceIdentifier[2];
303                    p[15] = referenceIdentifier[3];
304                    
305                    encodeTimestamp(p, 16, referenceTimestamp);
306                    encodeTimestamp(p, 24, originateTimestamp);
307                    encodeTimestamp(p, 32, receiveTimestamp);
308                    encodeTimestamp(p, 40, transmitTimestamp);
309                    
310                    return p; 
311            }
312            
313            
314            
315            /**
316             * Returns a string representation of a NtpMessage
317             * @return
318             */
319            public String toString()
320            {
321                    String precisionStr = new DecimalFormat("0.#E0").format(Math.pow(2, precision));
322                    return "Leap indicator: " + leapIndicator + "\n" +
323                    "Version: " + version + "\n" +
324                    "Mode: " + mode + "\n" +
325                    "Stratum: " + stratum + "\n" +
326                    "Poll: " + pollInterval + "\n" +
327                    "Precision: " + precision + " (" + precisionStr + " seconds)\n" + 
328                    "Root delay: " + new DecimalFormat("0.00").format(rootDelay*1000) + " ms\n" +
329                    "Root dispersion: " + new DecimalFormat("0.00").format(rootDispersion*1000) + " ms\n" + 
330                    "Reference identifier: " + referenceIdentifierToString(referenceIdentifier, stratum, version) + "\n" +
331                    "Reference timestamp: " + timestampToString(referenceTimestamp) + "\n" +
332                    "Originate timestamp: " + timestampToString(originateTimestamp) + "\n" +
333                    "Receive timestamp:   " + timestampToString(receiveTimestamp) + "\n" +
334                    "Transmit timestamp:  " + timestampToString(transmitTimestamp);
335            }
336            
337            
338            
339            /**
340             * Converts an unsigned byte to a short.  By default, Java assumes that
341             * a byte is signed.
342             * @param b
343             * @return
344             */
345            public static short unsignedByteToShort(byte b)
346            {
347                    if((b & 0x80)==0x80) return (short) (128 + (b & 0x7f));
348                    return b;
349            }
350            
351            
352            
353            /**
354             * Will read 8 bytes of a message beginning at <code>pointer</code>
355             * and return it as a double, according to the NTP 64-bit timestamp
356             * format.
357             * @param array
358             * @param pointer
359             * @return
360             */
361            public static double decodeTimestamp(byte[] array, int pointer)
362            {
363                    double r = 0.0;
364                    
365                    for(int i=0; i<8; i++)
366                    {
367                            r += unsignedByteToShort(array[pointer+i]) * Math.pow(2, (3-i)*8);
368                    }
369                    
370                    return r;
371            }
372            
373            
374            
375            /**
376             * Encodes a timestamp in the specified position in the message
377             * @param array
378             * @param pointer
379             * @param timestamp
380             */
381            public static void encodeTimestamp(byte[] array, int pointer, double timestamp)
382            {
383                    // Converts a double into a 64-bit fixed point
384                    for(int i=0; i<8; i++)
385                    {
386                            // 2^24, 2^16, 2^8, .. 2^-32
387                            double base = Math.pow(2, (3-i)*8);
388                            
389                            // Capture byte value
390                            array[pointer+i] = (byte) (timestamp / base);
391    
392                            // Subtract captured value from remaining total
393                            timestamp = timestamp - (unsignedByteToShort(array[pointer+i]) * base);
394                    }
395                    
396                    // From RFC 2030: It is advisable to fill the non-significan't
397                    // low order bits of the timestamp with a random, unbiased
398                    // bitstring, both to avoid systematic roundoff errors and as
399                    // a means of loop detection and replay detection.
400                    array[7] = (byte) (Math.random()*255.0);
401            }
402            
403            
404            
405            /**
406             * Returns a timestamp (number of seconds since 00:00 1-Jan-1900) as a
407             * formatted date/time string. 
408             * @param timestamp
409             * @return
410             */
411            public static String timestampToString(double timestamp)
412            {
413                    if(timestamp==0) return "0";
414                    
415                    // timestamp is relative to 1900, utc is used by Java and is relative
416                    // to 1970 
417                    double utc = timestamp - (2208988800.0);
418                    
419                    // milliseconds
420                    long ms = (long) (utc * 1000.0);
421                    
422                    // date/time
423                    String date = DateFormatPool.format("dd-MMM-yyyy HH:mm:ss",new Date(ms));
424                    
425                    // fraction
426                    double fraction = timestamp - ((long) timestamp);
427                    String fractionSting = new DecimalFormat(".000000").format(fraction);
428                    
429                    return date + fractionSting;
430            }
431            
432            
433            
434            /**
435             * Returns a string representation of a reference identifier according
436             * to the rules set out in RFC 2030.
437             * @param ref
438             * @param stratum
439             * @param version
440             * @return
441             */
442            public static String referenceIdentifierToString(byte[] ref, short stratum, byte version)
443            {
444                    // From the RFC 2030:
445                    // In the case of NTP Version 3 or Version 4 stratum-0 (unspecified)
446                    // or stratum-1 (primary) servers, this is a four-character ASCII
447                    // string, left justified and zero padded to 32 bits.
448                    if(stratum==0 || stratum==1)
449                    {
450                            return new String(ref);
451                    }
452                    
453                    // In NTP Version 3 secondary servers, this is the 32-bit IPv4
454                    // address of the reference source.
455                    else if(version==3)
456                    {
457                            return unsignedByteToShort(ref[0]) + "." +
458                                    unsignedByteToShort(ref[1]) + "." +
459                                    unsignedByteToShort(ref[2]) + "." +
460                                    unsignedByteToShort(ref[3]);
461                    }
462                    
463                    // In NTP Version 4 secondary servers, this is the low order 32 bits
464                    // of the latest transmit timestamp of the reference source.
465                    else if(version==4)
466                    {
467                            return "" + ((unsignedByteToShort(ref[0]) / 256.0) + 
468                                    (unsignedByteToShort(ref[1]) / 65536.0) +
469                                    (unsignedByteToShort(ref[2]) / 16777216.0) +
470                                    (unsignedByteToShort(ref[3]) / 4294967296.0));
471                    }
472                    
473                    return "";
474            }
475    }