blob: 6081af8d6a55f5c0591fde65b54d6ad7bfed969a [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
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Suprabh Shukla042a4782017-05-12 15:26:54 -070021import android.accounts.AccountManager;
Marvin Paula6533252014-11-24 12:57:48 -080022import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070023import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080024import android.content.ContentResolver;
Makoto Onuki75ad2492018-03-28 14:42:42 -070025import android.content.ContentResolver.SyncExemption;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.content.Context;
27import android.content.ISyncStatusObserver;
28import android.content.PeriodicSync;
29import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070030import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080031import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070032import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070035import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070037import android.os.Bundle;
38import android.os.Environment;
39import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080040import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.os.Message;
42import android.os.Parcel;
43import android.os.RemoteCallbackList;
44import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070045import android.os.UserHandle;
Shreyas Basarge8c834c02016-01-07 13:53:16 +000046import android.util.*;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080047
48import com.android.internal.annotations.VisibleForTesting;
49import com.android.internal.util.ArrayUtils;
50import com.android.internal.util.FastXmlSerializer;
51
52import org.xmlpull.v1.XmlPullParser;
53import org.xmlpull.v1.XmlPullParserException;
54import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
Dianne Hackborn231cc602009-04-27 17:10:36 -070056import java.io.File;
57import java.io.FileInputStream;
58import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010059import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070061import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080064import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070065import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060066import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
68/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070069 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070071 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 * @hide
73 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080074public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070077 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070078
Amith Yamasani04e0d262012-02-14 11:50:53 -080079 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
80 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070081 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080082 private static final String XML_ATTR_ENABLED = "enabled";
83 private static final String XML_ATTR_USER = "user";
84 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
85
Matthew Williamsfa774182013-06-18 15:44:11 -070086 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000087 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080088
Shreyas Basarge8c834c02016-01-07 13:53:16 +000089 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070090 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
91
92 /** Lower bound on sync time from which we assign a default flex time. */
93 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
94
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080095 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070096 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Dianne Hackborn231cc602009-04-27 17:10:36 -070098 /** Enum value for a sync start event. */
99 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Dianne Hackborn231cc602009-04-27 17:10:36 -0700101 /** Enum value for a sync stop event. */
102 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 /** Enum value for a server-initiated sync. */
105 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
Dianne Hackborn231cc602009-04-27 17:10:36 -0700107 /** Enum value for a local-initiated sync. */
108 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700109 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700110 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Dianne Hackborn231cc602009-04-27 17:10:36 -0700112 /** Enum value for a user-initiated sync. */
113 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800115 /** Enum value for a periodic sync. */
116 public static final int SOURCE_PERIODIC = 4;
117
Fred Quintana307da1a2010-01-21 14:24:20 -0800118 public static final long NOT_IN_BACKOFF_MODE = -1;
119
Dianne Hackborn231cc602009-04-27 17:10:36 -0700120 // TODO: i18n -- grab these out of resources.
121 /** String names for the sync source types. */
122 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000123 "LOCAL",
124 "POLL",
125 "USER",
126 "PERIODIC",
127 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborn231cc602009-04-27 17:10:36 -0700129 // The MESG column will contain one of these or one of the Error types.
130 public static final String MESG_SUCCESS = "success";
131 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700133 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700134
Dianne Hackborn231cc602009-04-27 17:10:36 -0700135 private static final int MSG_WRITE_STATUS = 1;
136 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700137
Dianne Hackborn231cc602009-04-27 17:10:36 -0700138 private static final int MSG_WRITE_STATISTICS = 2;
139 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700140
141 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700142
Fred Quintanac2e46912010-03-15 16:10:44 -0700143 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700144 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700145
146 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000147 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700148
149 static {
150 sAuthorityRenames = new HashMap<String, String>();
151 sAuthorityRenames.put("contacts", "com.android.contacts");
152 sAuthorityRenames.put("calendar", "com.android.calendar");
153 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700154
Dianne Hackborn231cc602009-04-27 17:10:36 -0700155 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700157 final HashMap<String, AuthorityInfo> authorities =
158 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700159
Amith Yamasani04e0d262012-02-14 11:50:53 -0800160 AccountInfo(AccountAndUser accountAndUser) {
161 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700162 }
163 }
Costin Manolache360e4542009-09-04 13:36:04 -0700164
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700165 /** Bare bones representation of a sync target. */
166 public static class EndPoint {
167 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
168 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700169 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800170 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700171 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700172
173 public EndPoint(Account account, String provider, int userId) {
174 this.account = account;
175 this.provider = provider;
176 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700177 }
178
179 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700180 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
181 *
182 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000183 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700184 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700185 public boolean matchesSpec(EndPoint spec) {
186 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700187 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700188 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700189 return false;
190 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000191 boolean accountsMatch;
192 if (spec.account == null) {
193 accountsMatch = true;
194 } else {
195 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700196 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000197 boolean providersMatch;
198 if (spec.provider == null) {
199 providersMatch = true;
200 } else {
201 providersMatch = provider.equals(spec.provider);
202 }
203 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700204 }
205
206 public String toString() {
207 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000208 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700209 .append("/")
210 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700211 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700212 return sb.toString();
213 }
214 }
215
216 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700217 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700218
219 /**
220 * The syncable state is undefined.
221 */
222 public static final int UNDEFINED = -2;
223
Matthew Williams53abfdb2015-06-10 20:06:37 -0700224 /**
225 * Default state for a newly installed adapter. An uninitialized adapter will receive an
226 * initialization sync which are governed by a different set of rules to that of regular
227 * syncs.
228 */
229 public static final int NOT_INITIALIZED = -1;
230 /**
231 * The adapter will not receive any syncs. This is behaviourally equivalent to
232 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
233 * while this is generally meant to be controlled by the developer.
234 */
235 public static final int NOT_SYNCABLE = 0;
236 /**
237 * The adapter is initialized and functioning. This is the normal state for an adapter.
238 */
239 public static final int SYNCABLE = 1;
240 /**
241 * The adapter is syncable but still requires an initialization sync. For example an adapter
242 * than has been restored from a previous device will be in this state. Not meant for
243 * external use.
244 */
245 public static final int SYNCABLE_NOT_INITIALIZED = 2;
246
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700247 /**
248 * The adapter is syncable but does not have access to the synced account and needs a
249 * user access approval.
250 */
251 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
252
Matthew Williams8ef22042013-07-26 12:56:39 -0700253 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700254 final int ident;
255 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700256 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700257 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800258 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700259 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800260 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700261 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800262 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700263
Matthew Williamsfa774182013-06-18 15:44:11 -0700264 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700265
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700266 /**
267 * Copy constructor for making deep-ish copies. Only the bundles stored
268 * in periodic syncs can make unexpected changes.
269 *
270 * @param toCopy AuthorityInfo to be copied.
271 */
272 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700273 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700274 ident = toCopy.ident;
275 enabled = toCopy.enabled;
276 syncable = toCopy.syncable;
277 backoffTime = toCopy.backoffTime;
278 backoffDelay = toCopy.backoffDelay;
279 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700280 periodicSyncs = new ArrayList<PeriodicSync>();
281 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700282 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700283 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700284 }
285 }
286
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700287 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700288 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700289 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000290 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700291 periodicSyncs = new ArrayList<PeriodicSync>();
292 defaultInitialisation();
293 }
294
295 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700296 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800297 backoffTime = -1; // if < 0 then we aren't in backoff mode
298 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000299
300 if (mPeriodicSyncAddedListener != null) {
301 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
302 DEFAULT_POLL_FREQUENCY_SECONDS,
303 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700304 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700305 }
Matthew Williams06485a72013-07-26 12:56:39 -0700306
307 @Override
308 public String toString() {
309 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
310 + backoffTime + ", delay=" + delayUntil;
311 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700312 }
Costin Manolache360e4542009-09-04 13:36:04 -0700313
Dianne Hackborn231cc602009-04-27 17:10:36 -0700314 public static class SyncHistoryItem {
315 int authorityId;
316 int historyId;
317 long eventTime;
318 long elapsedTime;
319 int source;
320 int event;
321 long upstreamActivity;
322 long downstreamActivity;
323 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700324 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700325 Bundle extras;
326 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700327 }
Costin Manolache360e4542009-09-04 13:36:04 -0700328
Dianne Hackborn231cc602009-04-27 17:10:36 -0700329 public static class DayStats {
330 public final int day;
331 public int successCount;
332 public long successTime;
333 public int failureCount;
334 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700335
Dianne Hackborn231cc602009-04-27 17:10:36 -0700336 public DayStats(int day) {
337 this.day = day;
338 }
339 }
Costin Manolache360e4542009-09-04 13:36:04 -0700340
Amith Yamasani04e0d262012-02-14 11:50:53 -0800341 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700342
343 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800344 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -0700345 @SyncExemption int syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800346 }
347
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000348 interface PeriodicSyncAddedListener {
349 /** Called when a periodic sync is added. */
350 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
351 }
352
353 interface OnAuthorityRemovedListener {
354 /** Called when an authority is removed. */
355 void onAuthorityRemoved(EndPoint removedAuthority);
356 }
357
Suprabh Shukla042a4782017-05-12 15:26:54 -0700358 /**
359 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
360 * account is valid.
361 */
362 private static class AccountAuthorityValidator {
363 final private AccountManager mAccountManager;
364 final private PackageManager mPackageManager;
365 final private SparseArray<Account[]> mAccountsCache;
366 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
367
368 AccountAuthorityValidator(Context context) {
369 mAccountManager = context.getSystemService(AccountManager.class);
370 mPackageManager = context.getPackageManager();
371 mAccountsCache = new SparseArray<>();
372 mProvidersPerUserCache = new SparseArray<>();
373 }
374
375 // An account is valid if an installed authenticator has previously created that account
376 // on the device
377 boolean isAccountValid(Account account, int userId) {
378 Account[] accountsForUser = mAccountsCache.get(userId);
379 if (accountsForUser == null) {
380 accountsForUser = mAccountManager.getAccountsAsUser(userId);
381 mAccountsCache.put(userId, accountsForUser);
382 }
383 return ArrayUtils.contains(accountsForUser, account);
384 }
385
386 // An authority is only valid if it has a content provider installed on the system
387 boolean isAuthorityValid(String authority, int userId) {
388 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
389 if (authorityMap == null) {
390 authorityMap = new ArrayMap<>();
391 mProvidersPerUserCache.put(userId, authorityMap);
392 }
393 if (!authorityMap.containsKey(authority)) {
394 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
395 PackageManager.MATCH_DIRECT_BOOT_AWARE
396 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
397 }
398 return authorityMap.get(authority);
399 }
400 }
401
Dianne Hackborn231cc602009-04-27 17:10:36 -0700402 // Primary list of all syncable authorities. Also our global lock.
403 private final SparseArray<AuthorityInfo> mAuthorities =
404 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700405
Amith Yamasani04e0d262012-02-14 11:50:53 -0800406 private final HashMap<AccountAndUser, AccountInfo> mAccounts
407 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800408
Amith Yamasani04e0d262012-02-14 11:50:53 -0800409 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
410 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700411
Dianne Hackborn231cc602009-04-27 17:10:36 -0700412 private final SparseArray<SyncStatusInfo> mSyncStatus =
413 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700414
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 private final ArrayList<SyncHistoryItem> mSyncHistory =
416 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700417
Dianne Hackborn231cc602009-04-27 17:10:36 -0700418 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
419 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700420
Matthew Williams8ef22042013-07-26 12:56:39 -0700421 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700422 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
423 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700424
Fred Quintana77c560f2010-03-29 22:20:26 -0700425 private int mNextAuthorityId = 0;
426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 // We keep 4 weeks of stats.
428 private final DayStats[] mDayStats = new DayStats[7*4];
429 private final Calendar mCal;
430 private int mYear;
431 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800434
Dianne Hackborn231cc602009-04-27 17:10:36 -0700435 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700436
Ashish Sharma69d95de2012-04-11 17:27:24 -0700437 private int mSyncRandomOffset;
438
Dianne Hackborn231cc602009-04-27 17:10:36 -0700439 /**
440 * This file contains the core engine state: all accounts and the
441 * settings for them. It must never be lost, and should be changed
442 * infrequently, so it is stored as an XML file.
443 */
444 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700445
Dianne Hackborn231cc602009-04-27 17:10:36 -0700446 /**
447 * This file contains the current sync status. We would like to retain
448 * it across boots, but its loss is not the end of the world, so we store
449 * this information as binary data.
450 */
451 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700452
Dianne Hackborn231cc602009-04-27 17:10:36 -0700453 /**
454 * This file contains sync statistics. This is purely debugging information
455 * so is written infrequently and can be thrown away at any time.
456 */
457 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700458
Dianne Hackborn231cc602009-04-27 17:10:36 -0700459 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800460 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800461 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800462
463 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000464 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700465
Svet Ganov65712b02016-09-01 10:24:11 -0700466 private boolean mGrantSyncAdaptersAccountAccess;
467
Makoto Onuki6963bea72017-12-12 10:42:39 -0800468 private final MyHandler mHandler;
469
470 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
471 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700474
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700476
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800477 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000478 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800479
Dianne Hackborn231cc602009-04-27 17:10:36 -0700480 File systemDir = new File(dataDir, "system");
481 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800482 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700483
484 maybeDeleteLegacyPendingInfoLocked(syncDir);
485
Dianne Hackborne17b4452018-01-10 13:15:40 -0800486 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
487 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
488 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700489
Dianne Hackborn231cc602009-04-27 17:10:36 -0700490 readAccountInfoLocked();
491 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700493 readAndDeleteLegacyAccountInfoLocked();
494 writeAccountInfoLocked();
495 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700496 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800497 }
498
499 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800500 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 }
502
Makoto Onuki6963bea72017-12-12 10:42:39 -0800503 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800505 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700507 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800508 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509 }
510
511 public static SyncStorageEngine getSingleton() {
512 if (sSyncStorageEngine == null) {
513 throw new IllegalStateException("not initialized");
514 }
515 return sSyncStorageEngine;
516 }
517
Amith Yamasani04e0d262012-02-14 11:50:53 -0800518 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
519 if (mSyncRequestListener == null) {
520 mSyncRequestListener = listener;
521 }
522 }
523
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000524 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
525 if (mAuthorityRemovedListener == null) {
526 mAuthorityRemovedListener = listener;
527 }
528 }
529
530 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
531 if (mPeriodicSyncAddedListener == null) {
532 mPeriodicSyncAddedListener = listener;
533 }
534 }
535
Makoto Onuki6963bea72017-12-12 10:42:39 -0800536 private class MyHandler extends Handler {
537 public MyHandler(Looper looper) {
538 super(looper);
539 }
540
541 @Override
542 public void handleMessage(Message msg) {
543 if (msg.what == MSG_WRITE_STATUS) {
544 synchronized (mAuthorities) {
545 writeStatusLocked();
546 }
547 } else if (msg.what == MSG_WRITE_STATISTICS) {
548 synchronized (mAuthorities) {
549 writeStatisticsLocked();
550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 }
552 }
553 }
Costin Manolache360e4542009-09-04 13:36:04 -0700554
Ashish Sharma69d95de2012-04-11 17:27:24 -0700555 public int getSyncRandomOffset() {
556 return mSyncRandomOffset;
557 }
558
Dianne Hackborn231cc602009-04-27 17:10:36 -0700559 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
560 synchronized (mAuthorities) {
561 mChangeListeners.register(callback, mask);
562 }
563 }
Costin Manolache360e4542009-09-04 13:36:04 -0700564
Dianne Hackborn231cc602009-04-27 17:10:36 -0700565 public void removeStatusChangeListener(ISyncStatusObserver callback) {
566 synchronized (mAuthorities) {
567 mChangeListeners.unregister(callback);
568 }
569 }
Costin Manolache360e4542009-09-04 13:36:04 -0700570
Matthew Williamsfa774182013-06-18 15:44:11 -0700571 /**
572 * Figure out a reasonable flex time for cases where none is provided (old api calls).
573 * @param syncTimeSeconds requested sync time from now.
574 * @return amount of seconds before syncTimeSeconds that the sync can occur.
575 * I.e.
576 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700577 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700578 */
579 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
580 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
581 // Small enough sync request time that we don't add flex time - developer probably
582 // wants to wait for an operation to occur before syncing so we honour the
583 // request time.
584 return 0L;
585 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
586 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
587 } else {
588 // Large enough sync request time that we cap the flex time.
589 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
590 }
591 }
592
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000593 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700594 ArrayList<ISyncStatusObserver> reports = null;
595 synchronized (mAuthorities) {
596 int i = mChangeListeners.beginBroadcast();
597 while (i > 0) {
598 i--;
599 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
600 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 continue;
602 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700603 if (reports == null) {
604 reports = new ArrayList<ISyncStatusObserver>(i);
605 }
606 reports.add(mChangeListeners.getBroadcastItem(i));
607 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700608 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700609 }
Costin Manolache360e4542009-09-04 13:36:04 -0700610
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700611 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000612 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700613 }
Costin Manolache360e4542009-09-04 13:36:04 -0700614
Dianne Hackborn231cc602009-04-27 17:10:36 -0700615 if (reports != null) {
616 int i = reports.size();
617 while (i > 0) {
618 i--;
619 try {
620 reports.get(i).onStatusChanged(which);
621 } catch (RemoteException e) {
622 // The remote callback list will take care of this for us.
623 }
624 }
625 }
626 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700627
Amith Yamasani04e0d262012-02-14 11:50:53 -0800628 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700629 synchronized (mAuthorities) {
630 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700631 AuthorityInfo authority = getAuthorityLocked(
632 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700633 "getSyncAutomatically");
634 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700636
Dianne Hackborn231cc602009-04-27 17:10:36 -0700637 int i = mAuthorities.size();
638 while (i > 0) {
639 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700640 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700641 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700642 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700643 return true;
644 }
645 }
646 return false;
647 }
648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
Amith Yamasani04e0d262012-02-14 11:50:53 -0800650 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onuki75ad2492018-03-28 14:42:42 -0700651 boolean sync, @SyncExemption int syncExemptionFlag) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700652 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000653 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800654 + ", user " + userId + " -> " + sync);
655 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700656 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700657 AuthorityInfo authority =
658 getOrCreateAuthorityLocked(
659 new EndPoint(account, providerName, userId),
660 -1 /* ident */,
661 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700662 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000664 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800665 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700666 return;
667 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700668 // If the adapter was syncable but missing its initialization sync, set it to
669 // uninitialized now. This is to give it a chance to run any one-time initialization
670 // logic.
671 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
672 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
673 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700674 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700675 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700677
Fred Quintana77c560f2010-03-29 22:20:26 -0700678 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700679 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800680 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700681 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700682 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700683 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800684 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 }
686
Amith Yamasani04e0d262012-02-14 11:50:53 -0800687 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700688 synchronized (mAuthorities) {
689 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700690 AuthorityInfo authority = getAuthorityLocked(
691 new EndPoint(account, providerName, userId),
692 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700693 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700694 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700695 }
696 return authority.syncable;
697 }
698
699 int i = mAuthorities.size();
700 while (i > 0) {
701 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700702 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700703 if (authorityInfo.target != null
704 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700705 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700706 }
707 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700708 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700709 }
710 }
711
Amith Yamasani04e0d262012-02-14 11:50:53 -0800712 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700713 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700714 }
715
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700716 /**
717 * An enabled sync service and a syncable provider's adapter both get resolved to the same
718 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700719 * @param target target to set value for.
720 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700721 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700722 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700723 AuthorityInfo aInfo;
724 synchronized (mAuthorities) {
725 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700726 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
727 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700729 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000730 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700731 }
732 if (aInfo.syncable == syncable) {
733 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000734 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700735 }
736 return;
737 }
738 aInfo.syncable = syncable;
739 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700740 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700741 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800742 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700743 ContentResolver.SYNC_EXEMPTION_NONE);
Fred Quintana5e787c42009-08-16 23:13:53 -0700744 }
745 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
746 }
747
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700748 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800749 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700750 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
751 if (authority != null) {
752 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800753 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700754 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800755 }
756 }
757
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700758 /**
759 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
760 * the account or provider info be null, which signifies all accounts or providers.
761 */
762 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000764 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800765 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
766 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700767 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800768 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000769 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700770 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000771 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700772 changed = setBackoffLocked(
773 info.account /* may be null */,
774 info.userId,
775 info.provider /* may be null */,
776 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800777 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700778 AuthorityInfo authorityInfo =
779 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
780 if (authorityInfo.backoffTime == nextSyncTime
781 && authorityInfo.backoffDelay == nextDelay) {
782 changed = false;
783 } else {
784 authorityInfo.backoffTime = nextSyncTime;
785 authorityInfo.backoffDelay = nextDelay;
786 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800787 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800788 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800789 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800790 if (changed) {
791 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
792 }
793 }
794
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700795 /**
796 * Either set backoff for a specific authority, or set backoff for all the
797 * accounts on a specific adapter/all adapters.
798 *
799 * @param account account for which to set backoff. Null to specify all accounts.
800 * @param userId id of the user making this request.
801 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700802 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700803 */
804 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000805 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 boolean changed = false;
807 for (AccountInfo accountInfo : mAccounts.values()) {
808 if (account != null && !account.equals(accountInfo.accountAndUser.account)
809 && userId != accountInfo.accountAndUser.userId) {
810 continue;
811 }
812 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
813 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700814 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700815 continue;
816 }
817 if (authorityInfo.backoffTime != nextSyncTime
818 || authorityInfo.backoffDelay != nextDelay) {
819 authorityInfo.backoffTime = nextSyncTime;
820 authorityInfo.backoffDelay = nextDelay;
821 changed = true;
822 }
823 }
824 }
825 return changed;
826 }
827
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000828 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800829 boolean changed = false;
830 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000831 // Clear backoff for all sync adapters.
832 for (AccountInfo accountInfo : mAccounts.values()) {
833 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
834 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
835 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
836 if (Log.isLoggable(TAG, Log.VERBOSE)) {
837 Slog.v(TAG, "clearAllBackoffsLocked:"
838 + " authority:" + authorityInfo.target
839 + " account:" + accountInfo.accountAndUser.account.name
840 + " user:" + accountInfo.accountAndUser.userId
841 + " backoffTime was: " + authorityInfo.backoffTime
842 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800843 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000844 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
845 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
846 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800847 }
848 }
849 }
850 }
851
852 if (changed) {
853 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
854 }
855 }
856
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700857 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800858 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700859 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800860 if (authority == null) {
861 return 0;
862 }
863 return authority.delayUntil;
864 }
865 }
866
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700867 public void setDelayUntilTime(EndPoint info, long delayUntil) {
868 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000869 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700870 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800871 }
872 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700873 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
874 if (authority.delayUntil == delayUntil) {
875 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700876 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700877 authority.delayUntil = delayUntil;
878 }
879 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
880 }
881
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700882 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000883 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
884 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700885 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000886 boolean restoreAllPeriodicSyncs() {
887 if (mPeriodicSyncAddedListener == null) {
888 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800889 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000890 synchronized (mAuthorities) {
891 for (int i=0; i<mAuthorities.size(); i++) {
892 AuthorityInfo authority = mAuthorities.valueAt(i);
893 for (PeriodicSync periodicSync: authority.periodicSyncs) {
894 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
895 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
896 }
897 authority.periodicSyncs.clear();
898 }
899 writeAccountInfoLocked();
900 }
901 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800902 }
903
Makoto Onuki75ad2492018-03-28 14:42:42 -0700904 public void setMasterSyncAutomatically(boolean flag, int userId,
905 @SyncExemption int syncExemptionFlag) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700906 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800907 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700908 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700909 return;
910 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700912 writeAccountInfoLocked();
913 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700914 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700915 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800916 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700917 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700918 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700919 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800920 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800921 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923
Amith Yamasani04e0d262012-02-14 11:50:53 -0800924 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700925 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800926 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800927 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700928 }
929 }
Costin Manolache360e4542009-09-04 13:36:04 -0700930
Makoto Onukib47e8942017-09-18 14:03:03 -0700931 public int getAuthorityCount() {
932 synchronized (mAuthorities) {
933 return mAuthorities.size();
934 }
935 }
936
Dianne Hackborn231cc602009-04-27 17:10:36 -0700937 public AuthorityInfo getAuthority(int authorityId) {
938 synchronized (mAuthorities) {
939 return mAuthorities.get(authorityId);
940 }
941 }
Costin Manolache360e4542009-09-04 13:36:04 -0700942
Dianne Hackborn231cc602009-04-27 17:10:36 -0700943 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700944 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700945 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700947 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700948 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700949 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700950 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700951 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 return true;
953 }
954 }
955 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700956 return false;
957 }
Costin Manolache360e4542009-09-04 13:36:04 -0700958
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000959 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000961 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
962 -1 /* desired identifier */,
963 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700964 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000965 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700966 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000968 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700970 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700971 }
Costin Manolache360e4542009-09-04 13:36:04 -0700972
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 /**
974 * Called when the set of account has changed, given the new array of
975 * active accounts.
976 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800977 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700978 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700979 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000980 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700981 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700982 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
983 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
984 while (accIt.hasNext()) {
985 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800986 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
987 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700988 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700989 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000990 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700991 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700992 for (AuthorityInfo auth : acc.authorities.values()) {
993 removing.put(auth.ident, auth);
994 }
995 accIt.remove();
996 }
997 }
Costin Manolache360e4542009-09-04 13:36:04 -0700998
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 // Clean out all data structures.
1000 int i = removing.size();
1001 if (i > 0) {
1002 while (i > 0) {
1003 i--;
1004 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001005 AuthorityInfo auth = removing.valueAt(i);
1006 if (mAuthorityRemovedListener != null) {
1007 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1008 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 mAuthorities.remove(ident);
1010 int j = mSyncStatus.size();
1011 while (j > 0) {
1012 j--;
1013 if (mSyncStatus.keyAt(j) == ident) {
1014 mSyncStatus.remove(mSyncStatus.keyAt(j));
1015 }
1016 }
1017 j = mSyncHistory.size();
1018 while (j > 0) {
1019 j--;
1020 if (mSyncHistory.get(j).authorityId == ident) {
1021 mSyncHistory.remove(j);
1022 }
1023 }
1024 }
1025 writeAccountInfoLocked();
1026 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001027 writeStatisticsLocked();
1028 }
1029 }
1030 }
1031
1032 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001033 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1034 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001035 */
Fred Quintana918339a2010-10-05 14:00:39 -07001036 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1037 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001039 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001040 Slog.v(TAG, "setActiveSync: account="
1041 + " auth=" + activeSyncContext.mSyncOperation.target
1042 + " src=" + activeSyncContext.mSyncOperation.syncSource
1043 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001045 final EndPoint info = activeSyncContext.mSyncOperation.target;
1046 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1047 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001048 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001049 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001050 syncInfo = new SyncInfo(
1051 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001052 authorityInfo.target.account,
1053 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001054 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001055 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 }
Fred Quintana918339a2010-10-05 14:00:39 -07001057 reportActiveChange();
1058 return syncInfo;
1059 }
1060
1061 /**
1062 * Called to indicate that a previously active sync is no longer active.
1063 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001064 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001065 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001066 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001067 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001068 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001069 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001070 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001071 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001072 }
1073
1074 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001075 }
1076
1077 /**
1078 * To allow others to send active change reports, to poke clients.
1079 */
1080 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001081 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001082 }
Costin Manolache360e4542009-09-04 13:36:04 -07001083
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001085 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001086 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001087 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 long id;
1089 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001090 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001091 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001092 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001093 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 if (authority == null) {
1095 return -1;
1096 }
1097 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001098 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001099 item.authorityId = authority.ident;
1100 item.historyId = mNextHistoryId++;
1101 if (mNextHistoryId < 0) mNextHistoryId = 0;
1102 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001103 item.source = op.syncSource;
1104 item.reason = op.reason;
1105 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001106 item.event = EVENT_START;
1107 mSyncHistory.add(0, item);
1108 while (mSyncHistory.size() > MAX_HISTORY) {
1109 mSyncHistory.remove(mSyncHistory.size()-1);
1110 }
1111 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001112 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001113 }
Costin Manolache360e4542009-09-04 13:36:04 -07001114
Fred Quintanaac9385e2009-06-22 18:00:59 -07001115 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001116 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118
Fred Quintana77c560f2010-03-29 22:20:26 -07001119 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001120 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -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, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001124 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001125 SyncHistoryItem item = null;
1126 int i = mSyncHistory.size();
1127 while (i > 0) {
1128 i--;
1129 item = mSyncHistory.get(i);
1130 if (item.historyId == historyId) {
1131 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
Costin Manolache360e4542009-09-04 13:36:04 -07001135
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001137 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 return;
1139 }
Costin Manolache360e4542009-09-04 13:36:04 -07001140
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 item.elapsedTime = elapsedTime;
1142 item.event = EVENT_STOP;
1143 item.mesg = resultMessage;
1144 item.downstreamActivity = downstreamActivity;
1145 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001146
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001148
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 status.numSyncs++;
1150 status.totalElapsedTime += elapsedTime;
1151 switch (item.source) {
1152 case SOURCE_LOCAL:
1153 status.numSourceLocal++;
1154 break;
1155 case SOURCE_POLL:
1156 status.numSourcePoll++;
1157 break;
1158 case SOURCE_USER:
1159 status.numSourceUser++;
1160 break;
1161 case SOURCE_SERVER:
1162 status.numSourceServer++;
1163 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001164 case SOURCE_PERIODIC:
1165 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001166 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001167 }
Costin Manolache360e4542009-09-04 13:36:04 -07001168
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001170 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 if (mDayStats[0] == null) {
1172 mDayStats[0] = new DayStats(day);
1173 } else if (day != mDayStats[0].day) {
1174 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1175 mDayStats[0] = new DayStats(day);
1176 writeStatisticsNow = true;
1177 } else if (mDayStats[0] == null) {
1178 }
1179 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001180
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 final long lastSyncTime = (item.eventTime + elapsedTime);
1182 boolean writeStatusNow = false;
1183 if (MESG_SUCCESS.equals(resultMessage)) {
1184 // - if successful, update the successful columns
1185 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1186 writeStatusNow = true;
1187 }
1188 status.lastSuccessTime = lastSyncTime;
1189 status.lastSuccessSource = item.source;
1190 status.lastFailureTime = 0;
1191 status.lastFailureSource = -1;
1192 status.lastFailureMesg = null;
1193 status.initialFailureTime = 0;
1194 ds.successCount++;
1195 ds.successTime += elapsedTime;
1196 } else if (!MESG_CANCELED.equals(resultMessage)) {
1197 if (status.lastFailureTime == 0) {
1198 writeStatusNow = true;
1199 }
1200 status.lastFailureTime = lastSyncTime;
1201 status.lastFailureSource = item.source;
1202 status.lastFailureMesg = resultMessage;
1203 if (status.initialFailureTime == 0) {
1204 status.initialFailureTime = lastSyncTime;
1205 }
1206 ds.failureCount++;
1207 ds.failureTime += elapsedTime;
1208 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001209 final StringBuilder event = new StringBuilder();
1210 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1211 + " Elapsed=");
1212 SyncManager.formatDurationHMS(event, elapsedTime);
1213 event.append(" Reason=");
1214 event.append(SyncOperation.reasonToString(null, item.reason));
1215 event.append(" Extras=");
1216 SyncOperation.extrasToStringBuilder(item.extras, event);
1217
1218 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001219
Dianne Hackborn231cc602009-04-27 17:10:36 -07001220 if (writeStatusNow) {
1221 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001222 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1223 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 WRITE_STATUS_DELAY);
1225 }
1226 if (writeStatisticsNow) {
1227 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001228 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1229 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001230 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001231 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001232 }
Costin Manolache360e4542009-09-04 13:36:04 -07001233
Fred Quintanaac9385e2009-06-22 18:00:59 -07001234 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 }
1236
1237 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001238 * Return a list of the currently active syncs. Note that the returned
1239 * items are the real, live active sync objects, so be careful what you do
1240 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001241 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001242 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001243 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001244 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 }
1246 }
Costin Manolache360e4542009-09-04 13:36:04 -07001247
Dianne Hackborn231cc602009-04-27 17:10:36 -07001248 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001249 * @param userId Id of user to return current sync info.
1250 * @param canAccessAccounts Determines whether to redact Account information from the result.
1251 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001252 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001253 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001254 synchronized (mAuthorities) {
1255 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1256 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1257 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001258 SyncInfo copy;
1259 if (!canAccessAccounts) {
1260 copy = SyncInfo.createAccountRedacted(
1261 sync.authorityId, sync.authority, sync.startTime);
1262 } else {
1263 copy = new SyncInfo(sync);
1264 }
1265 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001266 }
1267 return syncsCopy;
1268 }
1269 }
1270
1271 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1272 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1273 if (syncs == null) {
1274 syncs = new ArrayList<SyncInfo>();
1275 mCurrentSyncs.put(userId, syncs);
1276 }
1277 return syncs;
1278 }
1279
1280 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001281 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001282 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001283 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001284 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001285 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001286 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001287 true /* write to storage if this results in a change */);
1288 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1289 }
1290 }
1291
1292 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001293 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001294 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001295 * @param info the endpoint target we are querying status info for.
1296 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001298 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001299 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001300 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001301 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001302 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001304 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001305 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001307 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001308 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001309 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001310 }
1311 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001312 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001313 }
1314 }
Costin Manolache360e4542009-09-04 13:36:04 -07001315
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001316 /** Return true if the pending status is true of any matching authorities. */
1317 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001318 synchronized (mAuthorities) {
1319 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001320 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001321 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001322 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1323 if (ainfo == null) {
1324 continue;
1325 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001326 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001327 continue;
1328 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001329 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001330 return true;
1331 }
1332 }
1333 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335 }
1336
1337 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001338 * Return an array of the current sync status for all authorities. Note
1339 * that the objects inside the array are the real, live status objects,
1340 * so be careful what you do with them.
1341 */
1342 public ArrayList<SyncHistoryItem> getSyncHistory() {
1343 synchronized (mAuthorities) {
1344 final int N = mSyncHistory.size();
1345 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1346 for (int i=0; i<N; i++) {
1347 items.add(mSyncHistory.get(i));
1348 }
1349 return items;
1350 }
1351 }
Costin Manolache360e4542009-09-04 13:36:04 -07001352
Dianne Hackborn231cc602009-04-27 17:10:36 -07001353 /**
1354 * Return an array of the current per-day statistics. Note
1355 * that the objects inside the array are the real, live status objects,
1356 * so be careful what you do with them.
1357 */
1358 public DayStats[] getDayStatistics() {
1359 synchronized (mAuthorities) {
1360 DayStats[] ds = new DayStats[mDayStats.length];
1361 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1362 return ds;
1363 }
1364 }
Costin Manolache360e4542009-09-04 13:36:04 -07001365
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001366 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1367 AuthorityInfo authorityInfo) {
1368 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1369 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1370 }
1371
Dianne Hackborn55280a92009-05-07 15:53:46 -07001372 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 mCal.setTimeInMillis(System.currentTimeMillis());
1374 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1375 if (mYear != mCal.get(Calendar.YEAR)) {
1376 mYear = mCal.get(Calendar.YEAR);
1377 mCal.clear();
1378 mCal.set(Calendar.YEAR, mYear);
1379 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1380 }
1381 return dayOfYear + mYearInDays;
1382 }
Costin Manolache360e4542009-09-04 13:36:04 -07001383
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001385 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001386 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001387 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001389 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001390 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001391 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001392 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1393 AccountInfo accountInfo = mAccounts.get(au);
1394 if (accountInfo == null) {
1395 if (tag != null) {
1396 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1397 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001398 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001399 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 return null;
1401 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001402 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1403 if (authority == null) {
1404 if (tag != null) {
1405 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1406 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1407 }
1408 }
1409 return null;
1410 }
1411 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001412 }
Costin Manolache360e4542009-09-04 13:36:04 -07001413
Matthew Williamsfa774182013-06-18 15:44:11 -07001414 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001415 * @param info info identifying target.
1416 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001417 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001418 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001419 * exists.
1420 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001421 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1422 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001423 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1424 AccountInfo account = mAccounts.get(au);
1425 if (account == null) {
1426 account = new AccountInfo(au);
1427 mAccounts.put(au, account);
1428 }
1429 authority = account.authorities.get(info.provider);
1430 if (authority == null) {
1431 authority = createAuthorityLocked(info, ident, doWrite);
1432 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001433 }
1434 return authority;
1435 }
1436
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001437 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1438 AuthorityInfo authority;
1439 if (ident < 0) {
1440 ident = mNextAuthorityId;
1441 mNextAuthorityId++;
1442 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001443 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001444 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001445 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001446 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001447 authority = new AuthorityInfo(info, ident);
1448 mAuthorities.put(ident, authority);
1449 if (doWrite) {
1450 writeAccountInfoLocked();
1451 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001452 return authority;
1453 }
Costin Manolache360e4542009-09-04 13:36:04 -07001454
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001455 public void removeAuthority(EndPoint info) {
1456 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001457 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001458 }
1459 }
1460
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001461
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001462 /**
1463 * Remove an authority associated with a provider. Needs to be a standalone function for
1464 * backward compatibility.
1465 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001466 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001467 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001468 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001469 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001470 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1471 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001472 if (mAuthorityRemovedListener != null) {
1473 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1474 }
Fred Quintanafb084402010-03-23 17:57:03 -07001475 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001476 if (doWrite) {
1477 writeAccountInfoLocked();
1478 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001479 }
1480 }
1481 }
1482
Dianne Hackborn231cc602009-04-27 17:10:36 -07001483 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1484 SyncStatusInfo status = mSyncStatus.get(authorityId);
1485 if (status == null) {
1486 status = new SyncStatusInfo(authorityId);
1487 mSyncStatus.put(authorityId, status);
1488 }
1489 return status;
1490 }
Costin Manolache360e4542009-09-04 13:36:04 -07001491
Dianne Hackborn55280a92009-05-07 15:53:46 -07001492 public void writeAllState() {
1493 synchronized (mAuthorities) {
1494 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001495 writeStatusLocked();
1496 writeStatisticsLocked();
1497 }
1498 }
Costin Manolache360e4542009-09-04 13:36:04 -07001499
Svet Ganov65712b02016-09-01 10:24:11 -07001500 public boolean shouldGrantSyncAdaptersAccountAccess() {
1501 return mGrantSyncAdaptersAccountAccess;
1502 }
1503
Dianne Hackborn231cc602009-04-27 17:10:36 -07001504 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001505 * public for testing
1506 */
1507 public void clearAndReadState() {
1508 synchronized (mAuthorities) {
1509 mAuthorities.clear();
1510 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001511 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001512 mSyncStatus.clear();
1513 mSyncHistory.clear();
1514
1515 readAccountInfoLocked();
1516 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001517 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001518 readAndDeleteLegacyAccountInfoLocked();
1519 writeAccountInfoLocked();
1520 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001521 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001522 }
1523 }
1524
1525 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 * Read all account information back in to the initial engine state.
1527 */
1528 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001529 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001532 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001533 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001534 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001535 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001536 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001537 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001538 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001539 while (eventType != XmlPullParser.START_TAG &&
1540 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001541 eventType = parser.next();
1542 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001543 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001544 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001545 return;
1546 }
1547
Dianne Hackborn231cc602009-04-27 17:10:36 -07001548 String tagName = parser.getName();
1549 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001550 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001551 String versionString = parser.getAttributeValue(null, "version");
1552 int version;
1553 try {
1554 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1555 } catch (NumberFormatException e) {
1556 version = 0;
1557 }
Svet Ganov65712b02016-09-01 10:24:11 -07001558
1559 if (version < 3) {
1560 mGrantSyncAdaptersAccountAccess = true;
1561 }
1562
Amith Yamasani04e0d262012-02-14 11:50:53 -08001563 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001564 try {
1565 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1566 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1567 } catch (NumberFormatException e) {
1568 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001569 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001570 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1571 try {
1572 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1573 } catch (NumberFormatException e) {
1574 mSyncRandomOffset = 0;
1575 }
1576 if (mSyncRandomOffset == 0) {
1577 Random random = new Random(System.currentTimeMillis());
1578 mSyncRandomOffset = random.nextInt(86400);
1579 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001580 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001581 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001582 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001583 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001584 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001586 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001587 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001588 if (parser.getDepth() == 2) {
1589 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001590 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001591 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001592 if (authority != null) {
1593 if (authority.ident > highestAuthorityId) {
1594 highestAuthorityId = authority.ident;
1595 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001596 } else {
1597 EventLog.writeEvent(0x534e4554, "26513719", -1,
1598 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001599 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001600 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1601 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001602 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001603 } else if (parser.getDepth() == 3) {
1604 if ("periodicSync".equals(tagName) && authority != null) {
1605 periodicSync = parsePeriodicSync(parser, authority);
1606 }
1607 } else if (parser.getDepth() == 4 && periodicSync != null) {
1608 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001609 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001610 }
1611 }
1612 }
1613 eventType = parser.next();
1614 } while (eventType != XmlPullParser.END_DOCUMENT);
1615 }
1616 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001617 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001618 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001619 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001620 if (fis == null) Slog.i(TAG, "No initial accounts");
1621 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001622 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001623 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001624 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001625 if (fis != null) {
1626 try {
1627 fis.close();
1628 } catch (java.io.IOException e1) {
1629 }
1630 }
1631 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001632
Fred Quintana77c560f2010-03-29 22:20:26 -07001633 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001634 }
Costin Manolache360e4542009-09-04 13:36:04 -07001635
Fred Quintanafb084402010-03-23 17:57:03 -07001636 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001637 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1638 * pending.xml was used starting in KLP.
1639 * @param syncDir directory where the sync files are located.
1640 */
1641 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1642 File file = new File(syncDir, "pending.bin");
1643 if (!file.exists()) {
1644 return;
1645 } else {
1646 file.delete();
1647 }
1648 }
1649
1650 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001651 * some authority names have changed. copy over their settings and delete the old ones
1652 * @return true if a change was made
1653 */
1654 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1655 boolean writeNeeded = false;
1656
1657 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1658 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001659 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001660 AuthorityInfo authority = mAuthorities.valueAt(i);
1661 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001662 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001663 if (newAuthorityName == null) {
1664 continue;
1665 }
1666
1667 // remember this authority so we can remove it later. we can't remove it
1668 // now without messing up this loop iteration
1669 authoritiesToRemove.add(authority);
1670
1671 // this authority isn't enabled, no need to copy it to the new authority name since
1672 // the default is "disabled"
1673 if (!authority.enabled) {
1674 continue;
1675 }
1676
1677 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001678 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001679 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001680 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001681 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001682 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001683 continue;
1684 }
1685
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001686 AuthorityInfo newAuthority =
1687 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001688 newAuthority.enabled = true;
1689 writeNeeded = true;
1690 }
1691
1692 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001693 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001694 authorityInfo.target.account,
1695 authorityInfo.target.userId,
1696 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001697 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001698 writeNeeded = true;
1699 }
1700
1701 return writeNeeded;
1702 }
1703
Amith Yamasani04e0d262012-02-14 11:50:53 -08001704 private void parseListenForTickles(XmlPullParser parser) {
1705 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1706 int userId = 0;
1707 try {
1708 userId = Integer.parseInt(user);
1709 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001710 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001712 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001713 }
1714 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1715 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1716 mMasterSyncAutomatically.put(userId, listen);
1717 }
1718
Suprabh Shukla042a4782017-05-12 15:26:54 -07001719 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1720 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001721 AuthorityInfo authority = null;
1722 int id = -1;
1723 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001724 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001725 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001726 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001727 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001728 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001729 }
1730 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001731 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001732 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001733 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001734 String accountName = parser.getAttributeValue(null, "account");
1735 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001736 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001737 String packageName = parser.getAttributeValue(null, "package");
1738 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001739 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001740 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001741 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001742 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001743 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001744 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001745 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001746 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001747 + " account=" + accountName
1748 + " accountType=" + accountType
1749 + " auth=" + authorityName
1750 + " package=" + packageName
1751 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001752 + " user=" + userId
1753 + " enabled=" + enabled
1754 + " syncable=" + syncable);
1755 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001756 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001757 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001758 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001759 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001760 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001761 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001762 new Account(accountName, accountType),
1763 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001764 if (validator.isAccountValid(info.account, userId)
1765 && validator.isAuthorityValid(authorityName, userId)) {
1766 authority = getOrCreateAuthorityLocked(info, id, false);
1767 // If the version is 0 then we are upgrading from a file format that did not
1768 // know about periodic syncs. In that case don't clear the list since we
1769 // want the default, which is a daily periodic sync.
1770 // Otherwise clear out this default list since we will populate it later
1771 // with
1772 // the periodic sync descriptions that are read from the configuration file.
1773 if (version > 0) {
1774 authority.periodicSyncs.clear();
1775 }
1776 } else {
1777 EventLog.writeEvent(0x534e4554, "35028827", -1,
1778 "account:" + info.account + " provider:" + authorityName + " user:"
1779 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001780 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001781 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001782 }
1783 if (authority != null) {
1784 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001785 try {
1786 authority.syncable = (syncable == null) ?
1787 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1788 } catch (NumberFormatException e) {
1789 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1790 // format.
1791 if ("unknown".equals(syncable)) {
1792 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1793 } else {
1794 authority.syncable = Boolean.parseBoolean(syncable) ?
1795 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1796 }
1797
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001798 }
1799 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001800 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001801 + accountName + " auth=" + authorityName
1802 + " enabled=" + enabled
1803 + " syncable=" + syncable);
1804 }
1805 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001806 return authority;
1807 }
1808
Matthew Williamsfa774182013-06-18 15:44:11 -07001809 /**
1810 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1811 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001812 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001813 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001814 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001815 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001816 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001817 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001818 try {
1819 period = Long.parseLong(periodValue);
1820 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001821 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001822 return null;
1823 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001824 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001825 return null;
1826 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001827 try {
1828 flextime = Long.parseLong(flexValue);
1829 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001830 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001831 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001832 + ", using default: "
1833 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001834 } catch (NullPointerException expected) {
1835 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001836 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1837 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001838 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001839 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001840 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001841 new PeriodicSync(authorityInfo.target.account,
1842 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001843 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001844 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001845 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001846 return periodicSync;
1847 }
1848
Matthew Williamsfa774182013-06-18 15:44:11 -07001849 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001850 String name = parser.getAttributeValue(null, "name");
1851 String type = parser.getAttributeValue(null, "type");
1852 String value1 = parser.getAttributeValue(null, "value1");
1853 String value2 = parser.getAttributeValue(null, "value2");
1854
1855 try {
1856 if ("long".equals(type)) {
1857 extras.putLong(name, Long.parseLong(value1));
1858 } else if ("integer".equals(type)) {
1859 extras.putInt(name, Integer.parseInt(value1));
1860 } else if ("double".equals(type)) {
1861 extras.putDouble(name, Double.parseDouble(value1));
1862 } else if ("float".equals(type)) {
1863 extras.putFloat(name, Float.parseFloat(value1));
1864 } else if ("boolean".equals(type)) {
1865 extras.putBoolean(name, Boolean.parseBoolean(value1));
1866 } else if ("string".equals(type)) {
1867 extras.putString(name, value1);
1868 } else if ("account".equals(type)) {
1869 extras.putParcelable(name, new Account(value1, value2));
1870 }
1871 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001872 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001873 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001874 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001875 }
1876 }
1877
Dianne Hackborn231cc602009-04-27 17:10:36 -07001878 /**
1879 * Write all account information to the account file.
1880 */
1881 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001882 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001883 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001884 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001886
Dianne Hackborn231cc602009-04-27 17:10:36 -07001887 try {
1888 fos = mAccountInfoFile.startWrite();
1889 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001890 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001891 out.startDocument(null, true);
1892 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001893
Dianne Hackborn231cc602009-04-27 17:10:36 -07001894 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001895 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001897 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001898
1899 // Write the Sync Automatically flags for each user
1900 final int M = mMasterSyncAutomatically.size();
1901 for (int m = 0; m < M; m++) {
1902 int userId = mMasterSyncAutomatically.keyAt(m);
1903 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1904 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1905 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1906 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1907 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 }
Costin Manolache360e4542009-09-04 13:36:04 -07001909
Dianne Hackborn231cc602009-04-27 17:10:36 -07001910 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001911 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001912 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001913 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001914 out.startTag(null, "authority");
1915 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001916 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001917 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001918 out.attribute(null, "account", info.account.name);
1919 out.attribute(null, "type", info.account.type);
1920 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001921 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001922 out.endTag(null, "authority");
1923 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001924 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001925 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001926 mAccountInfoFile.finishWrite(fos);
1927 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001928 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001929 if (fos != null) {
1930 mAccountInfoFile.failWrite(fos);
1931 }
1932 }
1933 }
Costin Manolache360e4542009-09-04 13:36:04 -07001934
Dianne Hackborn231cc602009-04-27 17:10:36 -07001935 static int getIntColumn(Cursor c, String name) {
1936 return c.getInt(c.getColumnIndex(name));
1937 }
Costin Manolache360e4542009-09-04 13:36:04 -07001938
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 static long getLongColumn(Cursor c, String name) {
1940 return c.getLong(c.getColumnIndex(name));
1941 }
Costin Manolache360e4542009-09-04 13:36:04 -07001942
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 /**
1944 * Load sync engine state from the old syncmanager database, and then
1945 * erase it. Note that we don't deal with pending operations, active
1946 * sync, or history.
1947 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001948 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001949 // Look for old database to initialize from.
1950 File file = mContext.getDatabasePath("syncmanager.db");
1951 if (!file.exists()) {
1952 return;
1953 }
1954 String path = file.getPath();
1955 SQLiteDatabase db = null;
1956 try {
1957 db = SQLiteDatabase.openDatabase(path, null,
1958 SQLiteDatabase.OPEN_READONLY);
1959 } catch (SQLiteException e) {
1960 }
Costin Manolache360e4542009-09-04 13:36:04 -07001961
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001963 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001964
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001966 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001967 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001968 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1970 qb.setTables("stats, status");
1971 HashMap<String,String> map = new HashMap<String,String>();
1972 map.put("_id", "status._id as _id");
1973 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001974 if (hasType) {
1975 map.put("account_type", "stats.account_type as account_type");
1976 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001977 map.put("authority", "stats.authority as authority");
1978 map.put("totalElapsedTime", "totalElapsedTime");
1979 map.put("numSyncs", "numSyncs");
1980 map.put("numSourceLocal", "numSourceLocal");
1981 map.put("numSourcePoll", "numSourcePoll");
1982 map.put("numSourceServer", "numSourceServer");
1983 map.put("numSourceUser", "numSourceUser");
1984 map.put("lastSuccessSource", "lastSuccessSource");
1985 map.put("lastSuccessTime", "lastSuccessTime");
1986 map.put("lastFailureSource", "lastFailureSource");
1987 map.put("lastFailureTime", "lastFailureTime");
1988 map.put("lastFailureMesg", "lastFailureMesg");
1989 map.put("pending", "pending");
1990 qb.setProjectionMap(map);
1991 qb.appendWhere("stats._id = status.stats_id");
1992 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001995 String accountType = hasType
1996 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001997 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001998 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002001 AuthorityInfo authority =
2002 this.getOrCreateAuthorityLocked(
2003 new EndPoint(new Account(accountName, accountType),
2004 authorityName,
2005 0 /* legacy is single-user */)
2006 , -1,
2007 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002008 if (authority != null) {
2009 int i = mSyncStatus.size();
2010 boolean found = false;
2011 SyncStatusInfo st = null;
2012 while (i > 0) {
2013 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002014 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 if (st.authorityId == authority.ident) {
2016 found = true;
2017 break;
2018 }
2019 }
2020 if (!found) {
2021 st = new SyncStatusInfo(authority.ident);
2022 mSyncStatus.put(authority.ident, st);
2023 }
2024 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2025 st.numSyncs = getIntColumn(c, "numSyncs");
2026 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2027 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2028 st.numSourceServer = getIntColumn(c, "numSourceServer");
2029 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002030 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002031 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2032 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2033 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2034 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2035 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2036 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 }
Costin Manolache360e4542009-09-04 13:36:04 -07002039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002041
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 // Retrieve the settings.
2043 qb = new SQLiteQueryBuilder();
2044 qb.setTables("settings");
2045 c = qb.query(db, null, null, null, null, null, null);
2046 while (c.moveToNext()) {
2047 String name = c.getString(c.getColumnIndex("name"));
2048 String value = c.getString(c.getColumnIndex("value"));
2049 if (name == null) continue;
2050 if (name.equals("listen_for_tickles")) {
Makoto Onuki75ad2492018-03-28 14:42:42 -07002051 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0,
2052 ContentResolver.SYNC_EXEMPTION_NONE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002053 } else if (name.startsWith("sync_provider_")) {
2054 String provider = name.substring("sync_provider_".length(),
2055 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002056 int i = mAuthorities.size();
2057 while (i > 0) {
2058 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002059 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002060 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002061 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002062 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002063 }
2064 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
Costin Manolache360e4542009-09-04 13:36:04 -07002067
Dianne Hackborn231cc602009-04-27 17:10:36 -07002068 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002069
Dianne Hackborn231cc602009-04-27 17:10:36 -07002070 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002071
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 (new File(path)).delete();
2073 }
2074 }
Costin Manolache360e4542009-09-04 13:36:04 -07002075
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 public static final int STATUS_FILE_END = 0;
2077 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002078
Dianne Hackborn231cc602009-04-27 17:10:36 -07002079 /**
2080 * Read all sync status back in to the initial engine state.
2081 */
2082 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002083 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002084 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002085 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002086 try {
2087 byte[] data = mStatusFile.readFully();
2088 Parcel in = Parcel.obtain();
2089 in.unmarshall(data, 0, data.length);
2090 in.setDataPosition(0);
2091 int token;
2092 while ((token=in.readInt()) != STATUS_FILE_END) {
2093 if (token == STATUS_FILE_ITEM) {
2094 SyncStatusInfo status = new SyncStatusInfo(in);
2095 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2096 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002097 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002098 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002099 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002100 mSyncStatus.put(status.authorityId, status);
2101 }
2102 } else {
2103 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002104 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002105 break;
2106 }
2107 }
2108 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002109 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002110 }
2111 }
Costin Manolache360e4542009-09-04 13:36:04 -07002112
Dianne Hackborn231cc602009-04-27 17:10:36 -07002113 /**
2114 * Write all sync status to the sync status file.
2115 */
2116 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002117 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002118 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002119 }
Costin Manolache360e4542009-09-04 13:36:04 -07002120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 // The file is being written, so we don't need to have a scheduled
2122 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002123 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002124
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 FileOutputStream fos = null;
2126 try {
2127 fos = mStatusFile.startWrite();
2128 Parcel out = Parcel.obtain();
2129 final int N = mSyncStatus.size();
2130 for (int i=0; i<N; i++) {
2131 SyncStatusInfo status = mSyncStatus.valueAt(i);
2132 out.writeInt(STATUS_FILE_ITEM);
2133 status.writeToParcel(out, 0);
2134 }
2135 out.writeInt(STATUS_FILE_END);
2136 fos.write(out.marshall());
2137 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002138
Dianne Hackborn231cc602009-04-27 17:10:36 -07002139 mStatusFile.finishWrite(fos);
2140 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002141 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002142 if (fos != null) {
2143 mStatusFile.failWrite(fos);
2144 }
2145 }
2146 }
Costin Manolache360e4542009-09-04 13:36:04 -07002147
Makoto Onuki61283ec2018-01-31 17:22:36 -08002148 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002149 @SyncExemption int syncExemptionFlag) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002150 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2151 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002152 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002153 syncExemptionFlag);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002154 } else {
2155 SyncRequest.Builder req =
2156 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002157 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002158 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002159 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002160 ContentResolver.requestSync(req.build());
2161 }
2162 }
2163
Alon Albert57286f92012-10-09 14:21:38 -07002164 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002165 Bundle extras, @SyncExemption int syncExemptionFlag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002166 // If this is happening in the system process, then call the syncrequest listener
2167 // to make a request back to the SyncManager directly.
2168 // If this is probably a test instance, then call back through the ContentResolver
2169 // which will know which userId to apply based on the Binder id.
2170 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2171 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002172 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002173 new EndPoint(account, authority, userId),
Makoto Onuki75ad2492018-03-28 14:42:42 -07002174 reason, extras, syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002175 } else {
2176 ContentResolver.requestSync(account, authority, extras);
2177 }
2178 }
2179
Dianne Hackborn231cc602009-04-27 17:10:36 -07002180 public static final int STATISTICS_FILE_END = 0;
2181 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2182 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002183
Dianne Hackborn231cc602009-04-27 17:10:36 -07002184 /**
2185 * Read all sync statistics back in to the initial engine state.
2186 */
2187 private void readStatisticsLocked() {
2188 try {
2189 byte[] data = mStatisticsFile.readFully();
2190 Parcel in = Parcel.obtain();
2191 in.unmarshall(data, 0, data.length);
2192 in.setDataPosition(0);
2193 int token;
2194 int index = 0;
2195 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2196 if (token == STATISTICS_FILE_ITEM
2197 || token == STATISTICS_FILE_ITEM_OLD) {
2198 int day = in.readInt();
2199 if (token == STATISTICS_FILE_ITEM_OLD) {
2200 day = day - 2009 + 14245; // Magic!
2201 }
2202 DayStats ds = new DayStats(day);
2203 ds.successCount = in.readInt();
2204 ds.successTime = in.readLong();
2205 ds.failureCount = in.readInt();
2206 ds.failureTime = in.readLong();
2207 if (index < mDayStats.length) {
2208 mDayStats[index] = ds;
2209 index++;
2210 }
2211 } else {
2212 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002213 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002214 break;
2215 }
2216 }
2217 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002218 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002219 }
2220 }
Costin Manolache360e4542009-09-04 13:36:04 -07002221
Dianne Hackborn231cc602009-04-27 17:10:36 -07002222 /**
2223 * Write all sync statistics to the sync status file.
2224 */
2225 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002226 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002227 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002228 }
Costin Manolache360e4542009-09-04 13:36:04 -07002229
Dianne Hackborn231cc602009-04-27 17:10:36 -07002230 // The file is being written, so we don't need to have a scheduled
2231 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002232 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002233
Dianne Hackborn231cc602009-04-27 17:10:36 -07002234 FileOutputStream fos = null;
2235 try {
2236 fos = mStatisticsFile.startWrite();
2237 Parcel out = Parcel.obtain();
2238 final int N = mDayStats.length;
2239 for (int i=0; i<N; i++) {
2240 DayStats ds = mDayStats[i];
2241 if (ds == null) {
2242 break;
2243 }
2244 out.writeInt(STATISTICS_FILE_ITEM);
2245 out.writeInt(ds.day);
2246 out.writeInt(ds.successCount);
2247 out.writeLong(ds.successTime);
2248 out.writeInt(ds.failureCount);
2249 out.writeLong(ds.failureTime);
2250 }
2251 out.writeInt(STATISTICS_FILE_END);
2252 fos.write(out.marshall());
2253 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002254
Dianne Hackborn231cc602009-04-27 17:10:36 -07002255 mStatisticsFile.finishWrite(fos);
2256 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002257 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002258 if (fos != null) {
2259 mStatisticsFile.failWrite(fos);
2260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
2262 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002263
2264 /**
Marvin Paula6533252014-11-24 12:57:48 -08002265 * Let the BackupManager know that account sync settings have changed. This will trigger
2266 * {@link com.android.server.backup.SystemBackupAgent} to run.
2267 */
2268 public void queueBackup() {
2269 BackupManager.dataChanged("android");
2270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271}