blob: c7a3f4b173c3038120ac34e9a75c283e2087e398 [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;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080054
55import com.android.internal.annotations.VisibleForTesting;
56import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
Varun Shahfe009ec2019-04-29 14:26:45 -070058import com.android.internal.util.IntPair;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080059
60import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
62import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
Dianne Hackborn231cc602009-04-27 17:10:36 -070064import java.io.File;
65import java.io.FileInputStream;
66import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010067import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070069import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070071import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080072import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070073import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060074import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075
76/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070077 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070079 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 * @hide
81 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080082public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070085 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070086
Amith Yamasani04e0d262012-02-14 11:50:53 -080087 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
88 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070089 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080090 private static final String XML_ATTR_ENABLED = "enabled";
91 private static final String XML_ATTR_USER = "user";
92 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
93
Matthew Williamsfa774182013-06-18 15:44:11 -070094 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000095 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080096
Shreyas Basarge8c834c02016-01-07 13:53:16 +000097 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070098 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
99
100 /** Lower bound on sync time from which we assign a default flex time. */
101 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
102
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800103 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 /** Enum value for a sync start event. */
107 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 /** Enum value for a sync stop event. */
110 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Makoto Onuki94986212018-04-11 16:24:46 -0700112 /** Enum value for a sync with other sources. */
113 public static final int SOURCE_OTHER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Dianne Hackborn231cc602009-04-27 17:10:36 -0700115 /** Enum value for a local-initiated sync. */
116 public static final int SOURCE_LOCAL = 1;
Makoto Onuki94986212018-04-11 16:24:46 -0700117
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700118 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Dianne Hackborn231cc602009-04-27 17:10:36 -0700121 /** Enum value for a user-initiated sync. */
122 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800124 /** Enum value for a periodic sync. */
125 public static final int SOURCE_PERIODIC = 4;
126
Makoto Onuki94986212018-04-11 16:24:46 -0700127 /** Enum a sync with a "feed" extra */
128 public static final int SOURCE_FEED = 5;
129
Fred Quintana307da1a2010-01-21 14:24:20 -0800130 public static final long NOT_IN_BACKOFF_MODE = -1;
131
Makoto Onukif74cf942018-04-16 17:04:58 -0700132 /**
133 * String names for the sync source types.
134 *
135 * KEEP THIS AND {@link SyncStatusInfo#SOURCE_COUNT} IN SYNC.
136 */
137 public static final String[] SOURCES = {
138 "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000139 "LOCAL",
140 "POLL",
141 "USER",
142 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700143 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 // The MESG column will contain one of these or one of the Error types.
146 public static final String MESG_SUCCESS = "success";
147 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700149 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700150
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 private static final int MSG_WRITE_STATUS = 1;
152 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700153
Dianne Hackborn231cc602009-04-27 17:10:36 -0700154 private static final int MSG_WRITE_STATISTICS = 2;
155 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700156
157 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700158
Fred Quintanac2e46912010-03-15 16:10:44 -0700159 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700160 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700161
162 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000163 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700164
Makoto Onuki94986212018-04-11 16:24:46 -0700165 private volatile boolean mIsClockValid;
166
Fred Quintanafb084402010-03-23 17:57:03 -0700167 static {
168 sAuthorityRenames = new HashMap<String, String>();
169 sAuthorityRenames.put("contacts", "com.android.contacts");
170 sAuthorityRenames.put("calendar", "com.android.calendar");
171 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700172
Dianne Hackborn231cc602009-04-27 17:10:36 -0700173 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800174 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700175 final HashMap<String, AuthorityInfo> authorities =
176 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700177
Amith Yamasani04e0d262012-02-14 11:50:53 -0800178 AccountInfo(AccountAndUser accountAndUser) {
179 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700180 }
181 }
Costin Manolache360e4542009-09-04 13:36:04 -0700182
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 /** Bare bones representation of a sync target. */
184 public static class EndPoint {
185 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
186 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700187 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800188 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700189 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700190
191 public EndPoint(Account account, String provider, int userId) {
192 this.account = account;
193 this.provider = provider;
194 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700195 }
196
197 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700198 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
199 *
200 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000201 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700202 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700203 public boolean matchesSpec(EndPoint spec) {
204 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700206 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700207 return false;
208 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000209 boolean accountsMatch;
210 if (spec.account == null) {
211 accountsMatch = true;
212 } else {
213 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700214 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000215 boolean providersMatch;
216 if (spec.provider == null) {
217 providersMatch = true;
218 } else {
219 providersMatch = provider.equals(spec.provider);
220 }
221 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700222 }
223
224 public String toString() {
225 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000226 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700227 .append("/")
228 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700229 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700230 return sb.toString();
231 }
Makoto Onukidecc5ba2019-01-15 09:34:05 -0800232
233 public String toSafeString() {
234 StringBuilder sb = new StringBuilder();
235 sb.append(account == null ? "ALL ACCS" : logSafe(account))
236 .append("/")
237 .append(provider == null ? "ALL PDRS" : provider);
238 sb.append(":u" + userId);
239 return sb.toString();
240 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700241 }
242
243 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700244 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700245
246 /**
247 * The syncable state is undefined.
248 */
249 public static final int UNDEFINED = -2;
250
Matthew Williams53abfdb2015-06-10 20:06:37 -0700251 /**
252 * Default state for a newly installed adapter. An uninitialized adapter will receive an
253 * initialization sync which are governed by a different set of rules to that of regular
254 * syncs.
255 */
256 public static final int NOT_INITIALIZED = -1;
257 /**
258 * The adapter will not receive any syncs. This is behaviourally equivalent to
259 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
260 * while this is generally meant to be controlled by the developer.
261 */
262 public static final int NOT_SYNCABLE = 0;
263 /**
264 * The adapter is initialized and functioning. This is the normal state for an adapter.
265 */
266 public static final int SYNCABLE = 1;
267 /**
268 * The adapter is syncable but still requires an initialization sync. For example an adapter
269 * than has been restored from a previous device will be in this state. Not meant for
270 * external use.
271 */
272 public static final int SYNCABLE_NOT_INITIALIZED = 2;
273
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700274 /**
275 * The adapter is syncable but does not have access to the synced account and needs a
276 * user access approval.
277 */
278 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
279
Matthew Williams8ef22042013-07-26 12:56:39 -0700280 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700281 final int ident;
282 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700283 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700284 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800285 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700286 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800287 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700288 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800289 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700290
Matthew Williamsfa774182013-06-18 15:44:11 -0700291 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700292
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700293 /**
294 * Copy constructor for making deep-ish copies. Only the bundles stored
295 * in periodic syncs can make unexpected changes.
296 *
297 * @param toCopy AuthorityInfo to be copied.
298 */
299 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700300 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700301 ident = toCopy.ident;
302 enabled = toCopy.enabled;
303 syncable = toCopy.syncable;
304 backoffTime = toCopy.backoffTime;
305 backoffDelay = toCopy.backoffDelay;
306 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700307 periodicSyncs = new ArrayList<PeriodicSync>();
308 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700309 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700310 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700311 }
312 }
313
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700314 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700315 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700316 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000317 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700318 periodicSyncs = new ArrayList<PeriodicSync>();
319 defaultInitialisation();
320 }
321
322 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700323 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800324 backoffTime = -1; // if < 0 then we aren't in backoff mode
325 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000326
327 if (mPeriodicSyncAddedListener != null) {
328 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
329 DEFAULT_POLL_FREQUENCY_SECONDS,
330 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700331 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700332 }
Matthew Williams06485a72013-07-26 12:56:39 -0700333
334 @Override
335 public String toString() {
336 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
337 + backoffTime + ", delay=" + delayUntil;
338 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700339 }
Costin Manolache360e4542009-09-04 13:36:04 -0700340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 public static class SyncHistoryItem {
342 int authorityId;
343 int historyId;
344 long eventTime;
345 long elapsedTime;
346 int source;
347 int event;
348 long upstreamActivity;
349 long downstreamActivity;
350 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700351 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700352 Bundle extras;
353 int reason;
Makoto Onukid5f25d22018-05-22 16:02:17 -0700354 int syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700355 }
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 public static class DayStats {
358 public final int day;
359 public int successCount;
360 public long successTime;
361 public int failureCount;
362 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700363
Dianne Hackborn231cc602009-04-27 17:10:36 -0700364 public DayStats(int day) {
365 this.day = day;
366 }
367 }
Costin Manolache360e4542009-09-04 13:36:04 -0700368
Amith Yamasani04e0d262012-02-14 11:50:53 -0800369 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700370
371 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800372 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -0700373 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800374 }
375
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000376 interface PeriodicSyncAddedListener {
377 /** Called when a periodic sync is added. */
378 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
379 }
380
381 interface OnAuthorityRemovedListener {
382 /** Called when an authority is removed. */
383 void onAuthorityRemoved(EndPoint removedAuthority);
384 }
385
Suprabh Shukla042a4782017-05-12 15:26:54 -0700386 /**
387 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
388 * account is valid.
389 */
390 private static class AccountAuthorityValidator {
391 final private AccountManager mAccountManager;
392 final private PackageManager mPackageManager;
393 final private SparseArray<Account[]> mAccountsCache;
394 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
395
396 AccountAuthorityValidator(Context context) {
397 mAccountManager = context.getSystemService(AccountManager.class);
398 mPackageManager = context.getPackageManager();
399 mAccountsCache = new SparseArray<>();
400 mProvidersPerUserCache = new SparseArray<>();
401 }
402
403 // An account is valid if an installed authenticator has previously created that account
404 // on the device
405 boolean isAccountValid(Account account, int userId) {
406 Account[] accountsForUser = mAccountsCache.get(userId);
407 if (accountsForUser == null) {
408 accountsForUser = mAccountManager.getAccountsAsUser(userId);
409 mAccountsCache.put(userId, accountsForUser);
410 }
411 return ArrayUtils.contains(accountsForUser, account);
412 }
413
414 // An authority is only valid if it has a content provider installed on the system
415 boolean isAuthorityValid(String authority, int userId) {
416 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
417 if (authorityMap == null) {
418 authorityMap = new ArrayMap<>();
419 mProvidersPerUserCache.put(userId, authorityMap);
420 }
421 if (!authorityMap.containsKey(authority)) {
422 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
423 PackageManager.MATCH_DIRECT_BOOT_AWARE
424 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
425 }
426 return authorityMap.get(authority);
427 }
428 }
429
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 // Primary list of all syncable authorities. Also our global lock.
431 private final SparseArray<AuthorityInfo> mAuthorities =
432 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700433
Amith Yamasani04e0d262012-02-14 11:50:53 -0800434 private final HashMap<AccountAndUser, AccountInfo> mAccounts
435 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Amith Yamasani04e0d262012-02-14 11:50:53 -0800437 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
438 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700439
Dianne Hackborn231cc602009-04-27 17:10:36 -0700440 private final SparseArray<SyncStatusInfo> mSyncStatus =
441 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700442
Dianne Hackborn231cc602009-04-27 17:10:36 -0700443 private final ArrayList<SyncHistoryItem> mSyncHistory =
444 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Dianne Hackborn231cc602009-04-27 17:10:36 -0700446 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
447 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700448
Matthew Williams8ef22042013-07-26 12:56:39 -0700449 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700450 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
451 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700452
Fred Quintana77c560f2010-03-29 22:20:26 -0700453 private int mNextAuthorityId = 0;
454
Dianne Hackborn231cc602009-04-27 17:10:36 -0700455 // We keep 4 weeks of stats.
456 private final DayStats[] mDayStats = new DayStats[7*4];
457 private final Calendar mCal;
458 private int mYear;
459 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800462
Dianne Hackborn231cc602009-04-27 17:10:36 -0700463 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700464
Ashish Sharma69d95de2012-04-11 17:27:24 -0700465 private int mSyncRandomOffset;
466
Dianne Hackborn231cc602009-04-27 17:10:36 -0700467 /**
468 * This file contains the core engine state: all accounts and the
469 * settings for them. It must never be lost, and should be changed
470 * infrequently, so it is stored as an XML file.
471 */
472 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700473
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 /**
475 * This file contains the current sync status. We would like to retain
476 * it across boots, but its loss is not the end of the world, so we store
477 * this information as binary data.
478 */
479 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700480
Dianne Hackborn231cc602009-04-27 17:10:36 -0700481 /**
482 * This file contains sync statistics. This is purely debugging information
483 * so is written infrequently and can be thrown away at any time.
484 */
485 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700486
Dianne Hackborn231cc602009-04-27 17:10:36 -0700487 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800489 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800490
491 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000492 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700493
Svet Ganov65712b02016-09-01 10:24:11 -0700494 private boolean mGrantSyncAdaptersAccountAccess;
495
Makoto Onuki6963bea72017-12-12 10:42:39 -0800496 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700497 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800498
499 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
500 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700503 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700504
Dianne Hackborn231cc602009-04-27 17:10:36 -0700505 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700506
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800507 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000508 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800509
Dianne Hackborn231cc602009-04-27 17:10:36 -0700510 File systemDir = new File(dataDir, "system");
511 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800512 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700513
514 maybeDeleteLegacyPendingInfoLocked(syncDir);
515
Dianne Hackborne17b4452018-01-10 13:15:40 -0800516 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
517 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
518 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700519
Dianne Hackborn231cc602009-04-27 17:10:36 -0700520 readAccountInfoLocked();
521 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700522 readStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700523
524 if (mLogger.enabled()) {
525 final int size = mAuthorities.size();
526 mLogger.log("Loaded ", size, " items");
527 for (int i = 0; i < size; i++) {
528 mLogger.log(mAuthorities.valueAt(i));
529 }
530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
532
533 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800534 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535 }
536
Makoto Onuki6963bea72017-12-12 10:42:39 -0800537 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800539 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700541 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800542 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800543 }
544
545 public static SyncStorageEngine getSingleton() {
546 if (sSyncStorageEngine == null) {
547 throw new IllegalStateException("not initialized");
548 }
549 return sSyncStorageEngine;
550 }
551
Amith Yamasani04e0d262012-02-14 11:50:53 -0800552 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
553 if (mSyncRequestListener == null) {
554 mSyncRequestListener = listener;
555 }
556 }
557
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000558 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
559 if (mAuthorityRemovedListener == null) {
560 mAuthorityRemovedListener = listener;
561 }
562 }
563
564 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
565 if (mPeriodicSyncAddedListener == null) {
566 mPeriodicSyncAddedListener = listener;
567 }
568 }
569
Makoto Onuki6963bea72017-12-12 10:42:39 -0800570 private class MyHandler extends Handler {
571 public MyHandler(Looper looper) {
572 super(looper);
573 }
574
575 @Override
576 public void handleMessage(Message msg) {
577 if (msg.what == MSG_WRITE_STATUS) {
578 synchronized (mAuthorities) {
579 writeStatusLocked();
580 }
581 } else if (msg.what == MSG_WRITE_STATISTICS) {
582 synchronized (mAuthorities) {
583 writeStatisticsLocked();
584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 }
586 }
587 }
Costin Manolache360e4542009-09-04 13:36:04 -0700588
Ashish Sharma69d95de2012-04-11 17:27:24 -0700589 public int getSyncRandomOffset() {
590 return mSyncRandomOffset;
591 }
592
Varun Shahfe009ec2019-04-29 14:26:45 -0700593 public void addStatusChangeListener(int mask, int userId, ISyncStatusObserver callback) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700594 synchronized (mAuthorities) {
Varun Shahfe009ec2019-04-29 14:26:45 -0700595 final long cookie = IntPair.of(userId, mask);
596 mChangeListeners.register(callback, cookie);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700597 }
598 }
Costin Manolache360e4542009-09-04 13:36:04 -0700599
Dianne Hackborn231cc602009-04-27 17:10:36 -0700600 public void removeStatusChangeListener(ISyncStatusObserver callback) {
601 synchronized (mAuthorities) {
602 mChangeListeners.unregister(callback);
603 }
604 }
Costin Manolache360e4542009-09-04 13:36:04 -0700605
Matthew Williamsfa774182013-06-18 15:44:11 -0700606 /**
607 * Figure out a reasonable flex time for cases where none is provided (old api calls).
608 * @param syncTimeSeconds requested sync time from now.
609 * @return amount of seconds before syncTimeSeconds that the sync can occur.
610 * I.e.
611 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700612 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700613 */
614 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
615 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
616 // Small enough sync request time that we don't add flex time - developer probably
617 // wants to wait for an operation to occur before syncing so we honour the
618 // request time.
619 return 0L;
620 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
621 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
622 } else {
623 // Large enough sync request time that we cap the flex time.
624 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
625 }
626 }
627
Varun Shahfe009ec2019-04-29 14:26:45 -0700628 void reportChange(int which, int callingUserId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700629 ArrayList<ISyncStatusObserver> reports = null;
630 synchronized (mAuthorities) {
631 int i = mChangeListeners.beginBroadcast();
632 while (i > 0) {
633 i--;
Varun Shahfe009ec2019-04-29 14:26:45 -0700634 final long cookie = (long) mChangeListeners.getBroadcastCookie(i);
635 final int userId = IntPair.first(cookie);
636 final int mask = IntPair.second(cookie);
637 if ((which & mask) == 0 || callingUserId != userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 continue;
639 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700640 if (reports == null) {
641 reports = new ArrayList<ISyncStatusObserver>(i);
642 }
643 reports.add(mChangeListeners.getBroadcastItem(i));
644 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700645 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700646 }
Costin Manolache360e4542009-09-04 13:36:04 -0700647
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700648 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000649 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700650 }
Costin Manolache360e4542009-09-04 13:36:04 -0700651
Dianne Hackborn231cc602009-04-27 17:10:36 -0700652 if (reports != null) {
653 int i = reports.size();
654 while (i > 0) {
655 i--;
656 try {
657 reports.get(i).onStatusChanged(which);
658 } catch (RemoteException e) {
659 // The remote callback list will take care of this for us.
660 }
661 }
662 }
663 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700664
Amith Yamasani04e0d262012-02-14 11:50:53 -0800665 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700666 synchronized (mAuthorities) {
667 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700668 AuthorityInfo authority = getAuthorityLocked(
669 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700670 "getSyncAutomatically");
671 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700672 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700673
Dianne Hackborn231cc602009-04-27 17:10:36 -0700674 int i = mAuthorities.size();
675 while (i > 0) {
676 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700677 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700678 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700679 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700680 return true;
681 }
682 }
683 return false;
684 }
685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800686
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukie183a402018-08-29 11:46:41 -0700688 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000690 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800691 + ", user " + userId + " -> " + sync);
692 }
Makoto Onukid4764302018-03-30 17:32:57 -0700693 mLogger.log("Set sync auto account=", account,
694 " user=", userId,
695 " authority=", providerName,
696 " value=", Boolean.toString(sync),
Makoto Onukie183a402018-08-29 11:46:41 -0700697 " cuid=", callingUid,
698 " cpid=", callingPid
699 );
Dianne Hackborn231cc602009-04-27 17:10:36 -0700700 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700701 AuthorityInfo authority =
702 getOrCreateAuthorityLocked(
703 new EndPoint(account, providerName, userId),
704 -1 /* ident */,
705 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700706 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700707 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000708 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800709 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700710 return;
711 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700712 // If the adapter was syncable but missing its initialization sync, set it to
713 // uninitialized now. This is to give it a chance to run any one-time initialization
714 // logic.
715 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
716 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
717 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700718 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700719 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700721
Fred Quintana77c560f2010-03-29 22:20:26 -0700722 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700723 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800724 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700725 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700726 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700727 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, userId);
Marvin Paula6533252014-11-24 12:57:48 -0800728 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 }
730
Amith Yamasani04e0d262012-02-14 11:50:53 -0800731 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700732 synchronized (mAuthorities) {
733 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700734 AuthorityInfo authority = getAuthorityLocked(
735 new EndPoint(account, providerName, userId),
736 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700737 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700738 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700739 }
740 return authority.syncable;
741 }
742
743 int i = mAuthorities.size();
744 while (i > 0) {
745 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700746 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700747 if (authorityInfo.target != null
748 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700750 }
751 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700752 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700753 }
754 }
755
Makoto Onukid4764302018-03-30 17:32:57 -0700756 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700757 int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700758 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700759 callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700760 }
761
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700762 /**
763 * An enabled sync service and a syncable provider's adapter both get resolved to the same
764 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700765 * @param target target to set value for.
766 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700767 */
Makoto Onukie183a402018-08-29 11:46:41 -0700768 private void setSyncableStateForEndPoint(EndPoint target, int syncable,
769 int callingUid, int callingPid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700770 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700771 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
Makoto Onukie183a402018-08-29 11:46:41 -0700772 " cuid=", callingUid,
773 " cpid=", callingPid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700774 synchronized (mAuthorities) {
775 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700776 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
777 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700778 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700779 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000780 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700781 }
782 if (aInfo.syncable == syncable) {
783 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000784 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700785 }
786 return;
787 }
788 aInfo.syncable = syncable;
789 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700790 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700791 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800792 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700793 ContentResolver.SYNC_EXEMPTION_NONE, callingUid, callingPid);
Fred Quintana5e787c42009-08-16 23:13:53 -0700794 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700795 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, target.userId);
Fred Quintana5e787c42009-08-16 23:13:53 -0700796 }
797
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700800 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
801 if (authority != null) {
802 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800803 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800805 }
806 }
807
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700808 /**
809 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
810 * the account or provider info be null, which signifies all accounts or providers.
811 */
812 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
813 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000814 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800815 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
816 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700817 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800818 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000819 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700820 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000821 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700822 changed = setBackoffLocked(
823 info.account /* may be null */,
824 info.userId,
825 info.provider /* may be null */,
826 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800827 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700828 AuthorityInfo authorityInfo =
829 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
830 if (authorityInfo.backoffTime == nextSyncTime
831 && authorityInfo.backoffDelay == nextDelay) {
832 changed = false;
833 } else {
834 authorityInfo.backoffTime = nextSyncTime;
835 authorityInfo.backoffDelay = nextDelay;
836 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800837 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800838 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800839 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800840 if (changed) {
Varun Shahfe009ec2019-04-29 14:26:45 -0700841 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, info.userId);
Fred Quintana307da1a2010-01-21 14:24:20 -0800842 }
843 }
844
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700845 /**
846 * Either set backoff for a specific authority, or set backoff for all the
847 * accounts on a specific adapter/all adapters.
848 *
849 * @param account account for which to set backoff. Null to specify all accounts.
850 * @param userId id of the user making this request.
851 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700852 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700853 */
854 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000855 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700856 boolean changed = false;
857 for (AccountInfo accountInfo : mAccounts.values()) {
858 if (account != null && !account.equals(accountInfo.accountAndUser.account)
859 && userId != accountInfo.accountAndUser.userId) {
860 continue;
861 }
862 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
863 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700864 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700865 continue;
866 }
867 if (authorityInfo.backoffTime != nextSyncTime
868 || authorityInfo.backoffDelay != nextDelay) {
869 authorityInfo.backoffTime = nextSyncTime;
870 authorityInfo.backoffDelay = nextDelay;
871 changed = true;
872 }
873 }
874 }
875 return changed;
876 }
877
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000878 public void clearAllBackoffsLocked() {
Varun Shahfe009ec2019-04-29 14:26:45 -0700879 final ArraySet<Integer> changedUserIds = new ArraySet<>();
Alon Albert744e310f2010-12-14 11:37:20 -0800880 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000881 // Clear backoff for all sync adapters.
882 for (AccountInfo accountInfo : mAccounts.values()) {
883 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
884 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
885 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
886 if (Log.isLoggable(TAG, Log.VERBOSE)) {
887 Slog.v(TAG, "clearAllBackoffsLocked:"
888 + " authority:" + authorityInfo.target
889 + " account:" + accountInfo.accountAndUser.account.name
890 + " user:" + accountInfo.accountAndUser.userId
891 + " backoffTime was: " + authorityInfo.backoffTime
892 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800893 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000894 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
895 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
Varun Shahfe009ec2019-04-29 14:26:45 -0700896 changedUserIds.add(accountInfo.accountAndUser.userId);
Alon Albert744e310f2010-12-14 11:37:20 -0800897 }
898 }
899 }
900 }
901
Varun Shahfe009ec2019-04-29 14:26:45 -0700902 for (int i = changedUserIds.size() - 1; i > 0; i--) {
903 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, changedUserIds.valueAt(i));
Alon Albert744e310f2010-12-14 11:37:20 -0800904 }
905 }
906
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700907 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800908 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700909 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800910 if (authority == null) {
911 return 0;
912 }
913 return authority.delayUntil;
914 }
915 }
916
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700917 public void setDelayUntilTime(EndPoint info, long delayUntil) {
918 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000919 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700920 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800921 }
922 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700923 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
924 if (authority.delayUntil == delayUntil) {
925 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700926 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700927 authority.delayUntil = delayUntil;
928 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700929 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, info.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700930 }
931
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700932 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000933 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
934 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700935 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000936 boolean restoreAllPeriodicSyncs() {
937 if (mPeriodicSyncAddedListener == null) {
938 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800939 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000940 synchronized (mAuthorities) {
941 for (int i=0; i<mAuthorities.size(); i++) {
942 AuthorityInfo authority = mAuthorities.valueAt(i);
943 for (PeriodicSync periodicSync: authority.periodicSyncs) {
944 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
945 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
946 }
947 authority.periodicSyncs.clear();
948 }
949 writeAccountInfoLocked();
950 }
951 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800952 }
953
Makoto Onuki75ad2492018-03-28 14:42:42 -0700954 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700955 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700956 mLogger.log("Set master enabled=", flag, " user=", userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700957 " cuid=", callingUid,
958 " cpid=", callingPid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700959 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800960 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700961 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700962 return;
963 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800964 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700965 writeAccountInfoLocked();
966 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700967 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700968 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800969 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700970 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700971 }
Varun Shahfe009ec2019-04-29 14:26:45 -0700972 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, userId);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800973 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800974 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976
Amith Yamasani04e0d262012-02-14 11:50:53 -0800977 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700978 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800979 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800980 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700981 }
982 }
Costin Manolache360e4542009-09-04 13:36:04 -0700983
Makoto Onukib47e8942017-09-18 14:03:03 -0700984 public int getAuthorityCount() {
985 synchronized (mAuthorities) {
986 return mAuthorities.size();
987 }
988 }
989
Dianne Hackborn231cc602009-04-27 17:10:36 -0700990 public AuthorityInfo getAuthority(int authorityId) {
991 synchronized (mAuthorities) {
992 return mAuthorities.get(authorityId);
993 }
994 }
Costin Manolache360e4542009-09-04 13:36:04 -0700995
Dianne Hackborn231cc602009-04-27 17:10:36 -0700996 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700997 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700998 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001000 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001002 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -07001003 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -07001004 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 return true;
1006 }
1007 }
1008 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 return false;
1010 }
Costin Manolache360e4542009-09-04 13:36:04 -07001011
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001012 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001014 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
1015 -1 /* desired identifier */,
1016 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001018 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001019 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001020 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001021 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001022 }
Varun Shahfe009ec2019-04-29 14:26:45 -07001023 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING, info.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001024 }
Costin Manolache360e4542009-09-04 13:36:04 -07001025
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 /**
1027 * Called when the set of account has changed, given the new array of
1028 * active accounts.
1029 */
Makoto Onuki3ab77812018-07-09 14:29:33 -07001030 public void removeStaleAccounts(@Nullable Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001031 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001032 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001033 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001034 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001035 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1036 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1037 while (accIt.hasNext()) {
1038 AccountInfo acc = accIt.next();
Makoto Onuki3ab77812018-07-09 14:29:33 -07001039 if ((accounts == null) || (
1040 (acc.accountAndUser.userId == userId)
1041 && !ArrayUtils.contains(accounts, acc.accountAndUser.account))) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001043 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001044 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001045 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 for (AuthorityInfo auth : acc.authorities.values()) {
1047 removing.put(auth.ident, auth);
1048 }
1049 accIt.remove();
1050 }
1051 }
Costin Manolache360e4542009-09-04 13:36:04 -07001052
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 // Clean out all data structures.
1054 int i = removing.size();
1055 if (i > 0) {
1056 while (i > 0) {
1057 i--;
1058 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001059 AuthorityInfo auth = removing.valueAt(i);
1060 if (mAuthorityRemovedListener != null) {
1061 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1062 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001063 mAuthorities.remove(ident);
1064 int j = mSyncStatus.size();
1065 while (j > 0) {
1066 j--;
1067 if (mSyncStatus.keyAt(j) == ident) {
1068 mSyncStatus.remove(mSyncStatus.keyAt(j));
1069 }
1070 }
1071 j = mSyncHistory.size();
1072 while (j > 0) {
1073 j--;
1074 if (mSyncHistory.get(j).authorityId == ident) {
1075 mSyncHistory.remove(j);
1076 }
1077 }
1078 }
1079 writeAccountInfoLocked();
1080 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001081 writeStatisticsLocked();
1082 }
1083 }
1084 }
1085
1086 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001087 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1088 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001089 */
Fred Quintana918339a2010-10-05 14:00:39 -07001090 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1091 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001092 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001093 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001094 Slog.v(TAG, "setActiveSync: account="
1095 + " auth=" + activeSyncContext.mSyncOperation.target
1096 + " src=" + activeSyncContext.mSyncOperation.syncSource
1097 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001099 final EndPoint info = activeSyncContext.mSyncOperation.target;
1100 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1101 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001102 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001103 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001104 syncInfo = new SyncInfo(
1105 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001106 authorityInfo.target.account,
1107 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001108 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001109 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001110 }
Varun Shahfe009ec2019-04-29 14:26:45 -07001111 reportActiveChange(activeSyncContext.mSyncOperation.target.userId);
Fred Quintana918339a2010-10-05 14:00:39 -07001112 return syncInfo;
1113 }
1114
1115 /**
1116 * Called to indicate that a previously active sync is no longer active.
1117 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001118 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001119 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001121 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001122 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001123 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001124 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001125 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001126 }
1127
Varun Shahfe009ec2019-04-29 14:26:45 -07001128 reportActiveChange(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001129 }
1130
1131 /**
1132 * To allow others to send active change reports, to poke clients.
1133 */
Varun Shahfe009ec2019-04-29 14:26:45 -07001134 public void reportActiveChange(int userId) {
1135 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 }
Costin Manolache360e4542009-09-04 13:36:04 -07001137
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001139 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001140 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001141 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 long id;
1143 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001144 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001145 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001146 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001147 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 if (authority == null) {
1149 return -1;
1150 }
1151 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001152 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 item.authorityId = authority.ident;
1154 item.historyId = mNextHistoryId++;
1155 if (mNextHistoryId < 0) mNextHistoryId = 0;
1156 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001157 item.source = op.syncSource;
1158 item.reason = op.reason;
1159 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001161 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001162 mSyncHistory.add(0, item);
1163 while (mSyncHistory.size() > MAX_HISTORY) {
1164 mSyncHistory.remove(mSyncHistory.size()-1);
1165 }
1166 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001167 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001168 }
Costin Manolache360e4542009-09-04 13:36:04 -07001169
Varun Shahfe009ec2019-04-29 14:26:45 -07001170 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, op.target.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
1173
Fred Quintana77c560f2010-03-29 22:20:26 -07001174 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Varun Shahfe009ec2019-04-29 14:26:45 -07001175 long downstreamActivity, long upstreamActivity, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001177 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001178 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001179 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 SyncHistoryItem item = null;
1181 int i = mSyncHistory.size();
1182 while (i > 0) {
1183 i--;
1184 item = mSyncHistory.get(i);
1185 if (item.historyId == historyId) {
1186 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001188 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
Costin Manolache360e4542009-09-04 13:36:04 -07001190
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001192 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001193 return;
1194 }
Costin Manolache360e4542009-09-04 13:36:04 -07001195
Dianne Hackborn231cc602009-04-27 17:10:36 -07001196 item.elapsedTime = elapsedTime;
1197 item.event = EVENT_STOP;
1198 item.mesg = resultMessage;
1199 item.downstreamActivity = downstreamActivity;
1200 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001201
Dianne Hackborn231cc602009-04-27 17:10:36 -07001202 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001203
Makoto Onuki94986212018-04-11 16:24:46 -07001204 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1205
1206 status.totalStats.numSyncs++;
1207 status.todayStats.numSyncs++;
1208 status.totalStats.totalElapsedTime += elapsedTime;
1209 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001210 switch (item.source) {
1211 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001212 status.totalStats.numSourceLocal++;
1213 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 break;
1215 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001216 status.totalStats.numSourcePoll++;
1217 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 break;
1219 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001220 status.totalStats.numSourceUser++;
1221 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001222 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001223 case SOURCE_OTHER:
1224 status.totalStats.numSourceOther++;
1225 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001227 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001228 status.totalStats.numSourcePeriodic++;
1229 status.todayStats.numSourcePeriodic++;
1230 break;
1231 case SOURCE_FEED:
1232 status.totalStats.numSourceFeed++;
1233 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001234 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 }
Costin Manolache360e4542009-09-04 13:36:04 -07001236
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001238 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 if (mDayStats[0] == null) {
1240 mDayStats[0] = new DayStats(day);
1241 } else if (day != mDayStats[0].day) {
1242 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1243 mDayStats[0] = new DayStats(day);
1244 writeStatisticsNow = true;
1245 } else if (mDayStats[0] == null) {
1246 }
1247 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001248
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 final long lastSyncTime = (item.eventTime + elapsedTime);
1250 boolean writeStatusNow = false;
1251 if (MESG_SUCCESS.equals(resultMessage)) {
1252 // - if successful, update the successful columns
1253 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1254 writeStatusNow = true;
1255 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001256 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001257 ds.successCount++;
1258 ds.successTime += elapsedTime;
1259 } else if (!MESG_CANCELED.equals(resultMessage)) {
1260 if (status.lastFailureTime == 0) {
1261 writeStatusNow = true;
1262 }
Makoto Onuki94986212018-04-11 16:24:46 -07001263 status.totalStats.numFailures++;
1264 status.todayStats.numFailures++;
1265
Makoto Onukif74cf942018-04-16 17:04:58 -07001266 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1267
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 ds.failureCount++;
1269 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001270 } else {
1271 // Cancel
1272 status.totalStats.numCancels++;
1273 status.todayStats.numCancels++;
1274 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001275 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001276 final StringBuilder event = new StringBuilder();
1277 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1278 + " Elapsed=");
1279 SyncManager.formatDurationHMS(event, elapsedTime);
1280 event.append(" Reason=");
1281 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001282 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1283 event.append(" Exemption=");
1284 switch (item.syncExemptionFlag) {
1285 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1286 event.append("fg");
1287 break;
1288 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1289 event.append("top");
1290 break;
1291 default:
1292 event.append(item.syncExemptionFlag);
1293 break;
1294 }
1295 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001296 event.append(" Extras=");
1297 SyncOperation.extrasToStringBuilder(item.extras, event);
1298
1299 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001300
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 if (writeStatusNow) {
1302 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001303 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1304 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 WRITE_STATUS_DELAY);
1306 }
1307 if (writeStatisticsNow) {
1308 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001309 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1310 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001312 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001313 }
Costin Manolache360e4542009-09-04 13:36:04 -07001314
Varun Shahfe009ec2019-04-29 14:26:45 -07001315 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001316 }
1317
1318 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001319 * Return a list of the currently active syncs. Note that the returned
1320 * items are the real, live active sync objects, so be careful what you do
1321 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001322 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001323 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001324 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001325 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001326 }
1327 }
Costin Manolache360e4542009-09-04 13:36:04 -07001328
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001330 * @param userId Id of user to return current sync info.
1331 * @param canAccessAccounts Determines whether to redact Account information from the result.
1332 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001333 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001334 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001335 synchronized (mAuthorities) {
1336 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1337 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1338 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001339 SyncInfo copy;
1340 if (!canAccessAccounts) {
1341 copy = SyncInfo.createAccountRedacted(
1342 sync.authorityId, sync.authority, sync.startTime);
1343 } else {
1344 copy = new SyncInfo(sync);
1345 }
1346 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001347 }
1348 return syncsCopy;
1349 }
1350 }
1351
1352 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1353 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1354 if (syncs == null) {
1355 syncs = new ArrayList<SyncInfo>();
1356 mCurrentSyncs.put(userId, syncs);
1357 }
1358 return syncs;
1359 }
1360
1361 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001362 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001363 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001364 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001365 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001366 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001367 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001368 true /* write to storage if this results in a change */);
1369 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1370 }
1371 }
1372
1373 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001374 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001375 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001376 * @param info the endpoint target we are querying status info for.
1377 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001379 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001380 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001381 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001382 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001383 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001385 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001386 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001387 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001388 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001389 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001390 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001391 }
1392 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001393 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 }
1395 }
Costin Manolache360e4542009-09-04 13:36:04 -07001396
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001397 /** Return true if the pending status is true of any matching authorities. */
1398 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001399 synchronized (mAuthorities) {
1400 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001401 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001402 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001403 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1404 if (ainfo == null) {
1405 continue;
1406 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001407 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001408 continue;
1409 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001410 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001411 return true;
1412 }
1413 }
1414 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
1416 }
1417
1418 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001419 * Return an array of the current sync status for all authorities. Note
1420 * that the objects inside the array are the real, live status objects,
1421 * so be careful what you do with them.
1422 */
1423 public ArrayList<SyncHistoryItem> getSyncHistory() {
1424 synchronized (mAuthorities) {
1425 final int N = mSyncHistory.size();
1426 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1427 for (int i=0; i<N; i++) {
1428 items.add(mSyncHistory.get(i));
1429 }
1430 return items;
1431 }
1432 }
Costin Manolache360e4542009-09-04 13:36:04 -07001433
Dianne Hackborn231cc602009-04-27 17:10:36 -07001434 /**
1435 * Return an array of the current per-day statistics. Note
1436 * that the objects inside the array are the real, live status objects,
1437 * so be careful what you do with them.
1438 */
1439 public DayStats[] getDayStatistics() {
1440 synchronized (mAuthorities) {
1441 DayStats[] ds = new DayStats[mDayStats.length];
1442 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1443 return ds;
1444 }
1445 }
Costin Manolache360e4542009-09-04 13:36:04 -07001446
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001447 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1448 AuthorityInfo authorityInfo) {
1449 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1450 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1451 }
1452
Dianne Hackborn55280a92009-05-07 15:53:46 -07001453 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 mCal.setTimeInMillis(System.currentTimeMillis());
1455 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1456 if (mYear != mCal.get(Calendar.YEAR)) {
1457 mYear = mCal.get(Calendar.YEAR);
1458 mCal.clear();
1459 mCal.set(Calendar.YEAR, mYear);
1460 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1461 }
1462 return dayOfYear + mYearInDays;
1463 }
Costin Manolache360e4542009-09-04 13:36:04 -07001464
Dianne Hackborn231cc602009-04-27 17:10:36 -07001465 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001466 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001467 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001468 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001469 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001470 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001472 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001473 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1474 AccountInfo accountInfo = mAccounts.get(au);
1475 if (accountInfo == null) {
1476 if (tag != null) {
1477 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1478 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001479 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001480 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001481 return null;
1482 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001483 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1484 if (authority == null) {
1485 if (tag != null) {
1486 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1487 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1488 }
1489 }
1490 return null;
1491 }
1492 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001493 }
Costin Manolache360e4542009-09-04 13:36:04 -07001494
Matthew Williamsfa774182013-06-18 15:44:11 -07001495 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001496 * @param info info identifying target.
1497 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001498 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001499 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001500 * exists.
1501 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001502 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1503 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001504 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1505 AccountInfo account = mAccounts.get(au);
1506 if (account == null) {
1507 account = new AccountInfo(au);
1508 mAccounts.put(au, account);
1509 }
1510 authority = account.authorities.get(info.provider);
1511 if (authority == null) {
1512 authority = createAuthorityLocked(info, ident, doWrite);
1513 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001514 }
1515 return authority;
1516 }
1517
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001518 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1519 AuthorityInfo authority;
1520 if (ident < 0) {
1521 ident = mNextAuthorityId;
1522 mNextAuthorityId++;
1523 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001525 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001526 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001527 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001528 authority = new AuthorityInfo(info, ident);
1529 mAuthorities.put(ident, authority);
1530 if (doWrite) {
1531 writeAccountInfoLocked();
1532 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001533 return authority;
1534 }
Costin Manolache360e4542009-09-04 13:36:04 -07001535
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001536 public void removeAuthority(EndPoint info) {
1537 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001538 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001539 }
1540 }
1541
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001542
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001543 /**
1544 * Remove an authority associated with a provider. Needs to be a standalone function for
1545 * backward compatibility.
1546 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001547 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001548 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001549 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001550 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001551 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1552 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001553 if (mAuthorityRemovedListener != null) {
1554 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1555 }
Fred Quintanafb084402010-03-23 17:57:03 -07001556 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001557 if (doWrite) {
1558 writeAccountInfoLocked();
1559 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001560 }
1561 }
1562 }
1563
Dianne Hackborn231cc602009-04-27 17:10:36 -07001564 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1565 SyncStatusInfo status = mSyncStatus.get(authorityId);
1566 if (status == null) {
1567 status = new SyncStatusInfo(authorityId);
1568 mSyncStatus.put(authorityId, status);
1569 }
1570 return status;
1571 }
Costin Manolache360e4542009-09-04 13:36:04 -07001572
Dianne Hackborn55280a92009-05-07 15:53:46 -07001573 public void writeAllState() {
1574 synchronized (mAuthorities) {
1575 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001576 writeStatusLocked();
1577 writeStatisticsLocked();
1578 }
1579 }
Costin Manolache360e4542009-09-04 13:36:04 -07001580
Svet Ganov65712b02016-09-01 10:24:11 -07001581 public boolean shouldGrantSyncAdaptersAccountAccess() {
1582 return mGrantSyncAdaptersAccountAccess;
1583 }
1584
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001586 * public for testing
1587 */
1588 public void clearAndReadState() {
1589 synchronized (mAuthorities) {
1590 mAuthorities.clear();
1591 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001592 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001593 mSyncStatus.clear();
1594 mSyncHistory.clear();
1595
1596 readAccountInfoLocked();
1597 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001598 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001599 writeAccountInfoLocked();
1600 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001601 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001602 }
1603 }
1604
1605 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001606 * Read all account information back in to the initial engine state.
1607 */
1608 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001609 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001610 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001612 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001613 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001614 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001615 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001616 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001617 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001618 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001619 while (eventType != XmlPullParser.START_TAG &&
1620 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001621 eventType = parser.next();
1622 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001623 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001624 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001625 return;
1626 }
1627
Dianne Hackborn231cc602009-04-27 17:10:36 -07001628 String tagName = parser.getName();
1629 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001630 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001631 String versionString = parser.getAttributeValue(null, "version");
1632 int version;
1633 try {
1634 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1635 } catch (NumberFormatException e) {
1636 version = 0;
1637 }
Svet Ganov65712b02016-09-01 10:24:11 -07001638
1639 if (version < 3) {
1640 mGrantSyncAdaptersAccountAccess = true;
1641 }
1642
Amith Yamasani04e0d262012-02-14 11:50:53 -08001643 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001644 try {
1645 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1646 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1647 } catch (NumberFormatException e) {
1648 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001649 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001650 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1651 try {
1652 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1653 } catch (NumberFormatException e) {
1654 mSyncRandomOffset = 0;
1655 }
1656 if (mSyncRandomOffset == 0) {
1657 Random random = new Random(System.currentTimeMillis());
1658 mSyncRandomOffset = random.nextInt(86400);
1659 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001660 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001661 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001662 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001663 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001664 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001665 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001666 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001667 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001668 if (parser.getDepth() == 2) {
1669 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001670 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001671 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001672 if (authority != null) {
1673 if (authority.ident > highestAuthorityId) {
1674 highestAuthorityId = authority.ident;
1675 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001676 } else {
1677 EventLog.writeEvent(0x534e4554, "26513719", -1,
1678 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001679 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001680 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1681 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001682 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001683 } else if (parser.getDepth() == 3) {
1684 if ("periodicSync".equals(tagName) && authority != null) {
1685 periodicSync = parsePeriodicSync(parser, authority);
1686 }
1687 } else if (parser.getDepth() == 4 && periodicSync != null) {
1688 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001689 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001690 }
1691 }
1692 }
1693 eventType = parser.next();
1694 } while (eventType != XmlPullParser.END_DOCUMENT);
1695 }
1696 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001697 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001698 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001699 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001700 if (fis == null) Slog.i(TAG, "No initial accounts");
1701 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001702 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001703 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001704 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001705 if (fis != null) {
1706 try {
1707 fis.close();
1708 } catch (java.io.IOException e1) {
1709 }
1710 }
1711 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001712
Fred Quintana77c560f2010-03-29 22:20:26 -07001713 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001714 }
Costin Manolache360e4542009-09-04 13:36:04 -07001715
Fred Quintanafb084402010-03-23 17:57:03 -07001716 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001717 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1718 * pending.xml was used starting in KLP.
1719 * @param syncDir directory where the sync files are located.
1720 */
1721 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1722 File file = new File(syncDir, "pending.bin");
1723 if (!file.exists()) {
1724 return;
1725 } else {
1726 file.delete();
1727 }
1728 }
1729
1730 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001731 * some authority names have changed. copy over their settings and delete the old ones
1732 * @return true if a change was made
1733 */
1734 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1735 boolean writeNeeded = false;
1736
1737 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1738 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001739 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001740 AuthorityInfo authority = mAuthorities.valueAt(i);
1741 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001742 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001743 if (newAuthorityName == null) {
1744 continue;
1745 }
1746
1747 // remember this authority so we can remove it later. we can't remove it
1748 // now without messing up this loop iteration
1749 authoritiesToRemove.add(authority);
1750
1751 // this authority isn't enabled, no need to copy it to the new authority name since
1752 // the default is "disabled"
1753 if (!authority.enabled) {
1754 continue;
1755 }
1756
1757 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001758 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001759 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001760 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001761 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001762 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001763 continue;
1764 }
1765
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001766 AuthorityInfo newAuthority =
1767 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001768 newAuthority.enabled = true;
1769 writeNeeded = true;
1770 }
1771
1772 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001773 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001774 authorityInfo.target.account,
1775 authorityInfo.target.userId,
1776 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001777 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001778 writeNeeded = true;
1779 }
1780
1781 return writeNeeded;
1782 }
1783
Amith Yamasani04e0d262012-02-14 11:50:53 -08001784 private void parseListenForTickles(XmlPullParser parser) {
1785 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1786 int userId = 0;
1787 try {
1788 userId = Integer.parseInt(user);
1789 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001790 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001791 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001792 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001793 }
1794 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1795 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1796 mMasterSyncAutomatically.put(userId, listen);
1797 }
1798
Suprabh Shukla042a4782017-05-12 15:26:54 -07001799 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1800 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001801 AuthorityInfo authority = null;
1802 int id = -1;
1803 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001804 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001805 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001806 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001807 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001808 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001809 }
1810 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001811 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001812 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001813 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001814 String accountName = parser.getAttributeValue(null, "account");
1815 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001816 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001817 String packageName = parser.getAttributeValue(null, "package");
1818 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001819 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001820 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001821 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001822 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001823 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001824 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001825 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001826 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001827 + " account=" + accountName
1828 + " accountType=" + accountType
1829 + " auth=" + authorityName
1830 + " package=" + packageName
1831 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001832 + " user=" + userId
1833 + " enabled=" + enabled
1834 + " syncable=" + syncable);
1835 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001836 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001837 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001838 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001839 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001840 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001841 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001842 new Account(accountName, accountType),
1843 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001844 if (validator.isAccountValid(info.account, userId)
1845 && validator.isAuthorityValid(authorityName, userId)) {
1846 authority = getOrCreateAuthorityLocked(info, id, false);
1847 // If the version is 0 then we are upgrading from a file format that did not
1848 // know about periodic syncs. In that case don't clear the list since we
1849 // want the default, which is a daily periodic sync.
1850 // Otherwise clear out this default list since we will populate it later
1851 // with
1852 // the periodic sync descriptions that are read from the configuration file.
1853 if (version > 0) {
1854 authority.periodicSyncs.clear();
1855 }
1856 } else {
1857 EventLog.writeEvent(0x534e4554, "35028827", -1,
1858 "account:" + info.account + " provider:" + authorityName + " user:"
1859 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001860 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001861 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001862 }
1863 if (authority != null) {
1864 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001865 try {
1866 authority.syncable = (syncable == null) ?
1867 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1868 } catch (NumberFormatException e) {
1869 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1870 // format.
1871 if ("unknown".equals(syncable)) {
1872 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1873 } else {
1874 authority.syncable = Boolean.parseBoolean(syncable) ?
1875 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1876 }
1877
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001878 }
1879 } else {
Makoto Onukidecc5ba2019-01-15 09:34:05 -08001880 Slog.w(TAG, "Failure adding authority:"
1881 + " auth=" + authorityName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001882 + " enabled=" + enabled
1883 + " syncable=" + syncable);
1884 }
1885 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001886 return authority;
1887 }
1888
Matthew Williamsfa774182013-06-18 15:44:11 -07001889 /**
1890 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1891 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001892 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001893 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001894 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001895 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001896 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001897 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001898 try {
1899 period = Long.parseLong(periodValue);
1900 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001901 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001902 return null;
1903 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001904 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001905 return null;
1906 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001907 try {
1908 flextime = Long.parseLong(flexValue);
1909 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001910 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001911 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001912 + ", using default: "
1913 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001914 } catch (NullPointerException expected) {
1915 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001916 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1917 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001918 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001919 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001920 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001921 new PeriodicSync(authorityInfo.target.account,
1922 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001923 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001924 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001925 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001926 return periodicSync;
1927 }
1928
Matthew Williamsfa774182013-06-18 15:44:11 -07001929 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001930 String name = parser.getAttributeValue(null, "name");
1931 String type = parser.getAttributeValue(null, "type");
1932 String value1 = parser.getAttributeValue(null, "value1");
1933 String value2 = parser.getAttributeValue(null, "value2");
1934
1935 try {
1936 if ("long".equals(type)) {
1937 extras.putLong(name, Long.parseLong(value1));
1938 } else if ("integer".equals(type)) {
1939 extras.putInt(name, Integer.parseInt(value1));
1940 } else if ("double".equals(type)) {
1941 extras.putDouble(name, Double.parseDouble(value1));
1942 } else if ("float".equals(type)) {
1943 extras.putFloat(name, Float.parseFloat(value1));
1944 } else if ("boolean".equals(type)) {
1945 extras.putBoolean(name, Boolean.parseBoolean(value1));
1946 } else if ("string".equals(type)) {
1947 extras.putString(name, value1);
1948 } else if ("account".equals(type)) {
1949 extras.putParcelable(name, new Account(value1, value2));
1950 }
1951 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001952 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001953 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001954 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001955 }
1956 }
1957
Dianne Hackborn231cc602009-04-27 17:10:36 -07001958 /**
1959 * Write all account information to the account file.
1960 */
1961 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001962 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001963 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001964 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001966
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 try {
1968 fos = mAccountInfoFile.startWrite();
1969 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001970 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001971 out.startDocument(null, true);
1972 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001973
Dianne Hackborn231cc602009-04-27 17:10:36 -07001974 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001975 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001976 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001977 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978
1979 // Write the Sync Automatically flags for each user
1980 final int M = mMasterSyncAutomatically.size();
1981 for (int m = 0; m < M; m++) {
1982 int userId = mMasterSyncAutomatically.keyAt(m);
1983 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1984 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1985 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1986 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1987 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001988 }
Costin Manolache360e4542009-09-04 13:36:04 -07001989
Dianne Hackborn231cc602009-04-27 17:10:36 -07001990 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001991 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001992 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001993 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 out.startTag(null, "authority");
1995 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001996 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001997 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001998 out.attribute(null, "account", info.account.name);
1999 out.attribute(null, "type", info.account.type);
2000 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07002001 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 out.endTag(null, "authority");
2003 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 mAccountInfoFile.finishWrite(fos);
2007 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002008 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 if (fos != null) {
2010 mAccountInfoFile.failWrite(fos);
2011 }
2012 }
2013 }
Costin Manolache360e4542009-09-04 13:36:04 -07002014
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 public static final int STATUS_FILE_END = 0;
2016 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002017
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 /**
2019 * Read all sync status back in to the initial engine state.
2020 */
2021 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002022 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002023 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002024 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002025 try {
2026 byte[] data = mStatusFile.readFully();
2027 Parcel in = Parcel.obtain();
2028 in.unmarshall(data, 0, data.length);
2029 in.setDataPosition(0);
2030 int token;
2031 while ((token=in.readInt()) != STATUS_FILE_END) {
2032 if (token == STATUS_FILE_ITEM) {
2033 SyncStatusInfo status = new SyncStatusInfo(in);
2034 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2035 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002036 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002037 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002038 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002039 mSyncStatus.put(status.authorityId, status);
2040 }
2041 } else {
2042 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002043 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002044 break;
2045 }
2046 }
2047 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002048 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002049 }
2050 }
Costin Manolache360e4542009-09-04 13:36:04 -07002051
Dianne Hackborn231cc602009-04-27 17:10:36 -07002052 /**
2053 * Write all sync status to the sync status file.
2054 */
2055 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002056 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002057 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002058 }
Costin Manolache360e4542009-09-04 13:36:04 -07002059
Dianne Hackborn231cc602009-04-27 17:10:36 -07002060 // The file is being written, so we don't need to have a scheduled
2061 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002062 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002063
Dianne Hackborn231cc602009-04-27 17:10:36 -07002064 FileOutputStream fos = null;
2065 try {
2066 fos = mStatusFile.startWrite();
2067 Parcel out = Parcel.obtain();
2068 final int N = mSyncStatus.size();
2069 for (int i=0; i<N; i++) {
2070 SyncStatusInfo status = mSyncStatus.valueAt(i);
2071 out.writeInt(STATUS_FILE_ITEM);
2072 status.writeToParcel(out, 0);
2073 }
2074 out.writeInt(STATUS_FILE_END);
2075 fos.write(out.marshall());
2076 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002077
Dianne Hackborn231cc602009-04-27 17:10:36 -07002078 mStatusFile.finishWrite(fos);
2079 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002080 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002081 if (fos != null) {
2082 mStatusFile.failWrite(fos);
2083 }
2084 }
2085 }
Costin Manolache360e4542009-09-04 13:36:04 -07002086
Makoto Onuki61283ec2018-01-31 17:22:36 -08002087 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002088 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002089 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2090 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002091 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002092 syncExemptionFlag, callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002093 } else {
2094 SyncRequest.Builder req =
2095 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002096 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002097 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002098 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002099 ContentResolver.requestSync(req.build());
2100 }
2101 }
2102
Alon Albert57286f92012-10-09 14:21:38 -07002103 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onukie183a402018-08-29 11:46:41 -07002104 Bundle extras, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002105 // If this is happening in the system process, then call the syncrequest listener
2106 // to make a request back to the SyncManager directly.
2107 // If this is probably a test instance, then call back through the ContentResolver
2108 // which will know which userId to apply based on the Binder id.
2109 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2110 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002111 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002112 new EndPoint(account, authority, userId),
Makoto Onukie183a402018-08-29 11:46:41 -07002113 reason, extras, syncExemptionFlag, callingUid, callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002114 } else {
2115 ContentResolver.requestSync(account, authority, extras);
2116 }
2117 }
2118
Dianne Hackborn231cc602009-04-27 17:10:36 -07002119 public static final int STATISTICS_FILE_END = 0;
2120 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2121 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002122
Dianne Hackborn231cc602009-04-27 17:10:36 -07002123 /**
2124 * Read all sync statistics back in to the initial engine state.
2125 */
2126 private void readStatisticsLocked() {
2127 try {
2128 byte[] data = mStatisticsFile.readFully();
2129 Parcel in = Parcel.obtain();
2130 in.unmarshall(data, 0, data.length);
2131 in.setDataPosition(0);
2132 int token;
2133 int index = 0;
2134 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2135 if (token == STATISTICS_FILE_ITEM
2136 || token == STATISTICS_FILE_ITEM_OLD) {
2137 int day = in.readInt();
2138 if (token == STATISTICS_FILE_ITEM_OLD) {
2139 day = day - 2009 + 14245; // Magic!
2140 }
2141 DayStats ds = new DayStats(day);
2142 ds.successCount = in.readInt();
2143 ds.successTime = in.readLong();
2144 ds.failureCount = in.readInt();
2145 ds.failureTime = in.readLong();
2146 if (index < mDayStats.length) {
2147 mDayStats[index] = ds;
2148 index++;
2149 }
2150 } else {
2151 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002152 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002153 break;
2154 }
2155 }
2156 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002157 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002158 }
2159 }
Costin Manolache360e4542009-09-04 13:36:04 -07002160
Dianne Hackborn231cc602009-04-27 17:10:36 -07002161 /**
2162 * Write all sync statistics to the sync status file.
2163 */
2164 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002165 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002166 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002167 }
Costin Manolache360e4542009-09-04 13:36:04 -07002168
Dianne Hackborn231cc602009-04-27 17:10:36 -07002169 // The file is being written, so we don't need to have a scheduled
2170 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002171 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002172
Dianne Hackborn231cc602009-04-27 17:10:36 -07002173 FileOutputStream fos = null;
2174 try {
2175 fos = mStatisticsFile.startWrite();
2176 Parcel out = Parcel.obtain();
2177 final int N = mDayStats.length;
2178 for (int i=0; i<N; i++) {
2179 DayStats ds = mDayStats[i];
2180 if (ds == null) {
2181 break;
2182 }
2183 out.writeInt(STATISTICS_FILE_ITEM);
2184 out.writeInt(ds.day);
2185 out.writeInt(ds.successCount);
2186 out.writeLong(ds.successTime);
2187 out.writeInt(ds.failureCount);
2188 out.writeLong(ds.failureTime);
2189 }
2190 out.writeInt(STATISTICS_FILE_END);
2191 fos.write(out.marshall());
2192 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002193
Dianne Hackborn231cc602009-04-27 17:10:36 -07002194 mStatisticsFile.finishWrite(fos);
2195 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002196 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002197 if (fos != null) {
2198 mStatisticsFile.failWrite(fos);
2199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002202
2203 /**
Marvin Paula6533252014-11-24 12:57:48 -08002204 * Let the BackupManager know that account sync settings have changed. This will trigger
2205 * {@link com.android.server.backup.SystemBackupAgent} to run.
2206 */
2207 public void queueBackup() {
2208 BackupManager.dataChanged("android");
2209 }
Makoto Onuki94986212018-04-11 16:24:46 -07002210
2211 public void setClockValid() {
2212 if (!mIsClockValid) {
2213 mIsClockValid = true;
2214 Slog.w(TAG, "Clock is valid now.");
2215 }
2216 }
2217
2218 public boolean isClockValid() {
2219 return mIsClockValid;
2220 }
2221
2222 public void resetTodayStats(boolean force) {
2223 if (force) {
2224 Log.w(TAG, "Force resetting today stats.");
2225 }
2226 synchronized (mAuthorities) {
2227 final int N = mSyncStatus.size();
2228 for (int i = 0; i < N; i++) {
2229 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2230 cur.maybeResetTodayStats(isClockValid(), force);
2231 }
2232 writeStatusLocked();
2233 }
2234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235}