blob: 9f7437ec2a3a550a6bfc9842c8f9399b3be24db0 [file] [log] [blame]
Amith Yamasani6734b9f2010-09-13 16:24:08 -07001/*
2 * Copyright (C) 2010 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 com.android.server;
18
Amith Yamasani6734b9f2010-09-13 16:24:08 -070019import android.app.AlarmManager;
20import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080026import android.content.pm.PackageManager;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070027import android.database.ContentObserver;
Amith Yamasani8d394fa2011-03-01 12:41:04 -080028import android.net.ConnectivityManager;
zhoulei45d1b262017-05-10 18:09:50 +080029import android.net.ConnectivityManager.NetworkCallback;
30import android.net.Network;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080031import android.os.Binder;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070032import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -070033import android.os.HandlerThread;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070034import android.os.Looper;
35import android.os.Message;
36import android.os.SystemClock;
Thierry Strudel8c842172015-10-29 14:40:29 -070037import android.os.PowerManager;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070038import android.provider.Settings;
39import android.util.Log;
Jeff Sharkey104344e2011-07-10 14:20:41 -070040import android.util.NtpTrustedTime;
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080041import android.util.TimeUtils;
Jeff Sharkey104344e2011-07-10 14:20:41 -070042import android.util.TrustedTime;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070043
Jeff Sharkey104344e2011-07-10 14:20:41 -070044import com.android.internal.telephony.TelephonyIntents;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070045
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080046import java.io.FileDescriptor;
47import java.io.PrintWriter;
48
Amith Yamasani6734b9f2010-09-13 16:24:08 -070049/**
50 * Monitors the network time and updates the system time if it is out of sync
51 * and there hasn't been any NITZ update from the carrier recently.
52 * If looking up the network time fails for some reason, it tries a few times with a short
53 * interval and then resets to checking on longer intervals.
54 * <p>
55 * If the user enables AUTO_TIME, it will check immediately for the network time, if NITZ wasn't
56 * available.
57 * </p>
58 */
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080059public class NetworkTimeUpdateService extends Binder {
Amith Yamasani6734b9f2010-09-13 16:24:08 -070060
61 private static final String TAG = "NetworkTimeUpdateService";
62 private static final boolean DBG = false;
63
64 private static final int EVENT_AUTO_TIME_CHANGED = 1;
65 private static final int EVENT_POLL_NETWORK_TIME = 2;
Lorenzo Colittidf590532015-01-22 22:35:33 +090066 private static final int EVENT_NETWORK_CHANGED = 3;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070067
Amith Yamasani6734b9f2010-09-13 16:24:08 -070068 private static final String ACTION_POLL =
69 "com.android.server.NetworkTimeUpdateService.action.POLL";
Fyodor Kupolov32af07a2016-02-26 16:54:25 -080070
71 private static final int NETWORK_CHANGE_EVENT_DELAY_MS = 1000;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070072 private static int POLL_REQUEST = 0;
73
74 private static final long NOT_SET = -1;
75 private long mNitzTimeSetTime = NOT_SET;
76 // TODO: Have a way to look up the timezone we are in
77 private long mNitzZoneSetTime = NOT_SET;
zhoulei45d1b262017-05-10 18:09:50 +080078 private Network mDefaultNetwork = null;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070079
80 private Context mContext;
Jeff Sharkey104344e2011-07-10 14:20:41 -070081 private TrustedTime mTime;
82
Amith Yamasani6734b9f2010-09-13 16:24:08 -070083 // NTP lookup is done on this thread and handler
84 private Handler mHandler;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070085 private AlarmManager mAlarmManager;
86 private PendingIntent mPendingPollIntent;
87 private SettingsObserver mSettingsObserver;
zhoulei45d1b262017-05-10 18:09:50 +080088 private ConnectivityManager mCM;
89 private NetworkTimeUpdateCallback mNetworkTimeUpdateCallback;
Amith Yamasani6734b9f2010-09-13 16:24:08 -070090 // The last time that we successfully fetched the NTP time.
91 private long mLastNtpFetchTime = NOT_SET;
Thierry Strudel8c842172015-10-29 14:40:29 -070092 private final PowerManager.WakeLock mWakeLock;
Jaewan Kimc3560b82012-11-20 23:58:07 +090093
94 // Normal polling frequency
95 private final long mPollingIntervalMs;
96 // Try-again polling interval, in case the network request failed
97 private final long mPollingIntervalShorterMs;
98 // Number of times to try again
99 private final int mTryAgainTimesMax;
100 // If the time difference is greater than this threshold, then update the time.
101 private final int mTimeErrorThresholdMs;
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700102 // Keeps track of how many quick attempts were made to fetch NTP time.
103 // During bootup, the network may not have been up yet, or it's taking time for the
104 // connection to happen.
105 private int mTryAgainCounter;
106
107 public NetworkTimeUpdateService(Context context) {
108 mContext = context;
Jeff Sharkey104344e2011-07-10 14:20:41 -0700109 mTime = NtpTrustedTime.getInstance(context);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700110 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
zhoulei45d1b262017-05-10 18:09:50 +0800111 mCM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700112 Intent pollIntent = new Intent(ACTION_POLL, null);
113 mPendingPollIntent = PendingIntent.getBroadcast(mContext, POLL_REQUEST, pollIntent, 0);
Jaewan Kimc3560b82012-11-20 23:58:07 +0900114
115 mPollingIntervalMs = mContext.getResources().getInteger(
116 com.android.internal.R.integer.config_ntpPollingInterval);
117 mPollingIntervalShorterMs = mContext.getResources().getInteger(
118 com.android.internal.R.integer.config_ntpPollingIntervalShorter);
119 mTryAgainTimesMax = mContext.getResources().getInteger(
120 com.android.internal.R.integer.config_ntpRetry);
121 mTimeErrorThresholdMs = mContext.getResources().getInteger(
122 com.android.internal.R.integer.config_ntpThreshold);
Thierry Strudel8c842172015-10-29 14:40:29 -0700123
124 mWakeLock = ((PowerManager) context.getSystemService(Context.POWER_SERVICE)).newWakeLock(
125 PowerManager.PARTIAL_WAKE_LOCK, TAG);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700126 }
127
128 /** Initialize the receivers and initiate the first NTP request */
Svetoslav Ganova0027152013-06-25 14:59:53 -0700129 public void systemRunning() {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700130 registerForTelephonyIntents();
131 registerForAlarms();
132
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133 HandlerThread thread = new HandlerThread(TAG);
134 thread.start();
135 mHandler = new MyHandler(thread.getLooper());
zhoulei45d1b262017-05-10 18:09:50 +0800136 mNetworkTimeUpdateCallback = new NetworkTimeUpdateCallback();
137 mCM.registerDefaultNetworkCallback(mNetworkTimeUpdateCallback, mHandler);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700138
139 mSettingsObserver = new SettingsObserver(mHandler, EVENT_AUTO_TIME_CHANGED);
140 mSettingsObserver.observe(mContext);
141 }
142
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700143 private void registerForTelephonyIntents() {
144 IntentFilter intentFilter = new IntentFilter();
145 intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIME);
146 intentFilter.addAction(TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE);
147 mContext.registerReceiver(mNitzReceiver, intentFilter);
148 }
149
150 private void registerForAlarms() {
151 mContext.registerReceiver(
152 new BroadcastReceiver() {
153 @Override
154 public void onReceive(Context context, Intent intent) {
155 mHandler.obtainMessage(EVENT_POLL_NETWORK_TIME).sendToTarget();
156 }
157 }, new IntentFilter(ACTION_POLL));
158 }
159
160 private void onPollNetworkTime(int event) {
zhoulei45d1b262017-05-10 18:09:50 +0800161 // If Automatic time is not set, don't bother. Similarly, if we don't
162 // have any default network, don't bother.
163 if (!isAutomaticTimeRequested() || mDefaultNetwork == null) return;
Thierry Strudel8c842172015-10-29 14:40:29 -0700164 mWakeLock.acquire();
165 try {
166 onPollNetworkTimeUnderWakeLock(event);
167 } finally {
168 mWakeLock.release();
169 }
170 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700171
Thierry Strudel8c842172015-10-29 14:40:29 -0700172 private void onPollNetworkTimeUnderWakeLock(int event) {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700173 final long refTime = SystemClock.elapsedRealtime();
Jaewan Kimc3560b82012-11-20 23:58:07 +0900174 // If NITZ time was received less than mPollingIntervalMs time ago,
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700175 // no need to sync to NTP.
Jaewan Kimc3560b82012-11-20 23:58:07 +0900176 if (mNitzTimeSetTime != NOT_SET && refTime - mNitzTimeSetTime < mPollingIntervalMs) {
177 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700178 return;
179 }
180 final long currentTime = System.currentTimeMillis();
181 if (DBG) Log.d(TAG, "System time = " + currentTime);
182 // Get the NTP time
Jaewan Kimc3560b82012-11-20 23:58:07 +0900183 if (mLastNtpFetchTime == NOT_SET || refTime >= mLastNtpFetchTime + mPollingIntervalMs
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700184 || event == EVENT_AUTO_TIME_CHANGED) {
185 if (DBG) Log.d(TAG, "Before Ntp fetch");
Jeff Sharkey104344e2011-07-10 14:20:41 -0700186
187 // force refresh NTP cache when outdated
Jaewan Kimc3560b82012-11-20 23:58:07 +0900188 if (mTime.getCacheAge() >= mPollingIntervalMs) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700189 mTime.forceRefresh();
190 }
191
192 // only update when NTP time is fresh
Jaewan Kimc3560b82012-11-20 23:58:07 +0900193 if (mTime.getCacheAge() < mPollingIntervalMs) {
Jeff Sharkey104344e2011-07-10 14:20:41 -0700194 final long ntp = mTime.currentTimeMillis();
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700195 mTryAgainCounter = 0;
Amith Yamasani708d5d42012-05-02 11:50:31 -0700196 // If the clock is more than N seconds off or this is the first time it's been
197 // fetched since boot, set the current time.
Jaewan Kimc3560b82012-11-20 23:58:07 +0900198 if (Math.abs(ntp - currentTime) > mTimeErrorThresholdMs
Amith Yamasani708d5d42012-05-02 11:50:31 -0700199 || mLastNtpFetchTime == NOT_SET) {
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700200 // Set the system time
Amith Yamasani708d5d42012-05-02 11:50:31 -0700201 if (DBG && mLastNtpFetchTime == NOT_SET
Jaewan Kimc3560b82012-11-20 23:58:07 +0900202 && Math.abs(ntp - currentTime) <= mTimeErrorThresholdMs) {
Amith Yamasani708d5d42012-05-02 11:50:31 -0700203 Log.d(TAG, "For initial setup, rtc = " + currentTime);
204 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700205 if (DBG) Log.d(TAG, "Ntp time to be set = " + ntp);
206 // Make sure we don't overflow, since it's going to be converted to an int
207 if (ntp / 1000 < Integer.MAX_VALUE) {
208 SystemClock.setCurrentTimeMillis(ntp);
209 }
210 } else {
211 if (DBG) Log.d(TAG, "Ntp time is close enough = " + ntp);
212 }
Amith Yamasani708d5d42012-05-02 11:50:31 -0700213 mLastNtpFetchTime = SystemClock.elapsedRealtime();
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700214 } else {
215 // Try again shortly
216 mTryAgainCounter++;
Jaewan Kimc3560b82012-11-20 23:58:07 +0900217 if (mTryAgainTimesMax < 0 || mTryAgainCounter <= mTryAgainTimesMax) {
218 resetAlarm(mPollingIntervalShorterMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700219 } else {
220 // Try much later
221 mTryAgainCounter = 0;
Jaewan Kimc3560b82012-11-20 23:58:07 +0900222 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700223 }
224 return;
225 }
226 }
Jaewan Kimc3560b82012-11-20 23:58:07 +0900227 resetAlarm(mPollingIntervalMs);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700228 }
229
230 /**
231 * Cancel old alarm and starts a new one for the specified interval.
232 *
233 * @param interval when to trigger the alarm, starting from now.
234 */
235 private void resetAlarm(long interval) {
236 mAlarmManager.cancel(mPendingPollIntent);
237 long now = SystemClock.elapsedRealtime();
238 long next = now + interval;
239 mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, next, mPendingPollIntent);
240 }
241
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700242 /**
243 * Checks if the user prefers to automatically set the time.
244 */
245 private boolean isAutomaticTimeRequested() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700246 return Settings.Global.getInt(
247 mContext.getContentResolver(), Settings.Global.AUTO_TIME, 0) != 0;
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700248 }
249
250 /** Receiver for Nitz time events */
251 private BroadcastReceiver mNitzReceiver = new BroadcastReceiver() {
252
253 @Override
254 public void onReceive(Context context, Intent intent) {
255 String action = intent.getAction();
Fyodor Kupolov32af07a2016-02-26 16:54:25 -0800256 if (DBG) Log.d(TAG, "Received " + action);
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700257 if (TelephonyIntents.ACTION_NETWORK_SET_TIME.equals(action)) {
258 mNitzTimeSetTime = SystemClock.elapsedRealtime();
259 } else if (TelephonyIntents.ACTION_NETWORK_SET_TIMEZONE.equals(action)) {
260 mNitzZoneSetTime = SystemClock.elapsedRealtime();
261 }
262 }
263 };
264
265 /** Handler to do the network accesses on */
266 private class MyHandler extends Handler {
267
268 public MyHandler(Looper l) {
269 super(l);
270 }
271
272 @Override
273 public void handleMessage(Message msg) {
274 switch (msg.what) {
275 case EVENT_AUTO_TIME_CHANGED:
276 case EVENT_POLL_NETWORK_TIME:
Lorenzo Colittidf590532015-01-22 22:35:33 +0900277 case EVENT_NETWORK_CHANGED:
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700278 onPollNetworkTime(msg.what);
279 break;
280 }
281 }
282 }
283
zhoulei45d1b262017-05-10 18:09:50 +0800284 private class NetworkTimeUpdateCallback extends NetworkCallback {
285 @Override
286 public void onAvailable(Network network) {
287 Log.d(TAG, String.format("New default network %s; checking time.", network));
288 mDefaultNetwork = network;
289 // Running on mHandler so invoke directly.
290 onPollNetworkTime(EVENT_NETWORK_CHANGED);
291 }
292
293 @Override
294 public void onLost(Network network) {
295 if (network.equals(mDefaultNetwork)) mDefaultNetwork = null;
296 }
297 }
298
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700299 /** Observer to watch for changes to the AUTO_TIME setting */
300 private static class SettingsObserver extends ContentObserver {
301
302 private int mMsg;
303 private Handler mHandler;
304
305 SettingsObserver(Handler handler, int msg) {
306 super(handler);
307 mHandler = handler;
308 mMsg = msg;
309 }
310
311 void observe(Context context) {
312 ContentResolver resolver = context.getContentResolver();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700313 resolver.registerContentObserver(Settings.Global.getUriFor(Settings.Global.AUTO_TIME),
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700314 false, this);
315 }
316
317 @Override
318 public void onChange(boolean selfChange) {
319 mHandler.obtainMessage(mMsg).sendToTarget();
320 }
321 }
Fyodor Kupolov32af07a2016-02-26 16:54:25 -0800322
323 @Override
324 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
325 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
326 != PackageManager.PERMISSION_GRANTED) {
327 pw.println("Permission Denial: can't dump NetworkTimeUpdateService from from pid="
328 + Binder.getCallingPid()
329 + ", uid=" + Binder.getCallingUid()
330 + " without permission "
331 + android.Manifest.permission.DUMP);
332 return;
333 }
334 pw.print("PollingIntervalMs: ");
335 TimeUtils.formatDuration(mPollingIntervalMs, pw);
336 pw.print("\nPollingIntervalShorterMs: ");
337 TimeUtils.formatDuration(mPollingIntervalShorterMs, pw);
338 pw.println("\nTryAgainTimesMax: " + mTryAgainTimesMax);
339 pw.print("TimeErrorThresholdMs: ");
340 TimeUtils.formatDuration(mTimeErrorThresholdMs, pw);
341 pw.println("\nTryAgainCounter: " + mTryAgainCounter);
342 pw.print("LastNtpFetchTime: ");
343 TimeUtils.formatDuration(mLastNtpFetchTime, pw);
344 pw.println();
345 }
Amith Yamasani6734b9f2010-09-13 16:24:08 -0700346}