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;
25
26/**
27 * {@hide}
28 *
29 * Simple SNTP client class for retrieving network time.
30 *
31 * Sample usage:
32 * <pre>SntpClient client = new SntpClient();
33 * if (client.requestTime("time.foo.com")) {
34 *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
35 * }
36 * </pre>
37 */
38public class SntpClient
39{
40    private static final String TAG = "SntpClient";
41
42    private static final int REFERENCE_TIME_OFFSET = 16;
43    private static final int ORIGINATE_TIME_OFFSET = 24;
44    private static final int RECEIVE_TIME_OFFSET = 32;
45    private static final int TRANSMIT_TIME_OFFSET = 40;
46    private static final int NTP_PACKET_SIZE = 48;
47
48    private static final int NTP_PORT = 123;
49    private static final int NTP_MODE_CLIENT = 3;
50    private static final int NTP_VERSION = 3;
51
52    // Number of seconds between Jan 1, 1900 and Jan 1, 1970
53    // 70 years plus 17 leap days
54    private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;
55
56    // system time computed from NTP server response
57    private long mNtpTime;
58
59    // value of SystemClock.elapsedRealtime() corresponding to mNtpTime
60    private long mNtpTimeReference;
61
62    // round trip time in milliseconds
63    private long mRoundTripTime;
64
65    /**
66     * Sends an SNTP request to the given host and processes the response.
67     *
68     * @param host host name of the server.
69     * @param timeout network timeout in milliseconds.
70     * @return true if the transaction was successful.
71     */
72    public boolean requestTime(String host, int timeout) {
73        DatagramSocket socket = null;
74        try {
75            socket = new DatagramSocket();
76            socket.setSoTimeout(timeout);
77            InetAddress address = InetAddress.getByName(host);
78            byte[] buffer = new byte[NTP_PACKET_SIZE];
79            DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);
80
81            // set mode = 3 (client) and version = 3
82            // mode is in low 3 bits of first byte
83            // version is in bits 3-5 of first byte
84            buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);
85
86            // get current time and write it to the request packet
87            long requestTime = System.currentTimeMillis();
88            long requestTicks = SystemClock.elapsedRealtime();
89            writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);
90
91            socket.send(request);
92
93            // read the response
94            DatagramPacket response = new DatagramPacket(buffer, buffer.length);
95            socket.receive(response);
96            long responseTicks = SystemClock.elapsedRealtime();
97            long responseTime = requestTime + (responseTicks - requestTicks);
98
99            // extract the results
100            long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);
101            long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);
102            long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);
103            long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);
104            // receiveTime = originateTime + transit + skew
105            // responseTime = transmitTime + transit - skew
106            // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2
107            //             = ((originateTime + transit + skew - originateTime) +
108            //                (transmitTime - (transmitTime + transit - skew)))/2
109            //             = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2
110            //             = (transit + skew - transit + skew)/2
111            //             = (2 * skew)/2 = skew
112            long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2;
113            // if (false) Log.d(TAG, "round trip: " + roundTripTime + " ms");
114            // if (false) Log.d(TAG, "clock offset: " + clockOffset + " ms");
115
116            // save our results - use the times on this side of the network latency
117            // (response rather than request time)
118            mNtpTime = responseTime + clockOffset;
119            mNtpTimeReference = responseTicks;
120            mRoundTripTime = roundTripTime;
121        } catch (Exception e) {
122            if (false) Log.d(TAG, "request time failed: " + e);
123            return false;
124        } finally {
125            if (socket != null) {
126                socket.close();
127            }
128        }
129
130        return true;
131    }
132
133    /**
134     * Returns the time computed from the NTP transaction.
135     *
136     * @return time value computed from NTP server response.
137     */
138    public long getNtpTime() {
139        return mNtpTime;
140    }
141
142    /**
143     * Returns the reference clock value (value of SystemClock.elapsedRealtime())
144     * corresponding to the NTP time.
145     *
146     * @return reference clock corresponding to the NTP time.
147     */
148    public long getNtpTimeReference() {
149        return mNtpTimeReference;
150    }
151
152    /**
153     * Returns the round trip time of the NTP transaction
154     *
155     * @return round trip time in milliseconds.
156     */
157    public long getRoundTripTime() {
158        return mRoundTripTime;
159    }
160
161    /**
162     * Reads an unsigned 32 bit big endian number from the given offset in the buffer.
163     */
164    private long read32(byte[] buffer, int offset) {
165        byte b0 = buffer[offset];
166        byte b1 = buffer[offset+1];
167        byte b2 = buffer[offset+2];
168        byte b3 = buffer[offset+3];
169
170        // convert signed bytes to unsigned values
171        int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);
172        int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);
173        int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);
174        int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);
175
176        return ((long)i0 << 24) + ((long)i1 << 16) + ((long)i2 << 8) + (long)i3;
177    }
178
179    /**
180     * Reads the NTP time stamp at the given offset in the buffer and returns
181     * it as a system time (milliseconds since January 1, 1970).
182     */
183    private long readTimeStamp(byte[] buffer, int offset) {
184        long seconds = read32(buffer, offset);
185        long fraction = read32(buffer, offset + 4);
186        return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);
187    }
188
189    /**
190     * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp
191     * at the given offset in the buffer.
192     */
193    private void writeTimeStamp(byte[] buffer, int offset, long time) {
194        long seconds = time / 1000L;
195        long milliseconds = time - seconds * 1000L;
196        seconds += OFFSET_1900_TO_1970;
197
198        // write seconds in big endian format
199        buffer[offset++] = (byte)(seconds >> 24);
200        buffer[offset++] = (byte)(seconds >> 16);
201        buffer[offset++] = (byte)(seconds >> 8);
202        buffer[offset++] = (byte)(seconds >> 0);
203
204        long fraction = milliseconds * 0x100000000L / 1000L;
205        // write fraction in big endian format
206        buffer[offset++] = (byte)(fraction >> 24);
207        buffer[offset++] = (byte)(fraction >> 16);
208        buffer[offset++] = (byte)(fraction >> 8);
209        // low order bits should be random data
210        buffer[offset++] = (byte)(Math.random() * 255.0);
211    }
212}
213