• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 package android.net;
18 
19 import android.compat.annotation.UnsupportedAppUsage;
20 import android.os.SystemClock;
21 import android.util.Log;
22 
23 import com.android.internal.util.TrafficStatsConstants;
24 
25 import java.net.DatagramPacket;
26 import java.net.DatagramSocket;
27 import java.net.InetAddress;
28 import java.net.UnknownHostException;
29 import java.util.Arrays;
30 
31 /**
32  * {@hide}
33  *
34  * Simple SNTP client class for retrieving network time.
35  *
36  * Sample usage:
37  * <pre>SntpClient client = new SntpClient();
38  * if (client.requestTime("time.foo.com")) {
39  *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
40  * }
41  * </pre>
42  */
43 public class SntpClient {
44     private static final String TAG = "SntpClient";
45     private static final boolean DBG = true;
46 
47     private static final int REFERENCE_TIME_OFFSET = 16;
48     private static final int ORIGINATE_TIME_OFFSET = 24;
49     private static final int RECEIVE_TIME_OFFSET = 32;
50     private static final int TRANSMIT_TIME_OFFSET = 40;
51     private static final int NTP_PACKET_SIZE = 48;
52 
53     private static final int NTP_PORT = 123;
54     private static final int NTP_MODE_CLIENT = 3;
55     private static final int NTP_MODE_SERVER = 4;
56     private static final int NTP_MODE_BROADCAST = 5;
57     private static final int NTP_VERSION = 3;
58 
59     private static final int NTP_LEAP_NOSYNC = 3;
60     private static final int NTP_STRATUM_DEATH = 0;
61     private static final int NTP_STRATUM_MAX = 15;
62 
63     // Number of seconds between Jan 1, 1900 and Jan 1, 1970
64     // 70 years plus 17 leap days
65     private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
66 
67     // system time computed from NTP server response
68     private long mNtpTime;
69 
70     // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
71     private long mNtpTimeReference;
72 
73     // round trip time in milliseconds
74     private long mRoundTripTime;
75 
76     private static class InvalidServerReplyException extends Exception {
InvalidServerReplyException(String message)77         public InvalidServerReplyException(String message) {
78             super(message);
79         }
80     }
81 
82     @UnsupportedAppUsage
SntpClient()83     public SntpClient() {
84     }
85 
86     /**
87      * Sends an SNTP request to the given host and processes the response.
88      *
89      * @param host host name of the server.
90      * @param timeout network timeout in milliseconds. the timeout doesn't include the DNS lookup
91      *                time, and it applies to each individual query to the resolved addresses of
92      *                the NTP server.
93      * @param network network over which to send the request.
94      * @return true if the transaction was successful.
95      */
requestTime(String host, int timeout, Network network)96     public boolean requestTime(String host, int timeout, Network network) {
97         final Network networkForResolv = network.getPrivateDnsBypassingCopy();
98         try {
99             final InetAddress[] addresses = networkForResolv.getAllByName(host);
100             for (int i = 0; i < addresses.length; i++) {
101                 if (requestTime(addresses[i], NTP_PORT, timeout, networkForResolv)) return true;
102             }
103         } catch (UnknownHostException e) {
104             Log.w(TAG, "Unknown host: " + host);
105             EventLogTags.writeNtpFailure(host, e.toString());
106         }
107 
108         if (DBG) Log.d(TAG, "request time failed");
109         return false;
110     }
111 
requestTime(InetAddress address, int port, int timeout, Network network)112     public boolean requestTime(InetAddress address, int port, int timeout, Network network) {
113         DatagramSocket socket = null;
114         final int oldTag = TrafficStats.getAndSetThreadStatsTag(
115                 TrafficStatsConstants.TAG_SYSTEM_NTP);
116         try {
117             socket = new DatagramSocket();
118             network.bindSocket(socket);
119             socket.setSoTimeout(timeout);
120             byte[] buffer = new byte[NTP_PACKET_SIZE];
121             DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
122 
123             // set mode = 3 (client) and version = 3
124             // mode is in low 3 bits of first byte
125             // version is in bits 3-5 of first byte
126             buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
127 
128             // get current time and write it to the request packet
129             final long requestTime = System.currentTimeMillis();
130             final long requestTicks = SystemClock.elapsedRealtime();
131             writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
132 
133             socket.send(request);
134 
135             // read the response
136             DatagramPacket response = new DatagramPacket(buffer, buffer.length);
137             socket.receive(response);
138             final long responseTicks = SystemClock.elapsedRealtime();
139             final long responseTime = requestTime + (responseTicks - requestTicks);
140 
141             // extract the results
142             final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
143             final byte mode = (byte) (buffer[0] & 0x7);
144             final int stratum = (int) (buffer[1] & 0xff);
145             final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
146             final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
147             final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
148             final long referenceTime = readTimeStamp(buffer, REFERENCE_TIME_OFFSET);
149 
150             /* Do validation according to RFC */
151             // TODO: validate originateTime == requestTime.
152             checkValidServerReply(leap, mode, stratum, transmitTime, referenceTime);
153 
154             long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
155             // receiveTime = originateTime + transit + skew
156             // responseTime = transmitTime + transit - skew
157             // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
158             //             = ((originateTime + transit + skew - originateTime) +
159             //                (transmitTime - (transmitTime + transit - skew)))/2
160             //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
161             //             = (transit + skew - transit + skew)/2
162             //             = (2 * skew)/2 = skew
163             long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
164             EventLogTags.writeNtpSuccess(address.toString(), roundTripTime, clockOffset);
165             if (DBG) {
166                 Log.d(TAG, "round trip: " + roundTripTime + "ms, " +
167                         "clock offset: " + clockOffset + "ms");
168             }
169 
170             // save our results - use the times on this side of the network latency
171             // (response rather than request time)
172             mNtpTime = responseTime + clockOffset;
173             mNtpTimeReference = responseTicks;
174             mRoundTripTime = roundTripTime;
175         } catch (Exception e) {
176             EventLogTags.writeNtpFailure(address.toString(), e.toString());
177             if (DBG) Log.d(TAG, "request time failed: " + e);
178             return false;
179         } finally {
180             if (socket != null) {
181                 socket.close();
182             }
183             TrafficStats.setThreadStatsTag(oldTag);
184         }
185 
186         return true;
187     }
188 
189     @Deprecated
190     @UnsupportedAppUsage
requestTime(String host, int timeout)191     public boolean requestTime(String host, int timeout) {
192         Log.w(TAG, "Shame on you for calling the hidden API requestTime()!");
193         return false;
194     }
195 
196     /**
197      * Returns the time computed from the NTP transaction.
198      *
199      * @return time value computed from NTP server response.
200      */
201     @UnsupportedAppUsage
getNtpTime()202     public long getNtpTime() {
203         return mNtpTime;
204     }
205 
206     /**
207      * Returns the reference clock value (value of SystemClock.elapsedRealtime())
208      * corresponding to the NTP time.
209      *
210      * @return reference clock corresponding to the NTP time.
211      */
212     @UnsupportedAppUsage
getNtpTimeReference()213     public long getNtpTimeReference() {
214         return mNtpTimeReference;
215     }
216 
217     /**
218      * Returns the round trip time of the NTP transaction
219      *
220      * @return round trip time in milliseconds.
221      */
222     @UnsupportedAppUsage
getRoundTripTime()223     public long getRoundTripTime() {
224         return mRoundTripTime;
225     }
226 
checkValidServerReply( byte leap, byte mode, int stratum, long transmitTime, long referenceTime)227     private static void checkValidServerReply(
228             byte leap, byte mode, int stratum, long transmitTime, long referenceTime)
229             throws InvalidServerReplyException {
230         if (leap == NTP_LEAP_NOSYNC) {
231             throw new InvalidServerReplyException("unsynchronized server");
232         }
233         if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) {
234             throw new InvalidServerReplyException("untrusted mode: " + mode);
235         }
236         if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) {
237             throw new InvalidServerReplyException("untrusted stratum: " + stratum);
238         }
239         if (transmitTime == 0) {
240             throw new InvalidServerReplyException("zero transmitTime");
241         }
242         if (referenceTime == 0) {
243             throw new InvalidServerReplyException("zero reference timestamp");
244         }
245     }
246 
247     /**
248      * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
249      */
read32(byte[] buffer, int offset)250     private long read32(byte[] buffer, int offset) {
251         byte b0 = buffer[offset];
252         byte b1 = buffer[offset+1];
253         byte b2 = buffer[offset+2];
254         byte b3 = buffer[offset+3];
255 
256         // convert signed bytes to unsigned values
257         int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
258         int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
259         int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
260         int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
261 
262         return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
263     }
264 
265     /**
266      * Reads the NTP time stamp at the given offset in the buffer and returns
267      * it as a system time (milliseconds since January 1, 1970).
268      */
readTimeStamp(byte[] buffer, int offset)269     private long readTimeStamp(byte[] buffer, int offset) {
270         long seconds = read32(buffer, offset);
271         long fraction = read32(buffer, offset + 4);
272         // Special case: zero means zero.
273         if (seconds == 0 && fraction == 0) {
274             return 0;
275         }
276         return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
277     }
278 
279     /**
280      * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
281      * at the given offset in the buffer.
282      */
writeTimeStamp(byte[] buffer, int offset, long time)283     private void writeTimeStamp(byte[] buffer, int offset, long time) {
284         // Special case: zero means zero.
285         if (time == 0) {
286             Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
287             return;
288         }
289 
290         long seconds = time / 1000L;
291         long milliseconds = time - seconds * 1000L;
292         seconds += OFFSET_1900_TO_1970;
293 
294         // write seconds in big endian format
295         buffer[offset++] = (byte)(seconds >> 24);
296         buffer[offset++] = (byte)(seconds >> 16);
297         buffer[offset++] = (byte)(seconds >> 8);
298         buffer[offset++] = (byte)(seconds >> 0);
299 
300         long fraction = milliseconds * 0x100000000L / 1000L;
301         // write fraction in big endian format
302         buffer[offset++] = (byte)(fraction >> 24);
303         buffer[offset++] = (byte)(fraction >> 16);
304         buffer[offset++] = (byte)(fraction >> 8);
305         // low order bits should be random data
306         buffer[offset++] = (byte)(Math.random() * 255.0);
307     }
308 }
309