blob: e498666073edfa4409867f867cb2664b81312c4a [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;
25import android.content.Context;
26import android.content.ISyncStatusObserver;
27import android.content.PeriodicSync;
28import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070029import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080030import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070031import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070036import android.os.Bundle;
37import android.os.Environment;
38import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080039import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import android.os.Message;
41import android.os.Parcel;
42import android.os.RemoteCallbackList;
43import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070044import android.os.UserHandle;
Shreyas Basarge8c834c02016-01-07 13:53:16 +000045import android.util.*;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080046
47import com.android.internal.annotations.VisibleForTesting;
48import com.android.internal.util.ArrayUtils;
49import com.android.internal.util.FastXmlSerializer;
50
51import org.xmlpull.v1.XmlPullParser;
52import org.xmlpull.v1.XmlPullParserException;
53import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054
Dianne Hackborn231cc602009-04-27 17:10:36 -070055import java.io.File;
56import java.io.FileInputStream;
57import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010058import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070060import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070062import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080063import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070064import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060065import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
67/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070068 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070070 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071 * @hide
72 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080073public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070076 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070077
Amith Yamasani04e0d262012-02-14 11:50:53 -080078 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
79 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070080 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080081 private static final String XML_ATTR_ENABLED = "enabled";
82 private static final String XML_ATTR_USER = "user";
83 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
84
Matthew Williamsfa774182013-06-18 15:44:11 -070085 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000086 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080087
Shreyas Basarge8c834c02016-01-07 13:53:16 +000088 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070089 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
90
91 /** Lower bound on sync time from which we assign a default flex time. */
92 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
93
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080094 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070095 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a sync start event. */
98 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a sync stop event. */
101 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a server-initiated sync. */
104 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 /** Enum value for a local-initiated sync. */
107 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700108 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700109 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a user-initiated sync. */
112 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800114 /** Enum value for a periodic sync. */
115 public static final int SOURCE_PERIODIC = 4;
116
Fred Quintana307da1a2010-01-21 14:24:20 -0800117 public static final long NOT_IN_BACKOFF_MODE = -1;
118
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 // TODO: i18n -- grab these out of resources.
120 /** String names for the sync source types. */
121 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000122 "LOCAL",
123 "POLL",
124 "USER",
125 "PERIODIC",
126 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
Dianne Hackborn231cc602009-04-27 17:10:36 -0700128 // The MESG column will contain one of these or one of the Error types.
129 public static final String MESG_SUCCESS = "success";
130 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700132 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATUS = 1;
135 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700136
Dianne Hackborn231cc602009-04-27 17:10:36 -0700137 private static final int MSG_WRITE_STATISTICS = 2;
138 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700139
140 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700141
Fred Quintanac2e46912010-03-15 16:10:44 -0700142 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700143 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700144
145 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000146 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700147
148 static {
149 sAuthorityRenames = new HashMap<String, String>();
150 sAuthorityRenames.put("contacts", "com.android.contacts");
151 sAuthorityRenames.put("calendar", "com.android.calendar");
152 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700153
Dianne Hackborn231cc602009-04-27 17:10:36 -0700154 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800155 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700156 final HashMap<String, AuthorityInfo> authorities =
157 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700158
Amith Yamasani04e0d262012-02-14 11:50:53 -0800159 AccountInfo(AccountAndUser accountAndUser) {
160 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700161 }
162 }
Costin Manolache360e4542009-09-04 13:36:04 -0700163
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700164 /** Bare bones representation of a sync target. */
165 public static class EndPoint {
166 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
167 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700168 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800169 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700170 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700171
172 public EndPoint(Account account, String provider, int userId) {
173 this.account = account;
174 this.provider = provider;
175 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700176 }
177
178 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700179 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
180 *
181 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000182 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700184 public boolean matchesSpec(EndPoint spec) {
185 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700186 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700187 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700188 return false;
189 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000190 boolean accountsMatch;
191 if (spec.account == null) {
192 accountsMatch = true;
193 } else {
194 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700195 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000196 boolean providersMatch;
197 if (spec.provider == null) {
198 providersMatch = true;
199 } else {
200 providersMatch = provider.equals(spec.provider);
201 }
202 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700203 }
204
205 public String toString() {
206 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000207 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 .append("/")
209 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700210 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700211 return sb.toString();
212 }
213 }
214
215 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700216 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700217
218 /**
219 * The syncable state is undefined.
220 */
221 public static final int UNDEFINED = -2;
222
Matthew Williams53abfdb2015-06-10 20:06:37 -0700223 /**
224 * Default state for a newly installed adapter. An uninitialized adapter will receive an
225 * initialization sync which are governed by a different set of rules to that of regular
226 * syncs.
227 */
228 public static final int NOT_INITIALIZED = -1;
229 /**
230 * The adapter will not receive any syncs. This is behaviourally equivalent to
231 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
232 * while this is generally meant to be controlled by the developer.
233 */
234 public static final int NOT_SYNCABLE = 0;
235 /**
236 * The adapter is initialized and functioning. This is the normal state for an adapter.
237 */
238 public static final int SYNCABLE = 1;
239 /**
240 * The adapter is syncable but still requires an initialization sync. For example an adapter
241 * than has been restored from a previous device will be in this state. Not meant for
242 * external use.
243 */
244 public static final int SYNCABLE_NOT_INITIALIZED = 2;
245
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700246 /**
247 * The adapter is syncable but does not have access to the synced account and needs a
248 * user access approval.
249 */
250 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
251
Matthew Williams8ef22042013-07-26 12:56:39 -0700252 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700253 final int ident;
254 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700255 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700256 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800257 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700258 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800259 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700260 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800261 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700262
Matthew Williamsfa774182013-06-18 15:44:11 -0700263 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700264
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700265 /**
266 * Copy constructor for making deep-ish copies. Only the bundles stored
267 * in periodic syncs can make unexpected changes.
268 *
269 * @param toCopy AuthorityInfo to be copied.
270 */
271 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700272 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700273 ident = toCopy.ident;
274 enabled = toCopy.enabled;
275 syncable = toCopy.syncable;
276 backoffTime = toCopy.backoffTime;
277 backoffDelay = toCopy.backoffDelay;
278 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700279 periodicSyncs = new ArrayList<PeriodicSync>();
280 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700281 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700282 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700283 }
284 }
285
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700286 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700287 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700288 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000289 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700290 periodicSyncs = new ArrayList<PeriodicSync>();
291 defaultInitialisation();
292 }
293
294 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700295 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800296 backoffTime = -1; // if < 0 then we aren't in backoff mode
297 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000298
299 if (mPeriodicSyncAddedListener != null) {
300 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
301 DEFAULT_POLL_FREQUENCY_SECONDS,
302 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700303 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 }
Matthew Williams06485a72013-07-26 12:56:39 -0700305
306 @Override
307 public String toString() {
308 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
309 + backoffTime + ", delay=" + delayUntil;
310 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 }
Costin Manolache360e4542009-09-04 13:36:04 -0700312
Dianne Hackborn231cc602009-04-27 17:10:36 -0700313 public static class SyncHistoryItem {
314 int authorityId;
315 int historyId;
316 long eventTime;
317 long elapsedTime;
318 int source;
319 int event;
320 long upstreamActivity;
321 long downstreamActivity;
322 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700323 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700324 Bundle extras;
325 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700326 }
Costin Manolache360e4542009-09-04 13:36:04 -0700327
Dianne Hackborn231cc602009-04-27 17:10:36 -0700328 public static class DayStats {
329 public final int day;
330 public int successCount;
331 public long successTime;
332 public int failureCount;
333 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700334
Dianne Hackborn231cc602009-04-27 17:10:36 -0700335 public DayStats(int day) {
336 this.day = day;
337 }
338 }
Costin Manolache360e4542009-09-04 13:36:04 -0700339
Amith Yamasani04e0d262012-02-14 11:50:53 -0800340 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700341
342 /** Called when a sync is needed on an account(s) due to some change in state. */
343 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800344 }
345
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000346 interface PeriodicSyncAddedListener {
347 /** Called when a periodic sync is added. */
348 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
349 }
350
351 interface OnAuthorityRemovedListener {
352 /** Called when an authority is removed. */
353 void onAuthorityRemoved(EndPoint removedAuthority);
354 }
355
Suprabh Shukla042a4782017-05-12 15:26:54 -0700356 /**
357 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
358 * account is valid.
359 */
360 private static class AccountAuthorityValidator {
361 final private AccountManager mAccountManager;
362 final private PackageManager mPackageManager;
363 final private SparseArray<Account[]> mAccountsCache;
364 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
365
366 AccountAuthorityValidator(Context context) {
367 mAccountManager = context.getSystemService(AccountManager.class);
368 mPackageManager = context.getPackageManager();
369 mAccountsCache = new SparseArray<>();
370 mProvidersPerUserCache = new SparseArray<>();
371 }
372
373 // An account is valid if an installed authenticator has previously created that account
374 // on the device
375 boolean isAccountValid(Account account, int userId) {
376 Account[] accountsForUser = mAccountsCache.get(userId);
377 if (accountsForUser == null) {
378 accountsForUser = mAccountManager.getAccountsAsUser(userId);
379 mAccountsCache.put(userId, accountsForUser);
380 }
381 return ArrayUtils.contains(accountsForUser, account);
382 }
383
384 // An authority is only valid if it has a content provider installed on the system
385 boolean isAuthorityValid(String authority, int userId) {
386 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
387 if (authorityMap == null) {
388 authorityMap = new ArrayMap<>();
389 mProvidersPerUserCache.put(userId, authorityMap);
390 }
391 if (!authorityMap.containsKey(authority)) {
392 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
393 PackageManager.MATCH_DIRECT_BOOT_AWARE
394 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
395 }
396 return authorityMap.get(authority);
397 }
398 }
399
Dianne Hackborn231cc602009-04-27 17:10:36 -0700400 // Primary list of all syncable authorities. Also our global lock.
401 private final SparseArray<AuthorityInfo> mAuthorities =
402 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700403
Amith Yamasani04e0d262012-02-14 11:50:53 -0800404 private final HashMap<AccountAndUser, AccountInfo> mAccounts
405 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
408 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700409
Dianne Hackborn231cc602009-04-27 17:10:36 -0700410 private final SparseArray<SyncStatusInfo> mSyncStatus =
411 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700412
Dianne Hackborn231cc602009-04-27 17:10:36 -0700413 private final ArrayList<SyncHistoryItem> mSyncHistory =
414 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700415
Dianne Hackborn231cc602009-04-27 17:10:36 -0700416 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
417 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700418
Matthew Williams8ef22042013-07-26 12:56:39 -0700419 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700420 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
421 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700422
Fred Quintana77c560f2010-03-29 22:20:26 -0700423 private int mNextAuthorityId = 0;
424
Dianne Hackborn231cc602009-04-27 17:10:36 -0700425 // We keep 4 weeks of stats.
426 private final DayStats[] mDayStats = new DayStats[7*4];
427 private final Calendar mCal;
428 private int mYear;
429 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700430
Dianne Hackborn231cc602009-04-27 17:10:36 -0700431 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700434
Ashish Sharma69d95de2012-04-11 17:27:24 -0700435 private int mSyncRandomOffset;
436
Dianne Hackborn231cc602009-04-27 17:10:36 -0700437 /**
438 * This file contains the core engine state: all accounts and the
439 * settings for them. It must never be lost, and should be changed
440 * infrequently, so it is stored as an XML file.
441 */
442 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 /**
445 * This file contains the current sync status. We would like to retain
446 * it across boots, but its loss is not the end of the world, so we store
447 * this information as binary data.
448 */
449 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700450
Dianne Hackborn231cc602009-04-27 17:10:36 -0700451 /**
452 * This file contains sync statistics. This is purely debugging information
453 * so is written infrequently and can be thrown away at any time.
454 */
455 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700456
Dianne Hackborn231cc602009-04-27 17:10:36 -0700457 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800458 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800459 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800460
461 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000462 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700463
Svet Ganov65712b02016-09-01 10:24:11 -0700464 private boolean mGrantSyncAdaptersAccountAccess;
465
Makoto Onuki6963bea72017-12-12 10:42:39 -0800466 private final MyHandler mHandler;
467
468 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
469 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700472
Dianne Hackborn231cc602009-04-27 17:10:36 -0700473 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700474
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800475 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000476 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800477
Dianne Hackborn231cc602009-04-27 17:10:36 -0700478 File systemDir = new File(dataDir, "system");
479 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800480 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700481
482 maybeDeleteLegacyPendingInfoLocked(syncDir);
483
Dianne Hackborn231cc602009-04-27 17:10:36 -0700484 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
485 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700486 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700487
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 readAccountInfoLocked();
489 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700490 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700491 readAndDeleteLegacyAccountInfoLocked();
492 writeAccountInfoLocked();
493 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700494 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 }
496
497 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800498 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
Makoto Onuki6963bea72017-12-12 10:42:39 -0800501 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800502 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800503 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700505 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800506 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
508
509 public static SyncStorageEngine getSingleton() {
510 if (sSyncStorageEngine == null) {
511 throw new IllegalStateException("not initialized");
512 }
513 return sSyncStorageEngine;
514 }
515
Amith Yamasani04e0d262012-02-14 11:50:53 -0800516 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
517 if (mSyncRequestListener == null) {
518 mSyncRequestListener = listener;
519 }
520 }
521
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000522 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
523 if (mAuthorityRemovedListener == null) {
524 mAuthorityRemovedListener = listener;
525 }
526 }
527
528 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
529 if (mPeriodicSyncAddedListener == null) {
530 mPeriodicSyncAddedListener = listener;
531 }
532 }
533
Makoto Onuki6963bea72017-12-12 10:42:39 -0800534 private class MyHandler extends Handler {
535 public MyHandler(Looper looper) {
536 super(looper);
537 }
538
539 @Override
540 public void handleMessage(Message msg) {
541 if (msg.what == MSG_WRITE_STATUS) {
542 synchronized (mAuthorities) {
543 writeStatusLocked();
544 }
545 } else if (msg.what == MSG_WRITE_STATISTICS) {
546 synchronized (mAuthorities) {
547 writeStatisticsLocked();
548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 }
550 }
551 }
Costin Manolache360e4542009-09-04 13:36:04 -0700552
Ashish Sharma69d95de2012-04-11 17:27:24 -0700553 public int getSyncRandomOffset() {
554 return mSyncRandomOffset;
555 }
556
Dianne Hackborn231cc602009-04-27 17:10:36 -0700557 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
558 synchronized (mAuthorities) {
559 mChangeListeners.register(callback, mask);
560 }
561 }
Costin Manolache360e4542009-09-04 13:36:04 -0700562
Dianne Hackborn231cc602009-04-27 17:10:36 -0700563 public void removeStatusChangeListener(ISyncStatusObserver callback) {
564 synchronized (mAuthorities) {
565 mChangeListeners.unregister(callback);
566 }
567 }
Costin Manolache360e4542009-09-04 13:36:04 -0700568
Matthew Williamsfa774182013-06-18 15:44:11 -0700569 /**
570 * Figure out a reasonable flex time for cases where none is provided (old api calls).
571 * @param syncTimeSeconds requested sync time from now.
572 * @return amount of seconds before syncTimeSeconds that the sync can occur.
573 * I.e.
574 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700575 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700576 */
577 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
578 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
579 // Small enough sync request time that we don't add flex time - developer probably
580 // wants to wait for an operation to occur before syncing so we honour the
581 // request time.
582 return 0L;
583 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
584 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
585 } else {
586 // Large enough sync request time that we cap the flex time.
587 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
588 }
589 }
590
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000591 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700592 ArrayList<ISyncStatusObserver> reports = null;
593 synchronized (mAuthorities) {
594 int i = mChangeListeners.beginBroadcast();
595 while (i > 0) {
596 i--;
597 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
598 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 continue;
600 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700601 if (reports == null) {
602 reports = new ArrayList<ISyncStatusObserver>(i);
603 }
604 reports.add(mChangeListeners.getBroadcastItem(i));
605 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700606 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700607 }
Costin Manolache360e4542009-09-04 13:36:04 -0700608
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700609 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000610 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700611 }
Costin Manolache360e4542009-09-04 13:36:04 -0700612
Dianne Hackborn231cc602009-04-27 17:10:36 -0700613 if (reports != null) {
614 int i = reports.size();
615 while (i > 0) {
616 i--;
617 try {
618 reports.get(i).onStatusChanged(which);
619 } catch (RemoteException e) {
620 // The remote callback list will take care of this for us.
621 }
622 }
623 }
624 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700625
Amith Yamasani04e0d262012-02-14 11:50:53 -0800626 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700627 synchronized (mAuthorities) {
628 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700629 AuthorityInfo authority = getAuthorityLocked(
630 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700631 "getSyncAutomatically");
632 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700633 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700634
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 int i = mAuthorities.size();
636 while (i > 0) {
637 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700638 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700639 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700640 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700641 return true;
642 }
643 }
644 return false;
645 }
646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647
Amith Yamasani04e0d262012-02-14 11:50:53 -0800648 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000649 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700650 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000651 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800652 + ", user " + userId + " -> " + sync);
653 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700654 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700655 AuthorityInfo authority =
656 getOrCreateAuthorityLocked(
657 new EndPoint(account, providerName, userId),
658 -1 /* ident */,
659 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700660 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000662 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800663 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700664 return;
665 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700666 // If the adapter was syncable but missing its initialization sync, set it to
667 // uninitialized now. This is to give it a chance to run any one-time initialization
668 // logic.
669 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
670 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
671 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700672 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700673 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700675
Fred Quintana77c560f2010-03-29 22:20:26 -0700676 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700677 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
678 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700679 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700680 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800681 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 }
683
Amith Yamasani04e0d262012-02-14 11:50:53 -0800684 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700685 synchronized (mAuthorities) {
686 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700687 AuthorityInfo authority = getAuthorityLocked(
688 new EndPoint(account, providerName, userId),
689 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700690 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700691 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700692 }
693 return authority.syncable;
694 }
695
696 int i = mAuthorities.size();
697 while (i > 0) {
698 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700699 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700700 if (authorityInfo.target != null
701 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700702 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700703 }
704 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700705 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700706 }
707 }
708
Amith Yamasani04e0d262012-02-14 11:50:53 -0800709 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700710 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700711 }
712
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700713 /**
714 * An enabled sync service and a syncable provider's adapter both get resolved to the same
715 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700716 * @param target target to set value for.
717 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700718 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700719 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700720 AuthorityInfo aInfo;
721 synchronized (mAuthorities) {
722 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700723 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
724 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700725 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700726 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000727 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700728 }
729 if (aInfo.syncable == syncable) {
730 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000731 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700732 }
733 return;
734 }
735 aInfo.syncable = syncable;
736 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700737 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700738 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700739 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700740 }
741 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
742 }
743
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700744 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800745 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700746 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
747 if (authority != null) {
748 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800749 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700750 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800751 }
752 }
753
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700754 /**
755 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
756 * the account or provider info be null, which signifies all accounts or providers.
757 */
758 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
759 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000760 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800761 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
762 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700763 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800764 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000765 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700766 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000767 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700768 changed = setBackoffLocked(
769 info.account /* may be null */,
770 info.userId,
771 info.provider /* may be null */,
772 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800773 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700774 AuthorityInfo authorityInfo =
775 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
776 if (authorityInfo.backoffTime == nextSyncTime
777 && authorityInfo.backoffDelay == nextDelay) {
778 changed = false;
779 } else {
780 authorityInfo.backoffTime = nextSyncTime;
781 authorityInfo.backoffDelay = nextDelay;
782 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800783 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800784 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800785 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800786 if (changed) {
787 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
788 }
789 }
790
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700791 /**
792 * Either set backoff for a specific authority, or set backoff for all the
793 * accounts on a specific adapter/all adapters.
794 *
795 * @param account account for which to set backoff. Null to specify all accounts.
796 * @param userId id of the user making this request.
797 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700798 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700799 */
800 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000801 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700802 boolean changed = false;
803 for (AccountInfo accountInfo : mAccounts.values()) {
804 if (account != null && !account.equals(accountInfo.accountAndUser.account)
805 && userId != accountInfo.accountAndUser.userId) {
806 continue;
807 }
808 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
809 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700810 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700811 continue;
812 }
813 if (authorityInfo.backoffTime != nextSyncTime
814 || authorityInfo.backoffDelay != nextDelay) {
815 authorityInfo.backoffTime = nextSyncTime;
816 authorityInfo.backoffDelay = nextDelay;
817 changed = true;
818 }
819 }
820 }
821 return changed;
822 }
823
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000824 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800825 boolean changed = false;
826 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000827 // Clear backoff for all sync adapters.
828 for (AccountInfo accountInfo : mAccounts.values()) {
829 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
830 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
831 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
832 if (Log.isLoggable(TAG, Log.VERBOSE)) {
833 Slog.v(TAG, "clearAllBackoffsLocked:"
834 + " authority:" + authorityInfo.target
835 + " account:" + accountInfo.accountAndUser.account.name
836 + " user:" + accountInfo.accountAndUser.userId
837 + " backoffTime was: " + authorityInfo.backoffTime
838 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800839 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000840 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
841 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
842 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800843 }
844 }
845 }
846 }
847
848 if (changed) {
849 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
850 }
851 }
852
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700853 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800854 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700855 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800856 if (authority == null) {
857 return 0;
858 }
859 return authority.delayUntil;
860 }
861 }
862
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700863 public void setDelayUntilTime(EndPoint info, long delayUntil) {
864 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000865 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800867 }
868 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700869 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
870 if (authority.delayUntil == delayUntil) {
871 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700872 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700873 authority.delayUntil = delayUntil;
874 }
875 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
876 }
877
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700878 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000879 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
880 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700881 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000882 boolean restoreAllPeriodicSyncs() {
883 if (mPeriodicSyncAddedListener == null) {
884 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800885 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000886 synchronized (mAuthorities) {
887 for (int i=0; i<mAuthorities.size(); i++) {
888 AuthorityInfo authority = mAuthorities.valueAt(i);
889 for (PeriodicSync periodicSync: authority.periodicSyncs) {
890 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
891 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
892 }
893 authority.periodicSyncs.clear();
894 }
895 writeAccountInfoLocked();
896 }
897 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800898 }
899
Amith Yamasani04e0d262012-02-14 11:50:53 -0800900 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800902 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700903 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700904 return;
905 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800906 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 writeAccountInfoLocked();
908 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700909 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700910 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
911 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700912 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700913 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800914 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800915 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917
Amith Yamasani04e0d262012-02-14 11:50:53 -0800918 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700919 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800920 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800921 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700922 }
923 }
Costin Manolache360e4542009-09-04 13:36:04 -0700924
Makoto Onukib47e8942017-09-18 14:03:03 -0700925 public int getAuthorityCount() {
926 synchronized (mAuthorities) {
927 return mAuthorities.size();
928 }
929 }
930
Dianne Hackborn231cc602009-04-27 17:10:36 -0700931 public AuthorityInfo getAuthority(int authorityId) {
932 synchronized (mAuthorities) {
933 return mAuthorities.get(authorityId);
934 }
935 }
Costin Manolache360e4542009-09-04 13:36:04 -0700936
Dianne Hackborn231cc602009-04-27 17:10:36 -0700937 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700938 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700939 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700941 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700942 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700943 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700944 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700945 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 return true;
947 }
948 }
949 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 return false;
951 }
Costin Manolache360e4542009-09-04 13:36:04 -0700952
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000953 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000955 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
956 -1 /* desired identifier */,
957 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000959 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000962 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700964 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700965 }
Costin Manolache360e4542009-09-04 13:36:04 -0700966
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 /**
968 * Called when the set of account has changed, given the new array of
969 * active accounts.
970 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800971 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700972 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700973 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000974 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700975 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700976 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
977 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
978 while (accIt.hasNext()) {
979 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800980 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
981 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700982 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700983 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000984 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700985 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700986 for (AuthorityInfo auth : acc.authorities.values()) {
987 removing.put(auth.ident, auth);
988 }
989 accIt.remove();
990 }
991 }
Costin Manolache360e4542009-09-04 13:36:04 -0700992
Dianne Hackborn231cc602009-04-27 17:10:36 -0700993 // Clean out all data structures.
994 int i = removing.size();
995 if (i > 0) {
996 while (i > 0) {
997 i--;
998 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000999 AuthorityInfo auth = removing.valueAt(i);
1000 if (mAuthorityRemovedListener != null) {
1001 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1002 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 mAuthorities.remove(ident);
1004 int j = mSyncStatus.size();
1005 while (j > 0) {
1006 j--;
1007 if (mSyncStatus.keyAt(j) == ident) {
1008 mSyncStatus.remove(mSyncStatus.keyAt(j));
1009 }
1010 }
1011 j = mSyncHistory.size();
1012 while (j > 0) {
1013 j--;
1014 if (mSyncHistory.get(j).authorityId == ident) {
1015 mSyncHistory.remove(j);
1016 }
1017 }
1018 }
1019 writeAccountInfoLocked();
1020 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 writeStatisticsLocked();
1022 }
1023 }
1024 }
1025
1026 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001027 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1028 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001029 */
Fred Quintana918339a2010-10-05 14:00:39 -07001030 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1031 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001033 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001034 Slog.v(TAG, "setActiveSync: account="
1035 + " auth=" + activeSyncContext.mSyncOperation.target
1036 + " src=" + activeSyncContext.mSyncOperation.syncSource
1037 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001039 final EndPoint info = activeSyncContext.mSyncOperation.target;
1040 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1041 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001042 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001043 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001044 syncInfo = new SyncInfo(
1045 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001046 authorityInfo.target.account,
1047 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001048 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001049 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 }
Fred Quintana918339a2010-10-05 14:00:39 -07001051 reportActiveChange();
1052 return syncInfo;
1053 }
1054
1055 /**
1056 * Called to indicate that a previously active sync is no longer active.
1057 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001058 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001059 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001060 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001061 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001062 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001063 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001064 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001065 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001066 }
1067
1068 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001069 }
1070
1071 /**
1072 * To allow others to send active change reports, to poke clients.
1073 */
1074 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001075 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 }
Costin Manolache360e4542009-09-04 13:36:04 -07001077
Dianne Hackborn231cc602009-04-27 17:10:36 -07001078 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001079 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001080 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001081 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001082 long id;
1083 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001084 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001085 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001086 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001087 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 if (authority == null) {
1089 return -1;
1090 }
1091 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001092 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001093 item.authorityId = authority.ident;
1094 item.historyId = mNextHistoryId++;
1095 if (mNextHistoryId < 0) mNextHistoryId = 0;
1096 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001097 item.source = op.syncSource;
1098 item.reason = op.reason;
1099 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 item.event = EVENT_START;
1101 mSyncHistory.add(0, item);
1102 while (mSyncHistory.size() > MAX_HISTORY) {
1103 mSyncHistory.remove(mSyncHistory.size()-1);
1104 }
1105 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001106 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001107 }
Costin Manolache360e4542009-09-04 13:36:04 -07001108
Fred Quintanaac9385e2009-06-22 18:00:59 -07001109 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001110 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112
Fred Quintana77c560f2010-03-29 22:20:26 -07001113 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001114 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001116 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001117 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001118 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 SyncHistoryItem item = null;
1120 int i = mSyncHistory.size();
1121 while (i > 0) {
1122 i--;
1123 item = mSyncHistory.get(i);
1124 if (item.historyId == historyId) {
1125 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
Costin Manolache360e4542009-09-04 13:36:04 -07001129
Dianne Hackborn231cc602009-04-27 17:10:36 -07001130 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001131 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 return;
1133 }
Costin Manolache360e4542009-09-04 13:36:04 -07001134
Dianne Hackborn231cc602009-04-27 17:10:36 -07001135 item.elapsedTime = elapsedTime;
1136 item.event = EVENT_STOP;
1137 item.mesg = resultMessage;
1138 item.downstreamActivity = downstreamActivity;
1139 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001140
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001142
Dianne Hackborn231cc602009-04-27 17:10:36 -07001143 status.numSyncs++;
1144 status.totalElapsedTime += elapsedTime;
1145 switch (item.source) {
1146 case SOURCE_LOCAL:
1147 status.numSourceLocal++;
1148 break;
1149 case SOURCE_POLL:
1150 status.numSourcePoll++;
1151 break;
1152 case SOURCE_USER:
1153 status.numSourceUser++;
1154 break;
1155 case SOURCE_SERVER:
1156 status.numSourceServer++;
1157 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001158 case SOURCE_PERIODIC:
1159 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001160 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 }
Costin Manolache360e4542009-09-04 13:36:04 -07001162
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001164 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 if (mDayStats[0] == null) {
1166 mDayStats[0] = new DayStats(day);
1167 } else if (day != mDayStats[0].day) {
1168 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1169 mDayStats[0] = new DayStats(day);
1170 writeStatisticsNow = true;
1171 } else if (mDayStats[0] == null) {
1172 }
1173 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001174
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 final long lastSyncTime = (item.eventTime + elapsedTime);
1176 boolean writeStatusNow = false;
1177 if (MESG_SUCCESS.equals(resultMessage)) {
1178 // - if successful, update the successful columns
1179 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1180 writeStatusNow = true;
1181 }
1182 status.lastSuccessTime = lastSyncTime;
1183 status.lastSuccessSource = item.source;
1184 status.lastFailureTime = 0;
1185 status.lastFailureSource = -1;
1186 status.lastFailureMesg = null;
1187 status.initialFailureTime = 0;
1188 ds.successCount++;
1189 ds.successTime += elapsedTime;
1190 } else if (!MESG_CANCELED.equals(resultMessage)) {
1191 if (status.lastFailureTime == 0) {
1192 writeStatusNow = true;
1193 }
1194 status.lastFailureTime = lastSyncTime;
1195 status.lastFailureSource = item.source;
1196 status.lastFailureMesg = resultMessage;
1197 if (status.initialFailureTime == 0) {
1198 status.initialFailureTime = lastSyncTime;
1199 }
1200 ds.failureCount++;
1201 ds.failureTime += elapsedTime;
1202 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001203 final StringBuilder event = new StringBuilder();
1204 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1205 + " Elapsed=");
1206 SyncManager.formatDurationHMS(event, elapsedTime);
1207 event.append(" Reason=");
1208 event.append(SyncOperation.reasonToString(null, item.reason));
1209 event.append(" Extras=");
1210 SyncOperation.extrasToStringBuilder(item.extras, event);
1211
1212 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001213
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 if (writeStatusNow) {
1215 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001216 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1217 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 WRITE_STATUS_DELAY);
1219 }
1220 if (writeStatisticsNow) {
1221 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001222 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1223 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001225 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 }
Costin Manolache360e4542009-09-04 13:36:04 -07001227
Fred Quintanaac9385e2009-06-22 18:00:59 -07001228 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001229 }
1230
1231 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001232 * Return a list of the currently active syncs. Note that the returned
1233 * items are the real, live active sync objects, so be careful what you do
1234 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001235 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001236 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001237 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001238 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 }
1240 }
Costin Manolache360e4542009-09-04 13:36:04 -07001241
Dianne Hackborn231cc602009-04-27 17:10:36 -07001242 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001243 * @param userId Id of user to return current sync info.
1244 * @param canAccessAccounts Determines whether to redact Account information from the result.
1245 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001246 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001247 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001248 synchronized (mAuthorities) {
1249 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1250 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1251 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001252 SyncInfo copy;
1253 if (!canAccessAccounts) {
1254 copy = SyncInfo.createAccountRedacted(
1255 sync.authorityId, sync.authority, sync.startTime);
1256 } else {
1257 copy = new SyncInfo(sync);
1258 }
1259 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001260 }
1261 return syncsCopy;
1262 }
1263 }
1264
1265 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1266 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1267 if (syncs == null) {
1268 syncs = new ArrayList<SyncInfo>();
1269 mCurrentSyncs.put(userId, syncs);
1270 }
1271 return syncs;
1272 }
1273
1274 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001275 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001276 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001277 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001278 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001279 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001280 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001281 true /* write to storage if this results in a change */);
1282 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1283 }
1284 }
1285
1286 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001287 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001288 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001289 * @param info the endpoint target we are querying status info for.
1290 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001291 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001292 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001293 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001294 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001295 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001298 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001299 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001301 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001302 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001303 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001304 }
1305 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001306 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 }
1308 }
Costin Manolache360e4542009-09-04 13:36:04 -07001309
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001310 /** Return true if the pending status is true of any matching authorities. */
1311 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001312 synchronized (mAuthorities) {
1313 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001314 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001315 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001316 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1317 if (ainfo == null) {
1318 continue;
1319 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001320 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001321 continue;
1322 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001323 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001324 return true;
1325 }
1326 }
1327 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
1329 }
1330
1331 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001332 * Return an array of the current sync status for all authorities. Note
1333 * that the objects inside the array are the real, live status objects,
1334 * so be careful what you do with them.
1335 */
1336 public ArrayList<SyncHistoryItem> getSyncHistory() {
1337 synchronized (mAuthorities) {
1338 final int N = mSyncHistory.size();
1339 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1340 for (int i=0; i<N; i++) {
1341 items.add(mSyncHistory.get(i));
1342 }
1343 return items;
1344 }
1345 }
Costin Manolache360e4542009-09-04 13:36:04 -07001346
Dianne Hackborn231cc602009-04-27 17:10:36 -07001347 /**
1348 * Return an array of the current per-day statistics. Note
1349 * that the objects inside the array are the real, live status objects,
1350 * so be careful what you do with them.
1351 */
1352 public DayStats[] getDayStatistics() {
1353 synchronized (mAuthorities) {
1354 DayStats[] ds = new DayStats[mDayStats.length];
1355 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1356 return ds;
1357 }
1358 }
Costin Manolache360e4542009-09-04 13:36:04 -07001359
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001360 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1361 AuthorityInfo authorityInfo) {
1362 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1363 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1364 }
1365
Dianne Hackborn55280a92009-05-07 15:53:46 -07001366 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001367 mCal.setTimeInMillis(System.currentTimeMillis());
1368 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1369 if (mYear != mCal.get(Calendar.YEAR)) {
1370 mYear = mCal.get(Calendar.YEAR);
1371 mCal.clear();
1372 mCal.set(Calendar.YEAR, mYear);
1373 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1374 }
1375 return dayOfYear + mYearInDays;
1376 }
Costin Manolache360e4542009-09-04 13:36:04 -07001377
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001379 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001380 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001381 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001383 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001385 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001386 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1387 AccountInfo accountInfo = mAccounts.get(au);
1388 if (accountInfo == null) {
1389 if (tag != null) {
1390 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1391 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001392 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001393 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 return null;
1395 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001396 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1397 if (authority == null) {
1398 if (tag != null) {
1399 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1400 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1401 }
1402 }
1403 return null;
1404 }
1405 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001406 }
Costin Manolache360e4542009-09-04 13:36:04 -07001407
Matthew Williamsfa774182013-06-18 15:44:11 -07001408 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001409 * @param info info identifying target.
1410 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001411 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001412 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001413 * exists.
1414 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001415 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1416 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001417 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1418 AccountInfo account = mAccounts.get(au);
1419 if (account == null) {
1420 account = new AccountInfo(au);
1421 mAccounts.put(au, account);
1422 }
1423 authority = account.authorities.get(info.provider);
1424 if (authority == null) {
1425 authority = createAuthorityLocked(info, ident, doWrite);
1426 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001427 }
1428 return authority;
1429 }
1430
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001431 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1432 AuthorityInfo authority;
1433 if (ident < 0) {
1434 ident = mNextAuthorityId;
1435 mNextAuthorityId++;
1436 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001437 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001438 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001439 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001440 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001441 authority = new AuthorityInfo(info, ident);
1442 mAuthorities.put(ident, authority);
1443 if (doWrite) {
1444 writeAccountInfoLocked();
1445 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001446 return authority;
1447 }
Costin Manolache360e4542009-09-04 13:36:04 -07001448
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001449 public void removeAuthority(EndPoint info) {
1450 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001451 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001452 }
1453 }
1454
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001455
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001456 /**
1457 * Remove an authority associated with a provider. Needs to be a standalone function for
1458 * backward compatibility.
1459 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001460 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001461 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001462 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001463 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001464 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1465 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001466 if (mAuthorityRemovedListener != null) {
1467 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1468 }
Fred Quintanafb084402010-03-23 17:57:03 -07001469 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001470 if (doWrite) {
1471 writeAccountInfoLocked();
1472 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001473 }
1474 }
1475 }
1476
Dianne Hackborn231cc602009-04-27 17:10:36 -07001477 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1478 SyncStatusInfo status = mSyncStatus.get(authorityId);
1479 if (status == null) {
1480 status = new SyncStatusInfo(authorityId);
1481 mSyncStatus.put(authorityId, status);
1482 }
1483 return status;
1484 }
Costin Manolache360e4542009-09-04 13:36:04 -07001485
Dianne Hackborn55280a92009-05-07 15:53:46 -07001486 public void writeAllState() {
1487 synchronized (mAuthorities) {
1488 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001489 writeStatusLocked();
1490 writeStatisticsLocked();
1491 }
1492 }
Costin Manolache360e4542009-09-04 13:36:04 -07001493
Svet Ganov65712b02016-09-01 10:24:11 -07001494 public boolean shouldGrantSyncAdaptersAccountAccess() {
1495 return mGrantSyncAdaptersAccountAccess;
1496 }
1497
Dianne Hackborn231cc602009-04-27 17:10:36 -07001498 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001499 * public for testing
1500 */
1501 public void clearAndReadState() {
1502 synchronized (mAuthorities) {
1503 mAuthorities.clear();
1504 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001505 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001506 mSyncStatus.clear();
1507 mSyncHistory.clear();
1508
1509 readAccountInfoLocked();
1510 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001511 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001512 readAndDeleteLegacyAccountInfoLocked();
1513 writeAccountInfoLocked();
1514 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001515 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001516 }
1517 }
1518
1519 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 * Read all account information back in to the initial engine state.
1521 */
1522 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001523 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001527 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001528 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001529 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001531 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001532 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001533 while (eventType != XmlPullParser.START_TAG &&
1534 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001535 eventType = parser.next();
1536 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001537 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001538 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001539 return;
1540 }
1541
Dianne Hackborn231cc602009-04-27 17:10:36 -07001542 String tagName = parser.getName();
1543 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001544 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001545 String versionString = parser.getAttributeValue(null, "version");
1546 int version;
1547 try {
1548 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1549 } catch (NumberFormatException e) {
1550 version = 0;
1551 }
Svet Ganov65712b02016-09-01 10:24:11 -07001552
1553 if (version < 3) {
1554 mGrantSyncAdaptersAccountAccess = true;
1555 }
1556
Amith Yamasani04e0d262012-02-14 11:50:53 -08001557 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001558 try {
1559 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1560 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1561 } catch (NumberFormatException e) {
1562 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001563 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001564 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1565 try {
1566 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1567 } catch (NumberFormatException e) {
1568 mSyncRandomOffset = 0;
1569 }
1570 if (mSyncRandomOffset == 0) {
1571 Random random = new Random(System.currentTimeMillis());
1572 mSyncRandomOffset = random.nextInt(86400);
1573 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001574 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001575 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001576 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001577 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001578 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001579 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001580 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001581 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001582 if (parser.getDepth() == 2) {
1583 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001584 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001585 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001586 if (authority != null) {
1587 if (authority.ident > highestAuthorityId) {
1588 highestAuthorityId = authority.ident;
1589 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001590 } else {
1591 EventLog.writeEvent(0x534e4554, "26513719", -1,
1592 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001593 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001594 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1595 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001596 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001597 } else if (parser.getDepth() == 3) {
1598 if ("periodicSync".equals(tagName) && authority != null) {
1599 periodicSync = parsePeriodicSync(parser, authority);
1600 }
1601 } else if (parser.getDepth() == 4 && periodicSync != null) {
1602 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001603 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001604 }
1605 }
1606 }
1607 eventType = parser.next();
1608 } while (eventType != XmlPullParser.END_DOCUMENT);
1609 }
1610 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001611 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001612 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001613 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001614 if (fis == null) Slog.i(TAG, "No initial accounts");
1615 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001616 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001617 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001618 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001619 if (fis != null) {
1620 try {
1621 fis.close();
1622 } catch (java.io.IOException e1) {
1623 }
1624 }
1625 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001626
Fred Quintana77c560f2010-03-29 22:20:26 -07001627 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001628 }
Costin Manolache360e4542009-09-04 13:36:04 -07001629
Fred Quintanafb084402010-03-23 17:57:03 -07001630 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001631 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1632 * pending.xml was used starting in KLP.
1633 * @param syncDir directory where the sync files are located.
1634 */
1635 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1636 File file = new File(syncDir, "pending.bin");
1637 if (!file.exists()) {
1638 return;
1639 } else {
1640 file.delete();
1641 }
1642 }
1643
1644 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001645 * some authority names have changed. copy over their settings and delete the old ones
1646 * @return true if a change was made
1647 */
1648 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1649 boolean writeNeeded = false;
1650
1651 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1652 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001653 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001654 AuthorityInfo authority = mAuthorities.valueAt(i);
1655 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001656 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001657 if (newAuthorityName == null) {
1658 continue;
1659 }
1660
1661 // remember this authority so we can remove it later. we can't remove it
1662 // now without messing up this loop iteration
1663 authoritiesToRemove.add(authority);
1664
1665 // this authority isn't enabled, no need to copy it to the new authority name since
1666 // the default is "disabled"
1667 if (!authority.enabled) {
1668 continue;
1669 }
1670
1671 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001672 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001673 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001674 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001675 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001676 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001677 continue;
1678 }
1679
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001680 AuthorityInfo newAuthority =
1681 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001682 newAuthority.enabled = true;
1683 writeNeeded = true;
1684 }
1685
1686 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001687 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001688 authorityInfo.target.account,
1689 authorityInfo.target.userId,
1690 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001691 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001692 writeNeeded = true;
1693 }
1694
1695 return writeNeeded;
1696 }
1697
Amith Yamasani04e0d262012-02-14 11:50:53 -08001698 private void parseListenForTickles(XmlPullParser parser) {
1699 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1700 int userId = 0;
1701 try {
1702 userId = Integer.parseInt(user);
1703 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001704 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001705 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001706 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001707 }
1708 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1709 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1710 mMasterSyncAutomatically.put(userId, listen);
1711 }
1712
Suprabh Shukla042a4782017-05-12 15:26:54 -07001713 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1714 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 AuthorityInfo authority = null;
1716 int id = -1;
1717 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001718 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001719 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001720 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001721 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001722 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001723 }
1724 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001725 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001726 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001727 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001728 String accountName = parser.getAttributeValue(null, "account");
1729 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001730 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001731 String packageName = parser.getAttributeValue(null, "package");
1732 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001733 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001734 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001735 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001736 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001737 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001738 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001739 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001740 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001741 + " account=" + accountName
1742 + " accountType=" + accountType
1743 + " auth=" + authorityName
1744 + " package=" + packageName
1745 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001746 + " user=" + userId
1747 + " enabled=" + enabled
1748 + " syncable=" + syncable);
1749 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001750 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001751 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001752 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001753 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001754 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001755 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001756 new Account(accountName, accountType),
1757 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001758 if (validator.isAccountValid(info.account, userId)
1759 && validator.isAuthorityValid(authorityName, userId)) {
1760 authority = getOrCreateAuthorityLocked(info, id, false);
1761 // If the version is 0 then we are upgrading from a file format that did not
1762 // know about periodic syncs. In that case don't clear the list since we
1763 // want the default, which is a daily periodic sync.
1764 // Otherwise clear out this default list since we will populate it later
1765 // with
1766 // the periodic sync descriptions that are read from the configuration file.
1767 if (version > 0) {
1768 authority.periodicSyncs.clear();
1769 }
1770 } else {
1771 EventLog.writeEvent(0x534e4554, "35028827", -1,
1772 "account:" + info.account + " provider:" + authorityName + " user:"
1773 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001774 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001775 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001776 }
1777 if (authority != null) {
1778 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001779 try {
1780 authority.syncable = (syncable == null) ?
1781 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1782 } catch (NumberFormatException e) {
1783 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1784 // format.
1785 if ("unknown".equals(syncable)) {
1786 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1787 } else {
1788 authority.syncable = Boolean.parseBoolean(syncable) ?
1789 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1790 }
1791
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001792 }
1793 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001794 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001795 + accountName + " auth=" + authorityName
1796 + " enabled=" + enabled
1797 + " syncable=" + syncable);
1798 }
1799 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001800 return authority;
1801 }
1802
Matthew Williamsfa774182013-06-18 15:44:11 -07001803 /**
1804 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1805 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001806 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001807 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001808 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001809 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001810 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001811 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001812 try {
1813 period = Long.parseLong(periodValue);
1814 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001815 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001816 return null;
1817 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001818 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001819 return null;
1820 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001821 try {
1822 flextime = Long.parseLong(flexValue);
1823 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001824 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001825 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001826 + ", using default: "
1827 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001828 } catch (NullPointerException expected) {
1829 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001830 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1831 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001832 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001833 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001834 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001835 new PeriodicSync(authorityInfo.target.account,
1836 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001837 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001838 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001839 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001840 return periodicSync;
1841 }
1842
Matthew Williamsfa774182013-06-18 15:44:11 -07001843 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001844 String name = parser.getAttributeValue(null, "name");
1845 String type = parser.getAttributeValue(null, "type");
1846 String value1 = parser.getAttributeValue(null, "value1");
1847 String value2 = parser.getAttributeValue(null, "value2");
1848
1849 try {
1850 if ("long".equals(type)) {
1851 extras.putLong(name, Long.parseLong(value1));
1852 } else if ("integer".equals(type)) {
1853 extras.putInt(name, Integer.parseInt(value1));
1854 } else if ("double".equals(type)) {
1855 extras.putDouble(name, Double.parseDouble(value1));
1856 } else if ("float".equals(type)) {
1857 extras.putFloat(name, Float.parseFloat(value1));
1858 } else if ("boolean".equals(type)) {
1859 extras.putBoolean(name, Boolean.parseBoolean(value1));
1860 } else if ("string".equals(type)) {
1861 extras.putString(name, value1);
1862 } else if ("account".equals(type)) {
1863 extras.putParcelable(name, new Account(value1, value2));
1864 }
1865 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001866 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001867 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001868 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001869 }
1870 }
1871
Dianne Hackborn231cc602009-04-27 17:10:36 -07001872 /**
1873 * Write all account information to the account file.
1874 */
1875 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001876 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001877 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001878 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001879 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001880
Dianne Hackborn231cc602009-04-27 17:10:36 -07001881 try {
1882 fos = mAccountInfoFile.startWrite();
1883 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001884 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 out.startDocument(null, true);
1886 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001887
Dianne Hackborn231cc602009-04-27 17:10:36 -07001888 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001889 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001890 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001891 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001892
1893 // Write the Sync Automatically flags for each user
1894 final int M = mMasterSyncAutomatically.size();
1895 for (int m = 0; m < M; m++) {
1896 int userId = mMasterSyncAutomatically.keyAt(m);
1897 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1898 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1899 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1900 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1901 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001902 }
Costin Manolache360e4542009-09-04 13:36:04 -07001903
Dianne Hackborn231cc602009-04-27 17:10:36 -07001904 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001905 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001906 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001907 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 out.startTag(null, "authority");
1909 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001910 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001911 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001912 out.attribute(null, "account", info.account.name);
1913 out.attribute(null, "type", info.account.type);
1914 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001915 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001916 out.endTag(null, "authority");
1917 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001918 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001919 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001920 mAccountInfoFile.finishWrite(fos);
1921 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001922 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 if (fos != null) {
1924 mAccountInfoFile.failWrite(fos);
1925 }
1926 }
1927 }
Costin Manolache360e4542009-09-04 13:36:04 -07001928
Dianne Hackborn231cc602009-04-27 17:10:36 -07001929 static int getIntColumn(Cursor c, String name) {
1930 return c.getInt(c.getColumnIndex(name));
1931 }
Costin Manolache360e4542009-09-04 13:36:04 -07001932
Dianne Hackborn231cc602009-04-27 17:10:36 -07001933 static long getLongColumn(Cursor c, String name) {
1934 return c.getLong(c.getColumnIndex(name));
1935 }
Costin Manolache360e4542009-09-04 13:36:04 -07001936
Dianne Hackborn231cc602009-04-27 17:10:36 -07001937 /**
1938 * Load sync engine state from the old syncmanager database, and then
1939 * erase it. Note that we don't deal with pending operations, active
1940 * sync, or history.
1941 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001942 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 // Look for old database to initialize from.
1944 File file = mContext.getDatabasePath("syncmanager.db");
1945 if (!file.exists()) {
1946 return;
1947 }
1948 String path = file.getPath();
1949 SQLiteDatabase db = null;
1950 try {
1951 db = SQLiteDatabase.openDatabase(path, null,
1952 SQLiteDatabase.OPEN_READONLY);
1953 } catch (SQLiteException e) {
1954 }
Costin Manolache360e4542009-09-04 13:36:04 -07001955
Dianne Hackborn231cc602009-04-27 17:10:36 -07001956 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001957 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001958
Dianne Hackborn231cc602009-04-27 17:10:36 -07001959 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001960 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001961 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001962 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001963 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1964 qb.setTables("stats, status");
1965 HashMap<String,String> map = new HashMap<String,String>();
1966 map.put("_id", "status._id as _id");
1967 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001968 if (hasType) {
1969 map.put("account_type", "stats.account_type as account_type");
1970 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001971 map.put("authority", "stats.authority as authority");
1972 map.put("totalElapsedTime", "totalElapsedTime");
1973 map.put("numSyncs", "numSyncs");
1974 map.put("numSourceLocal", "numSourceLocal");
1975 map.put("numSourcePoll", "numSourcePoll");
1976 map.put("numSourceServer", "numSourceServer");
1977 map.put("numSourceUser", "numSourceUser");
1978 map.put("lastSuccessSource", "lastSuccessSource");
1979 map.put("lastSuccessTime", "lastSuccessTime");
1980 map.put("lastFailureSource", "lastFailureSource");
1981 map.put("lastFailureTime", "lastFailureTime");
1982 map.put("lastFailureMesg", "lastFailureMesg");
1983 map.put("pending", "pending");
1984 qb.setProjectionMap(map);
1985 qb.appendWhere("stats._id = status.stats_id");
1986 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001988 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001989 String accountType = hasType
1990 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001991 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001992 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001995 AuthorityInfo authority =
1996 this.getOrCreateAuthorityLocked(
1997 new EndPoint(new Account(accountName, accountType),
1998 authorityName,
1999 0 /* legacy is single-user */)
2000 , -1,
2001 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 if (authority != null) {
2003 int i = mSyncStatus.size();
2004 boolean found = false;
2005 SyncStatusInfo st = null;
2006 while (i > 0) {
2007 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002008 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 if (st.authorityId == authority.ident) {
2010 found = true;
2011 break;
2012 }
2013 }
2014 if (!found) {
2015 st = new SyncStatusInfo(authority.ident);
2016 mSyncStatus.put(authority.ident, st);
2017 }
2018 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2019 st.numSyncs = getIntColumn(c, "numSyncs");
2020 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2021 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2022 st.numSourceServer = getIntColumn(c, "numSourceServer");
2023 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002024 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002025 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2026 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2027 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2028 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2029 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2030 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
Costin Manolache360e4542009-09-04 13:36:04 -07002033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002035
Dianne Hackborn231cc602009-04-27 17:10:36 -07002036 // Retrieve the settings.
2037 qb = new SQLiteQueryBuilder();
2038 qb.setTables("settings");
2039 c = qb.query(db, null, null, null, null, null, null);
2040 while (c.moveToNext()) {
2041 String name = c.getString(c.getColumnIndex("name"));
2042 String value = c.getString(c.getColumnIndex("value"));
2043 if (name == null) continue;
2044 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002045 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002046 } else if (name.startsWith("sync_provider_")) {
2047 String provider = name.substring("sync_provider_".length(),
2048 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002049 int i = mAuthorities.size();
2050 while (i > 0) {
2051 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002052 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002053 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002054 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002055 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002056 }
2057 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002059 }
Costin Manolache360e4542009-09-04 13:36:04 -07002060
Dianne Hackborn231cc602009-04-27 17:10:36 -07002061 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002062
Dianne Hackborn231cc602009-04-27 17:10:36 -07002063 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002064
Dianne Hackborn231cc602009-04-27 17:10:36 -07002065 (new File(path)).delete();
2066 }
2067 }
Costin Manolache360e4542009-09-04 13:36:04 -07002068
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 public static final int STATUS_FILE_END = 0;
2070 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002071
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 /**
2073 * Read all sync status back in to the initial engine state.
2074 */
2075 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002076 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002077 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002078 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002079 try {
2080 byte[] data = mStatusFile.readFully();
2081 Parcel in = Parcel.obtain();
2082 in.unmarshall(data, 0, data.length);
2083 in.setDataPosition(0);
2084 int token;
2085 while ((token=in.readInt()) != STATUS_FILE_END) {
2086 if (token == STATUS_FILE_ITEM) {
2087 SyncStatusInfo status = new SyncStatusInfo(in);
2088 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2089 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002090 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002091 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002092 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002093 mSyncStatus.put(status.authorityId, status);
2094 }
2095 } else {
2096 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002097 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002098 break;
2099 }
2100 }
2101 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002102 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002103 }
2104 }
Costin Manolache360e4542009-09-04 13:36:04 -07002105
Dianne Hackborn231cc602009-04-27 17:10:36 -07002106 /**
2107 * Write all sync status to the sync status file.
2108 */
2109 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002110 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002111 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002112 }
Costin Manolache360e4542009-09-04 13:36:04 -07002113
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 // The file is being written, so we don't need to have a scheduled
2115 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002116 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002117
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 FileOutputStream fos = null;
2119 try {
2120 fos = mStatusFile.startWrite();
2121 Parcel out = Parcel.obtain();
2122 final int N = mSyncStatus.size();
2123 for (int i=0; i<N; i++) {
2124 SyncStatusInfo status = mSyncStatus.valueAt(i);
2125 out.writeInt(STATUS_FILE_ITEM);
2126 status.writeToParcel(out, 0);
2127 }
2128 out.writeInt(STATUS_FILE_END);
2129 fos.write(out.marshall());
2130 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002131
Dianne Hackborn231cc602009-04-27 17:10:36 -07002132 mStatusFile.finishWrite(fos);
2133 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002134 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002135 if (fos != null) {
2136 mStatusFile.failWrite(fos);
2137 }
2138 }
2139 }
Costin Manolache360e4542009-09-04 13:36:04 -07002140
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002141 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2142 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2143 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002144 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002145 } else {
2146 SyncRequest.Builder req =
2147 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002148 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002149 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002150 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002151 ContentResolver.requestSync(req.build());
2152 }
2153 }
2154
Alon Albert57286f92012-10-09 14:21:38 -07002155 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002156 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002157 // If this is happening in the system process, then call the syncrequest listener
2158 // to make a request back to the SyncManager directly.
2159 // If this is probably a test instance, then call back through the ContentResolver
2160 // which will know which userId to apply based on the Binder id.
2161 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2162 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002163 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002164 new EndPoint(account, authority, userId),
2165 reason,
2166 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002167 } else {
2168 ContentResolver.requestSync(account, authority, extras);
2169 }
2170 }
2171
Dianne Hackborn231cc602009-04-27 17:10:36 -07002172 public static final int STATISTICS_FILE_END = 0;
2173 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2174 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002175
Dianne Hackborn231cc602009-04-27 17:10:36 -07002176 /**
2177 * Read all sync statistics back in to the initial engine state.
2178 */
2179 private void readStatisticsLocked() {
2180 try {
2181 byte[] data = mStatisticsFile.readFully();
2182 Parcel in = Parcel.obtain();
2183 in.unmarshall(data, 0, data.length);
2184 in.setDataPosition(0);
2185 int token;
2186 int index = 0;
2187 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2188 if (token == STATISTICS_FILE_ITEM
2189 || token == STATISTICS_FILE_ITEM_OLD) {
2190 int day = in.readInt();
2191 if (token == STATISTICS_FILE_ITEM_OLD) {
2192 day = day - 2009 + 14245; // Magic!
2193 }
2194 DayStats ds = new DayStats(day);
2195 ds.successCount = in.readInt();
2196 ds.successTime = in.readLong();
2197 ds.failureCount = in.readInt();
2198 ds.failureTime = in.readLong();
2199 if (index < mDayStats.length) {
2200 mDayStats[index] = ds;
2201 index++;
2202 }
2203 } else {
2204 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002205 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002206 break;
2207 }
2208 }
2209 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002210 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002211 }
2212 }
Costin Manolache360e4542009-09-04 13:36:04 -07002213
Dianne Hackborn231cc602009-04-27 17:10:36 -07002214 /**
2215 * Write all sync statistics to the sync status file.
2216 */
2217 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002218 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002219 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002220 }
Costin Manolache360e4542009-09-04 13:36:04 -07002221
Dianne Hackborn231cc602009-04-27 17:10:36 -07002222 // The file is being written, so we don't need to have a scheduled
2223 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002224 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002225
Dianne Hackborn231cc602009-04-27 17:10:36 -07002226 FileOutputStream fos = null;
2227 try {
2228 fos = mStatisticsFile.startWrite();
2229 Parcel out = Parcel.obtain();
2230 final int N = mDayStats.length;
2231 for (int i=0; i<N; i++) {
2232 DayStats ds = mDayStats[i];
2233 if (ds == null) {
2234 break;
2235 }
2236 out.writeInt(STATISTICS_FILE_ITEM);
2237 out.writeInt(ds.day);
2238 out.writeInt(ds.successCount);
2239 out.writeLong(ds.successTime);
2240 out.writeInt(ds.failureCount);
2241 out.writeLong(ds.failureTime);
2242 }
2243 out.writeInt(STATISTICS_FILE_END);
2244 fos.write(out.marshall());
2245 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002246
Dianne Hackborn231cc602009-04-27 17:10:36 -07002247 mStatisticsFile.finishWrite(fos);
2248 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002249 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002250 if (fos != null) {
2251 mStatisticsFile.failWrite(fos);
2252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 }
2254 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002255
2256 /**
Marvin Paula6533252014-11-24 12:57:48 -08002257 * Let the BackupManager know that account sync settings have changed. This will trigger
2258 * {@link com.android.server.backup.SystemBackupAgent} to run.
2259 */
2260 public void queueBackup() {
2261 BackupManager.dataChanged("android");
2262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263}