blob: e09c661c627b06d6d0c9124ba2e70c19c0f8f198 [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 Onuki76f0e0d2019-05-22 12:26:56 -07001030 public void removeStaleAccounts(@Nullable Account[] currentAccounts, 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 Onuki76f0e0d2019-05-22 12:26:56 -07001039 if (acc.accountAndUser.userId != userId) {
1040 continue; // Irrelevant user.
1041 }
1042 if ((currentAccounts == null)
1043 || !ArrayUtils.contains(currentAccounts, acc.accountAndUser.account)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001045 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001046 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001047 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 for (AuthorityInfo auth : acc.authorities.values()) {
1049 removing.put(auth.ident, auth);
1050 }
1051 accIt.remove();
1052 }
1053 }
Costin Manolache360e4542009-09-04 13:36:04 -07001054
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 // Clean out all data structures.
1056 int i = removing.size();
1057 if (i > 0) {
1058 while (i > 0) {
1059 i--;
1060 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001061 AuthorityInfo auth = removing.valueAt(i);
1062 if (mAuthorityRemovedListener != null) {
1063 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1064 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 mAuthorities.remove(ident);
1066 int j = mSyncStatus.size();
1067 while (j > 0) {
1068 j--;
1069 if (mSyncStatus.keyAt(j) == ident) {
1070 mSyncStatus.remove(mSyncStatus.keyAt(j));
1071 }
1072 }
1073 j = mSyncHistory.size();
1074 while (j > 0) {
1075 j--;
1076 if (mSyncHistory.get(j).authorityId == ident) {
1077 mSyncHistory.remove(j);
1078 }
1079 }
1080 }
1081 writeAccountInfoLocked();
1082 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001083 writeStatisticsLocked();
1084 }
1085 }
1086 }
1087
1088 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001089 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1090 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001091 */
Fred Quintana918339a2010-10-05 14:00:39 -07001092 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1093 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001095 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001096 Slog.v(TAG, "setActiveSync: account="
1097 + " auth=" + activeSyncContext.mSyncOperation.target
1098 + " src=" + activeSyncContext.mSyncOperation.syncSource
1099 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001101 final EndPoint info = activeSyncContext.mSyncOperation.target;
1102 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1103 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001104 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001105 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001106 syncInfo = new SyncInfo(
1107 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001108 authorityInfo.target.account,
1109 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001110 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001111 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 }
Varun Shahfe009ec2019-04-29 14:26:45 -07001113 reportActiveChange(activeSyncContext.mSyncOperation.target.userId);
Fred Quintana918339a2010-10-05 14:00:39 -07001114 return syncInfo;
1115 }
1116
1117 /**
1118 * Called to indicate that a previously active sync is no longer active.
1119 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001120 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001121 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001122 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001123 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001124 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001125 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001126 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001127 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001128 }
1129
Varun Shahfe009ec2019-04-29 14:26:45 -07001130 reportActiveChange(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 }
1132
1133 /**
1134 * To allow others to send active change reports, to poke clients.
1135 */
Varun Shahfe009ec2019-04-29 14:26:45 -07001136 public void reportActiveChange(int userId) {
1137 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 }
Costin Manolache360e4542009-09-04 13:36:04 -07001139
Dianne Hackborn231cc602009-04-27 17:10:36 -07001140 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001141 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001143 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001144 long id;
1145 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001146 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001147 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001148 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001149 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 if (authority == null) {
1151 return -1;
1152 }
1153 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001154 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001155 item.authorityId = authority.ident;
1156 item.historyId = mNextHistoryId++;
1157 if (mNextHistoryId < 0) mNextHistoryId = 0;
1158 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001159 item.source = op.syncSource;
1160 item.reason = op.reason;
1161 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001162 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001163 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001164 mSyncHistory.add(0, item);
1165 while (mSyncHistory.size() > MAX_HISTORY) {
1166 mSyncHistory.remove(mSyncHistory.size()-1);
1167 }
1168 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001169 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 }
Costin Manolache360e4542009-09-04 13:36:04 -07001171
Varun Shahfe009ec2019-04-29 14:26:45 -07001172 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, op.target.userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001173 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
1175
Fred Quintana77c560f2010-03-29 22:20:26 -07001176 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Varun Shahfe009ec2019-04-29 14:26:45 -07001177 long downstreamActivity, long upstreamActivity, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001178 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001179 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001180 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001181 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001182 SyncHistoryItem item = null;
1183 int i = mSyncHistory.size();
1184 while (i > 0) {
1185 i--;
1186 item = mSyncHistory.get(i);
1187 if (item.historyId == historyId) {
1188 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001190 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Costin Manolache360e4542009-09-04 13:36:04 -07001192
Dianne Hackborn231cc602009-04-27 17:10:36 -07001193 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001194 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 return;
1196 }
Costin Manolache360e4542009-09-04 13:36:04 -07001197
Dianne Hackborn231cc602009-04-27 17:10:36 -07001198 item.elapsedTime = elapsedTime;
1199 item.event = EVENT_STOP;
1200 item.mesg = resultMessage;
1201 item.downstreamActivity = downstreamActivity;
1202 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001203
Dianne Hackborn231cc602009-04-27 17:10:36 -07001204 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001205
Makoto Onuki94986212018-04-11 16:24:46 -07001206 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1207
1208 status.totalStats.numSyncs++;
1209 status.todayStats.numSyncs++;
1210 status.totalStats.totalElapsedTime += elapsedTime;
1211 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001212 switch (item.source) {
1213 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001214 status.totalStats.numSourceLocal++;
1215 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 break;
1217 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001218 status.totalStats.numSourcePoll++;
1219 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001220 break;
1221 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001222 status.totalStats.numSourceUser++;
1223 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001225 case SOURCE_OTHER:
1226 status.totalStats.numSourceOther++;
1227 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001229 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001230 status.totalStats.numSourcePeriodic++;
1231 status.todayStats.numSourcePeriodic++;
1232 break;
1233 case SOURCE_FEED:
1234 status.totalStats.numSourceFeed++;
1235 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001236 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 }
Costin Manolache360e4542009-09-04 13:36:04 -07001238
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001240 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001241 if (mDayStats[0] == null) {
1242 mDayStats[0] = new DayStats(day);
1243 } else if (day != mDayStats[0].day) {
1244 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1245 mDayStats[0] = new DayStats(day);
1246 writeStatisticsNow = true;
1247 } else if (mDayStats[0] == null) {
1248 }
1249 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001250
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 final long lastSyncTime = (item.eventTime + elapsedTime);
1252 boolean writeStatusNow = false;
1253 if (MESG_SUCCESS.equals(resultMessage)) {
1254 // - if successful, update the successful columns
1255 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1256 writeStatusNow = true;
1257 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001258 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001259 ds.successCount++;
1260 ds.successTime += elapsedTime;
1261 } else if (!MESG_CANCELED.equals(resultMessage)) {
1262 if (status.lastFailureTime == 0) {
1263 writeStatusNow = true;
1264 }
Makoto Onuki94986212018-04-11 16:24:46 -07001265 status.totalStats.numFailures++;
1266 status.todayStats.numFailures++;
1267
Makoto Onukif74cf942018-04-16 17:04:58 -07001268 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1269
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 ds.failureCount++;
1271 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001272 } else {
1273 // Cancel
1274 status.totalStats.numCancels++;
1275 status.todayStats.numCancels++;
1276 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001277 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001278 final StringBuilder event = new StringBuilder();
1279 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1280 + " Elapsed=");
1281 SyncManager.formatDurationHMS(event, elapsedTime);
1282 event.append(" Reason=");
1283 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001284 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1285 event.append(" Exemption=");
1286 switch (item.syncExemptionFlag) {
1287 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1288 event.append("fg");
1289 break;
1290 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1291 event.append("top");
1292 break;
1293 default:
1294 event.append(item.syncExemptionFlag);
1295 break;
1296 }
1297 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001298 event.append(" Extras=");
1299 SyncOperation.extrasToStringBuilder(item.extras, event);
1300
1301 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001302
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 if (writeStatusNow) {
1304 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001305 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1306 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 WRITE_STATUS_DELAY);
1308 }
1309 if (writeStatisticsNow) {
1310 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001311 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1312 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001313 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001314 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 }
Costin Manolache360e4542009-09-04 13:36:04 -07001316
Varun Shahfe009ec2019-04-29 14:26:45 -07001317 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS, userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001318 }
1319
1320 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001321 * Return a list of the currently active syncs. Note that the returned
1322 * items are the real, live active sync objects, so be careful what you do
1323 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001324 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001325 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001326 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001327 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001328 }
1329 }
Costin Manolache360e4542009-09-04 13:36:04 -07001330
Dianne Hackborn231cc602009-04-27 17:10:36 -07001331 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001332 * @param userId Id of user to return current sync info.
1333 * @param canAccessAccounts Determines whether to redact Account information from the result.
1334 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001335 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001336 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001337 synchronized (mAuthorities) {
1338 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1339 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1340 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001341 SyncInfo copy;
1342 if (!canAccessAccounts) {
1343 copy = SyncInfo.createAccountRedacted(
1344 sync.authorityId, sync.authority, sync.startTime);
1345 } else {
1346 copy = new SyncInfo(sync);
1347 }
1348 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001349 }
1350 return syncsCopy;
1351 }
1352 }
1353
1354 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1355 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1356 if (syncs == null) {
1357 syncs = new ArrayList<SyncInfo>();
1358 mCurrentSyncs.put(userId, syncs);
1359 }
1360 return syncs;
1361 }
1362
1363 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001364 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001365 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001366 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001367 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001368 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001369 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001370 true /* write to storage if this results in a change */);
1371 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1372 }
1373 }
1374
1375 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001376 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001377 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001378 * @param info the endpoint target we are querying status info for.
1379 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001380 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001381 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001382 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001383 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001384 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001385 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001387 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001388 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001389 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001390 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001391 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001392 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001393 }
1394 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001395 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001396 }
1397 }
Costin Manolache360e4542009-09-04 13:36:04 -07001398
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001399 /** Return true if the pending status is true of any matching authorities. */
1400 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001401 synchronized (mAuthorities) {
1402 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001403 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001404 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001405 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1406 if (ainfo == null) {
1407 continue;
1408 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001409 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001410 continue;
1411 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001412 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 return true;
1414 }
1415 }
1416 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
1418 }
1419
1420 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001421 * Return an array of the current sync status for all authorities. Note
1422 * that the objects inside the array are the real, live status objects,
1423 * so be careful what you do with them.
1424 */
1425 public ArrayList<SyncHistoryItem> getSyncHistory() {
1426 synchronized (mAuthorities) {
1427 final int N = mSyncHistory.size();
1428 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1429 for (int i=0; i<N; i++) {
1430 items.add(mSyncHistory.get(i));
1431 }
1432 return items;
1433 }
1434 }
Costin Manolache360e4542009-09-04 13:36:04 -07001435
Dianne Hackborn231cc602009-04-27 17:10:36 -07001436 /**
1437 * Return an array of the current per-day statistics. Note
1438 * that the objects inside the array are the real, live status objects,
1439 * so be careful what you do with them.
1440 */
1441 public DayStats[] getDayStatistics() {
1442 synchronized (mAuthorities) {
1443 DayStats[] ds = new DayStats[mDayStats.length];
1444 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1445 return ds;
1446 }
1447 }
Costin Manolache360e4542009-09-04 13:36:04 -07001448
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001449 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1450 AuthorityInfo authorityInfo) {
1451 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1452 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1453 }
1454
Dianne Hackborn55280a92009-05-07 15:53:46 -07001455 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001456 mCal.setTimeInMillis(System.currentTimeMillis());
1457 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1458 if (mYear != mCal.get(Calendar.YEAR)) {
1459 mYear = mCal.get(Calendar.YEAR);
1460 mCal.clear();
1461 mCal.set(Calendar.YEAR, mYear);
1462 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1463 }
1464 return dayOfYear + mYearInDays;
1465 }
Costin Manolache360e4542009-09-04 13:36:04 -07001466
Dianne Hackborn231cc602009-04-27 17:10:36 -07001467 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001468 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001469 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001470 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001471 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001472 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001473 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001474 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001475 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1476 AccountInfo accountInfo = mAccounts.get(au);
1477 if (accountInfo == null) {
1478 if (tag != null) {
1479 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1480 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001481 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001482 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 return null;
1484 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001485 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1486 if (authority == null) {
1487 if (tag != null) {
1488 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1489 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1490 }
1491 }
1492 return null;
1493 }
1494 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001495 }
Costin Manolache360e4542009-09-04 13:36:04 -07001496
Matthew Williamsfa774182013-06-18 15:44:11 -07001497 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001498 * @param info info identifying target.
1499 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001500 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001501 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001502 * exists.
1503 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001504 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1505 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001506 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1507 AccountInfo account = mAccounts.get(au);
1508 if (account == null) {
1509 account = new AccountInfo(au);
1510 mAccounts.put(au, account);
1511 }
1512 authority = account.authorities.get(info.provider);
1513 if (authority == null) {
1514 authority = createAuthorityLocked(info, ident, doWrite);
1515 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001516 }
1517 return authority;
1518 }
1519
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001520 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1521 AuthorityInfo authority;
1522 if (ident < 0) {
1523 ident = mNextAuthorityId;
1524 mNextAuthorityId++;
1525 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001527 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001528 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001529 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001530 authority = new AuthorityInfo(info, ident);
1531 mAuthorities.put(ident, authority);
1532 if (doWrite) {
1533 writeAccountInfoLocked();
1534 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001535 return authority;
1536 }
Costin Manolache360e4542009-09-04 13:36:04 -07001537
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001538 public void removeAuthority(EndPoint info) {
1539 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001540 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001541 }
1542 }
1543
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001544
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001545 /**
1546 * Remove an authority associated with a provider. Needs to be a standalone function for
1547 * backward compatibility.
1548 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001549 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001550 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001551 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001552 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001553 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1554 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001555 if (mAuthorityRemovedListener != null) {
1556 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1557 }
Fred Quintanafb084402010-03-23 17:57:03 -07001558 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001559 if (doWrite) {
1560 writeAccountInfoLocked();
1561 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001562 }
1563 }
1564 }
1565
Dianne Hackborn231cc602009-04-27 17:10:36 -07001566 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1567 SyncStatusInfo status = mSyncStatus.get(authorityId);
1568 if (status == null) {
1569 status = new SyncStatusInfo(authorityId);
1570 mSyncStatus.put(authorityId, status);
1571 }
1572 return status;
1573 }
Costin Manolache360e4542009-09-04 13:36:04 -07001574
Dianne Hackborn55280a92009-05-07 15:53:46 -07001575 public void writeAllState() {
1576 synchronized (mAuthorities) {
1577 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001578 writeStatusLocked();
1579 writeStatisticsLocked();
1580 }
1581 }
Costin Manolache360e4542009-09-04 13:36:04 -07001582
Svet Ganov65712b02016-09-01 10:24:11 -07001583 public boolean shouldGrantSyncAdaptersAccountAccess() {
1584 return mGrantSyncAdaptersAccountAccess;
1585 }
1586
Dianne Hackborn231cc602009-04-27 17:10:36 -07001587 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001588 * public for testing
1589 */
1590 public void clearAndReadState() {
1591 synchronized (mAuthorities) {
1592 mAuthorities.clear();
1593 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001594 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001595 mSyncStatus.clear();
1596 mSyncHistory.clear();
1597
1598 readAccountInfoLocked();
1599 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001600 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001601 writeAccountInfoLocked();
1602 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001603 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001604 }
1605 }
1606
1607 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001608 * Read all account information back in to the initial engine state.
1609 */
1610 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001611 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001612 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001614 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001615 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001616 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001617 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001618 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001619 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001620 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001621 while (eventType != XmlPullParser.START_TAG &&
1622 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001623 eventType = parser.next();
1624 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001625 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001626 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001627 return;
1628 }
1629
Dianne Hackborn231cc602009-04-27 17:10:36 -07001630 String tagName = parser.getName();
1631 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001632 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001633 String versionString = parser.getAttributeValue(null, "version");
1634 int version;
1635 try {
1636 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1637 } catch (NumberFormatException e) {
1638 version = 0;
1639 }
Svet Ganov65712b02016-09-01 10:24:11 -07001640
1641 if (version < 3) {
1642 mGrantSyncAdaptersAccountAccess = true;
1643 }
1644
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001646 try {
1647 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1648 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1649 } catch (NumberFormatException e) {
1650 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001651 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001652 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1653 try {
1654 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1655 } catch (NumberFormatException e) {
1656 mSyncRandomOffset = 0;
1657 }
1658 if (mSyncRandomOffset == 0) {
1659 Random random = new Random(System.currentTimeMillis());
1660 mSyncRandomOffset = random.nextInt(86400);
1661 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001662 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001663 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001664 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001665 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001666 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001667 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001668 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001669 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001670 if (parser.getDepth() == 2) {
1671 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001672 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001673 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001674 if (authority != null) {
1675 if (authority.ident > highestAuthorityId) {
1676 highestAuthorityId = authority.ident;
1677 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001678 } else {
1679 EventLog.writeEvent(0x534e4554, "26513719", -1,
1680 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001681 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001682 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1683 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001684 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001685 } else if (parser.getDepth() == 3) {
1686 if ("periodicSync".equals(tagName) && authority != null) {
1687 periodicSync = parsePeriodicSync(parser, authority);
1688 }
1689 } else if (parser.getDepth() == 4 && periodicSync != null) {
1690 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001691 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001692 }
1693 }
1694 }
1695 eventType = parser.next();
1696 } while (eventType != XmlPullParser.END_DOCUMENT);
1697 }
1698 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001699 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001700 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001701 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001702 if (fis == null) Slog.i(TAG, "No initial accounts");
1703 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001704 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001705 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001706 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001707 if (fis != null) {
1708 try {
1709 fis.close();
1710 } catch (java.io.IOException e1) {
1711 }
1712 }
1713 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001714
Fred Quintana77c560f2010-03-29 22:20:26 -07001715 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001716 }
Costin Manolache360e4542009-09-04 13:36:04 -07001717
Fred Quintanafb084402010-03-23 17:57:03 -07001718 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001719 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1720 * pending.xml was used starting in KLP.
1721 * @param syncDir directory where the sync files are located.
1722 */
1723 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1724 File file = new File(syncDir, "pending.bin");
1725 if (!file.exists()) {
1726 return;
1727 } else {
1728 file.delete();
1729 }
1730 }
1731
1732 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001733 * some authority names have changed. copy over their settings and delete the old ones
1734 * @return true if a change was made
1735 */
1736 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1737 boolean writeNeeded = false;
1738
1739 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1740 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001741 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001742 AuthorityInfo authority = mAuthorities.valueAt(i);
1743 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001744 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001745 if (newAuthorityName == null) {
1746 continue;
1747 }
1748
1749 // remember this authority so we can remove it later. we can't remove it
1750 // now without messing up this loop iteration
1751 authoritiesToRemove.add(authority);
1752
1753 // this authority isn't enabled, no need to copy it to the new authority name since
1754 // the default is "disabled"
1755 if (!authority.enabled) {
1756 continue;
1757 }
1758
1759 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001760 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001761 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001762 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001763 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001764 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001765 continue;
1766 }
1767
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001768 AuthorityInfo newAuthority =
1769 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001770 newAuthority.enabled = true;
1771 writeNeeded = true;
1772 }
1773
1774 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001775 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001776 authorityInfo.target.account,
1777 authorityInfo.target.userId,
1778 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001779 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001780 writeNeeded = true;
1781 }
1782
1783 return writeNeeded;
1784 }
1785
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 private void parseListenForTickles(XmlPullParser parser) {
1787 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1788 int userId = 0;
1789 try {
1790 userId = Integer.parseInt(user);
1791 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001792 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001793 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001794 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001795 }
1796 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1797 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1798 mMasterSyncAutomatically.put(userId, listen);
1799 }
1800
Suprabh Shukla042a4782017-05-12 15:26:54 -07001801 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1802 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001803 AuthorityInfo authority = null;
1804 int id = -1;
1805 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001806 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001807 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001808 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001809 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001810 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001811 }
1812 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001813 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001815 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001816 String accountName = parser.getAttributeValue(null, "account");
1817 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001818 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001819 String packageName = parser.getAttributeValue(null, "package");
1820 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001821 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001822 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001823 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001824 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001825 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001826 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001827 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001828 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001829 + " account=" + accountName
1830 + " accountType=" + accountType
1831 + " auth=" + authorityName
1832 + " package=" + packageName
1833 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001834 + " user=" + userId
1835 + " enabled=" + enabled
1836 + " syncable=" + syncable);
1837 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001838 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001839 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001840 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001841 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001842 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001843 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001844 new Account(accountName, accountType),
1845 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001846 if (validator.isAccountValid(info.account, userId)
1847 && validator.isAuthorityValid(authorityName, userId)) {
1848 authority = getOrCreateAuthorityLocked(info, id, false);
1849 // If the version is 0 then we are upgrading from a file format that did not
1850 // know about periodic syncs. In that case don't clear the list since we
1851 // want the default, which is a daily periodic sync.
1852 // Otherwise clear out this default list since we will populate it later
1853 // with
1854 // the periodic sync descriptions that are read from the configuration file.
1855 if (version > 0) {
1856 authority.periodicSyncs.clear();
1857 }
1858 } else {
1859 EventLog.writeEvent(0x534e4554, "35028827", -1,
1860 "account:" + info.account + " provider:" + authorityName + " user:"
1861 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001862 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001863 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001864 }
1865 if (authority != null) {
1866 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001867 try {
1868 authority.syncable = (syncable == null) ?
1869 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1870 } catch (NumberFormatException e) {
1871 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1872 // format.
1873 if ("unknown".equals(syncable)) {
1874 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1875 } else {
1876 authority.syncable = Boolean.parseBoolean(syncable) ?
1877 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1878 }
1879
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001880 }
1881 } else {
Makoto Onukidecc5ba2019-01-15 09:34:05 -08001882 Slog.w(TAG, "Failure adding authority:"
1883 + " auth=" + authorityName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001884 + " enabled=" + enabled
1885 + " syncable=" + syncable);
1886 }
1887 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001888 return authority;
1889 }
1890
Matthew Williamsfa774182013-06-18 15:44:11 -07001891 /**
1892 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1893 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001894 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001895 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001896 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001897 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001898 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001899 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001900 try {
1901 period = Long.parseLong(periodValue);
1902 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001903 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001904 return null;
1905 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001906 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001907 return null;
1908 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001909 try {
1910 flextime = Long.parseLong(flexValue);
1911 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001912 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001913 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001914 + ", using default: "
1915 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001916 } catch (NullPointerException expected) {
1917 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001918 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1919 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001920 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001921 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001922 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001923 new PeriodicSync(authorityInfo.target.account,
1924 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001925 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001926 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001927 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001928 return periodicSync;
1929 }
1930
Matthew Williamsfa774182013-06-18 15:44:11 -07001931 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001932 String name = parser.getAttributeValue(null, "name");
1933 String type = parser.getAttributeValue(null, "type");
1934 String value1 = parser.getAttributeValue(null, "value1");
1935 String value2 = parser.getAttributeValue(null, "value2");
1936
1937 try {
1938 if ("long".equals(type)) {
1939 extras.putLong(name, Long.parseLong(value1));
1940 } else if ("integer".equals(type)) {
1941 extras.putInt(name, Integer.parseInt(value1));
1942 } else if ("double".equals(type)) {
1943 extras.putDouble(name, Double.parseDouble(value1));
1944 } else if ("float".equals(type)) {
1945 extras.putFloat(name, Float.parseFloat(value1));
1946 } else if ("boolean".equals(type)) {
1947 extras.putBoolean(name, Boolean.parseBoolean(value1));
1948 } else if ("string".equals(type)) {
1949 extras.putString(name, value1);
1950 } else if ("account".equals(type)) {
1951 extras.putParcelable(name, new Account(value1, value2));
1952 }
1953 } catch (NumberFormatException 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 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001956 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001957 }
1958 }
1959
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 /**
1961 * Write all account information to the account file.
1962 */
1963 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001964 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001965 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001966 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 try {
1970 fos = mAccountInfoFile.startWrite();
1971 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001972 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001973 out.startDocument(null, true);
1974 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001975
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001977 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001978 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001979 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001980
1981 // Write the Sync Automatically flags for each user
1982 final int M = mMasterSyncAutomatically.size();
1983 for (int m = 0; m < M; m++) {
1984 int userId = mMasterSyncAutomatically.keyAt(m);
1985 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1986 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1987 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1988 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1989 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001990 }
Costin Manolache360e4542009-09-04 13:36:04 -07001991
Dianne Hackborn231cc602009-04-27 17:10:36 -07001992 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001993 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001994 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001995 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001996 out.startTag(null, "authority");
1997 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001998 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001999 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002000 out.attribute(null, "account", info.account.name);
2001 out.attribute(null, "type", info.account.type);
2002 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07002003 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 out.endTag(null, "authority");
2005 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002007 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002008 mAccountInfoFile.finishWrite(fos);
2009 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002010 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002011 if (fos != null) {
2012 mAccountInfoFile.failWrite(fos);
2013 }
2014 }
2015 }
Costin Manolache360e4542009-09-04 13:36:04 -07002016
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 public static final int STATUS_FILE_END = 0;
2018 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002019
Dianne Hackborn231cc602009-04-27 17:10:36 -07002020 /**
2021 * Read all sync status back in to the initial engine state.
2022 */
2023 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002024 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002025 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002026 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 try {
2028 byte[] data = mStatusFile.readFully();
2029 Parcel in = Parcel.obtain();
2030 in.unmarshall(data, 0, data.length);
2031 in.setDataPosition(0);
2032 int token;
2033 while ((token=in.readInt()) != STATUS_FILE_END) {
2034 if (token == STATUS_FILE_ITEM) {
2035 SyncStatusInfo status = new SyncStatusInfo(in);
2036 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2037 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002038 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002039 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002040 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002041 mSyncStatus.put(status.authorityId, status);
2042 }
2043 } else {
2044 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002045 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002046 break;
2047 }
2048 }
2049 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002050 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002051 }
2052 }
Costin Manolache360e4542009-09-04 13:36:04 -07002053
Dianne Hackborn231cc602009-04-27 17:10:36 -07002054 /**
2055 * Write all sync status to the sync status file.
2056 */
2057 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002058 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002059 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002060 }
Costin Manolache360e4542009-09-04 13:36:04 -07002061
Dianne Hackborn231cc602009-04-27 17:10:36 -07002062 // The file is being written, so we don't need to have a scheduled
2063 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002064 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002065
Dianne Hackborn231cc602009-04-27 17:10:36 -07002066 FileOutputStream fos = null;
2067 try {
2068 fos = mStatusFile.startWrite();
2069 Parcel out = Parcel.obtain();
2070 final int N = mSyncStatus.size();
2071 for (int i=0; i<N; i++) {
2072 SyncStatusInfo status = mSyncStatus.valueAt(i);
2073 out.writeInt(STATUS_FILE_ITEM);
2074 status.writeToParcel(out, 0);
2075 }
2076 out.writeInt(STATUS_FILE_END);
2077 fos.write(out.marshall());
2078 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002079
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 mStatusFile.finishWrite(fos);
2081 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002082 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002083 if (fos != null) {
2084 mStatusFile.failWrite(fos);
2085 }
2086 }
2087 }
Costin Manolache360e4542009-09-04 13:36:04 -07002088
Makoto Onuki61283ec2018-01-31 17:22:36 -08002089 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002090 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002091 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2092 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002093 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002094 syncExemptionFlag, callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002095 } else {
2096 SyncRequest.Builder req =
2097 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002098 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002099 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002100 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002101 ContentResolver.requestSync(req.build());
2102 }
2103 }
2104
Alon Albert57286f92012-10-09 14:21:38 -07002105 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onukie183a402018-08-29 11:46:41 -07002106 Bundle extras, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002107 // If this is happening in the system process, then call the syncrequest listener
2108 // to make a request back to the SyncManager directly.
2109 // If this is probably a test instance, then call back through the ContentResolver
2110 // which will know which userId to apply based on the Binder id.
2111 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2112 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002113 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002114 new EndPoint(account, authority, userId),
Makoto Onukie183a402018-08-29 11:46:41 -07002115 reason, extras, syncExemptionFlag, callingUid, callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002116 } else {
2117 ContentResolver.requestSync(account, authority, extras);
2118 }
2119 }
2120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 public static final int STATISTICS_FILE_END = 0;
2122 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2123 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002124
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 /**
2126 * Read all sync statistics back in to the initial engine state.
2127 */
2128 private void readStatisticsLocked() {
2129 try {
2130 byte[] data = mStatisticsFile.readFully();
2131 Parcel in = Parcel.obtain();
2132 in.unmarshall(data, 0, data.length);
2133 in.setDataPosition(0);
2134 int token;
2135 int index = 0;
2136 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2137 if (token == STATISTICS_FILE_ITEM
2138 || token == STATISTICS_FILE_ITEM_OLD) {
2139 int day = in.readInt();
2140 if (token == STATISTICS_FILE_ITEM_OLD) {
2141 day = day - 2009 + 14245; // Magic!
2142 }
2143 DayStats ds = new DayStats(day);
2144 ds.successCount = in.readInt();
2145 ds.successTime = in.readLong();
2146 ds.failureCount = in.readInt();
2147 ds.failureTime = in.readLong();
2148 if (index < mDayStats.length) {
2149 mDayStats[index] = ds;
2150 index++;
2151 }
2152 } else {
2153 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002154 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002155 break;
2156 }
2157 }
2158 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002159 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002160 }
2161 }
Costin Manolache360e4542009-09-04 13:36:04 -07002162
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 /**
2164 * Write all sync statistics to the sync status file.
2165 */
2166 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002167 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002168 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002169 }
Costin Manolache360e4542009-09-04 13:36:04 -07002170
Dianne Hackborn231cc602009-04-27 17:10:36 -07002171 // The file is being written, so we don't need to have a scheduled
2172 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002173 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002174
Dianne Hackborn231cc602009-04-27 17:10:36 -07002175 FileOutputStream fos = null;
2176 try {
2177 fos = mStatisticsFile.startWrite();
2178 Parcel out = Parcel.obtain();
2179 final int N = mDayStats.length;
2180 for (int i=0; i<N; i++) {
2181 DayStats ds = mDayStats[i];
2182 if (ds == null) {
2183 break;
2184 }
2185 out.writeInt(STATISTICS_FILE_ITEM);
2186 out.writeInt(ds.day);
2187 out.writeInt(ds.successCount);
2188 out.writeLong(ds.successTime);
2189 out.writeInt(ds.failureCount);
2190 out.writeLong(ds.failureTime);
2191 }
2192 out.writeInt(STATISTICS_FILE_END);
2193 fos.write(out.marshall());
2194 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002195
Dianne Hackborn231cc602009-04-27 17:10:36 -07002196 mStatisticsFile.finishWrite(fos);
2197 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002198 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002199 if (fos != null) {
2200 mStatisticsFile.failWrite(fos);
2201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 }
2203 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002204
2205 /**
Marvin Paula6533252014-11-24 12:57:48 -08002206 * Let the BackupManager know that account sync settings have changed. This will trigger
2207 * {@link com.android.server.backup.SystemBackupAgent} to run.
2208 */
2209 public void queueBackup() {
2210 BackupManager.dataChanged("android");
2211 }
Makoto Onuki94986212018-04-11 16:24:46 -07002212
2213 public void setClockValid() {
2214 if (!mIsClockValid) {
2215 mIsClockValid = true;
2216 Slog.w(TAG, "Clock is valid now.");
2217 }
2218 }
2219
2220 public boolean isClockValid() {
2221 return mIsClockValid;
2222 }
2223
2224 public void resetTodayStats(boolean force) {
2225 if (force) {
2226 Log.w(TAG, "Force resetting today stats.");
2227 }
2228 synchronized (mAuthorities) {
2229 final int N = mSyncStatus.size();
2230 for (int i = 0; i < N; i++) {
2231 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2232 cur.maybeResetTodayStats(isClockValid(), force);
2233 }
2234 writeStatusLocked();
2235 }
2236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237}