-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNtpV3Impl.java
More file actions
689 lines (623 loc) · 18.4 KB
/
Copy pathNtpV3Impl.java
File metadata and controls
689 lines (623 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nts;
import java.io.IOException;
import java.net.DatagramPacket;
/**
* Implements {@link NtpV3Packet} to convert Java objects to and from the Network Time Protocol
* (NTP) data message header format described in RFC-1305.
*/
public class NtpV3Impl implements NtpV3Packet {
private static final int MODE_INDEX = 0;
private static final int MODE_SHIFT = 0;
private static final int VERSION_INDEX = 0;
private static final int VERSION_SHIFT = 3;
private static final int LI_INDEX = 0;
private static final int LI_SHIFT = 6;
private static final int STRATUM_INDEX = 1;
private static final int POLL_INDEX = 2;
private static final int PRECISION_INDEX = 3;
private static final int ROOT_DELAY_INDEX = 4;
private static final int ROOT_DISPERSION_INDEX = 8;
private static final int REFERENCE_ID_INDEX = 12;
private static final int REFERENCE_TIMESTAMP_INDEX = 16;
private static final int ORIGINATE_TIMESTAMP_INDEX = 24;
private static final int RECEIVE_TIMESTAMP_INDEX = 32;
private static final int TRANSMIT_TIMESTAMP_INDEX = 40;
// private static final int KEY_IDENTIFIER_INDEX = 48;
// private static final int MESSAGE_DIGEST = 54; /* len 16 bytes */
/**
* Convert byte to unsigned integer. Java only has signed types, so we have to do more work to get
* unsigned ops.
*
* @param b input byte
* @return unsigned int value of byte
*/
protected static final int ui(final byte b) {
return b & 0xFF;
}
/**
* Convert byte to unsigned long. Java only has signed types, so we have to do more work to get
* unsigned ops
*
* @param b input byte
* @return unsigned long value of byte
*/
protected static final long ul(final byte b) {
return b & 0xFF;
}
protected byte[] buf = new byte[48];
private volatile DatagramPacket dp;
/** Creates a new instance of NtpV3Impl */
public NtpV3Impl() {
setVersion(3);
}
/**
* Compares this object against the specified object. The result is {@code true} if and only if
* the argument is not {@code null} and is a <code>NtpV3Impl</code> object that contains the same
* values as this object.
*
* @param obj the object to compare with.
* @return {@code true} if the objects are the same; {@code false} otherwise.
* @since 3.4
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final NtpV3Impl other = (NtpV3Impl) obj;
return java.util.Arrays.equals(buf, other.buf);
}
/** Build a request packet */
public void buildRequest() {
setMode(NtsImpl.MODE_CLIENT);
}
/**
* Returns the datagram packet with the NTP details already filled in.
*
* @return a datagram packet.
*/
@Override
public synchronized DatagramPacket getDatagramPacket(int sz) {
int curr_buf_sz = buf.length;
if (sz < 48 || sz % 4 != 0) {
throw new RuntimeException();
}
if (sz != curr_buf_sz) {
byte[] new_buf = new byte[sz];
System.arraycopy(buf, 0, new_buf, 0, Math.min(sz, curr_buf_sz));
buf = new_buf;
}
if (dp == null || sz != curr_buf_sz) {
dp = new DatagramPacket(buf, buf.length);
dp.setPort(NTP_PORT);
}
return dp;
}
/**
* Returns the datagram packet with the NTP details already filled in.
*
* @return a datagram packet.
*/
@Override
public synchronized DatagramPacket getDatagramPacket() {
return getDatagramPacket(buf.length);
}
/**
* @return 4 bytes as 32-bit int
*/
private int getInt(final int index) {
return ui(buf[index]) << 24
| ui(buf[index + 1]) << 16
| ui(buf[index + 2]) << 8
| ui(buf[index + 3]);
}
/**
* Returns leap indicator as defined in RFC-1305 which is a two-bit code: 0=no warning 1=last
* minute has 61 seconds 2=last minute has 59 seconds 3=alarm condition (clock not synchronized)
*
* @return leap indicator as defined in RFC-1305.
*/
@Override
public int getLeapIndicator() {
return ui(buf[LI_INDEX]) >> LI_SHIFT & 0x3;
}
/**
* Gets Long value represented by bits starting at specified index.
*
* @return 8 bytes as 64-bit long
*/
private long getLong(final int index) {
return ul(buf[index]) << 56
| ul(buf[index + 1]) << 48
| ul(buf[index + 2]) << 40
| ul(buf[index + 3]) << 32
| ul(buf[index + 4]) << 24
| ul(buf[index + 5]) << 16
| ul(buf[index + 6]) << 8
| ul(buf[index + 7]);
}
/**
* Returns mode as defined in RFC-1305 which is a 3-bit integer whose value is indicated by the
* MODE_xxx parameters.
*
* @return mode as defined in RFC-1305.
*/
@Override
public int getMode() {
return ui(buf[MODE_INDEX]) >> MODE_SHIFT & 0x7;
}
/**
* Return human-readable name of message mode type as described in RFC 1305.
*
* @return mode name as string.
*/
@Override
public String getModeName() {
return NtpUtils.getModeName(getMode());
}
/**
* Returns the {@code originate} time as defined in RFC-1305.
*
* @return the {@code originate} time. Never returns null.
*/
@Override
public TimeStamp getOriginateTimeStamp() {
return getTimestamp(ORIGINATE_TIMESTAMP_INDEX);
}
/**
* Returns poll interval as defined in RFC-1305, which is an eight-bit signed integer indicating
* the maximum interval between successive messages, in seconds to the nearest power of two (e.g.
* value of six indicates an interval of 64 seconds). The values that can appear in this field
* range from NTP_MINPOLL to NTP_MAXPOLL inclusive.
*
* @return poll interval as defined in RFC-1305.
*/
@Override
public int getPoll() {
return buf[POLL_INDEX];
}
/**
* Returns precision as defined in RFC-1305 encoded as an 8-bit signed integer (seconds to the
* nearest power of two). Values normally range from -6 to -20.
*
* @return precision as defined in RFC-1305.
*/
@Override
public int getPrecision() {
return buf[PRECISION_INDEX];
}
/**
* Returns {@code receive} timestamp as defined in RFC-1305.
*
* @return the {@code receive} time. Never returns null.
*/
@Override
public TimeStamp getReceiveTimeStamp() {
return getTimestamp(RECEIVE_TIMESTAMP_INDEX);
}
/**
* Returns the reference id as defined in RFC-1305, which is a 32-bit integer whose value is
* dependent on several criteria.
*
* @return the reference id as defined in RFC-1305.
*/
@Override
public int getReferenceId() {
return getInt(REFERENCE_ID_INDEX);
}
/**
* Returns the reference id string. String cannot be null but value is dependent on the version of
* the NTP spec supported and stratum level. Value can be an empty string, clock type string, IP
* address, or a hexadecimal string.
*
* @return the reference id string.
*/
@Override
public String getReferenceIdString() {
final int version = getVersion();
final int stratum = getStratum();
if (version == VERSION_3 || version == VERSION_4) {
if (stratum == 0 || stratum == 1) {
return idAsString(); // 4-character ASCII string (e.g. GPS, USNO)
}
// in NTPv4 servers this is latest transmit timestamp of ref source
if (version == VERSION_4) {
return idAsHex();
}
}
// Stratum 2 and higher this is a four-octet IPv4 address
// of the primary reference host.
if (stratum >= 2) {
return idAsIPAddress();
}
return idAsHex();
}
/**
* Returns the reference time as defined in RFC-1305.
*
* @return the reference time as <code>TimeStamp</code> object. Never returns null.
*/
@Override
public TimeStamp getReferenceTimeStamp() {
return getTimestamp(REFERENCE_TIMESTAMP_INDEX);
}
/**
* Return root delay as defined in RFC-1305, which is the total roundtrip delay to the primary
* reference source, in seconds. Values can take positive and negative values, depending on clock
* precision and skew.
*
* @return root delay as defined in RFC-1305.
*/
@Override
public int getRootDelay() {
return getInt(ROOT_DELAY_INDEX);
}
/**
* Return root delay as defined in RFC-1305 in milliseconds, which is the total roundtrip delay to
* the primary reference source, in seconds. Values can take positive and negative values,
* depending on clock precision and skew.
*
* @return root delay in milliseconds
*/
@Override
public double getRootDelayInMillisDouble() {
final double l = getRootDelay();
return l / 65.536;
}
/**
* Returns root dispersion as defined in RFC-1305.
*
* @return root dispersion.
*/
@Override
public int getRootDispersion() {
return getInt(ROOT_DISPERSION_INDEX);
}
/**
* Returns root dispersion (as defined in RFC-1305) in milliseconds.
*
* @return root dispersion in milliseconds
*/
@Override
public long getRootDispersionInMillis() {
final long l = getRootDispersion();
return l * 1000 / 65536L;
}
/**
* Returns root dispersion (as defined in RFC-1305) in milliseconds as double precision value.
*
* @return root dispersion in milliseconds
*/
@Override
public double getRootDispersionInMillisDouble() {
final double l = getRootDispersion();
return l / 65.536;
}
/**
* Returns Stratum as defined in RFC-1305, which indicates the stratum level of the local clock,
* with values defined as follows: 0=unspecified, 1=primary ref clock, and all others a secondary
* reference (via NTP).
*
* @return Stratum level as defined in RFC-1305.
*/
@Override
public int getStratum() {
return ui(buf[STRATUM_INDEX]);
}
/**
* Gets NTP Timestamp at specified starting index.
*
* @param index index into data array
* @return TimeStamp object for 64 bits starting at index
*/
private TimeStamp getTimestamp(final int index) {
return new TimeStamp(getLong(index));
}
/**
* Returns the {@code transmit} timestamp as defined in RFC-1305.
*
* @return the {@code transmit} timestamp as defined in RFC-1305. Never returns a null object.
*/
@Override
public TimeStamp getTransmitTimeStamp() {
return getTimestamp(TRANSMIT_TIMESTAMP_INDEX);
}
/**
* Return type of time packet. The values (e.g. NTP, TIME, ICMP, ...) correspond to the protocol
* used to obtain the timing information.
*
* @return packet type string identifier which in this case is "NTP".
*/
@Override
public String getType() {
return "NTP";
}
/**
* Returns NTP version number as defined in RFC-1305.
*
* @return NTP version number.
*/
@Override
public int getVersion() {
return ui(buf[VERSION_INDEX]) >> VERSION_SHIFT & 0x7;
}
/**
* Computes a hash code for this object. The result is the exclusive OR of the values of this
* object stored as a byte array.
*
* @return a hash code value for this object.
* @since 3.4
*/
@Override
public int hashCode() {
return java.util.Arrays.hashCode(buf);
}
private String idAsHex() {
return Integer.toHexString(getReferenceId());
}
/**
* Returns Reference id as dotted IP address.
*
* @return refId as IP address string.
*/
private String idAsIPAddress() {
return ui(buf[REFERENCE_ID_INDEX])
+ "."
+ ui(buf[REFERENCE_ID_INDEX + 1])
+ "."
+ ui(buf[REFERENCE_ID_INDEX + 2])
+ "."
+ ui(buf[REFERENCE_ID_INDEX + 3]);
}
private String idAsString() {
final StringBuilder id = new StringBuilder();
for (int i = 0; i <= 3; i++) {
final char c = (char) buf[REFERENCE_ID_INDEX + i];
if (c == 0) { // 0-terminated string
break;
}
id.append(c);
}
return id.toString();
}
/**
* Sets the contents of this object from source datagram packet.
*
* @param srcDp source DatagramPacket to copy contents from, never null.
* @throws IllegalArgumentException if srcDp is null or byte length is less than minimum length of
* 48 bytes
*/
@Override
public void setDatagramPacket(final DatagramPacket srcDp) {
if (srcDp == null || srcDp.getLength() < buf.length) {
throw new IllegalArgumentException();
}
final byte[] incomingBuf = srcDp.getData();
int len = srcDp.getLength();
if (len > buf.length) {
len = buf.length;
}
System.arraycopy(incomingBuf, 0, buf, 0, len);
final DatagramPacket dp = getDatagramPacket();
dp.setAddress(srcDp.getAddress());
final int port = srcDp.getPort();
dp.setPort(port > 0 ? port : NTP_PORT);
dp.setData(buf);
}
/**
* Sets integer value at index position.
*
* @param idx index position
* @param value 32-bit int value
*/
private void setInt(final int idx, int value) {
for (int i = 3; i >= 0; i--) {
buf[idx + i] = (byte) (value & 0xff);
value >>>= 8; // shift right one-byte
}
}
/**
* Sets leap indicator as defined in RFC-1305.
*
* @param li leap indicator.
*/
@Override
public void setLeapIndicator(final int li) {
buf[LI_INDEX] = (byte) (buf[LI_INDEX] & 0x3F | (li & 0x3) << LI_SHIFT);
}
/**
* Sets mode as defined in RFC-1305.
*
* @param mode the mode to set
*/
@Override
public void setMode(final int mode) {
buf[MODE_INDEX] = (byte) (buf[MODE_INDEX] & 0xF8 | mode & 0x7);
}
/**
* Sets originate timestamp given NTP TimeStamp object. If <code>ts</code> is null then zero time
* is used.
*
* @param ts NTP timestamp
*/
@Override
public void setOriginateTimeStamp(final TimeStamp ts) {
setTimestamp(ORIGINATE_TIMESTAMP_INDEX, ts);
}
/**
* Sets poll interval as defined in RFC-1305.
*
* @param poll poll interval.
*/
@Override
public void setPoll(final int poll) {
buf[POLL_INDEX] = (byte) (poll & 0xFF);
}
/**
* Sets precision as defined in RFC-1305.
*
* @param precision the precision to set
* @since 3.4
*/
@Override
public void setPrecision(final int precision) {
buf[PRECISION_INDEX] = (byte) (precision & 0xFF);
}
/**
* Sets receive timestamp given NTP TimeStamp object. If <code>ts</code> is null then zero time is
* used.
*
* @param ts timestamp
*/
@Override
public void setReceiveTimeStamp(final TimeStamp ts) {
setTimestamp(RECEIVE_TIMESTAMP_INDEX, ts);
}
/**
* Sets reference clock identifier field with 32-bit unsigned integer value. See RFC-1305 for
* description.
*
* @param refId reference clock identifier.
*/
@Override
public void setReferenceId(final int refId) {
setInt(REFERENCE_ID_INDEX, refId);
}
/**
* Sets Reference time with NTP timestamp. If <code>ts</code> is null then zero time is used.
*
* @param ts NTP timestamp
*/
@Override
public void setReferenceTime(final TimeStamp ts) {
setTimestamp(REFERENCE_TIMESTAMP_INDEX, ts);
}
/**
* Sets root delay as defined in RFC-1305.
*
* @param delay root delay
* @since 3.4
*/
@Override
public void setRootDelay(final int delay) {
setInt(ROOT_DELAY_INDEX, delay);
}
/**
* Sets root dispersion as defined in RFC-1305.
*
* @param dispersion root dispersion
* @since 3.4
*/
@Override
public void setRootDispersion(final int dispersion) {
setInt(ROOT_DISPERSION_INDEX, dispersion);
}
/**
* Sets stratum level as defined in RFC-1305.
*
* @param stratum stratum level.
*/
@Override
public void setStratum(final int stratum) {
buf[STRATUM_INDEX] = (byte) (stratum & 0xFF);
}
/**
* Sets the NTP timestamp at the given array index.
*
* @param index index into the byte array.
* @param t TimeStamp.
*/
private void setTimestamp(final int index, final TimeStamp t) {
long ntpTime = t == null ? 0 : t.ntpValue();
// copy 64-bits from Long value into 8 x 8-bit bytes of array
// one byte at a time shifting 8-bits for each position.
for (int i = 7; i >= 0; i--) {
buf[index + i] = (byte) (ntpTime & 0xFF);
ntpTime >>>= 8; // shift to next byte
}
// buf[index] |= 0x80; // only set if 1900 baseline....
}
/**
* Sets transmit time with NTP timestamp. If <code>ts</code> is null then zero time is used.
*
* @param ts NTP timestamp
*/
@Override
public void setTransmitTime(final TimeStamp ts) {
setTimestamp(TRANSMIT_TIMESTAMP_INDEX, ts);
}
/**
* Sets NTP version as defined in RFC-1305.
*
* @param version NTP version.
*/
@Override
public void setVersion(final int version) {
buf[VERSION_INDEX] = (byte) (buf[VERSION_INDEX] & 0xC7 | (version & 0x7) << VERSION_SHIFT);
}
/**
* Returns details of NTP packet as a string.
*
* @return details of NTP packet as a string.
*/
@Override
public String toString() {
return "["
+ "version:"
+ getVersion()
+ ", mode:"
+ getMode()
+ ", poll:"
+ getPoll()
+ ", precision:"
+ getPrecision()
+ ", delay:"
+ getRootDelay()
+ ", dispersion(ms):"
+ getRootDispersionInMillisDouble()
+ ", id:"
+ getReferenceIdString()
+ ", xmitTime:"
+ getTransmitTimeStamp().toDateString()
+ " ]";
}
/**
* Validate a response packet given a request packet
*
* @param req - The request packet
* @throws IOException - On failure
*/
@Override
public void validate(NtpV3Packet req) throws IOException {
if (this.getStratum() == 0) {
if (getReferenceIdString().equals("DENY")) {
throw new IOException("NTP Access denied");
}
if (getOriginateTimeStamp() != req.getTransmitTimeStamp()) {
throw new IOException("Timestamp mismatch");
}
if (getTransmitTimeStamp() == new TimeStamp(0)) {
throw new IOException("Invalid timestamp");
}
}
}
}