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