SntpClient.java revision 7eccfeb9ca60aa6e09afbdf3a4435cb2f0d12987
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
17package android.net;
18
19import android.os.SystemClock;
20import android.util.Log;
21
22import java.net.DatagramPacket;
23import java.net.DatagramSocket;
24import java.net.InetAddress;
25import java.util.Arrays;
26
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    private static final String TAG = "SntpClient";
41    private static final boolean DBG = true;
42
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;
51    private static final int NTP_MODE_SERVER = 4;
52    private static final int NTP_MODE_BROADCAST = 5;
53    private static final int NTP_VERSION = 3;
54
55    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
59    // 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
72    private static class InvalidServerReplyException extends Exception {
73        public InvalidServerReplyException(String message) {
74            super(message);
75        }
76    }
77
78    /**
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     * @param network network over which to send the request.
84     * @return true if the transaction was successful.
85     */
86    public boolean requestTime(String host, int timeout, Network network) {
87        // This flag only affects DNS resolution and not other socket semantics,
88        // therefore it's safe to set unilaterally rather than take more
89        // defensive measures like making a copy.
90        network.setPrivateDnsBypass(true);
91        InetAddress address = null;
92        try {
93            address = network.getByName(host);
94        } catch (Exception e) {
95            EventLogTags.writeNtpFailure(host, e.toString());
96            if (DBG) Log.d(TAG, "request time failed: " + e);
97            return false;
98        }
99        return requestTime(address, NTP_PORT, timeout, network);
100    }
101
102    public boolean requestTime(InetAddress address, int port, int timeout, Network network) {
103        DatagramSocket socket = null;
104        final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_NTP);
105        try {
106            socket = new DatagramSocket();
107            network.bindSocket(socket);
108            socket.setSoTimeout(timeout);
109            byte[] buffer = new byte[NTP_PACKET_SIZE];
110            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port);
111
112            // set mode = 3 (client) and version = 3
113            // mode is in low 3 bits of first byte
114            // version is in bits 3-5 of first byte
115            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
116
117            // get current time and write it to the request packet
118            final long requestTime = System.currentTimeMillis();
119            final long requestTicks = SystemClock.elapsedRealtime();
120            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
121
122            socket.send(request);
123
124            // read the response
125            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
126            socket.receive(response);
127            final long responseTicks = SystemClock.elapsedRealtime();
128            final long responseTime = requestTime + (responseTicks - requestTicks);
129
130            // extract the results
131            final byte leap = (byte) ((buffer[0] >> 6) & 0x3);
132            final byte mode = (byte) (buffer[0] & 0x7);
133            final int stratum = (int) (buffer[1] & 0xff);
134            final long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
135            final long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
136            final long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
137
138            /* do sanity check according to RFC */
139            // TODO: validate originateTime == requestTime.
140            checkValidServerReply(leap, mode, stratum, transmitTime);
141
142            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
143            // receiveTime = originateTime + transit + skew
144            // responseTime = transmitTime + transit - skew
145            // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
146            //             = ((originateTime + transit + skew - originateTime) +
147            //                (transmitTime - (transmitTime + transit - skew)))/2
148            //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
149            //             = (transit + skew - transit + skew)/2
150            //             = (2 * skew)/2 = skew
151            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
152            EventLogTags.writeNtpSuccess(address.toString(), roundTripTime, clockOffset);
153            if (DBG) {
154                Log.d(TAG, "round trip: " + roundTripTime + "ms, " +
155                        "clock offset: " + clockOffset + "ms");
156            }
157
158            // save our results - use the times on this side of the network latency
159            // (response rather than request time)
160            mNtpTime = responseTime + clockOffset;
161            mNtpTimeReference = responseTicks;
162            mRoundTripTime = roundTripTime;
163        } catch (Exception e) {
164            EventLogTags.writeNtpFailure(address.toString(), e.toString());
165            if (DBG) Log.d(TAG, "request time failed: " + e);
166            return false;
167        } finally {
168            if (socket != null) {
169                socket.close();
170            }
171            TrafficStats.setThreadStatsTag(oldTag);
172        }
173
174        return true;
175    }
176
177    @Deprecated
178    public boolean requestTime(String host, int timeout) {
179        Log.w(TAG, "Shame on you for calling the hidden API requestTime()!");
180        return false;
181    }
182
183    /**
184     * Returns the time computed from the NTP transaction.
185     *
186     * @return time value computed from NTP server response.
187     */
188    public long getNtpTime() {
189        return mNtpTime;
190    }
191
192    /**
193     * Returns the reference clock value (value of SystemClock.elapsedRealtime())
194     * corresponding to the NTP time.
195     *
196     * @return reference clock corresponding to the NTP time.
197     */
198    public long getNtpTimeReference() {
199        return mNtpTimeReference;
200    }
201
202    /**
203     * Returns the round trip time of the NTP transaction
204     *
205     * @return round trip time in milliseconds.
206     */
207    public long getRoundTripTime() {
208        return mRoundTripTime;
209    }
210
211    private static void checkValidServerReply(
212            byte leap, byte mode, int stratum, long transmitTime)
213            throws InvalidServerReplyException {
214        if (leap == NTP_LEAP_NOSYNC) {
215            throw new InvalidServerReplyException("unsynchronized server");
216        }
217        if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) {
218            throw new InvalidServerReplyException("untrusted mode: " + mode);
219        }
220        if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) {
221            throw new InvalidServerReplyException("untrusted stratum: " + stratum);
222        }
223        if (transmitTime == 0) {
224            throw new InvalidServerReplyException("zero transmitTime");
225        }
226    }
227
228    /**
229     * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
230     */
231    private long read32(byte[] buffer, int offset) {
232        byte b0 = buffer[offset];
233        byte b1 = buffer[offset+1];
234        byte b2 = buffer[offset+2];
235        byte b3 = buffer[offset+3];
236
237        // convert signed bytes to unsigned values
238        int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
239        int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
240        int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
241        int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
242
243        return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
244    }
245
246    /**
247     * Reads the NTP time stamp at the given offset in the buffer and returns
248     * it as a system time (milliseconds since January 1, 1970).
249     */
250    private long readTimeStamp(byte[] buffer, int offset) {
251        long seconds = read32(buffer, offset);
252        long fraction = read32(buffer, offset + 4);
253        // Special case: zero means zero.
254        if (seconds == 0 && fraction == 0) {
255            return 0;
256        }
257        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
258    }
259
260    /**
261     * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
262     * at the given offset in the buffer.
263     */
264    private void writeTimeStamp(byte[] buffer, int offset, long time) {
265        // Special case: zero means zero.
266        if (time == 0) {
267            Arrays.fill(buffer, offset, offset + 8, (byte) 0x00);
268            return;
269        }
270
271        long seconds = time / 1000L;
272        long milliseconds = time - seconds * 1000L;
273        seconds += OFFSET_1900_TO_1970;
274
275        // write seconds in big endian format
276        buffer[offset++] = (byte)(seconds >> 24);
277        buffer[offset++] = (byte)(seconds >> 16);
278        buffer[offset++] = (byte)(seconds >> 8);
279        buffer[offset++] = (byte)(seconds >> 0);
280
281        long fraction = milliseconds * 0x100000000L / 1000L;
282        // write fraction in big endian format
283        buffer[offset++] = (byte)(fraction >> 24);
284        buffer[offset++] = (byte)(fraction >> 16);
285        buffer[offset++] = (byte)(fraction >> 8);
286        // low order bits should be random data
287        buffer[offset++] = (byte)(Math.random() * 255.0);
288    }
289}
290