blob: dea47db62b9c6d0674c732de44d2601462a853e7 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 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
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Makoto Onukidecc5ba2019-01-15 09:34:05 -080019import static com.android.server.content.SyncLogger.logSafe;
20
Fred Quintanad9d2f112009-04-23 13:36:27 -070021import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070022import android.accounts.AccountAndUser;
Suprabh Shukla042a4782017-05-12 15:26:54 -070023import android.accounts.AccountManager;
Makoto Onuki3ab77812018-07-09 14:29:33 -070024import android.annotation.Nullable;
Marvin Paula6533252014-11-24 12:57:48 -080025import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070026import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.content.ContentResolver;
Makoto Onuki75ad2492018-03-28 14:42:42 -070028import android.content.ContentResolver.SyncExemption;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.Context;
30import android.content.ISyncStatusObserver;
31import android.content.PeriodicSync;
32import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070033import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080034import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070035import android.content.pm.PackageManager;
Dianne Hackborn231cc602009-04-27 17:10:36 -070036import android.os.Bundle;
37import android.os.Environment;
38import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080039import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import android.os.Message;
41import android.os.Parcel;
42import android.os.RemoteCallbackList;
43import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070044import android.os.UserHandle;
Makoto Onukid4764302018-03-30 17:32:57 -070045import android.util.ArrayMap;
Varun Shahfe009ec2019-04-29 14:26:45 -070046import android.util.ArraySet;
Makoto Onukid4764302018-03-30 17:32:57 -070047import android.util.AtomicFile;
48import android.util.EventLog;
49import android.util.Log;
50import android.util.Pair;
51import android.util.Slog;
52import android.util.SparseArray;
53import android.util.Xml;
Varun Shah816cf632019-10-30 17:40:15 -070054import android.util.proto.ProtoInputStream;
55import android.util.proto.ProtoOutputStream;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080056
57import com.android.internal.annotations.VisibleForTesting;
58import com.android.internal.util.ArrayUtils;
59import com.android.internal.util.FastXmlSerializer;
Varun Shahfe009ec2019-04-29 14:26:45 -070060import com.android.internal.util.IntPair;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080061
62import org.xmlpull.v1.XmlPullParser;
63import org.xmlpull.v1.XmlPullParserException;
64import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Dianne Hackborn231cc602009-04-27 17:10:36 -070066import java.io.File;
67import java.io.FileInputStream;
68import java.io.FileOutputStream;
Varun Shah816cf632019-10-30 17:40:15 -070069import java.io.IOException;
70import java.io.InputStream;
71import java.io.OutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010072import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070074import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070076import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080077import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070078import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060079import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080
81/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070082 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070084 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085 * @hide
86 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080087public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070090 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070091
Amith Yamasani04e0d262012-02-14 11:50:53 -080092 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
93 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070094 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080095 private static final String XML_ATTR_ENABLED = "enabled";
96 private static final String XML_ATTR_USER = "user";
97 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
98
Matthew Williamsfa774182013-06-18 15:44:11 -070099 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +0000100 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800101
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000102 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -0700103 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
104
105 /** Lower bound on sync time from which we assign a default flex time. */
106 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
107
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800108 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a sync start event. */
112 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Dianne Hackborn231cc602009-04-27 17:10:36 -0700114 /** Enum value for a sync stop event. */
115 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Makoto Onuki94986212018-04-11 16:24:46 -0700117 /** Enum value for a sync with other sources. */
118 public static final int SOURCE_OTHER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Dianne Hackborn231cc602009-04-27 17:10:36 -0700120 /** Enum value for a local-initiated sync. */
121 public static final int SOURCE_LOCAL = 1;
Makoto Onuki94986212018-04-11 16:24:46 -0700122
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700123 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700124 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
Dianne Hackborn231cc602009-04-27 17:10:36 -0700126 /** Enum value for a user-initiated sync. */
127 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800129 /** Enum value for a periodic sync. */
130 public static final int SOURCE_PERIODIC = 4;
131
Makoto Onuki94986212018-04-11 16:24:46 -0700132 /** Enum a sync with a "feed" extra */
133 public static final int SOURCE_FEED = 5;
134
Fred Quintana307da1a2010-01-21 14:24:20 -0800135 public static final long NOT_IN_BACKOFF_MODE = -1;
136
Makoto Onukif74cf942018-04-16 17:04:58 -0700137 /**
138 * String names for the sync source types.
139 *
140 * KEEP THIS AND {@link SyncStatusInfo#SOURCE_COUNT} IN SYNC.
141 */
142 public static final String[] SOURCES = {
143 "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000144 "LOCAL",
145 "POLL",
146 "USER",
147 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700148 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Dianne Hackborn231cc602009-04-27 17:10:36 -0700150 // The MESG column will contain one of these or one of the Error types.
151 public static final String MESG_SUCCESS = "success";
152 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700154 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Dianne Hackborn231cc602009-04-27 17:10:36 -0700156 private static final int MSG_WRITE_STATUS = 1;
157 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700158
Dianne Hackborn231cc602009-04-27 17:10:36 -0700159 private static final int MSG_WRITE_STATISTICS = 2;
160 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700161
162 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700163
Fred Quintanac2e46912010-03-15 16:10:44 -0700164 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700165 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700166
167 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000168 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700169
Makoto Onuki94986212018-04-11 16:24:46 -0700170 private volatile boolean mIsClockValid;
171
Fred Quintanafb084402010-03-23 17:57:03 -0700172 static {
173 sAuthorityRenames = new HashMap<String, String>();
174 sAuthorityRenames.put("contacts", "com.android.contacts");
175 sAuthorityRenames.put("calendar", "com.android.calendar");
176 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700177
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800179 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 final HashMap<String, AuthorityInfo> authorities =
181 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700182
Amith Yamasani04e0d262012-02-14 11:50:53 -0800183 AccountInfo(AccountAndUser accountAndUser) {
184 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700185 }
186 }
Costin Manolache360e4542009-09-04 13:36:04 -0700187
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700188 /** Bare bones representation of a sync target. */
189 public static class EndPoint {
190 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
191 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700192 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800193 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700194 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700195
196 public EndPoint(Account account, String provider, int userId) {
197 this.account = account;
198 this.provider = provider;
199 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 }
201
202 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700203 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
204 *
205 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000206 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700207 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700208 public boolean matchesSpec(EndPoint spec) {
209 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700210 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700211 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700212 return false;
213 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000214 boolean accountsMatch;
215 if (spec.account == null) {
216 accountsMatch = true;
217 } else {
218 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700219 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000220 boolean providersMatch;
221 if (spec.provider == null) {
222 providersMatch = true;
223 } else {
224 providersMatch = provider.equals(spec.provider);
225 }
226 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700227 }
228
229 public String toString() {
230 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000231 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700232 .append("/")
233 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700234 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700235 return sb.toString();
236 }
Makoto Onukidecc5ba2019-01-15 09:34:05 -0800237
238 public String toSafeString() {
239 StringBuilder sb = new StringBuilder();
240 sb.append(account == null ? "ALL ACCS" : logSafe(account))
241 .append("/")
242 .append(provider == null ? "ALL PDRS" : provider);
243 sb.append(":u" + userId);
244 return sb.toString();
245 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700246 }
247
248 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700249 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700250
251 /**
252 * The syncable state is undefined.
253 */
254 public static final int UNDEFINED = -2;
255
Matthew Williams53abfdb2015-06-10 20:06:37 -0700256 /**
257 * Default state for a newly installed adapter. An uninitialized adapter will receive an
258 * initialization sync which are governed by a different set of rules to that of regular
259 * syncs.
260 */
261 public static final int NOT_INITIALIZED = -1;
262 /**
263 * The adapter will not receive any syncs. This is behaviourally equivalent to
264 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
265 * while this is generally meant to be controlled by the developer.
266 */
267 public static final int NOT_SYNCABLE = 0;
268 /**
269 * The adapter is initialized and functioning. This is the normal state for an adapter.
270 */
271 public static final int SYNCABLE = 1;
272 /**
273 * The adapter is syncable but still requires an initialization sync. For example an adapter
274 * than has been restored from a previous device will be in this state. Not meant for
275 * external use.
276 */
277 public static final int SYNCABLE_NOT_INITIALIZED = 2;
278
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700279 /**
280 * The adapter is syncable but does not have access to the synced account and needs a
281 * user access approval.
282 */
283 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
284
Matthew Williams8ef22042013-07-26 12:56:39 -0700285 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700286 final int ident;
287 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700288 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700289 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800290 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700291 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800292 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700293 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800294 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700295
Matthew Williamsfa774182013-06-18 15:44:11 -0700296 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700297
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700298 /**
299 * Copy constructor for making deep-ish copies. Only the bundles stored
300 * in periodic syncs can make unexpected changes.
301 *
302 * @param toCopy AuthorityInfo to be copied.
303 */
304 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700305 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700306 ident = toCopy.ident;
307 enabled = toCopy.enabled;
308 syncable = toCopy.syncable;
309 backoffTime = toCopy.backoffTime;
310 backoffDelay = toCopy.backoffDelay;
311 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700312 periodicSyncs = new ArrayList<PeriodicSync>();
313 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700314 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700315 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700316 }
317 }
318
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700319 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700320 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700321 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000322 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700323 periodicSyncs = new ArrayList<PeriodicSync>();
324 defaultInitialisation();
325 }
326
327 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700328 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800329 backoffTime = -1; // if < 0 then we aren't in backoff mode
330 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000331
332 if (mPeriodicSyncAddedListener != null) {
333 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
334 DEFAULT_POLL_FREQUENCY_SECONDS,
335 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700336 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700337 }
Matthew Williams06485a72013-07-26 12:56:39 -0700338
339 @Override
340 public String toString() {
341 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
342 + backoffTime + ", delay=" + delayUntil;
343 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700344 }
Costin Manolache360e4542009-09-04 13:36:04 -0700345
Dianne Hackborn231cc602009-04-27 17:10:36 -0700346 public static class SyncHistoryItem {
347 int authorityId;
348 int historyId;
349 long eventTime;
350 long elapsedTime;
351 int source;
352 int event;
353 long upstreamActivity;
354 long downstreamActivity;
355 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700356 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700357 Bundle extras;
358 int reason;
Makoto Onukid5f25d22018-05-22 16:02:17 -0700359 int syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700360 }
Costin Manolache360e4542009-09-04 13:36:04 -0700361
Dianne Hackborn231cc602009-04-27 17:10:36 -0700362 public static class DayStats {
363 public final int day;
364 public int successCount;
365 public long successTime;
366 public int failureCount;
367 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700368
Dianne Hackborn231cc602009-04-27 17:10:36 -0700369 public DayStats(int day) {
370 this.day = day;
371 }
372 }
Costin Manolache360e4542009-09-04 13:36:04 -0700373
Amith Yamasani04e0d262012-02-14 11:50:53 -0800374 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700375
376 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800377 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -0700378 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800379 }
380
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000381 interface PeriodicSyncAddedListener {
382 /** Called when a periodic sync is added. */
383 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
384 }
385
386 interface OnAuthorityRemovedListener {
387 /** Called when an authority is removed. */
388 void onAuthorityRemoved(EndPoint removedAuthority);
389 }
390
Suprabh Shukla042a4782017-05-12 15:26:54 -0700391 /**
392 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
393 * account is valid.
394 */
395 private static class AccountAuthorityValidator {
396 final private AccountManager mAccountManager;
397 final private PackageManager mPackageManager;
398 final private SparseArray<Account[]> mAccountsCache;
399 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
400
401 AccountAuthorityValidator(Context context) {
402 mAccountManager = context.getSystemService(AccountManager.class);
403 mPackageManager = context.getPackageManager();
404 mAccountsCache = new SparseArray<>();
405 mProvidersPerUserCache = new SparseArray<>();
406 }
407
408 // An account is valid if an installed authenticator has previously created that account
409 // on the device
410 boolean isAccountValid(Account account, int userId) {
411 Account[] accountsForUser = mAccountsCache.get(userId);
412 if (accountsForUser == null) {
413 accountsForUser = mAccountManager.getAccountsAsUser(userId);
414 mAccountsCache.put(userId, accountsForUser);
415 }
416 return ArrayUtils.contains(accountsForUser, account);
417 }
418
419 // An authority is only valid if it has a content provider installed on the system
420 boolean isAuthorityValid(String authority, int userId) {
421 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
422 if (authorityMap == null) {
423 authorityMap = new ArrayMap<>();
424 mProvidersPerUserCache.put(userId, authorityMap);
425 }
426 if (!authorityMap.containsKey(authority)) {
427 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
428 PackageManager.MATCH_DIRECT_BOOT_AWARE
429 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
430 }
431 return authorityMap.get(authority);
432 }
433 }
434
Dianne Hackborn231cc602009-04-27 17:10:36 -0700435 // Primary list of all syncable authorities. Also our global lock.
Varun Shah816cf632019-10-30 17:40:15 -0700436 @VisibleForTesting
437 final SparseArray<AuthorityInfo> mAuthorities =
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700439
Amith Yamasani04e0d262012-02-14 11:50:53 -0800440 private final HashMap<AccountAndUser, AccountInfo> mAccounts
441 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442
Amith Yamasani04e0d262012-02-14 11:50:53 -0800443 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
444 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Varun Shah816cf632019-10-30 17:40:15 -0700446 @VisibleForTesting
447 final SparseArray<SyncStatusInfo> mSyncStatus =
Dianne Hackborn231cc602009-04-27 17:10:36 -0700448 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700449
Dianne Hackborn231cc602009-04-27 17:10:36 -0700450 private final ArrayList<SyncHistoryItem> mSyncHistory =
451 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700452
Dianne Hackborn231cc602009-04-27 17:10:36 -0700453 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
454 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700455
Matthew Williams8ef22042013-07-26 12:56:39 -0700456 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700457 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
458 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700459
Fred Quintana77c560f2010-03-29 22:20:26 -0700460 private int mNextAuthorityId = 0;
461
Dianne Hackborn231cc602009-04-27 17:10:36 -0700462 // We keep 4 weeks of stats.
Varun Shah816cf632019-10-30 17:40:15 -0700463 @VisibleForTesting
464 final DayStats[] mDayStats = new DayStats[7*4];
Dianne Hackborn231cc602009-04-27 17:10:36 -0700465 private final Calendar mCal;
466 private int mYear;
467 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700468
Dianne Hackborn231cc602009-04-27 17:10:36 -0700469 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800470
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700472
Ashish Sharma69d95de2012-04-11 17:27:24 -0700473 private int mSyncRandomOffset;
474
Varun Shah816cf632019-10-30 17:40:15 -0700475 // STOPSHIP: b/143656271 this should be true on launch
476 private static final boolean DELETE_LEGACY_PARCEL_FILES = false;
477 private static final String LEGACY_STATUS_FILE_NAME = "status.bin";
478 private static final String LEGACY_STATISTICS_FILE_NAME = "stats.bin";
479
480 private static final String SYNC_DIR_NAME = "sync";
481 private static final String ACCOUNT_INFO_FILE_NAME = "accounts.xml";
482 private static final String STATUS_FILE_NAME = "status";
483 private static final String STATISTICS_FILE_NAME = "stats";
484
485 private File mSyncDir;
486
Dianne Hackborn231cc602009-04-27 17:10:36 -0700487 /**
488 * This file contains the core engine state: all accounts and the
489 * settings for them. It must never be lost, and should be changed
490 * infrequently, so it is stored as an XML file.
491 */
492 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700493
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 /**
495 * This file contains the current sync status. We would like to retain
496 * it across boots, but its loss is not the end of the world, so we store
497 * this information as binary data.
498 */
499 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700500
Dianne Hackborn231cc602009-04-27 17:10:36 -0700501 /**
502 * This file contains sync statistics. This is purely debugging information
503 * so is written infrequently and can be thrown away at any time.
504 */
505 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700506
Dianne Hackborn231cc602009-04-27 17:10:36 -0700507 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800508 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800509 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800510
511 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000512 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700513
Svet Ganov65712b02016-09-01 10:24:11 -0700514 private boolean mGrantSyncAdaptersAccountAccess;
515
Makoto Onuki6963bea72017-12-12 10:42:39 -0800516 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700517 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800518
519 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
520 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700523 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700524
Dianne Hackborn231cc602009-04-27 17:10:36 -0700525 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700526
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800527 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000528 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800529
Dianne Hackborn231cc602009-04-27 17:10:36 -0700530 File systemDir = new File(dataDir, "system");
Varun Shah816cf632019-10-30 17:40:15 -0700531 mSyncDir = new File(systemDir, SYNC_DIR_NAME);
532 mSyncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700533
Varun Shah816cf632019-10-30 17:40:15 -0700534 maybeDeleteLegacyPendingInfoLocked(mSyncDir);
Matthew Williamsba352712013-08-13 15:53:31 -0700535
Varun Shah816cf632019-10-30 17:40:15 -0700536 mAccountInfoFile = new AtomicFile(new File(mSyncDir, ACCOUNT_INFO_FILE_NAME),
537 "sync-accounts");
538 mStatusFile = new AtomicFile(new File(mSyncDir, STATUS_FILE_NAME), "sync-status");
539 mStatisticsFile = new AtomicFile(new File(mSyncDir, STATISTICS_FILE_NAME), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700540
Dianne Hackborn231cc602009-04-27 17:10:36 -0700541 readAccountInfoLocked();
542 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700543 readStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700544
545 if (mLogger.enabled()) {
546 final int size = mAuthorities.size();
547 mLogger.log("Loaded ", size, " items");
548 for (int i = 0; i < size; i++) {
549 mLogger.log(mAuthorities.valueAt(i));
550 }
551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 }
553
554 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800555 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800556 }
557
Makoto Onuki6963bea72017-12-12 10:42:39 -0800558 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800560 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700562 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800563 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 }
565
566 public static SyncStorageEngine getSingleton() {
567 if (sSyncStorageEngine == null) {
568 throw new IllegalStateException("not initialized");
569 }
570 return sSyncStorageEngine;
571 }
572
Amith Yamasani04e0d262012-02-14 11:50:53 -0800573 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
574 if (mSyncRequestListener == null) {
575 mSyncRequestListener = listener;
576 }
577 }
578
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000579 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
580 if (mAuthorityRemovedListener == null) {
581 mAuthorityRemovedListener = listener;
582 }
583 }
584
585 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
586 if (mPeriodicSyncAddedListener == null) {
587 mPeriodicSyncAddedListener = listener;
588 }
589 }
590
Makoto Onuki6963bea72017-12-12 10:42:39 -0800591 private class MyHandler extends Handler {
592 public MyHandler(Looper looper) {
593 super(looper);
594 }
595
596 @Override
597 public void handleMessage(Message msg) {
598 if (msg.what == MSG_WRITE_STATUS) {
599 synchronized (mAuthorities) {
600 writeStatusLocked();
601 }
602 } else if (msg.what == MSG_WRITE_STATISTICS) {
603 synchronized (mAuthorities) {
604 writeStatisticsLocked();
605 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607 }
608 }
Costin Manolache360e4542009-09-04 13:36:04 -0700609
Ashish Sharma69d95de2012-04-11 17:27:24 -0700610 public int getSyncRandomOffset() {
611 return mSyncRandomOffset;
612 }
613
Varun Shahfe009ec2019-04-29 14:26:45 -0700614 public void addStatusChangeListener(int mask, int userId, ISyncStatusObserver callback) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700615 synchronized (mAuthorities) {
Varun Shahfe009ec2019-04-29 14:26:45 -0700616 final long cookie = IntPair.of(userId, mask);
617 mChangeListeners.register(callback, cookie);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700618 }
619 }
Costin Manolache360e4542009-09-04 13:36:04 -0700620
Dianne Hackborn231cc602009-04-27 17:10:36 -0700621 public void removeStatusChangeListener(ISyncStatusObserver callback) {
622 synchronized (mAuthorities) {
623 mChangeListeners.unregister(callback);
624 }
625 }
Costin Manolache360e4542009-09-04 13:36:04 -0700626
Matthew Williamsfa774182013-06-18 15:44:11 -0700627 /**
628 * Figure out a reasonable flex time for cases where none is provided (old api calls).
629 * @param syncTimeSeconds requested sync time from now.
630 * @return amount of seconds before syncTimeSeconds that the sync can occur.
631 * I.e.
632 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700633 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700634 */
635 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
636 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
637 // Small enough sync request time that we don't add flex time - developer probably
638 // wants to wait for an operation to occur before syncing so we honour the
639 // request time.
640 return 0L;
641 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
642 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
643 } else {
644 // Large enough sync request time that we cap the flex time.
645 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
646 }
647 }
648
Varun Shahfe009ec2019-04-29 14:26:45 -0700649 void reportChange(int which, int callingUserId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700650 ArrayList<ISyncStatusObserver> reports = null;
651 synchronized (mAuthorities) {
652 int i = mChangeListeners.beginBroadcast();
653 while (i > 0) {
654 i--;
Varun Shahfe009ec2019-04-29 14:26:45 -0700655 final long cookie = (long) mChangeListeners.getBroadcastCookie(i);
656 final int userId = IntPair.first(cookie);
657 final int mask = IntPair.second(cookie);
658 if ((which & mask) == 0 || callingUserId != userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 continue;
660 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700661 if (reports == null) {
662 reports = new ArrayList<ISyncStatusObserver>(i);
663 }
664 reports.add(mChangeListeners.getBroadcastItem(i));
665 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700666 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700667 }
Costin Manolache360e4542009-09-04 13:36:04 -0700668
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700669 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000670 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700671 }
Costin Manolache360e4542009-09-04 13:36:04 -0700672
Dianne Hackborn231cc602009-04-27 17:10:36 -0700673 if (reports != null) {
674 int i = reports.size();
675 while (i > 0) {
676 i--;
677 try {
678 reports.get(i).onStatusChanged(which);
679 } catch (RemoteException e) {
680 // The remote callback list will take care of this for us.
681 }
682 }
683 }
684 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700685
Amith Yamasani04e0d262012-02-14 11:50:53 -0800686 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700687 synchronized (mAuthorities) {
688 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 AuthorityInfo authority = getAuthorityLocked(
690 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700691 "getSyncAutomatically");
692 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700693 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700694
Dianne Hackborn231cc602009-04-27 17:10:36 -0700695 int i = mAuthorities.size();
696 while (i > 0) {
697 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700698 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700699 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700700 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700701 return true;
702 }
703 }
704 return false;
705 }
706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707
Amith Yamasani04e0d262012-02-14 11:50:53 -0800708 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukie183a402018-08-29 11:46:41 -0700709 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700710 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000711 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800712 + ", user " + userId + " -> " + sync);
713 }
Makoto Onukid4764302018-03-30 17:32:57 -0700714 mLogger.log("Set sync auto account=", account,
715 " user=", userId,
716 " authority=", providerName,
717 " value=", Boolean.toString(sync),
Makoto Onukie183a402018-08-29 11:46:41 -0700718 " cuid=", callingUid,
719 " cpid=", callingPid
720 );
Dianne Hackborn231cc602009-04-27 17:10:36 -0700721 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700722 AuthorityInfo authority =
723 getOrCreateAuthorityLocked(
724 new EndPoint(account, providerName, userId),
725 -1 /* ident */,
726 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700727 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000729 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800730 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700731 return;
732 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700733 // If the adapter was syncable but missing its initialization sync, set it to
734 // uninitialized now. This is to give it a chance to run any one-time initialization
735 // logic.
736 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
737 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
738 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700739 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700740 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700742
Fred Quintana77c560f2010-03-29 22:20:26 -0700743 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700744 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800745 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700746 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700747 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700748 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, userId);
Marvin Paula6533252014-11-24 12:57:48 -0800749 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
751
Amith Yamasani04e0d262012-02-14 11:50:53 -0800752 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700753 synchronized (mAuthorities) {
754 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700755 AuthorityInfo authority = getAuthorityLocked(
756 new EndPoint(account, providerName, userId),
757 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700758 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700759 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700760 }
761 return authority.syncable;
762 }
763
764 int i = mAuthorities.size();
765 while (i > 0) {
766 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700767 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700768 if (authorityInfo.target != null
769 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700770 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700771 }
772 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700773 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700774 }
775 }
776
Makoto Onukid4764302018-03-30 17:32:57 -0700777 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700778 int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700779 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700780 callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700781 }
782
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700783 /**
784 * An enabled sync service and a syncable provider's adapter both get resolved to the same
785 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700786 * @param target target to set value for.
787 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700788 */
Makoto Onukie183a402018-08-29 11:46:41 -0700789 private void setSyncableStateForEndPoint(EndPoint target, int syncable,
790 int callingUid, int callingPid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700791 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700792 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
Makoto Onukie183a402018-08-29 11:46:41 -0700793 " cuid=", callingUid,
794 " cpid=", callingPid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700795 synchronized (mAuthorities) {
796 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700797 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
798 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700799 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700800 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000801 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700802 }
803 if (aInfo.syncable == syncable) {
804 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000805 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700806 }
807 return;
808 }
809 aInfo.syncable = syncable;
810 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700811 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700812 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800813 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700814 ContentResolver.SYNC_EXEMPTION_NONE, callingUid, callingPid);
Fred Quintana5e787c42009-08-16 23:13:53 -0700815 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700816 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, target.userId);
Fred Quintana5e787c42009-08-16 23:13:53 -0700817 }
818
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700819 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800820 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700821 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
822 if (authority != null) {
823 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800824 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700825 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800826 }
827 }
828
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700829 /**
830 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
831 * the account or provider info be null, which signifies all accounts or providers.
832 */
833 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
834 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000835 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800836 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
837 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700838 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800839 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000840 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700841 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000842 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700843 changed = setBackoffLocked(
844 info.account /* may be null */,
845 info.userId,
846 info.provider /* may be null */,
847 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800848 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700849 AuthorityInfo authorityInfo =
850 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
851 if (authorityInfo.backoffTime == nextSyncTime
852 && authorityInfo.backoffDelay == nextDelay) {
853 changed = false;
854 } else {
855 authorityInfo.backoffTime = nextSyncTime;
856 authorityInfo.backoffDelay = nextDelay;
857 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800858 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800859 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800860 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800861 if (changed) {
Varun Shahfe009ec2019-04-29 14:26:45 -0700862 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, info.userId);
Fred Quintana307da1a2010-01-21 14:24:20 -0800863 }
864 }
865
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 /**
867 * Either set backoff for a specific authority, or set backoff for all the
868 * accounts on a specific adapter/all adapters.
869 *
870 * @param account account for which to set backoff. Null to specify all accounts.
871 * @param userId id of the user making this request.
872 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700873 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700874 */
875 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000876 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700877 boolean changed = false;
878 for (AccountInfo accountInfo : mAccounts.values()) {
879 if (account != null && !account.equals(accountInfo.accountAndUser.account)
880 && userId != accountInfo.accountAndUser.userId) {
881 continue;
882 }
883 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
884 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700885 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700886 continue;
887 }
888 if (authorityInfo.backoffTime != nextSyncTime
889 || authorityInfo.backoffDelay != nextDelay) {
890 authorityInfo.backoffTime = nextSyncTime;
891 authorityInfo.backoffDelay = nextDelay;
892 changed = true;
893 }
894 }
895 }
896 return changed;
897 }
898
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000899 public void clearAllBackoffsLocked() {
Varun Shahfe009ec2019-04-29 14:26:45 -0700900 final ArraySet<Integer> changedUserIds = new ArraySet<>();
Alon Albert744e310f2010-12-14 11:37:20 -0800901 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000902 // Clear backoff for all sync adapters.
903 for (AccountInfo accountInfo : mAccounts.values()) {
904 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
905 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
906 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
907 if (Log.isLoggable(TAG, Log.VERBOSE)) {
908 Slog.v(TAG, "clearAllBackoffsLocked:"
909 + " authority:" + authorityInfo.target
910 + " account:" + accountInfo.accountAndUser.account.name
911 + " user:" + accountInfo.accountAndUser.userId
912 + " backoffTime was: " + authorityInfo.backoffTime
913 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800914 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000915 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
916 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Varun Shahfe009ec2019-04-29 14:26:45 -0700917 changedUserIds.add(accountInfo.accountAndUser.userId);
Alon Albert744e310f2010-12-14 11:37:20 -0800918 }
919 }
920 }
921 }
922
Varun Shahfe009ec2019-04-29 14:26:45 -0700923 for (int i = changedUserIds.size() - 1; i > 0; i--) {
924 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, changedUserIds.valueAt(i));
Alon Albert744e310f2010-12-14 11:37:20 -0800925 }
926 }
927
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700928 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800929 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700930 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800931 if (authority == null) {
932 return 0;
933 }
934 return authority.delayUntil;
935 }
936 }
937
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700938 public void setDelayUntilTime(EndPoint info, long delayUntil) {
939 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000940 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700941 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800942 }
943 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700944 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
945 if (authority.delayUntil == delayUntil) {
946 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700947 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700948 authority.delayUntil = delayUntil;
949 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700950 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700951 }
952
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700953 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000954 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
955 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700956 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000957 boolean restoreAllPeriodicSyncs() {
958 if (mPeriodicSyncAddedListener == null) {
959 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800960 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000961 synchronized (mAuthorities) {
962 for (int i=0; i<mAuthorities.size(); i++) {
963 AuthorityInfo authority = mAuthorities.valueAt(i);
964 for (PeriodicSync periodicSync: authority.periodicSyncs) {
965 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
966 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
967 }
968 authority.periodicSyncs.clear();
969 }
970 writeAccountInfoLocked();
971 }
972 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800973 }
974
Makoto Onuki75ad2492018-03-28 14:42:42 -0700975 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700976 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700977 mLogger.log("Set master enabled=", flag, " user=", userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700978 " cuid=", callingUid,
979 " cpid=", callingPid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700980 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800981 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700982 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700983 return;
984 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800985 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700986 writeAccountInfoLocked();
987 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700988 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700989 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800990 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700991 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700992 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700993 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, userId);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800994 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800995 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
Amith Yamasani04e0d262012-02-14 11:50:53 -0800998 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001000 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +08001001 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001002 }
1003 }
Costin Manolache360e4542009-09-04 13:36:04 -07001004
Makoto Onukib47e8942017-09-18 14:03:03 -07001005 public int getAuthorityCount() {
1006 synchronized (mAuthorities) {
1007 return mAuthorities.size();
1008 }
1009 }
1010
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 public AuthorityInfo getAuthority(int authorityId) {
1012 synchronized (mAuthorities) {
1013 return mAuthorities.get(authorityId);
1014 }
1015 }
Costin Manolache360e4542009-09-04 13:36:04 -07001016
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001018 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -07001019 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001020 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001021 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001022 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001023 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001024 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001025 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 return true;
1027 }
1028 }
1029 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 return false;
1031 }
Costin Manolache360e4542009-09-04 13:36:04 -07001032
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001033 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001034 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001035 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
1036 -1 /* desired identifier */,
1037 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001039 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001042 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001043 }
Varun Shahfe009ec2019-04-29 14:26:45 -07001044 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING, info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001045 }
Costin Manolache360e4542009-09-04 13:36:04 -07001046
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 /**
1048 * Called when the set of account has changed, given the new array of
1049 * active accounts.
1050 */
Makoto Onuki76f0e0d2019-05-22 12:26:56 -07001051 public void removeStaleAccounts(@Nullable Account[] currentAccounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001053 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001054 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001055 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1057 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1058 while (accIt.hasNext()) {
1059 AccountInfo acc = accIt.next();
Makoto Onuki76f0e0d2019-05-22 12:26:56 -07001060 if (acc.accountAndUser.userId != userId) {
1061 continue; // Irrelevant user.
1062 }
1063 if ((currentAccounts == null)
1064 || !ArrayUtils.contains(currentAccounts, acc.accountAndUser.account)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001066 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001067 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001068 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001069 for (AuthorityInfo auth : acc.authorities.values()) {
1070 removing.put(auth.ident, auth);
1071 }
1072 accIt.remove();
1073 }
1074 }
Costin Manolache360e4542009-09-04 13:36:04 -07001075
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 // Clean out all data structures.
1077 int i = removing.size();
1078 if (i > 0) {
1079 while (i > 0) {
1080 i--;
1081 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001082 AuthorityInfo auth = removing.valueAt(i);
1083 if (mAuthorityRemovedListener != null) {
1084 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1085 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001086 mAuthorities.remove(ident);
1087 int j = mSyncStatus.size();
1088 while (j > 0) {
1089 j--;
1090 if (mSyncStatus.keyAt(j) == ident) {
1091 mSyncStatus.remove(mSyncStatus.keyAt(j));
1092 }
1093 }
1094 j = mSyncHistory.size();
1095 while (j > 0) {
1096 j--;
1097 if (mSyncHistory.get(j).authorityId == ident) {
1098 mSyncHistory.remove(j);
1099 }
1100 }
1101 }
1102 writeAccountInfoLocked();
1103 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 writeStatisticsLocked();
1105 }
1106 }
1107 }
1108
1109 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001110 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1111 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 */
Fred Quintana918339a2010-10-05 14:00:39 -07001113 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1114 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001116 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001117 Slog.v(TAG, "setActiveSync: account="
1118 + " auth=" + activeSyncContext.mSyncOperation.target
1119 + " src=" + activeSyncContext.mSyncOperation.syncSource
1120 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001122 final EndPoint info = activeSyncContext.mSyncOperation.target;
1123 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1124 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001125 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001126 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001127 syncInfo = new SyncInfo(
1128 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001129 authorityInfo.target.account,
1130 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001131 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001132 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 }
Varun Shahfe009ec2019-04-29 14:26:45 -07001134 reportActiveChange(activeSyncContext.mSyncOperation.target.userId);
Fred Quintana918339a2010-10-05 14:00:39 -07001135 return syncInfo;
1136 }
1137
1138 /**
1139 * Called to indicate that a previously active sync is no longer active.
1140 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001141 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001142 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001143 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001144 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001145 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001146 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001147 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001148 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001149 }
1150
Varun Shahfe009ec2019-04-29 14:26:45 -07001151 reportActiveChange(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 }
1153
1154 /**
1155 * To allow others to send active change reports, to poke clients.
1156 */
Varun Shahfe009ec2019-04-29 14:26:45 -07001157 public void reportActiveChange(int userId) {
1158 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001159 }
Costin Manolache360e4542009-09-04 13:36:04 -07001160
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001162 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001164 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 long id;
1166 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001167 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001168 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001169 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001170 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 if (authority == null) {
1172 return -1;
1173 }
1174 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001175 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 item.authorityId = authority.ident;
1177 item.historyId = mNextHistoryId++;
1178 if (mNextHistoryId < 0) mNextHistoryId = 0;
1179 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001180 item.source = op.syncSource;
1181 item.reason = op.reason;
1182 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001183 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001184 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001185 mSyncHistory.add(0, item);
1186 while (mSyncHistory.size() > MAX_HISTORY) {
1187 mSyncHistory.remove(mSyncHistory.size()-1);
1188 }
1189 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001190 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 }
Costin Manolache360e4542009-09-04 13:36:04 -07001192
Varun Shahfe009ec2019-04-29 14:26:45 -07001193 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, op.target.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001194 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 }
1196
Fred Quintana77c560f2010-03-29 22:20:26 -07001197 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Varun Shahfe009ec2019-04-29 14:26:45 -07001198 long downstreamActivity, long upstreamActivity, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001199 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001200 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001201 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001202 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001203 SyncHistoryItem item = null;
1204 int i = mSyncHistory.size();
1205 while (i > 0) {
1206 i--;
1207 item = mSyncHistory.get(i);
1208 if (item.historyId == historyId) {
1209 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001211 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
Costin Manolache360e4542009-09-04 13:36:04 -07001213
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001215 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 return;
1217 }
Costin Manolache360e4542009-09-04 13:36:04 -07001218
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 item.elapsedTime = elapsedTime;
1220 item.event = EVENT_STOP;
1221 item.mesg = resultMessage;
1222 item.downstreamActivity = downstreamActivity;
1223 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001224
Dianne Hackborn231cc602009-04-27 17:10:36 -07001225 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001226
Makoto Onuki94986212018-04-11 16:24:46 -07001227 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1228
1229 status.totalStats.numSyncs++;
1230 status.todayStats.numSyncs++;
1231 status.totalStats.totalElapsedTime += elapsedTime;
1232 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 switch (item.source) {
1234 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001235 status.totalStats.numSourceLocal++;
1236 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 break;
1238 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001239 status.totalStats.numSourcePoll++;
1240 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001241 break;
1242 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001243 status.totalStats.numSourceUser++;
1244 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001246 case SOURCE_OTHER:
1247 status.totalStats.numSourceOther++;
1248 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001250 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001251 status.totalStats.numSourcePeriodic++;
1252 status.todayStats.numSourcePeriodic++;
1253 break;
1254 case SOURCE_FEED:
1255 status.totalStats.numSourceFeed++;
1256 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001257 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001258 }
Costin Manolache360e4542009-09-04 13:36:04 -07001259
Dianne Hackborn231cc602009-04-27 17:10:36 -07001260 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001261 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001262 if (mDayStats[0] == null) {
1263 mDayStats[0] = new DayStats(day);
1264 } else if (day != mDayStats[0].day) {
1265 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1266 mDayStats[0] = new DayStats(day);
1267 writeStatisticsNow = true;
1268 } else if (mDayStats[0] == null) {
1269 }
1270 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001271
Dianne Hackborn231cc602009-04-27 17:10:36 -07001272 final long lastSyncTime = (item.eventTime + elapsedTime);
1273 boolean writeStatusNow = false;
1274 if (MESG_SUCCESS.equals(resultMessage)) {
1275 // - if successful, update the successful columns
1276 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1277 writeStatusNow = true;
1278 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001279 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 ds.successCount++;
1281 ds.successTime += elapsedTime;
1282 } else if (!MESG_CANCELED.equals(resultMessage)) {
1283 if (status.lastFailureTime == 0) {
1284 writeStatusNow = true;
1285 }
Makoto Onuki94986212018-04-11 16:24:46 -07001286 status.totalStats.numFailures++;
1287 status.todayStats.numFailures++;
1288
Makoto Onukif74cf942018-04-16 17:04:58 -07001289 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1290
Dianne Hackborn231cc602009-04-27 17:10:36 -07001291 ds.failureCount++;
1292 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001293 } else {
1294 // Cancel
1295 status.totalStats.numCancels++;
1296 status.todayStats.numCancels++;
1297 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001298 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001299 final StringBuilder event = new StringBuilder();
1300 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1301 + " Elapsed=");
1302 SyncManager.formatDurationHMS(event, elapsedTime);
1303 event.append(" Reason=");
1304 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001305 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1306 event.append(" Exemption=");
1307 switch (item.syncExemptionFlag) {
1308 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1309 event.append("fg");
1310 break;
1311 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1312 event.append("top");
1313 break;
1314 default:
1315 event.append(item.syncExemptionFlag);
1316 break;
1317 }
1318 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001319 event.append(" Extras=");
1320 SyncOperation.extrasToStringBuilder(item.extras, event);
1321
1322 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001323
Dianne Hackborn231cc602009-04-27 17:10:36 -07001324 if (writeStatusNow) {
1325 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001326 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1327 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001328 WRITE_STATUS_DELAY);
1329 }
1330 if (writeStatisticsNow) {
1331 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001332 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1333 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001334 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001335 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001336 }
Costin Manolache360e4542009-09-04 13:36:04 -07001337
Varun Shahfe009ec2019-04-29 14:26:45 -07001338 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001339 }
1340
1341 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001342 * Return a list of the currently active syncs. Note that the returned
1343 * items are the real, live active sync objects, so be careful what you do
1344 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001345 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001346 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001347 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001348 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001349 }
1350 }
Costin Manolache360e4542009-09-04 13:36:04 -07001351
Dianne Hackborn231cc602009-04-27 17:10:36 -07001352 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001353 * @param userId Id of user to return current sync info.
1354 * @param canAccessAccounts Determines whether to redact Account information from the result.
1355 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001356 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001357 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001358 synchronized (mAuthorities) {
1359 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1360 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1361 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001362 SyncInfo copy;
1363 if (!canAccessAccounts) {
1364 copy = SyncInfo.createAccountRedacted(
1365 sync.authorityId, sync.authority, sync.startTime);
1366 } else {
1367 copy = new SyncInfo(sync);
1368 }
1369 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001370 }
1371 return syncsCopy;
1372 }
1373 }
1374
1375 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1376 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1377 if (syncs == null) {
1378 syncs = new ArrayList<SyncInfo>();
1379 mCurrentSyncs.put(userId, syncs);
1380 }
1381 return syncs;
1382 }
1383
1384 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001385 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001386 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001387 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001388 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001389 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001390 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001391 true /* write to storage if this results in a change */);
1392 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1393 }
1394 }
1395
1396 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001397 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001398 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001399 * @param info the endpoint target we are querying status info for.
1400 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001402 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001403 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001404 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001405 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001406 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001408 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001409 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001410 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001411 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001412 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001413 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001414 }
1415 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001416 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001417 }
1418 }
Costin Manolache360e4542009-09-04 13:36:04 -07001419
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001420 /** Return true if the pending status is true of any matching authorities. */
1421 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001422 synchronized (mAuthorities) {
1423 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001424 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001425 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001426 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1427 if (ainfo == null) {
1428 continue;
1429 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001430 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001431 continue;
1432 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001433 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001434 return true;
1435 }
1436 }
1437 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 }
1440
1441 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001442 * Return an array of the current sync status for all authorities. Note
1443 * that the objects inside the array are the real, live status objects,
1444 * so be careful what you do with them.
1445 */
1446 public ArrayList<SyncHistoryItem> getSyncHistory() {
1447 synchronized (mAuthorities) {
1448 final int N = mSyncHistory.size();
1449 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1450 for (int i=0; i<N; i++) {
1451 items.add(mSyncHistory.get(i));
1452 }
1453 return items;
1454 }
1455 }
Costin Manolache360e4542009-09-04 13:36:04 -07001456
Dianne Hackborn231cc602009-04-27 17:10:36 -07001457 /**
1458 * Return an array of the current per-day statistics. Note
1459 * that the objects inside the array are the real, live status objects,
1460 * so be careful what you do with them.
1461 */
1462 public DayStats[] getDayStatistics() {
1463 synchronized (mAuthorities) {
1464 DayStats[] ds = new DayStats[mDayStats.length];
1465 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1466 return ds;
1467 }
1468 }
Costin Manolache360e4542009-09-04 13:36:04 -07001469
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001470 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1471 AuthorityInfo authorityInfo) {
1472 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1473 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1474 }
1475
Dianne Hackborn55280a92009-05-07 15:53:46 -07001476 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001477 mCal.setTimeInMillis(System.currentTimeMillis());
1478 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1479 if (mYear != mCal.get(Calendar.YEAR)) {
1480 mYear = mCal.get(Calendar.YEAR);
1481 mCal.clear();
1482 mCal.set(Calendar.YEAR, mYear);
1483 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1484 }
1485 return dayOfYear + mYearInDays;
1486 }
Costin Manolache360e4542009-09-04 13:36:04 -07001487
Dianne Hackborn231cc602009-04-27 17:10:36 -07001488 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001489 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001490 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001491 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001492 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001493 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001494 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001495 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001496 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1497 AccountInfo accountInfo = mAccounts.get(au);
1498 if (accountInfo == null) {
1499 if (tag != null) {
1500 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1501 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001502 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001503 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001504 return null;
1505 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001506 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1507 if (authority == null) {
1508 if (tag != null) {
1509 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1510 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1511 }
1512 }
1513 return null;
1514 }
1515 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001516 }
Costin Manolache360e4542009-09-04 13:36:04 -07001517
Matthew Williamsfa774182013-06-18 15:44:11 -07001518 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001519 * @param info info identifying target.
1520 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001521 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001522 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001523 * exists.
1524 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001525 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1526 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001527 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1528 AccountInfo account = mAccounts.get(au);
1529 if (account == null) {
1530 account = new AccountInfo(au);
1531 mAccounts.put(au, account);
1532 }
1533 authority = account.authorities.get(info.provider);
1534 if (authority == null) {
1535 authority = createAuthorityLocked(info, ident, doWrite);
1536 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001537 }
1538 return authority;
1539 }
1540
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001541 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1542 AuthorityInfo authority;
1543 if (ident < 0) {
1544 ident = mNextAuthorityId;
1545 mNextAuthorityId++;
1546 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001547 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001548 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001549 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001550 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001551 authority = new AuthorityInfo(info, ident);
1552 mAuthorities.put(ident, authority);
1553 if (doWrite) {
1554 writeAccountInfoLocked();
1555 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001556 return authority;
1557 }
Costin Manolache360e4542009-09-04 13:36:04 -07001558
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001559 public void removeAuthority(EndPoint info) {
1560 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001561 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001562 }
1563 }
1564
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001565
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001566 /**
1567 * Remove an authority associated with a provider. Needs to be a standalone function for
1568 * backward compatibility.
1569 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001570 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001571 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001572 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001573 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001574 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1575 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001576 if (mAuthorityRemovedListener != null) {
1577 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1578 }
Fred Quintanafb084402010-03-23 17:57:03 -07001579 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001580 if (doWrite) {
1581 writeAccountInfoLocked();
1582 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001583 }
1584 }
1585 }
1586
Dianne Hackborn231cc602009-04-27 17:10:36 -07001587 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1588 SyncStatusInfo status = mSyncStatus.get(authorityId);
1589 if (status == null) {
1590 status = new SyncStatusInfo(authorityId);
1591 mSyncStatus.put(authorityId, status);
1592 }
1593 return status;
1594 }
Costin Manolache360e4542009-09-04 13:36:04 -07001595
Dianne Hackborn55280a92009-05-07 15:53:46 -07001596 public void writeAllState() {
1597 synchronized (mAuthorities) {
1598 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001599 writeStatusLocked();
1600 writeStatisticsLocked();
1601 }
1602 }
Costin Manolache360e4542009-09-04 13:36:04 -07001603
Svet Ganov65712b02016-09-01 10:24:11 -07001604 public boolean shouldGrantSyncAdaptersAccountAccess() {
1605 return mGrantSyncAdaptersAccountAccess;
1606 }
1607
Dianne Hackborn231cc602009-04-27 17:10:36 -07001608 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001609 * public for testing
1610 */
1611 public void clearAndReadState() {
1612 synchronized (mAuthorities) {
1613 mAuthorities.clear();
1614 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001615 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001616 mSyncStatus.clear();
1617 mSyncHistory.clear();
1618
1619 readAccountInfoLocked();
1620 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001621 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001622 writeAccountInfoLocked();
1623 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001624 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001625 }
1626 }
1627
1628 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001629 * Read all account information back in to the initial engine state.
1630 */
1631 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001632 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001633 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001635 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001636 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001637 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001638 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001639 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001640 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001641 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001642 while (eventType != XmlPullParser.START_TAG &&
1643 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001644 eventType = parser.next();
1645 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001646 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001647 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001648 return;
1649 }
1650
Dianne Hackborn231cc602009-04-27 17:10:36 -07001651 String tagName = parser.getName();
1652 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001653 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001654 String versionString = parser.getAttributeValue(null, "version");
1655 int version;
1656 try {
1657 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1658 } catch (NumberFormatException e) {
1659 version = 0;
1660 }
Svet Ganov65712b02016-09-01 10:24:11 -07001661
1662 if (version < 3) {
1663 mGrantSyncAdaptersAccountAccess = true;
1664 }
1665
Amith Yamasani04e0d262012-02-14 11:50:53 -08001666 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001667 try {
1668 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1669 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1670 } catch (NumberFormatException e) {
1671 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001672 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001673 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1674 try {
1675 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1676 } catch (NumberFormatException e) {
1677 mSyncRandomOffset = 0;
1678 }
1679 if (mSyncRandomOffset == 0) {
1680 Random random = new Random(System.currentTimeMillis());
1681 mSyncRandomOffset = random.nextInt(86400);
1682 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001683 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001684 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001685 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001686 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001687 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001688 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001689 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001690 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001691 if (parser.getDepth() == 2) {
1692 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001693 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001694 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001695 if (authority != null) {
1696 if (authority.ident > highestAuthorityId) {
1697 highestAuthorityId = authority.ident;
1698 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001699 } else {
1700 EventLog.writeEvent(0x534e4554, "26513719", -1,
1701 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001702 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001703 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1704 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001705 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001706 } else if (parser.getDepth() == 3) {
1707 if ("periodicSync".equals(tagName) && authority != null) {
1708 periodicSync = parsePeriodicSync(parser, authority);
1709 }
1710 } else if (parser.getDepth() == 4 && periodicSync != null) {
1711 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001712 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001713 }
1714 }
1715 }
1716 eventType = parser.next();
1717 } while (eventType != XmlPullParser.END_DOCUMENT);
1718 }
1719 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001720 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001721 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001722 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001723 if (fis == null) Slog.i(TAG, "No initial accounts");
1724 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001725 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001726 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001727 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001728 if (fis != null) {
1729 try {
1730 fis.close();
1731 } catch (java.io.IOException e1) {
1732 }
1733 }
1734 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001735
Fred Quintana77c560f2010-03-29 22:20:26 -07001736 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001737 }
Costin Manolache360e4542009-09-04 13:36:04 -07001738
Fred Quintanafb084402010-03-23 17:57:03 -07001739 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001740 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1741 * pending.xml was used starting in KLP.
1742 * @param syncDir directory where the sync files are located.
1743 */
1744 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1745 File file = new File(syncDir, "pending.bin");
1746 if (!file.exists()) {
1747 return;
1748 } else {
1749 file.delete();
1750 }
1751 }
1752
1753 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001754 * some authority names have changed. copy over their settings and delete the old ones
1755 * @return true if a change was made
1756 */
1757 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1758 boolean writeNeeded = false;
1759
1760 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1761 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001762 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001763 AuthorityInfo authority = mAuthorities.valueAt(i);
1764 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001765 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001766 if (newAuthorityName == null) {
1767 continue;
1768 }
1769
1770 // remember this authority so we can remove it later. we can't remove it
1771 // now without messing up this loop iteration
1772 authoritiesToRemove.add(authority);
1773
1774 // this authority isn't enabled, no need to copy it to the new authority name since
1775 // the default is "disabled"
1776 if (!authority.enabled) {
1777 continue;
1778 }
1779
1780 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001781 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001782 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001783 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001784 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001785 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001786 continue;
1787 }
1788
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001789 AuthorityInfo newAuthority =
1790 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001791 newAuthority.enabled = true;
1792 writeNeeded = true;
1793 }
1794
1795 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001796 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001797 authorityInfo.target.account,
1798 authorityInfo.target.userId,
1799 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001800 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001801 writeNeeded = true;
1802 }
1803
1804 return writeNeeded;
1805 }
1806
Amith Yamasani04e0d262012-02-14 11:50:53 -08001807 private void parseListenForTickles(XmlPullParser parser) {
1808 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1809 int userId = 0;
1810 try {
1811 userId = Integer.parseInt(user);
1812 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001813 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001815 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001816 }
1817 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1818 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1819 mMasterSyncAutomatically.put(userId, listen);
1820 }
1821
Suprabh Shukla042a4782017-05-12 15:26:54 -07001822 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1823 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001824 AuthorityInfo authority = null;
1825 int id = -1;
1826 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001827 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001828 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001829 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001830 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001831 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001832 }
1833 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001834 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001835 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001836 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001837 String accountName = parser.getAttributeValue(null, "account");
1838 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001839 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001840 String packageName = parser.getAttributeValue(null, "package");
1841 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001842 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001843 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001844 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001845 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001846 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001847 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001848 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001849 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001850 + " account=" + accountName
1851 + " accountType=" + accountType
1852 + " auth=" + authorityName
1853 + " package=" + packageName
1854 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001855 + " user=" + userId
1856 + " enabled=" + enabled
1857 + " syncable=" + syncable);
1858 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001859 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001860 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001861 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001862 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001863 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001864 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001865 new Account(accountName, accountType),
1866 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001867 if (validator.isAccountValid(info.account, userId)
1868 && validator.isAuthorityValid(authorityName, userId)) {
1869 authority = getOrCreateAuthorityLocked(info, id, false);
1870 // If the version is 0 then we are upgrading from a file format that did not
1871 // know about periodic syncs. In that case don't clear the list since we
1872 // want the default, which is a daily periodic sync.
1873 // Otherwise clear out this default list since we will populate it later
1874 // with
1875 // the periodic sync descriptions that are read from the configuration file.
1876 if (version > 0) {
1877 authority.periodicSyncs.clear();
1878 }
1879 } else {
1880 EventLog.writeEvent(0x534e4554, "35028827", -1,
1881 "account:" + info.account + " provider:" + authorityName + " user:"
1882 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001883 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001884 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001885 }
1886 if (authority != null) {
1887 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001888 try {
1889 authority.syncable = (syncable == null) ?
1890 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1891 } catch (NumberFormatException e) {
1892 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1893 // format.
1894 if ("unknown".equals(syncable)) {
1895 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1896 } else {
1897 authority.syncable = Boolean.parseBoolean(syncable) ?
1898 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1899 }
1900
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001901 }
1902 } else {
Makoto Onukidecc5ba2019-01-15 09:34:05 -08001903 Slog.w(TAG, "Failure adding authority:"
1904 + " auth=" + authorityName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001905 + " enabled=" + enabled
1906 + " syncable=" + syncable);
1907 }
1908 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001909 return authority;
1910 }
1911
Matthew Williamsfa774182013-06-18 15:44:11 -07001912 /**
1913 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1914 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001915 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001916 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001917 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001918 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001919 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001920 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001921 try {
1922 period = Long.parseLong(periodValue);
1923 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001924 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001925 return null;
1926 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001927 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001928 return null;
1929 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001930 try {
1931 flextime = Long.parseLong(flexValue);
1932 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001933 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001934 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001935 + ", using default: "
1936 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001937 } catch (NullPointerException expected) {
1938 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001939 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1940 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001941 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001942 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001943 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001944 new PeriodicSync(authorityInfo.target.account,
1945 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001946 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001947 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001948 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001949 return periodicSync;
1950 }
1951
Matthew Williamsfa774182013-06-18 15:44:11 -07001952 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001953 String name = parser.getAttributeValue(null, "name");
1954 String type = parser.getAttributeValue(null, "type");
1955 String value1 = parser.getAttributeValue(null, "value1");
1956 String value2 = parser.getAttributeValue(null, "value2");
1957
1958 try {
1959 if ("long".equals(type)) {
1960 extras.putLong(name, Long.parseLong(value1));
1961 } else if ("integer".equals(type)) {
1962 extras.putInt(name, Integer.parseInt(value1));
1963 } else if ("double".equals(type)) {
1964 extras.putDouble(name, Double.parseDouble(value1));
1965 } else if ("float".equals(type)) {
1966 extras.putFloat(name, Float.parseFloat(value1));
1967 } else if ("boolean".equals(type)) {
1968 extras.putBoolean(name, Boolean.parseBoolean(value1));
1969 } else if ("string".equals(type)) {
1970 extras.putString(name, value1);
1971 } else if ("account".equals(type)) {
1972 extras.putParcelable(name, new Account(value1, value2));
1973 }
1974 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001975 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001976 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001977 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001978 }
1979 }
1980
Dianne Hackborn231cc602009-04-27 17:10:36 -07001981 /**
1982 * Write all account information to the account file.
1983 */
1984 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001985 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001986 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001987 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001988 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001989
Dianne Hackborn231cc602009-04-27 17:10:36 -07001990 try {
1991 fos = mAccountInfoFile.startWrite();
1992 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001993 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 out.startDocument(null, true);
1995 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001996
Dianne Hackborn231cc602009-04-27 17:10:36 -07001997 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001998 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001999 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07002000 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002001
2002 // Write the Sync Automatically flags for each user
2003 final int M = mMasterSyncAutomatically.size();
2004 for (int m = 0; m < M; m++) {
2005 int userId = mMasterSyncAutomatically.keyAt(m);
2006 Boolean listen = mMasterSyncAutomatically.valueAt(m);
2007 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
2008 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
2009 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
2010 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002011 }
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07002014 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07002015 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002016 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 out.startTag(null, "authority");
2018 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002019 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08002020 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002021 out.attribute(null, "account", info.account.name);
2022 out.attribute(null, "type", info.account.type);
2023 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07002024 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07002025 out.endTag(null, "authority");
2026 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002029 mAccountInfoFile.finishWrite(fos);
2030 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002031 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002032 if (fos != null) {
2033 mAccountInfoFile.failWrite(fos);
2034 }
2035 }
2036 }
Costin Manolache360e4542009-09-04 13:36:04 -07002037
Dianne Hackborn231cc602009-04-27 17:10:36 -07002038 public static final int STATUS_FILE_END = 0;
2039 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002040
Varun Shah816cf632019-10-30 17:40:15 -07002041 private void readStatusParcelLocked(File parcel) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 try {
Varun Shah816cf632019-10-30 17:40:15 -07002043 final AtomicFile parcelFile = new AtomicFile(parcel);
2044 byte[] data = parcelFile.readFully();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002045 Parcel in = Parcel.obtain();
2046 in.unmarshall(data, 0, data.length);
2047 in.setDataPosition(0);
2048 int token;
2049 while ((token=in.readInt()) != STATUS_FILE_END) {
2050 if (token == STATUS_FILE_ITEM) {
Varun Shahc9a04252019-10-16 17:31:38 -07002051 try {
2052 SyncStatusInfo status = new SyncStatusInfo(in);
2053 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2054 status.pending = false;
Varun Shahc9a04252019-10-16 17:31:38 -07002055 mSyncStatus.put(status.authorityId, status);
Matthew Williamsba352712013-08-13 15:53:31 -07002056 }
Varun Shahc9a04252019-10-16 17:31:38 -07002057 } catch (Exception e) {
2058 Slog.e(TAG, "Unable to parse some sync status.", e);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002059 }
2060 } else {
2061 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002062 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002063 break;
2064 }
2065 }
Varun Shah816cf632019-10-30 17:40:15 -07002066 } catch (IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002067 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002068 }
2069 }
Costin Manolache360e4542009-09-04 13:36:04 -07002070
Varun Shah816cf632019-10-30 17:40:15 -07002071 private void upgradeStatusIfNeededLocked() {
2072 final File parcelStatus = new File(mSyncDir, LEGACY_STATUS_FILE_NAME);
2073 if (parcelStatus.exists() && !mStatusFile.exists()) {
2074 readStatusParcelLocked(parcelStatus);
2075 writeStatusLocked();
2076 }
2077
2078 // if upgrade to proto was successful, delete parcel file
2079 if (DELETE_LEGACY_PARCEL_FILES && mStatusFile.exists()) {
2080 parcelStatus.delete();
2081 }
2082 }
2083
2084 /**
2085 * Read all sync status back in to the initial engine state.
2086 */
2087 @VisibleForTesting
2088 void readStatusLocked() {
2089 upgradeStatusIfNeededLocked();
2090
2091 if (!mStatusFile.exists()) {
2092 return;
2093 }
2094 try {
2095 try (FileInputStream in = mStatusFile.openRead()) {
2096 readStatusInfoLocked(in);
2097 }
2098 } catch (IOException e) {
2099 Slog.e(TAG, "Unable to read status info file.", e);
2100 }
2101 }
2102
2103 private void readStatusInfoLocked(InputStream in) throws IOException {
2104 final ProtoInputStream proto = new ProtoInputStream(in);
2105 while (true) {
2106 switch (proto.nextField()) {
2107 case (int) SyncStatusProto.STATUS:
2108 final long token = proto.start(SyncStatusProto.STATUS);
2109 final SyncStatusInfo status = readSyncStatusInfoLocked(proto);
2110 proto.end(token);
2111 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2112 status.pending = false;
2113 mSyncStatus.put(status.authorityId, status);
2114 }
2115 break;
2116 case ProtoInputStream.NO_MORE_FIELDS:
2117 return;
2118 }
2119 }
2120 }
2121
2122 private SyncStatusInfo readSyncStatusInfoLocked(ProtoInputStream proto) throws IOException {
2123 SyncStatusInfo status;
2124 if (proto.nextField(SyncStatusProto.StatusInfo.AUTHORITY_ID)) {
2125 //fast-path; this should work for most cases since the authority id is written first
2126 status = new SyncStatusInfo(proto.readInt(SyncStatusProto.StatusInfo.AUTHORITY_ID));
2127 } else {
2128 // placeholder to read other data; assume the default authority id as 0
2129 status = new SyncStatusInfo(0);
2130 }
2131
2132 int successTimesCount = 0;
2133 int failureTimesCount = 0;
2134 ArrayList<Pair<Long, String>> lastEventInformation = new ArrayList<>();
2135 while (true) {
2136 switch (proto.nextField()) {
2137 case (int) SyncStatusProto.StatusInfo.AUTHORITY_ID:
2138 // fast-path failed for some reason, rebuild the status from placeholder object
2139 Slog.w(TAG, "Failed to read the authority id via fast-path; "
2140 + "some data might not have been read.");
2141 status = new SyncStatusInfo(
2142 proto.readInt(SyncStatusProto.StatusInfo.AUTHORITY_ID), status);
2143 break;
2144 case (int) SyncStatusProto.StatusInfo.LAST_SUCCESS_TIME:
2145 status.lastSuccessTime = proto.readLong(
2146 SyncStatusProto.StatusInfo.LAST_SUCCESS_TIME);
2147 break;
2148 case (int) SyncStatusProto.StatusInfo.LAST_SUCCESS_SOURCE:
2149 status.lastSuccessSource = proto.readInt(
2150 SyncStatusProto.StatusInfo.LAST_SUCCESS_SOURCE);
2151 break;
2152 case (int) SyncStatusProto.StatusInfo.LAST_FAILURE_TIME:
2153 status.lastFailureTime = proto.readLong(
2154 SyncStatusProto.StatusInfo.LAST_FAILURE_TIME);
2155 break;
2156 case (int) SyncStatusProto.StatusInfo.LAST_FAILURE_SOURCE:
2157 status.lastFailureSource = proto.readInt(
2158 SyncStatusProto.StatusInfo.LAST_FAILURE_SOURCE);
2159 break;
2160 case (int) SyncStatusProto.StatusInfo.LAST_FAILURE_MESSAGE:
2161 status.lastFailureMesg = proto.readString(
2162 SyncStatusProto.StatusInfo.LAST_FAILURE_MESSAGE);
2163 break;
2164 case (int) SyncStatusProto.StatusInfo.INITIAL_FAILURE_TIME:
2165 status.initialFailureTime = proto.readLong(
2166 SyncStatusProto.StatusInfo.INITIAL_FAILURE_TIME);
2167 break;
2168 case (int) SyncStatusProto.StatusInfo.PENDING:
2169 status.pending = proto.readBoolean(SyncStatusProto.StatusInfo.PENDING);
2170 break;
2171 case (int) SyncStatusProto.StatusInfo.INITIALIZE:
2172 status.initialize = proto.readBoolean(SyncStatusProto.StatusInfo.INITIALIZE);
2173 break;
2174 case (int) SyncStatusProto.StatusInfo.PERIODIC_SYNC_TIMES:
2175 status.addPeriodicSyncTime(
2176 proto.readLong(SyncStatusProto.StatusInfo.PERIODIC_SYNC_TIMES));
2177 break;
2178 case (int) SyncStatusProto.StatusInfo.LAST_EVENT_INFO:
2179 final long eventToken = proto.start(SyncStatusProto.StatusInfo.LAST_EVENT_INFO);
2180 final Pair<Long, String> lastEventInfo = parseLastEventInfoLocked(proto);
2181 if (lastEventInfo != null) {
2182 lastEventInformation.add(lastEventInfo);
2183 }
2184 proto.end(eventToken);
2185 break;
2186 case (int) SyncStatusProto.StatusInfo.LAST_TODAY_RESET_TIME:
2187 status.lastTodayResetTime = proto.readLong(
2188 SyncStatusProto.StatusInfo.LAST_TODAY_RESET_TIME);
2189 break;
2190 case (int) SyncStatusProto.StatusInfo.TOTAL_STATS:
2191 final long totalStatsToken = proto.start(
2192 SyncStatusProto.StatusInfo.TOTAL_STATS);
2193 readSyncStatusStatsLocked(proto, status.totalStats);
2194 proto.end(totalStatsToken);
2195 break;
2196 case (int) SyncStatusProto.StatusInfo.TODAY_STATS:
2197 final long todayStatsToken = proto.start(
2198 SyncStatusProto.StatusInfo.TODAY_STATS);
2199 readSyncStatusStatsLocked(proto, status.todayStats);
2200 proto.end(todayStatsToken);
2201 break;
2202 case (int) SyncStatusProto.StatusInfo.YESTERDAY_STATS:
2203 final long yesterdayStatsToken = proto.start(
2204 SyncStatusProto.StatusInfo.YESTERDAY_STATS);
2205 readSyncStatusStatsLocked(proto, status.yesterdayStats);
2206 proto.end(yesterdayStatsToken);
2207 break;
2208 case (int) SyncStatusProto.StatusInfo.PER_SOURCE_LAST_SUCCESS_TIMES:
2209 final long successTime = proto.readLong(
2210 SyncStatusProto.StatusInfo.PER_SOURCE_LAST_SUCCESS_TIMES);
2211 if (successTimesCount == status.perSourceLastSuccessTimes.length) {
2212 Slog.w(TAG, "Attempted to read more per source last success times "
2213 + "than expected; data might be corrupted.");
2214 break;
2215 }
2216 status.perSourceLastSuccessTimes[successTimesCount] = successTime;
2217 successTimesCount++;
2218 break;
2219 case (int) SyncStatusProto.StatusInfo.PER_SOURCE_LAST_FAILURE_TIMES:
2220 final long failureTime = proto.readLong(
2221 SyncStatusProto.StatusInfo.PER_SOURCE_LAST_FAILURE_TIMES);
2222 if (failureTimesCount == status.perSourceLastFailureTimes.length) {
2223 Slog.w(TAG, "Attempted to read more per source last failure times "
2224 + "than expected; data might be corrupted.");
2225 break;
2226 }
2227 status.perSourceLastFailureTimes[failureTimesCount] = failureTime;
2228 failureTimesCount++;
2229 break;
2230 case ProtoInputStream.NO_MORE_FIELDS:
2231 status.populateLastEventsInformation(lastEventInformation);
2232 return status;
2233 }
2234 }
2235 }
2236
2237 private Pair<Long, String> parseLastEventInfoLocked(ProtoInputStream proto) throws IOException {
2238 long time = 0;
2239 String message = null;
2240 while (true) {
2241 switch (proto.nextField()) {
2242 case (int) SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT_TIME:
2243 time = proto.readLong(SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT_TIME);
2244 break;
2245 case (int) SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT:
2246 message = proto.readString(SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT);
2247 break;
2248 case ProtoInputStream.NO_MORE_FIELDS:
2249 return message == null ? null : new Pair<>(time, message);
2250 }
2251 }
2252 }
2253
2254 private void readSyncStatusStatsLocked(ProtoInputStream proto, SyncStatusInfo.Stats stats)
2255 throws IOException {
2256 while (true) {
2257 switch (proto.nextField()) {
2258 case (int) SyncStatusProto.StatusInfo.Stats.TOTAL_ELAPSED_TIME:
2259 stats.totalElapsedTime = proto.readLong(
2260 SyncStatusProto.StatusInfo.Stats.TOTAL_ELAPSED_TIME);
2261 break;
2262 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SYNCS:
2263 stats.numSyncs = proto.readInt(SyncStatusProto.StatusInfo.Stats.NUM_SYNCS);
2264 break;
2265 case (int) SyncStatusProto.StatusInfo.Stats.NUM_FAILURES:
2266 stats.numFailures = proto.readInt(
2267 SyncStatusProto.StatusInfo.Stats.NUM_FAILURES);
2268 break;
2269 case (int) SyncStatusProto.StatusInfo.Stats.NUM_CANCELS:
2270 stats.numCancels = proto.readInt(SyncStatusProto.StatusInfo.Stats.NUM_CANCELS);
2271 break;
2272 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_OTHER:
2273 stats.numSourceOther = proto.readInt(
2274 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_OTHER);
2275 break;
2276 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_LOCAL:
2277 stats.numSourceLocal = proto.readInt(
2278 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_LOCAL);
2279 break;
2280 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_POLL:
2281 stats.numSourcePoll = proto.readInt(
2282 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_POLL);
2283 break;
2284 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_USER:
2285 stats.numSourceUser = proto.readInt(
2286 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_USER);
2287 break;
2288 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_PERIODIC:
2289 stats.numSourcePeriodic = proto.readInt(
2290 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_PERIODIC);
2291 break;
2292 case (int) SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_FEED:
2293 stats.numSourceFeed = proto.readInt(
2294 SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_FEED);
2295 break;
2296 case ProtoInputStream.NO_MORE_FIELDS:
2297 return;
2298 }
2299 }
2300 }
2301
Dianne Hackborn231cc602009-04-27 17:10:36 -07002302 /**
2303 * Write all sync status to the sync status file.
2304 */
Varun Shah816cf632019-10-30 17:40:15 -07002305 @VisibleForTesting
2306 void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002307 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002308 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002309 }
Costin Manolache360e4542009-09-04 13:36:04 -07002310
Dianne Hackborn231cc602009-04-27 17:10:36 -07002311 // The file is being written, so we don't need to have a scheduled
2312 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002313 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002314
Dianne Hackborn231cc602009-04-27 17:10:36 -07002315 FileOutputStream fos = null;
2316 try {
2317 fos = mStatusFile.startWrite();
Varun Shah816cf632019-10-30 17:40:15 -07002318 writeStatusInfoLocked(fos);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002319 mStatusFile.finishWrite(fos);
Varun Shah816cf632019-10-30 17:40:15 -07002320 fos = null;
2321 } catch (IOException | IllegalArgumentException e) {
2322 Slog.e(TAG, "Unable to write sync status to proto.", e);
2323 } finally {
2324 // when fos is null (successful write), this is a no-op.
2325 mStatusFile.failWrite(fos);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002326 }
2327 }
Costin Manolache360e4542009-09-04 13:36:04 -07002328
Varun Shah816cf632019-10-30 17:40:15 -07002329 private void writeStatusInfoLocked(OutputStream out) {
2330 final ProtoOutputStream proto = new ProtoOutputStream(out);
2331 final int size = mSyncStatus.size();
2332 for (int i = 0; i < size; i++) {
2333 final SyncStatusInfo info = mSyncStatus.valueAt(i);
2334 final long token = proto.start(SyncStatusProto.STATUS);
2335 // authority id should be written first to take advantage of the fast path in read
2336 proto.write(SyncStatusProto.StatusInfo.AUTHORITY_ID, info.authorityId);
2337 proto.write(SyncStatusProto.StatusInfo.LAST_SUCCESS_TIME, info.lastSuccessTime);
2338 proto.write(SyncStatusProto.StatusInfo.LAST_SUCCESS_SOURCE, info.lastSuccessSource);
2339 proto.write(SyncStatusProto.StatusInfo.LAST_FAILURE_TIME, info.lastFailureTime);
2340 proto.write(SyncStatusProto.StatusInfo.LAST_FAILURE_SOURCE, info.lastFailureSource);
2341 proto.write(SyncStatusProto.StatusInfo.LAST_FAILURE_MESSAGE, info.lastFailureMesg);
2342 proto.write(SyncStatusProto.StatusInfo.INITIAL_FAILURE_TIME, info.initialFailureTime);
2343 proto.write(SyncStatusProto.StatusInfo.PENDING, info.pending);
2344 proto.write(SyncStatusProto.StatusInfo.INITIALIZE, info.initialize);
2345 final int periodicSyncTimesSize = info.getPeriodicSyncTimesSize();
2346 for (int j = 0; j < periodicSyncTimesSize; j++) {
2347 proto.write(SyncStatusProto.StatusInfo.PERIODIC_SYNC_TIMES,
2348 info.getPeriodicSyncTime(j));
2349 }
2350 final int lastEventsSize = info.getEventCount();
2351 for (int j = 0; j < lastEventsSize; j++) {
2352 final long eventToken = proto.start(SyncStatusProto.StatusInfo.LAST_EVENT_INFO);
2353 proto.write(SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT_TIME,
2354 info.getEventTime(j));
2355 proto.write(SyncStatusProto.StatusInfo.LastEventInfo.LAST_EVENT, info.getEvent(j));
2356 proto.end(eventToken);
2357 }
2358 proto.write(SyncStatusProto.StatusInfo.LAST_TODAY_RESET_TIME, info.lastTodayResetTime);
2359
2360 final long totalStatsToken = proto.start(SyncStatusProto.StatusInfo.TOTAL_STATS);
2361 writeStatusStatsLocked(proto, info.totalStats);
2362 proto.end(totalStatsToken);
2363 final long todayStatsToken = proto.start(SyncStatusProto.StatusInfo.TODAY_STATS);
2364 writeStatusStatsLocked(proto, info.todayStats);
2365 proto.end(todayStatsToken);
2366 final long yesterdayStatsToken = proto.start(
2367 SyncStatusProto.StatusInfo.YESTERDAY_STATS);
2368 writeStatusStatsLocked(proto, info.yesterdayStats);
2369 proto.end(yesterdayStatsToken);
2370
2371 final int lastSuccessTimesSize = info.perSourceLastSuccessTimes.length;
2372 for (int j = 0; j < lastSuccessTimesSize; j++) {
2373 proto.write(SyncStatusProto.StatusInfo.PER_SOURCE_LAST_SUCCESS_TIMES,
2374 info.perSourceLastSuccessTimes[j]);
2375 }
2376 final int lastFailureTimesSize = info.perSourceLastFailureTimes.length;
2377 for (int j = 0; j < lastFailureTimesSize; j++) {
2378 proto.write(SyncStatusProto.StatusInfo.PER_SOURCE_LAST_FAILURE_TIMES,
2379 info.perSourceLastFailureTimes[j]);
2380 }
2381 proto.end(token);
2382 }
2383 proto.flush();
2384 }
2385
2386 private void writeStatusStatsLocked(ProtoOutputStream proto, SyncStatusInfo.Stats stats) {
2387 proto.write(SyncStatusProto.StatusInfo.Stats.TOTAL_ELAPSED_TIME, stats.totalElapsedTime);
2388 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SYNCS, stats.numSyncs);
2389 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_FAILURES, stats.numFailures);
2390 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_CANCELS, stats.numCancels);
2391 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_OTHER, stats.numSourceOther);
2392 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_LOCAL, stats.numSourceLocal);
2393 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_POLL, stats.numSourcePoll);
2394 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_USER, stats.numSourceUser);
2395 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_PERIODIC, stats.numSourcePeriodic);
2396 proto.write(SyncStatusProto.StatusInfo.Stats.NUM_SOURCE_FEED, stats.numSourceFeed);
2397 }
2398
Makoto Onuki61283ec2018-01-31 17:22:36 -08002399 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002400 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002401 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2402 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002403 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002404 syncExemptionFlag, callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002405 } else {
2406 SyncRequest.Builder req =
2407 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002408 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002409 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002410 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002411 ContentResolver.requestSync(req.build());
2412 }
2413 }
2414
Alon Albert57286f92012-10-09 14:21:38 -07002415 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onukie183a402018-08-29 11:46:41 -07002416 Bundle extras, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002417 // If this is happening in the system process, then call the syncrequest listener
2418 // to make a request back to the SyncManager directly.
2419 // If this is probably a test instance, then call back through the ContentResolver
2420 // which will know which userId to apply based on the Binder id.
2421 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2422 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002423 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002424 new EndPoint(account, authority, userId),
Makoto Onukie183a402018-08-29 11:46:41 -07002425 reason, extras, syncExemptionFlag, callingUid, callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002426 } else {
2427 ContentResolver.requestSync(account, authority, extras);
2428 }
2429 }
2430
Dianne Hackborn231cc602009-04-27 17:10:36 -07002431 public static final int STATISTICS_FILE_END = 0;
2432 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2433 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002434
Varun Shah816cf632019-10-30 17:40:15 -07002435 private void readStatsParcelLocked(File parcel) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002436 try {
Varun Shah816cf632019-10-30 17:40:15 -07002437 final AtomicFile parcelFile = new AtomicFile(parcel);
2438 byte[] data = parcelFile.readFully();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002439 Parcel in = Parcel.obtain();
2440 in.unmarshall(data, 0, data.length);
2441 in.setDataPosition(0);
2442 int token;
2443 int index = 0;
2444 while ((token=in.readInt()) != STATISTICS_FILE_END) {
Varun Shah816cf632019-10-30 17:40:15 -07002445 if (token == STATISTICS_FILE_ITEM || token == STATISTICS_FILE_ITEM_OLD) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002446 int day = in.readInt();
2447 if (token == STATISTICS_FILE_ITEM_OLD) {
2448 day = day - 2009 + 14245; // Magic!
2449 }
2450 DayStats ds = new DayStats(day);
2451 ds.successCount = in.readInt();
2452 ds.successTime = in.readLong();
2453 ds.failureCount = in.readInt();
2454 ds.failureTime = in.readLong();
2455 if (index < mDayStats.length) {
2456 mDayStats[index] = ds;
2457 index++;
2458 }
2459 } else {
2460 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002461 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002462 break;
2463 }
2464 }
Varun Shah816cf632019-10-30 17:40:15 -07002465 } catch (IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002466 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002467 }
2468 }
Costin Manolache360e4542009-09-04 13:36:04 -07002469
Varun Shah816cf632019-10-30 17:40:15 -07002470 private void upgradeStatisticsIfNeededLocked() {
2471 final File parcelStats = new File(mSyncDir, LEGACY_STATISTICS_FILE_NAME);
2472 if (parcelStats.exists() && !mStatisticsFile.exists()) {
2473 readStatsParcelLocked(parcelStats);
2474 writeStatisticsLocked();
2475 }
2476
2477 // if upgrade to proto was successful, delete parcel file
2478 if (DELETE_LEGACY_PARCEL_FILES && mStatisticsFile.exists()) {
2479 parcelStats.delete();
2480 }
2481 }
2482
2483 /**
2484 * Read all sync statistics back in to the initial engine state.
2485 */
2486 private void readStatisticsLocked() {
2487 upgradeStatisticsIfNeededLocked();
2488
2489 if (!mStatisticsFile.exists()) {
2490 return;
2491 }
2492 try {
2493 try (FileInputStream in = mStatisticsFile.openRead()) {
2494 readDayStatsLocked(in);
2495 }
2496 } catch (IOException e) {
2497 Slog.e(TAG, "Unable to read day stats file.", e);
2498 }
2499 }
2500
2501 private void readDayStatsLocked(InputStream in) throws IOException {
2502 final ProtoInputStream proto = new ProtoInputStream(in);
2503 int statsCount = 0;
2504 while (true) {
2505 switch (proto.nextField()) {
2506 case (int) SyncStatisticsProto.STATS:
2507 final long token = proto.start(SyncStatisticsProto.STATS);
2508 final DayStats stats = readIndividualDayStatsLocked(proto);
2509 proto.end(token);
2510 mDayStats[statsCount] = stats;
2511 statsCount++;
2512 if (statsCount == mDayStats.length) {
2513 return;
2514 }
2515 break;
2516 case ProtoInputStream.NO_MORE_FIELDS:
2517 return;
2518 }
2519 }
2520 }
2521
2522 private DayStats readIndividualDayStatsLocked(ProtoInputStream proto) throws IOException {
2523 DayStats stats;
2524 if (proto.nextField(SyncStatisticsProto.DayStats.DAY)) {
2525 // fast-path; this should work for most cases since the day is written first
2526 stats = new DayStats(proto.readInt(SyncStatisticsProto.DayStats.DAY));
2527 } else {
2528 // placeholder to read other data; assume the default day as 0
2529 stats = new DayStats(0);
2530 }
2531
2532 while (true) {
2533 switch (proto.nextField()) {
2534 case (int) SyncStatisticsProto.DayStats.DAY:
2535 // fast-path failed for some reason, rebuild stats from placeholder object
2536 Slog.w(TAG, "Failed to read the day via fast-path; some data "
2537 + "might not have been read.");
2538 final DayStats temp = new DayStats(
2539 proto.readInt(SyncStatisticsProto.DayStats.DAY));
2540 temp.successCount = stats.successCount;
2541 temp.successTime = stats.successTime;
2542 temp.failureCount = stats.failureCount;
2543 temp.failureTime = stats.failureTime;
2544 stats = temp;
2545 break;
2546 case (int) SyncStatisticsProto.DayStats.SUCCESS_COUNT:
2547 stats.successCount = proto.readInt(SyncStatisticsProto.DayStats.SUCCESS_COUNT);
2548 break;
2549 case (int) SyncStatisticsProto.DayStats.SUCCESS_TIME:
2550 stats.successTime = proto.readLong(SyncStatisticsProto.DayStats.SUCCESS_TIME);
2551 break;
2552 case (int) SyncStatisticsProto.DayStats.FAILURE_COUNT:
2553 stats.failureCount = proto.readInt(SyncStatisticsProto.DayStats.FAILURE_COUNT);
2554 break;
2555 case (int) SyncStatisticsProto.DayStats.FAILURE_TIME:
2556 stats.failureTime = proto.readLong(SyncStatisticsProto.DayStats.FAILURE_TIME);
2557 break;
2558 case ProtoInputStream.NO_MORE_FIELDS:
2559 return stats;
2560 }
2561 }
2562 }
2563
Dianne Hackborn231cc602009-04-27 17:10:36 -07002564 /**
2565 * Write all sync statistics to the sync status file.
2566 */
Varun Shah816cf632019-10-30 17:40:15 -07002567 @VisibleForTesting
2568 void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002569 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002570 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002571 }
Costin Manolache360e4542009-09-04 13:36:04 -07002572
Dianne Hackborn231cc602009-04-27 17:10:36 -07002573 // The file is being written, so we don't need to have a scheduled
2574 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002575 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002576
Dianne Hackborn231cc602009-04-27 17:10:36 -07002577 FileOutputStream fos = null;
2578 try {
2579 fos = mStatisticsFile.startWrite();
Varun Shah816cf632019-10-30 17:40:15 -07002580 writeDayStatsLocked(fos);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002581 mStatisticsFile.finishWrite(fos);
Varun Shah816cf632019-10-30 17:40:15 -07002582 fos = null;
2583 } catch (IOException | IllegalArgumentException e) {
2584 Slog.e(TAG, "Unable to write day stats to proto.", e);
2585 } finally {
2586 // when fos is null (successful write), this is a no-op.
2587 mStatisticsFile.failWrite(fos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 }
2589 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002590
Varun Shah816cf632019-10-30 17:40:15 -07002591 private void writeDayStatsLocked(OutputStream out)
2592 throws IOException, IllegalArgumentException {
2593 final ProtoOutputStream proto = new ProtoOutputStream(out);
2594 final int size = mDayStats.length;
2595 for (int i = 0; i < size; i++) {
2596 final DayStats stats = mDayStats[i];
2597 if (stats == null) {
2598 break;
2599 }
2600 final long token = proto.start(SyncStatisticsProto.STATS);
2601 // day should be written first to take advantage of the fast path in read
2602 proto.write(SyncStatisticsProto.DayStats.DAY, stats.day);
2603 proto.write(SyncStatisticsProto.DayStats.SUCCESS_COUNT, stats.successCount);
2604 proto.write(SyncStatisticsProto.DayStats.SUCCESS_TIME, stats.successTime);
2605 proto.write(SyncStatisticsProto.DayStats.FAILURE_COUNT, stats.failureCount);
2606 proto.write(SyncStatisticsProto.DayStats.FAILURE_TIME, stats.failureTime);
2607 proto.end(token);
2608 }
2609 proto.flush();
2610 }
2611
Matthew Williamsfa774182013-06-18 15:44:11 -07002612 /**
Marvin Paula6533252014-11-24 12:57:48 -08002613 * Let the BackupManager know that account sync settings have changed. This will trigger
2614 * {@link com.android.server.backup.SystemBackupAgent} to run.
2615 */
2616 public void queueBackup() {
2617 BackupManager.dataChanged("android");
2618 }
Makoto Onuki94986212018-04-11 16:24:46 -07002619
2620 public void setClockValid() {
2621 if (!mIsClockValid) {
2622 mIsClockValid = true;
2623 Slog.w(TAG, "Clock is valid now.");
2624 }
2625 }
2626
2627 public boolean isClockValid() {
2628 return mIsClockValid;
2629 }
2630
2631 public void resetTodayStats(boolean force) {
2632 if (force) {
2633 Log.w(TAG, "Force resetting today stats.");
2634 }
2635 synchronized (mAuthorities) {
2636 final int N = mSyncStatus.size();
2637 for (int i = 0; i < N; i++) {
2638 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2639 cur.maybeResetTodayStats(isClockValid(), force);
2640 }
2641 writeStatusLocked();
2642 }
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644}