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