| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.net; |
| 18 |
|
| 19 |
import android.compat.annotation.UnsupportedAppUsage; |
| 20 |
import android.net.sntp.Duration64; |
| 21 |
import android.net.sntp.Timestamp64; |
| 22 |
import android.os.SystemClock; |
| 23 |
import android.util.Log; |
| 24 |
import android.util.Slog; |
| 25 |
|
| 26 |
import com.android.internal.annotations.VisibleForTesting; |
| 27 |
import com.android.internal.util.TrafficStatsConstants; |
| 28 |
|
| 29 |
import java.net.DatagramPacket; |
| 30 |
import java.net.DatagramSocket; |
| 31 |
import java.net.InetAddress; |
| 32 |
import java.net.UnknownHostException; |
| 33 |
import java.security.NoSuchAlgorithmException; |
| 34 |
import java.security.SecureRandom; |
| 35 |
import java.time.Duration; |
| 36 |
import java.time.Instant; |
| 37 |
import java.util.Objects; |
| 38 |
import java.util.Random; |
| 39 |
import java.util.function.Supplier; |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
public class SntpClient { |
| 54 |
private static final String TAG = "SntpClient"; |
| 55 |
private static final boolean DBG = true; |
| 56 |
|
| 57 |
private static final int REFERENCE_TIME_OFFSET = 16; |
| 58 |
private static final int ORIGINATE_TIME_OFFSET = 24; |
| 59 |
private static final int RECEIVE_TIME_OFFSET = 32; |
| 60 |
private static final int TRANSMIT_TIME_OFFSET = 40; |
| 61 |
private static final int NTP_PACKET_SIZE = 48; |
| 62 |
|
| 63 |
public static final int STANDARD_NTP_PORT = 123; |
| 64 |
private static final int NTP_MODE_CLIENT = 3; |
| 65 |
private static final int NTP_MODE_SERVER = 4; |
| 66 |
private static final int NTP_MODE_BROADCAST = 5; |
| 67 |
private static final int NTP_VERSION = 3; |
| 68 |
|
| 69 |
private static final int NTP_LEAP_NOSYNC = 3; |
| 70 |
private static final int NTP_STRATUM_DEATH = 0; |
| 71 |
private static final int NTP_STRATUM_MAX = 15; |
| 72 |
|
| 73 |
|
| 74 |
private final Supplier<Instant> mSystemTimeSupplier; |
| 75 |
|
| 76 |
private final Random mRandom; |
| 77 |
|
| 78 |
|
| 79 |
private long mClockOffset; |
| 80 |
|
| 81 |
|
| 82 |
private long mNtpTime; |
| 83 |
|
| 84 |
|
| 85 |
private long mNtpTimeReference; |
| 86 |
|
| 87 |
|
| 88 |
private long mRoundTripTime; |
| 89 |
|
| 90 |
private static class InvalidServerReplyException extends Exception { |
| 91 |
public InvalidServerReplyException(String message) { |
| 92 |
super(message); |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
@UnsupportedAppUsage |
| 97 |
public SntpClient() { |
| 98 |
this(Instant::now, defaultRandom()); |
| 99 |
} |
| 100 |
|
| 101 |
@VisibleForTesting |
| 102 |
public SntpClient(Supplier<Instant> systemTimeSupplier, Random random) { |
| 103 |
mSystemTimeSupplier = Objects.requireNonNull(systemTimeSupplier); |
| 104 |
mRandom = Objects.requireNonNull(random); |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
public boolean requestTime(String host, int port, int timeout, Network network) { |
| 119 |
final Network networkForResolv = network.getPrivateDnsBypassingCopy(); |
| 120 |
try { |
| 121 |
final InetAddress[] addresses = networkForResolv.getAllByName(host); |
| 122 |
for (int i = 0; i < addresses.length; i++) { |
| 123 |
if (requestTime(addresses[i], port, timeout, networkForResolv)) { |
| 124 |
return true; |
| 125 |
} |
| 126 |
} |
| 127 |
} catch (UnknownHostException e) { |
| 128 |
Log.w(TAG, "Unknown host: " + host); |
| 129 |
EventLogTags.writeNtpFailure(host, e.toString()); |
| 130 |
} |
| 131 |
|
| 132 |
if (DBG) Log.d(TAG, "request time failed"); |
| 133 |
return false; |
| 134 |
} |
| 135 |
|
| 136 |
public boolean requestTime(InetAddress address, int port, int timeout, Network network) { |
| 137 |
DatagramSocket socket = null; |
| 138 |
final int oldTag = TrafficStats.getAndSetThreadStatsTag( |
| 139 |
TrafficStatsConstants.TAG_SYSTEM_NTP); |
| 140 |
try { |
| 141 |
socket = new DatagramSocket(); |
| 142 |
network.bindSocket(socket); |
| 143 |
socket.setSoTimeout(timeout); |
| 144 |
byte[] buffer = new byte[NTP_PACKET_SIZE]; |
| 145 |
DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, port); |
| 146 |
|
| 147 |
|
| 148 |
|
| 149 |
|
| 150 |
buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3); |
| 151 |
|
| 152 |
|
| 153 |
final Instant requestTime = mSystemTimeSupplier.get(); |
| 154 |
final Timestamp64 requestTimestamp = Timestamp64.fromInstant(requestTime); |
| 155 |
|
| 156 |
final Timestamp64 randomizedRequestTimestamp = |
| 157 |
requestTimestamp.randomizeSubMillis(mRandom); |
| 158 |
final long requestTicks = SystemClock.elapsedRealtime(); |
| 159 |
writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, randomizedRequestTimestamp); |
| 160 |
|
| 161 |
socket.send(request); |
| 162 |
|
| 163 |
|
| 164 |
DatagramPacket response = new DatagramPacket(buffer, buffer.length); |
| 165 |
socket.receive(response); |
| 166 |
final long responseTicks = SystemClock.elapsedRealtime(); |
| 167 |
final Instant responseTime = requestTime.plusMillis(responseTicks - requestTicks); |
| 168 |
final Timestamp64 responseTimestamp = Timestamp64.fromInstant(responseTime); |
| 169 |
|
| 170 |
|
| 171 |
final byte leap = (byte) ((buffer[0] >> 6) & 0x3); |
| 172 |
final byte mode = (byte) (buffer[0] & 0x7); |
| 173 |
final int stratum = (int) (buffer[1] & 0xff); |
| 174 |
final Timestamp64 referenceTimestamp = readTimeStamp(buffer, REFERENCE_TIME_OFFSET); |
| 175 |
final Timestamp64 originateTimestamp = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET); |
| 176 |
final Timestamp64 receiveTimestamp = readTimeStamp(buffer, RECEIVE_TIME_OFFSET); |
| 177 |
final Timestamp64 transmitTimestamp = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET); |
| 178 |
|
| 179 |
|
| 180 |
checkValidServerReply(leap, mode, stratum, transmitTimestamp, referenceTimestamp, |
| 181 |
randomizedRequestTimestamp, originateTimestamp); |
| 182 |
|
| 183 |
long totalTransactionDurationMillis = responseTicks - requestTicks; |
| 184 |
long serverDurationMillis = |
| 185 |
Duration64.between(receiveTimestamp, transmitTimestamp).toDuration().toMillis(); |
| 186 |
long roundTripTimeMillis = totalTransactionDurationMillis - serverDurationMillis; |
| 187 |
|
| 188 |
Duration clockOffsetDuration = calculateClockOffset(requestTimestamp, |
| 189 |
receiveTimestamp, transmitTimestamp, responseTimestamp); |
| 190 |
long clockOffsetMillis = clockOffsetDuration.toMillis(); |
| 191 |
|
| 192 |
EventLogTags.writeNtpSuccess( |
| 193 |
address.toString(), roundTripTimeMillis, clockOffsetMillis); |
| 194 |
if (DBG) { |
| 195 |
Log.d(TAG, "round trip: " + roundTripTimeMillis + "ms, " |
| 196 |
+ "clock offset: " + clockOffsetMillis + "ms"); |
| 197 |
} |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
mClockOffset = clockOffsetMillis; |
| 202 |
mNtpTime = responseTime.plus(clockOffsetDuration).toEpochMilli(); |
| 203 |
mNtpTimeReference = responseTicks; |
| 204 |
mRoundTripTime = roundTripTimeMillis; |
| 205 |
} catch (Exception e) { |
| 206 |
EventLogTags.writeNtpFailure(address.toString(), e.toString()); |
| 207 |
if (DBG) Log.d(TAG, "request time failed: " + e); |
| 208 |
return false; |
| 209 |
} finally { |
| 210 |
if (socket != null) { |
| 211 |
socket.close(); |
| 212 |
} |
| 213 |
TrafficStats.setThreadStatsTag(oldTag); |
| 214 |
} |
| 215 |
|
| 216 |
return true; |
| 217 |
} |
| 218 |
|
| 219 |
|
| 220 |
@VisibleForTesting |
| 221 |
public static Duration calculateClockOffset(Timestamp64 clientRequestTimestamp, |
| 222 |
Timestamp64 serverReceiveTimestamp, Timestamp64 serverTransmitTimestamp, |
| 223 |
Timestamp64 clientResponseTimestamp) { |
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
return Duration64.between(clientRequestTimestamp, serverReceiveTimestamp) |
| 237 |
.plus(Duration64.between(clientResponseTimestamp, serverTransmitTimestamp)) |
| 238 |
.dividedBy(2); |
| 239 |
} |
| 240 |
|
| 241 |
@Deprecated |
| 242 |
@UnsupportedAppUsage |
| 243 |
public boolean requestTime(String host, int timeout) { |
| 244 |
Log.w(TAG, "Shame on you for calling the hidden API requestTime()!"); |
| 245 |
return false; |
| 246 |
} |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
@VisibleForTesting |
| 252 |
public long getClockOffset() { |
| 253 |
return mClockOffset; |
| 254 |
} |
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
|
| 261 |
@UnsupportedAppUsage |
| 262 |
public long getNtpTime() { |
| 263 |
return mNtpTime; |
| 264 |
} |
| 265 |
|
| 266 |
|
| 267 |
|
| 268 |
|
| 269 |
|
| 270 |
|
| 271 |
|
| 272 |
@UnsupportedAppUsage |
| 273 |
public long getNtpTimeReference() { |
| 274 |
return mNtpTimeReference; |
| 275 |
} |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
@UnsupportedAppUsage |
| 283 |
public long getRoundTripTime() { |
| 284 |
return mRoundTripTime; |
| 285 |
} |
| 286 |
|
| 287 |
private static void checkValidServerReply( |
| 288 |
byte leap, byte mode, int stratum, Timestamp64 transmitTimestamp, |
| 289 |
Timestamp64 referenceTimestamp, Timestamp64 randomizedRequestTimestamp, |
| 290 |
Timestamp64 originateTimestamp) throws InvalidServerReplyException { |
| 291 |
if (leap == NTP_LEAP_NOSYNC) { |
| 292 |
throw new InvalidServerReplyException("unsynchronized server"); |
| 293 |
} |
| 294 |
if ((mode != NTP_MODE_SERVER) && (mode != NTP_MODE_BROADCAST)) { |
| 295 |
throw new InvalidServerReplyException("untrusted mode: " + mode); |
| 296 |
} |
| 297 |
if ((stratum == NTP_STRATUM_DEATH) || (stratum > NTP_STRATUM_MAX)) { |
| 298 |
throw new InvalidServerReplyException("untrusted stratum: " + stratum); |
| 299 |
} |
| 300 |
if (!randomizedRequestTimestamp.equals(originateTimestamp)) { |
| 301 |
throw new InvalidServerReplyException( |
| 302 |
"originateTimestamp != randomizedRequestTimestamp"); |
| 303 |
} |
| 304 |
if (transmitTimestamp.equals(Timestamp64.ZERO)) { |
| 305 |
throw new InvalidServerReplyException("zero transmitTimestamp"); |
| 306 |
} |
| 307 |
if (referenceTimestamp.equals(Timestamp64.ZERO)) { |
| 308 |
throw new InvalidServerReplyException("zero referenceTimestamp"); |
| 309 |
} |
| 310 |
} |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
private long readUnsigned32(byte[] buffer, int offset) { |
| 316 |
int i0 = buffer[offset++] & 0xFF; |
| 317 |
int i1 = buffer[offset++] & 0xFF; |
| 318 |
int i2 = buffer[offset++] & 0xFF; |
| 319 |
int i3 = buffer[offset] & 0xFF; |
| 320 |
|
| 321 |
int bits = (i0 << 24) | (i1 << 16) | (i2 << 8) | i3; |
| 322 |
return bits & 0xFFFF_FFFFL; |
| 323 |
} |
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
private Timestamp64 readTimeStamp(byte[] buffer, int offset) { |
| 329 |
long seconds = readUnsigned32(buffer, offset); |
| 330 |
int fractionBits = (int) readUnsigned32(buffer, offset + 4); |
| 331 |
return Timestamp64.fromComponents(seconds, fractionBits); |
| 332 |
} |
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
|
| 337 |
private void writeTimeStamp(byte[] buffer, int offset, Timestamp64 timestamp) { |
| 338 |
long seconds = timestamp.getEraSeconds(); |
| 339 |
|
| 340 |
buffer[offset++] = (byte) (seconds >>> 24); |
| 341 |
buffer[offset++] = (byte) (seconds >>> 16); |
| 342 |
buffer[offset++] = (byte) (seconds >>> 8); |
| 343 |
buffer[offset++] = (byte) (seconds); |
| 344 |
|
| 345 |
int fractionBits = timestamp.getFractionBits(); |
| 346 |
|
| 347 |
buffer[offset++] = (byte) (fractionBits >>> 24); |
| 348 |
buffer[offset++] = (byte) (fractionBits >>> 16); |
| 349 |
buffer[offset++] = (byte) (fractionBits >>> 8); |
| 350 |
buffer[offset] = (byte) (fractionBits); |
| 351 |
} |
| 352 |
|
| 353 |
private static Random defaultRandom() { |
| 354 |
Random random; |
| 355 |
try { |
| 356 |
random = SecureRandom.getInstanceStrong(); |
| 357 |
} catch (NoSuchAlgorithmException e) { |
| 358 |
|
| 359 |
Slog.wtf(TAG, "Unable to access SecureRandom", e); |
| 360 |
random = new Random(System.currentTimeMillis()); |
| 361 |
} |
| 362 |
return random; |
| 363 |
} |
| 364 |
} |