blob: cf9243f7e7a3101d76fb171a53407b0c73a70de1 [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 */
39public class SntpClient
40{
41 private static final String TAG = "SntpClient";
Jerry Wong32d52f32015-10-06 22:18:11 -070042 private static final boolean DBG = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
44 private static final int REFERENCE_TIME_OFFSET = 16;
45 private static final int ORIGINATE_TIME_OFFSET = 24;
46 private static final int RECEIVE_TIME_OFFSET = 32;
47 private static final int TRANSMIT_TIME_OFFSET = 40;
48 private static final int NTP_PACKET_SIZE = 48;
49
50 private static final int NTP_PORT = 123;
51 private static final int NTP_MODE_CLIENT = 3;
Jerry Wong32d52f32015-10-06 22:18:11 -070052 private static final int NTP_MODE_SERVER = 4;
53 private static final int NTP_MODE_BROADCAST = 5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054 private static final int NTP_VERSION = 3;
55
Jerry Wong32d52f32015-10-06 22:18:11 -070056 private static final int NTP_LEAP_NOSYNC = 3;
57 private static final int NTP_STRATUM_DEATH = 0;
58 private static final int NTP_STRATUM_MAX = 15;
59
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060 // Number of seconds between Jan 1, 1900 and Jan 1, 1970
61 // 70 years plus 17 leap days
62 private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
63
64 // system time computed from NTP server response
65 private long mNtpTime;
66
67 // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
68 private long mNtpTimeReference;
69
70 // round trip time in milliseconds
71 private long mRoundTripTime;
72
Jerry Wong32d52f32015-10-06 22:18:11 -070073 private static class InvalidServerReplyException extends Exception {
74 public InvalidServerReplyException(String message) {
75 super(message);
76 }
77 }
78
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 /**
80 * Sends an SNTP request to the given host and processes the response.
81 *
82 * @param host host name of the server.
83 * @param timeout network timeout in milliseconds.
84 * @return true if the transaction was successful.
85 */
86 public boolean requestTime(String host, int timeout) {
Jerry Wong32d52f32015-10-06 22:18:11 -070087 InetAddress address = null;
88 try {
89 address = InetAddress.getByName(host);
90 } catch (Exception e) {
91 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;
Jerry Wong32d52f32015-10-06 22:18:11 -0700145 if (DBG) {
146 Log.d(TAG, "round trip: " + roundTripTime + "ms, " +
147 "clock offset: " + clockOffset + "ms");
148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Robert Greenwalt499a1212010-04-15 12:31:55 -0700150 // save our results - use the times on this side of the network latency
151 // (response rather than request time)
152 mNtpTime = responseTime + clockOffset;
153 mNtpTimeReference = responseTicks;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154 mRoundTripTime = roundTripTime;
155 } catch (Exception e) {
Jerry Wong32d52f32015-10-06 22:18:11 -0700156 if (DBG) Log.d(TAG, "request time failed: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 return false;
Nick Kralevich2ed20f82010-12-13 14:32:17 -0800158 } finally {
159 if (socket != null) {
160 socket.close();
161 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 }
163
164 return true;
165 }
166
167 /**
168 * Returns the time computed from the NTP transaction.
169 *
170 * @return time value computed from NTP server response.
171 */
172 public long getNtpTime() {
173 return mNtpTime;
174 }
175
176 /**
177 * Returns the reference clock value (value of SystemClock.elapsedRealtime())
178 * corresponding to the NTP time.
179 *
180 * @return reference clock corresponding to the NTP time.
181 */
182 public long getNtpTimeReference() {
183 return mNtpTimeReference;
184 }
185
186 /**
187 * Returns the round trip time of the NTP transaction
188 *
189 * @return round trip time in milliseconds.
190 */
191 public long getRoundTripTime() {
192 return mRoundTripTime;
193 }
194
Jerry Wong32d52f32015-10-06 22:18:11 -0700195 private static void checkValidServerReply(
196 byte leap, byte mode, int stratum, long transmitTime)
197 throws InvalidServerReplyException {
198 if (leap == NTP_LEAP_NOSYNC) {
199 throw new InvalidServerReplyException("unsynchronized server");
200 }
201 if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) {
202 throw new InvalidServerReplyException("untrusted mode: " + mode);
203 }
204 if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) {
205 throw new InvalidServerReplyException("untrusted stratum: " + stratum);
206 }
207 if (transmitTime == 0) {
208 throw new InvalidServerReplyException("zero transmitTime");
209 }
210 }
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 /**
213 * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
214 */
215 private long read32(byte[] buffer, int offset) {
216 byte b0 = buffer[offset];
217 byte b1 = buffer[offset+1];
218 byte b2 = buffer[offset+2];
219 byte b3 = buffer[offset+3];
220
221 // convert signed bytes to unsigned values
222 int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
223 int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
224 int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
225 int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
226
227 return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
228 }
229
230 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700231 * Reads the NTP time stamp at the given offset in the buffer and returns
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 * it as a system time (milliseconds since January 1, 1970).
Jerry Wong32d52f32015-10-06 22:18:11 -0700233 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private long readTimeStamp(byte[] buffer, int offset) {
235 long seconds = read32(buffer, offset);
236 long fraction = read32(buffer, offset + 4);
Jerry Wong32d52f32015-10-06 22:18:11 -0700237 // Special case: zero means zero.
238 if (seconds == 0 && fraction == 0) {
239 return 0;
240 }
241 return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 }
243
244 /**
Jerry Wong32d52f32015-10-06 22:18:11 -0700245 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 * at the given offset in the buffer.
Jerry Wong32d52f32015-10-06 22:18:11 -0700247 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 private void writeTimeStamp(byte[] buffer, int offset, long time) {
Jerry Wong32d52f32015-10-06 22:18:11 -0700249 // Special case: zero means zero.
250 if (time == 0) {
251 Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
252 return;
253 }
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 long seconds = time / 1000L;
256 long milliseconds = time - seconds * 1000L;
257 seconds += OFFSET_1900_TO_1970;
258
259 // write seconds in big endian format
260 buffer[offset++] = (byte)(seconds >> 24);
261 buffer[offset++] = (byte)(seconds >> 16);
262 buffer[offset++] = (byte)(seconds >> 8);
263 buffer[offset++] = (byte)(seconds >> 0);
264
265 long fraction = milliseconds * 0x100000000L / 1000L;
266 // write fraction in big endian format
267 buffer[offset++] = (byte)(fraction >> 24);
268 buffer[offset++] = (byte)(fraction >> 16);
269 buffer[offset++] = (byte)(fraction >> 8);
270 // low order bits should be random data
271 buffer[offset++] = (byte)(Math.random() * 255.0);
272 }
273}