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