blob: cea56b53d76374c3bc515feb8ea5e57caa767037 [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
19import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.util.Log;
21
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import java.net.DatagramPacket;
23import java.net.DatagramSocket;
24import java.net.InetAddress;
Jerry Wong32d52f32015-10-06 22:18:11 -070025import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27/**
28 * {@hide}
29 *
30 * Simple SNTP client class for retrieving network time.
31 *
32 * Sample usage:
33 * <pre>SntpClient client = new SntpClient();
34 * if (client.requestTime("time.foo.com")) {
35 * long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
36 * }
37 * </pre>
38 */
Jeff Sharkey389b8532016-12-02 12:17:21 -070039public class SntpClient {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040 private static final String TAG = "SntpClient";
Jerry Wong32d52f32015-10-06 22:18:11 -070041 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43 private static final int REFERENCE_TIME_OFFSET = 16;
44 private static final int ORIGINATE_TIME_OFFSET = 24;
45 private static final int RECEIVE_TIME_OFFSET = 32;
46 private static final int TRANSMIT_TIME_OFFSET = 40;
47 private static final int NTP_PACKET_SIZE = 48;
48
49 private static final int NTP_PORT = 123;
50 private static final int NTP_MODE_CLIENT = 3;
Jerry Wong32d52f32015-10-06 22:18:11 -070051 private static final int NTP_MODE_SERVER = 4;
52 private static final int NTP_MODE_BROADCAST = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 private static final int NTP_VERSION = 3;
54
Jerry Wong32d52f32015-10-06 22:18:11 -070055 private static final int NTP_LEAP_NOSYNC = 3;
56 private static final int NTP_STRATUM_DEATH = 0;
57 private static final int NTP_STRATUM_MAX = 15;
58
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059 // Number of seconds between Jan 1, 1900 and Jan 1, 1970
60 // 70 years plus 17 leap days
61 private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
62
63 // system time computed from NTP server response
64 private long mNtpTime;
65
66 // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
67 private long mNtpTimeReference;
68
69 // round trip time in milliseconds
70 private long mRoundTripTime;
71
Jerry Wong32d52f32015-10-06 22:18:11 -070072 private static class InvalidServerReplyException extends Exception {
73 public InvalidServerReplyException(String message) {
74 super(message);
75 }
76 }
77
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 /**
79 * Sends an SNTP request to the given host and processes the response.
80 *
81 * @param host host name of the server.
82 * @param timeout network timeout in milliseconds.
83 * @return true if the transaction was successful.
84 */
85 public boolean requestTime(String host, int timeout) {
Jerry Wong32d52f32015-10-06 22:18:11 -070086 InetAddress address = null;
87 try {
88 address = InetAddress.getByName(host);
89 } catch (Exception e) {
Jeff Sharkey389b8532016-12-02 12:17:21 -070090 EventLogTags.writeNtpFailure(host, e.toString());
Jerry Wong32d52f32015-10-06 22:18:11 -070091 if (DBG) Log.d(TAG, "request time failed: " + e);
92 return false;
93 }
94 return requestTime(address, NTP_PORT, timeout);
95 }
96
97 public boolean requestTime(InetAddress address, int port, int timeout) {
Nick Kralevich2ed20f82010-12-13 14:32:17 -080098 DatagramSocket socket = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099 try {
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800100 socket = new DatagramSocket();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101 socket.setSoTimeout(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 byte[] buffer = new byte[NTP_PACKET_SIZE];
Jerry Wong32d52f32015-10-06 22:18:11 -0700103 DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700105 // set mode = 3 (client) and version = 3
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 // mode is in low 3 bits of first byte
107 // version is in bits 3-5 of first byte
108 buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
109
110 // get current time and write it to the request packet
Jerry Wong32d52f32015-10-06 22:18:11 -0700111 final long requestTime = System.currentTimeMillis();
112 final long requestTicks = SystemClock.elapsedRealtime();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
114
115 socket.send(request);
Robert Greenwaltbf7de392010-04-21 17:09:38 -0700116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 // read the response
118 DatagramPacket response = new DatagramPacket(buffer, buffer.length);
119 socket.receive(response);
Jerry Wong32d52f32015-10-06 22:18:11 -0700120 final long responseTicks = SystemClock.elapsedRealtime();
121 final long responseTime = requestTime + (responseTicks - requestTicks);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
123 // extract the results
Jerry Wong32d52f32015-10-06 22:18:11 -0700124 final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
125 final byte mode = (byte) (buffer[0] & 0x7);
126 final int stratum = (int) (buffer[1] & 0xff);
127 final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
128 final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
129 final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
130
131 /* do sanity check according to RFC */
132 // TODO: validate originateTime == requestTime.
133 checkValidServerReply(leap, mode, stratum, transmitTime);
134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
Robert Greenwalt499a1212010-04-15 12:31:55 -0700136 // receiveTime = originateTime + transit + skew
137 // responseTime = transmitTime + transit - skew
138 // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
139 // = ((originateTime + transit + skew - originateTime) +
140 // (transmitTime - (transmitTime + transit - skew)))/2
141 // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
142 // = (transit + skew - transit + skew)/2
143 // = (2 * skew)/2 = skew
144 long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
Jeff Sharkey389b8532016-12-02 12:17:21 -0700145 EventLogTags.writeNtpSuccess(address.toString(), roundTripTime, clockOffset);
Jerry Wong32d52f32015-10-06 22:18:11 -0700146 if (DBG) {
147 Log.d(TAG, "round trip: " + roundTripTime + "ms, " +
148 "clock offset: " + clockOffset + "ms");
149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
Robert Greenwalt499a1212010-04-15 12:31:55 -0700151 // save our results - use the times on this side of the network latency
152 // (response rather than request time)
153 mNtpTime = responseTime + clockOffset;
154 mNtpTimeReference = responseTicks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 mRoundTripTime = roundTripTime;
156 } catch (Exception e) {
Jeff Sharkey389b8532016-12-02 12:17:21 -0700157 EventLogTags.writeNtpFailure(address.toString(), e.toString());
Jerry Wong32d52f32015-10-06 22:18:11 -0700158 if (DBG) Log.d(TAG, "request time failed: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 return false;
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800160 } finally {
161 if (socket != null) {
162 socket.close();
163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 }
165
166 return true;
167 }
168
169 /**
170 * Returns the time computed from the NTP transaction.
171 *
172 * @return time value computed from NTP server response.
173 */
174 public long getNtpTime() {
175 return mNtpTime;
176 }
177
178 /**
179 * Returns the reference clock value (value of SystemClock.elapsedRealtime())
180 * corresponding to the NTP time.
181 *
182 * @return reference clock corresponding to the NTP time.
183 */
184 public long getNtpTimeReference() {
185 return mNtpTimeReference;
186 }
187
188 /**
189 * Returns the round trip time of the NTP transaction
190 *
191 * @return round trip time in milliseconds.
192 */
193 public long getRoundTripTime() {
194 return mRoundTripTime;
195 }
196
Jerry Wong32d52f32015-10-06 22:18:11 -0700197 private static void checkValidServerReply(
198 byte leap, byte mode, int stratum, long transmitTime)
199 throws InvalidServerReplyException {
200 if (leap == NTP_LEAP_NOSYNC) {
201 throw new InvalidServerReplyException("unsynchronized server");
202 }
203 if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) {
204 throw new InvalidServerReplyException("untrusted mode: " + mode);
205 }
206 if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) {
207 throw new InvalidServerReplyException("untrusted stratum: " + stratum);
208 }
209 if (transmitTime == 0) {
210 throw new InvalidServerReplyException("zero transmitTime");
211 }
212 }
213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214 /**
215 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
216 */
217 private long read32(byte[] buffer, int offset) {
218 byte b0 = buffer[offset];
219 byte b1 = buffer[offset+1];
220 byte b2 = buffer[offset+2];
221 byte b3 = buffer[offset+3];
222
223 // convert signed bytes to unsigned values
224 int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
225 int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
226 int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
227 int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
228
229 return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
230 }
231
232 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700233 * Reads the NTP time stamp at the given offset in the buffer and returns
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 * it as a system time (milliseconds since January 1, 1970).
Jerry Wong32d52f32015-10-06 22:18:11 -0700235 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236 private long readTimeStamp(byte[] buffer, int offset) {
237 long seconds = read32(buffer, offset);
238 long fraction = read32(buffer, offset + 4);
Jerry Wong32d52f32015-10-06 22:18:11 -0700239 // Special case: zero means zero.
240 if (seconds == 0 && fraction == 0) {
241 return 0;
242 }
243 return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 }
245
246 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700247 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 * at the given offset in the buffer.
Jerry Wong32d52f32015-10-06 22:18:11 -0700249 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 private void writeTimeStamp(byte[] buffer, int offset, long time) {
Jerry Wong32d52f32015-10-06 22:18:11 -0700251 // Special case: zero means zero.
252 if (time == 0) {
253 Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
254 return;
255 }
256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800257 long seconds = time / 1000L;
258 long milliseconds = time - seconds * 1000L;
259 seconds += OFFSET_1900_TO_1970;
260
261 // write seconds in big endian format
262 buffer[offset++] = (byte)(seconds >> 24);
263 buffer[offset++] = (byte)(seconds >> 16);
264 buffer[offset++] = (byte)(seconds >> 8);
265 buffer[offset++] = (byte)(seconds >> 0);
266
267 long fraction = milliseconds * 0x100000000L / 1000L;
268 // write fraction in big endian format
269 buffer[offset++] = (byte)(fraction >> 24);
270 buffer[offset++] = (byte)(fraction >> 16);
271 buffer[offset++] = (byte)(fraction >> 8);
272 // low order bits should be random data
273 buffer[offset++] = (byte)(Math.random() * 255.0);
274 }
275}