blob: 8c6faf6d99703c598ddb2d376aa13eefbf8fae84 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net;
18
Artur Satayev26958002019-12-10 17:47:52 +000019import android.compat.annotation.UnsupportedAppUsage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.util.Log;
22
Chalard Jean6a76b7e2019-04-09 11:16:56 +090023import com.android.internal.util.TrafficStatsConstants;
24
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import java.net.DatagramPacket;
26import java.net.DatagramSocket;
27import java.net.InetAddress;
Jerry Wong32d52f32015-10-06 22:18:11 -070028import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029
30/**
31 * {@hide}
32 *
33 * Simple SNTP client class for retrieving network time.
34 *
35 * Sample usage:
36 * <pre>SntpClient client = new SntpClient();
37 * if (client.requestTime("time.foo.com")) {
38 * long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
39 * }
40 * </pre>
41 */
Jeff Sharkeyd3f689b2016-12-02 12:17:21 -070042public class SntpClient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043 private static final String TAG = "SntpClient";
Jerry Wong32d52f32015-10-06 22:18:11 -070044 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045
46 private static final int REFERENCE_TIME_OFFSET = 16;
47 private static final int ORIGINATE_TIME_OFFSET = 24;
48 private static final int RECEIVE_TIME_OFFSET = 32;
49 private static final int TRANSMIT_TIME_OFFSET = 40;
50 private static final int NTP_PACKET_SIZE = 48;
51
52 private static final int NTP_PORT = 123;
53 private static final int NTP_MODE_CLIENT = 3;
Jerry Wong32d52f32015-10-06 22:18:11 -070054 private static final int NTP_MODE_SERVER = 4;
55 private static final int NTP_MODE_BROADCAST = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 private static final int NTP_VERSION = 3;
57
Jerry Wong32d52f32015-10-06 22:18:11 -070058 private static final int NTP_LEAP_NOSYNC = 3;
59 private static final int NTP_STRATUM_DEATH = 0;
60 private static final int NTP_STRATUM_MAX = 15;
61
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 // Number of seconds between Jan 1, 1900 and Jan 1, 1970
63 // 70 years plus 17 leap days
64 private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
65
66 // system time computed from NTP server response
67 private long mNtpTime;
68
69 // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
70 private long mNtpTimeReference;
71
72 // round trip time in milliseconds
73 private long mRoundTripTime;
74
Jerry Wong32d52f32015-10-06 22:18:11 -070075 private static class InvalidServerReplyException extends Exception {
76 public InvalidServerReplyException(String message) {
77 super(message);
78 }
79 }
80
Artur Satayev751e5512019-11-15 19:12:49 +000081 @UnsupportedAppUsage
82 public SntpClient() {
83 }
84
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 /**
86 * Sends an SNTP request to the given host and processes the response.
87 *
88 * @param host host name of the server.
89 * @param timeout network timeout in milliseconds.
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -080090 * @param network network over which to send the request.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 * @return true if the transaction was successful.
92 */
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -080093 public boolean requestTime(String host, int timeout, Network network) {
Erik Klinef4fa9822018-04-27 22:48:33 +090094 final Network networkForResolv = network.getPrivateDnsBypassingCopy();
Jerry Wong32d52f32015-10-06 22:18:11 -070095 InetAddress address = null;
96 try {
Erik Klinef4fa9822018-04-27 22:48:33 +090097 address = networkForResolv.getByName(host);
Jerry Wong32d52f32015-10-06 22:18:11 -070098 } catch (Exception e) {
Jeff Sharkeyd3f689b2016-12-02 12:17:21 -070099 EventLogTags.writeNtpFailure(host, e.toString());
Jerry Wong32d52f32015-10-06 22:18:11 -0700100 if (DBG) Log.d(TAG, "request time failed: " + e);
101 return false;
102 }
Erik Klinef4fa9822018-04-27 22:48:33 +0900103 return requestTime(address, NTP_PORT, timeout, networkForResolv);
Jerry Wong32d52f32015-10-06 22:18:11 -0700104 }
105
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -0800106 public boolean requestTime(InetAddress address, int port, int timeout, Network network) {
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800107 DatagramSocket socket = null;
Chalard Jean6a76b7e2019-04-09 11:16:56 +0900108 final int oldTag = TrafficStats.getAndSetThreadStatsTag(
109 TrafficStatsConstants.TAG_SYSTEM_NTP);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 try {
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800111 socket = new DatagramSocket();
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -0800112 network.bindSocket(socket);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 socket.setSoTimeout(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 byte[] buffer = new byte[NTP_PACKET_SIZE];
Jerry Wong32d52f32015-10-06 22:18:11 -0700115 DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700117 // set mode = 3 (client) and version = 3
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 // mode is in low 3 bits of first byte
119 // version is in bits 3-5 of first byte
120 buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
121
122 // get current time and write it to the request packet
Jerry Wong32d52f32015-10-06 22:18:11 -0700123 final long requestTime = System.currentTimeMillis();
124 final long requestTicks = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
126
127 socket.send(request);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 // read the response
130 DatagramPacket response = new DatagramPacket(buffer, buffer.length);
131 socket.receive(response);
Jerry Wong32d52f32015-10-06 22:18:11 -0700132 final long responseTicks = SystemClock.elapsedRealtime();
133 final long responseTime = requestTime + (responseTicks - requestTicks);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134
135 // extract the results
Jerry Wong32d52f32015-10-06 22:18:11 -0700136 final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
137 final byte mode = (byte) (buffer[0] & 0x7);
138 final int stratum = (int) (buffer[1] & 0xff);
139 final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
140 final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
141 final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
142
143 /* do sanity check according to RFC */
144 // TODO: validate originateTime == requestTime.
145 checkValidServerReply(leap, mode, stratum, transmitTime);
146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
Robert Greenwalt499a1212010-04-15 12:31:55 -0700148 // receiveTime = originateTime + transit + skew
149 // responseTime = transmitTime + transit - skew
150 // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
151 // = ((originateTime + transit + skew - originateTime) +
152 // (transmitTime - (transmitTime + transit - skew)))/2
153 // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
154 // = (transit + skew - transit + skew)/2
155 // = (2 * skew)/2 = skew
156 long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
Jeff Sharkeyd3f689b2016-12-02 12:17:21 -0700157 EventLogTags.writeNtpSuccess(address.toString(), roundTripTime, clockOffset);
Jerry Wong32d52f32015-10-06 22:18:11 -0700158 if (DBG) {
159 Log.d(TAG, "round trip: " + roundTripTime + "ms, " +
160 "clock offset: " + clockOffset + "ms");
161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Robert Greenwalt499a1212010-04-15 12:31:55 -0700163 // save our results - use the times on this side of the network latency
164 // (response rather than request time)
165 mNtpTime = responseTime + clockOffset;
166 mNtpTimeReference = responseTicks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 mRoundTripTime = roundTripTime;
168 } catch (Exception e) {
Jeff Sharkeyd3f689b2016-12-02 12:17:21 -0700169 EventLogTags.writeNtpFailure(address.toString(), e.toString());
Jerry Wong32d52f32015-10-06 22:18:11 -0700170 if (DBG) Log.d(TAG, "request time failed: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 return false;
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800172 } finally {
173 if (socket != null) {
174 socket.close();
175 }
Jeff Sharkey619a5112017-01-19 11:55:54 -0700176 TrafficStats.setThreadStatsTag(oldTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 }
178
179 return true;
180 }
181
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -0800182 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100183 @UnsupportedAppUsage
Kurt Marcinkiewicz7a4ff642018-03-05 14:45:04 -0800184 public boolean requestTime(String host, int timeout) {
185 Log.w(TAG, "Shame on you for calling the hidden API requestTime()!");
186 return false;
187 }
188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 /**
190 * Returns the time computed from the NTP transaction.
191 *
192 * @return time value computed from NTP server response.
193 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100194 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 public long getNtpTime() {
196 return mNtpTime;
197 }
198
199 /**
200 * Returns the reference clock value (value of SystemClock.elapsedRealtime())
201 * corresponding to the NTP time.
202 *
203 * @return reference clock corresponding to the NTP time.
204 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100205 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 public long getNtpTimeReference() {
207 return mNtpTimeReference;
208 }
209
210 /**
211 * Returns the round trip time of the NTP transaction
212 *
213 * @return round trip time in milliseconds.
214 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100215 @UnsupportedAppUsage
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 public long getRoundTripTime() {
217 return mRoundTripTime;
218 }
219
Jerry Wong32d52f32015-10-06 22:18:11 -0700220 private static void checkValidServerReply(
221 byte leap, byte mode, int stratum, long transmitTime)
222 throws InvalidServerReplyException {
223 if (leap == NTP_LEAP_NOSYNC) {
224 throw new InvalidServerReplyException("unsynchronized server");
225 }
226 if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) {
227 throw new InvalidServerReplyException("untrusted mode: " + mode);
228 }
229 if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) {
230 throw new InvalidServerReplyException("untrusted stratum: " + stratum);
231 }
232 if (transmitTime == 0) {
233 throw new InvalidServerReplyException("zero transmitTime");
234 }
235 }
236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 /**
238 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
239 */
240 private long read32(byte[] buffer, int offset) {
241 byte b0 = buffer[offset];
242 byte b1 = buffer[offset+1];
243 byte b2 = buffer[offset+2];
244 byte b3 = buffer[offset+3];
245
246 // convert signed bytes to unsigned values
247 int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
248 int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
249 int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
250 int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
251
252 return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
253 }
254
255 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700256 * Reads the NTP time stamp at the given offset in the buffer and returns
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 * it as a system time (milliseconds since January 1, 1970).
Jerry Wong32d52f32015-10-06 22:18:11 -0700258 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 private long readTimeStamp(byte[] buffer, int offset) {
260 long seconds = read32(buffer, offset);
261 long fraction = read32(buffer, offset + 4);
Jerry Wong32d52f32015-10-06 22:18:11 -0700262 // Special case: zero means zero.
263 if (seconds == 0 && fraction == 0) {
264 return 0;
265 }
266 return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 }
268
269 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700270 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800271 * at the given offset in the buffer.
Jerry Wong32d52f32015-10-06 22:18:11 -0700272 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 private void writeTimeStamp(byte[] buffer, int offset, long time) {
Jerry Wong32d52f32015-10-06 22:18:11 -0700274 // Special case: zero means zero.
275 if (time == 0) {
276 Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
277 return;
278 }
279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280 long seconds = time / 1000L;
281 long milliseconds = time - seconds * 1000L;
282 seconds += OFFSET_1900_TO_1970;
283
284 // write seconds in big endian format
285 buffer[offset++] = (byte)(seconds >> 24);
286 buffer[offset++] = (byte)(seconds >> 16);
287 buffer[offset++] = (byte)(seconds >> 8);
288 buffer[offset++] = (byte)(seconds >> 0);
289
290 long fraction = milliseconds * 0x100000000L / 1000L;
291 // write fraction in big endian format
292 buffer[offset++] = (byte)(fraction >> 24);
293 buffer[offset++] = (byte)(fraction >> 16);
294 buffer[offset++] = (byte)(fraction >> 8);
295 // low order bits should be random data
296 buffer[offset++] = (byte)(Math.random() * 255.0);
297 }
298}