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.os.SystemClock; 20 import android.util.Log; 21 22 import java.net.DatagramPacket; 23 import java.net.DatagramSocket; 24 import java.net.InetAddress; 25 import 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 */ 39 public class SntpClient 40 { 41 private static final String TAG = "SntpClient"; 42 private static final boolean DBG = true; 43 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; 52 private static final int NTP_MODE_SERVER = 4; 53 private static final int NTP_MODE_BROADCAST = 5; 54 private static final int NTP_VERSION = 3; 55 56 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 60 // 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 73 private static class InvalidServerReplyException extends Exception { InvalidServerReplyException(String message)74 public InvalidServerReplyException(String message) { 75 super(message); 76 } 77 } 78 79 /** 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 */ requestTime(String host, int timeout)86 public boolean requestTime(String host, int timeout) { 87 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 requestTime(InetAddress address, int port, int timeout)97 public boolean requestTime(InetAddress address, int port, int timeout) { 98 DatagramSocket socket = null; 99 try { 100 socket = new DatagramSocket(); 101 socket.setSoTimeout(timeout); 102 byte[] buffer = new byte[NTP_PACKET_SIZE]; 103 DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port); 104 105 // set mode = 3 (client) and version = 3 106 // 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 111 final long requestTime = System.currentTimeMillis(); 112 final long requestTicks = SystemClock.elapsedRealtime(); 113 writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime); 114 115 socket.send(request); 116 117 // read the response 118 DatagramPacket response = new DatagramPacket(buffer, buffer.length); 119 socket.receive(response); 120 final long responseTicks = SystemClock.elapsedRealtime(); 121 final long responseTime = requestTime + (responseTicks - requestTicks); 122 123 // extract the results 124 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 135 long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime); 136 // 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; 145 if (DBG) { 146 Log.d(TAG, "round trip: " + roundTripTime + "ms, " + 147 "clock offset: " + clockOffset + "ms"); 148 } 149 150 // 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; 154 mRoundTripTime = roundTripTime; 155 } catch (Exception e) { 156 if (DBG) Log.d(TAG, "request time failed: " + e); 157 return false; 158 } finally { 159 if (socket != null) { 160 socket.close(); 161 } 162 } 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 */ getNtpTime()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 */ getNtpTimeReference()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 */ getRoundTripTime()191 public long getRoundTripTime() { 192 return mRoundTripTime; 193 } 194 checkValidServerReply( byte leap, byte mode, int stratum, long transmitTime)195 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 212 /** 213 * Reads an unsigned 32 bit big endian number from the given offset in the buffer. 214 */ read32(byte[] buffer, int offset)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 /** 231 * Reads the NTP time stamp at the given offset in the buffer and returns 232 * it as a system time (milliseconds since January 1, 1970). 233 */ readTimeStamp(byte[] buffer, int offset)234 private long readTimeStamp(byte[] buffer, int offset) { 235 long seconds = read32(buffer, offset); 236 long fraction = read32(buffer, offset + 4); 237 // 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); 242 } 243 244 /** 245 * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp 246 * at the given offset in the buffer. 247 */ writeTimeStamp(byte[] buffer, int offset, long time)248 private void writeTimeStamp(byte[] buffer, int offset, long time) { 249 // Special case: zero means zero. 250 if (time == 0) { 251 Arrays.fill(buffer, offset, offset + 8, (byte) 0x00); 252 return; 253 } 254 255 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 } 274