blob: 8b67b7a27e7ee003fe19f325d09291714ca5c9db [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. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800343 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
344 boolean exemptFromAppStandby);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800345 }
346
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000347 interface PeriodicSyncAddedListener {
348 /** Called when a periodic sync is added. */
349 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
350 }
351
352 interface OnAuthorityRemovedListener {
353 /** Called when an authority is removed. */
354 void onAuthorityRemoved(EndPoint removedAuthority);
355 }
356
Suprabh Shukla042a4782017-05-12 15:26:54 -0700357 /**
358 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
359 * account is valid.
360 */
361 private static class AccountAuthorityValidator {
362 final private AccountManager mAccountManager;
363 final private PackageManager mPackageManager;
364 final private SparseArray<Account[]> mAccountsCache;
365 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
366
367 AccountAuthorityValidator(Context context) {
368 mAccountManager = context.getSystemService(AccountManager.class);
369 mPackageManager = context.getPackageManager();
370 mAccountsCache = new SparseArray<>();
371 mProvidersPerUserCache = new SparseArray<>();
372 }
373
374 // An account is valid if an installed authenticator has previously created that account
375 // on the device
376 boolean isAccountValid(Account account, int userId) {
377 Account[] accountsForUser = mAccountsCache.get(userId);
378 if (accountsForUser == null) {
379 accountsForUser = mAccountManager.getAccountsAsUser(userId);
380 mAccountsCache.put(userId, accountsForUser);
381 }
382 return ArrayUtils.contains(accountsForUser, account);
383 }
384
385 // An authority is only valid if it has a content provider installed on the system
386 boolean isAuthorityValid(String authority, int userId) {
387 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
388 if (authorityMap == null) {
389 authorityMap = new ArrayMap<>();
390 mProvidersPerUserCache.put(userId, authorityMap);
391 }
392 if (!authorityMap.containsKey(authority)) {
393 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
394 PackageManager.MATCH_DIRECT_BOOT_AWARE
395 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
396 }
397 return authorityMap.get(authority);
398 }
399 }
400
Dianne Hackborn231cc602009-04-27 17:10:36 -0700401 // Primary list of all syncable authorities. Also our global lock.
402 private final SparseArray<AuthorityInfo> mAuthorities =
403 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700404
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 private final HashMap<AccountAndUser, AccountInfo> mAccounts
406 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
Amith Yamasani04e0d262012-02-14 11:50:53 -0800408 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
409 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Dianne Hackborn231cc602009-04-27 17:10:36 -0700411 private final SparseArray<SyncStatusInfo> mSyncStatus =
412 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 private final ArrayList<SyncHistoryItem> mSyncHistory =
415 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
418 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700419
Matthew Williams8ef22042013-07-26 12:56:39 -0700420 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700421 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
422 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700423
Fred Quintana77c560f2010-03-29 22:20:26 -0700424 private int mNextAuthorityId = 0;
425
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 // We keep 4 weeks of stats.
427 private final DayStats[] mDayStats = new DayStats[7*4];
428 private final Calendar mCal;
429 private int mYear;
430 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700431
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800433
Dianne Hackborn231cc602009-04-27 17:10:36 -0700434 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700435
Ashish Sharma69d95de2012-04-11 17:27:24 -0700436 private int mSyncRandomOffset;
437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 /**
439 * This file contains the core engine state: all accounts and the
440 * settings for them. It must never be lost, and should be changed
441 * infrequently, so it is stored as an XML file.
442 */
443 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700444
Dianne Hackborn231cc602009-04-27 17:10:36 -0700445 /**
446 * This file contains the current sync status. We would like to retain
447 * it across boots, but its loss is not the end of the world, so we store
448 * this information as binary data.
449 */
450 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700451
Dianne Hackborn231cc602009-04-27 17:10:36 -0700452 /**
453 * This file contains sync statistics. This is purely debugging information
454 * so is written infrequently and can be thrown away at any time.
455 */
456 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700457
Dianne Hackborn231cc602009-04-27 17:10:36 -0700458 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800459 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800460 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800461
462 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000463 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700464
Svet Ganov65712b02016-09-01 10:24:11 -0700465 private boolean mGrantSyncAdaptersAccountAccess;
466
Makoto Onuki6963bea72017-12-12 10:42:39 -0800467 private final MyHandler mHandler;
468
469 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
470 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700473
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700475
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800476 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000477 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800478
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 File systemDir = new File(dataDir, "system");
480 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800481 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700482
483 maybeDeleteLegacyPendingInfoLocked(syncDir);
484
Dianne Hackborne17b4452018-01-10 13:15:40 -0800485 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
486 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
487 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700488
Dianne Hackborn231cc602009-04-27 17:10:36 -0700489 readAccountInfoLocked();
490 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700491 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700492 readAndDeleteLegacyAccountInfoLocked();
493 writeAccountInfoLocked();
494 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700495 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800496 }
497
498 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800499 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 }
501
Makoto Onuki6963bea72017-12-12 10:42:39 -0800502 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800504 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700506 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800507 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 }
509
510 public static SyncStorageEngine getSingleton() {
511 if (sSyncStorageEngine == null) {
512 throw new IllegalStateException("not initialized");
513 }
514 return sSyncStorageEngine;
515 }
516
Amith Yamasani04e0d262012-02-14 11:50:53 -0800517 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
518 if (mSyncRequestListener == null) {
519 mSyncRequestListener = listener;
520 }
521 }
522
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000523 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
524 if (mAuthorityRemovedListener == null) {
525 mAuthorityRemovedListener = listener;
526 }
527 }
528
529 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
530 if (mPeriodicSyncAddedListener == null) {
531 mPeriodicSyncAddedListener = listener;
532 }
533 }
534
Makoto Onuki6963bea72017-12-12 10:42:39 -0800535 private class MyHandler extends Handler {
536 public MyHandler(Looper looper) {
537 super(looper);
538 }
539
540 @Override
541 public void handleMessage(Message msg) {
542 if (msg.what == MSG_WRITE_STATUS) {
543 synchronized (mAuthorities) {
544 writeStatusLocked();
545 }
546 } else if (msg.what == MSG_WRITE_STATISTICS) {
547 synchronized (mAuthorities) {
548 writeStatisticsLocked();
549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 }
551 }
552 }
Costin Manolache360e4542009-09-04 13:36:04 -0700553
Ashish Sharma69d95de2012-04-11 17:27:24 -0700554 public int getSyncRandomOffset() {
555 return mSyncRandomOffset;
556 }
557
Dianne Hackborn231cc602009-04-27 17:10:36 -0700558 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
559 synchronized (mAuthorities) {
560 mChangeListeners.register(callback, mask);
561 }
562 }
Costin Manolache360e4542009-09-04 13:36:04 -0700563
Dianne Hackborn231cc602009-04-27 17:10:36 -0700564 public void removeStatusChangeListener(ISyncStatusObserver callback) {
565 synchronized (mAuthorities) {
566 mChangeListeners.unregister(callback);
567 }
568 }
Costin Manolache360e4542009-09-04 13:36:04 -0700569
Matthew Williamsfa774182013-06-18 15:44:11 -0700570 /**
571 * Figure out a reasonable flex time for cases where none is provided (old api calls).
572 * @param syncTimeSeconds requested sync time from now.
573 * @return amount of seconds before syncTimeSeconds that the sync can occur.
574 * I.e.
575 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700576 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700577 */
578 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
579 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
580 // Small enough sync request time that we don't add flex time - developer probably
581 // wants to wait for an operation to occur before syncing so we honour the
582 // request time.
583 return 0L;
584 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
585 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
586 } else {
587 // Large enough sync request time that we cap the flex time.
588 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
589 }
590 }
591
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000592 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700593 ArrayList<ISyncStatusObserver> reports = null;
594 synchronized (mAuthorities) {
595 int i = mChangeListeners.beginBroadcast();
596 while (i > 0) {
597 i--;
598 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
599 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 continue;
601 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700602 if (reports == null) {
603 reports = new ArrayList<ISyncStatusObserver>(i);
604 }
605 reports.add(mChangeListeners.getBroadcastItem(i));
606 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700607 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700608 }
Costin Manolache360e4542009-09-04 13:36:04 -0700609
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700610 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000611 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700612 }
Costin Manolache360e4542009-09-04 13:36:04 -0700613
Dianne Hackborn231cc602009-04-27 17:10:36 -0700614 if (reports != null) {
615 int i = reports.size();
616 while (i > 0) {
617 i--;
618 try {
619 reports.get(i).onStatusChanged(which);
620 } catch (RemoteException e) {
621 // The remote callback list will take care of this for us.
622 }
623 }
624 }
625 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700626
Amith Yamasani04e0d262012-02-14 11:50:53 -0800627 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700628 synchronized (mAuthorities) {
629 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700630 AuthorityInfo authority = getAuthorityLocked(
631 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700632 "getSyncAutomatically");
633 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700634 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700635
Dianne Hackborn231cc602009-04-27 17:10:36 -0700636 int i = mAuthorities.size();
637 while (i > 0) {
638 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700639 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700640 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700641 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700642 return true;
643 }
644 }
645 return false;
646 }
647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000650 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700651 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000652 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800653 + ", user " + userId + " -> " + sync);
654 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700655 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700656 AuthorityInfo authority =
657 getOrCreateAuthorityLocked(
658 new EndPoint(account, providerName, userId),
659 -1 /* ident */,
660 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700661 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700662 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000663 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800664 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700665 return;
666 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700667 // If the adapter was syncable but missing its initialization sync, set it to
668 // uninitialized now. This is to give it a chance to run any one-time initialization
669 // logic.
670 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
671 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
672 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700673 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700674 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700676
Fred Quintana77c560f2010-03-29 22:20:26 -0700677 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700678 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800679 new Bundle(),
680 /* exemptFromAppStandby=*/ false);
Joe Onorato8294fad2009-07-15 16:08:44 -0700681 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700682 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800683 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685
Amith Yamasani04e0d262012-02-14 11:50:53 -0800686 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700687 synchronized (mAuthorities) {
688 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 AuthorityInfo authority = getAuthorityLocked(
690 new EndPoint(account, providerName, userId),
691 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700692 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700693 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700694 }
695 return authority.syncable;
696 }
697
698 int i = mAuthorities.size();
699 while (i > 0) {
700 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700701 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700702 if (authorityInfo.target != null
703 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700704 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700705 }
706 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700707 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700708 }
709 }
710
Amith Yamasani04e0d262012-02-14 11:50:53 -0800711 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700712 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700713 }
714
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700715 /**
716 * An enabled sync service and a syncable provider's adapter both get resolved to the same
717 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700718 * @param target target to set value for.
719 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700720 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700721 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700722 AuthorityInfo aInfo;
723 synchronized (mAuthorities) {
724 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700725 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
726 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700727 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700728 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000729 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700730 }
731 if (aInfo.syncable == syncable) {
732 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000733 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700734 }
735 return;
736 }
737 aInfo.syncable = syncable;
738 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700739 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700740 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800741 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
742 /*exemptFromAppStandby=*/ false); // Or the caller FG state?
Fred Quintana5e787c42009-08-16 23:13:53 -0700743 }
744 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
745 }
746
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700747 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800748 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
750 if (authority != null) {
751 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800752 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700753 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800754 }
755 }
756
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700757 /**
758 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
759 * the account or provider info be null, which signifies all accounts or providers.
760 */
761 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
762 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000763 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800764 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
765 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700766 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800767 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000768 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700769 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000770 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700771 changed = setBackoffLocked(
772 info.account /* may be null */,
773 info.userId,
774 info.provider /* may be null */,
775 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800776 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700777 AuthorityInfo authorityInfo =
778 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
779 if (authorityInfo.backoffTime == nextSyncTime
780 && authorityInfo.backoffDelay == nextDelay) {
781 changed = false;
782 } else {
783 authorityInfo.backoffTime = nextSyncTime;
784 authorityInfo.backoffDelay = nextDelay;
785 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800786 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800787 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800788 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800789 if (changed) {
790 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
791 }
792 }
793
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700794 /**
795 * Either set backoff for a specific authority, or set backoff for all the
796 * accounts on a specific adapter/all adapters.
797 *
798 * @param account account for which to set backoff. Null to specify all accounts.
799 * @param userId id of the user making this request.
800 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700801 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700802 */
803 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000804 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700805 boolean changed = false;
806 for (AccountInfo accountInfo : mAccounts.values()) {
807 if (account != null && !account.equals(accountInfo.accountAndUser.account)
808 && userId != accountInfo.accountAndUser.userId) {
809 continue;
810 }
811 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
812 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700813 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700814 continue;
815 }
816 if (authorityInfo.backoffTime != nextSyncTime
817 || authorityInfo.backoffDelay != nextDelay) {
818 authorityInfo.backoffTime = nextSyncTime;
819 authorityInfo.backoffDelay = nextDelay;
820 changed = true;
821 }
822 }
823 }
824 return changed;
825 }
826
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000827 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800828 boolean changed = false;
829 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000830 // Clear backoff for all sync adapters.
831 for (AccountInfo accountInfo : mAccounts.values()) {
832 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
833 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
834 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
835 if (Log.isLoggable(TAG, Log.VERBOSE)) {
836 Slog.v(TAG, "clearAllBackoffsLocked:"
837 + " authority:" + authorityInfo.target
838 + " account:" + accountInfo.accountAndUser.account.name
839 + " user:" + accountInfo.accountAndUser.userId
840 + " backoffTime was: " + authorityInfo.backoffTime
841 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800842 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000843 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
844 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
845 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800846 }
847 }
848 }
849 }
850
851 if (changed) {
852 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
853 }
854 }
855
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700856 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800857 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700858 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800859 if (authority == null) {
860 return 0;
861 }
862 return authority.delayUntil;
863 }
864 }
865
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 public void setDelayUntilTime(EndPoint info, long delayUntil) {
867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000868 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700869 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800870 }
871 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700872 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
873 if (authority.delayUntil == delayUntil) {
874 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700875 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700876 authority.delayUntil = delayUntil;
877 }
878 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
879 }
880
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700881 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000882 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
883 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700884 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000885 boolean restoreAllPeriodicSyncs() {
886 if (mPeriodicSyncAddedListener == null) {
887 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800888 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000889 synchronized (mAuthorities) {
890 for (int i=0; i<mAuthorities.size(); i++) {
891 AuthorityInfo authority = mAuthorities.valueAt(i);
892 for (PeriodicSync periodicSync: authority.periodicSyncs) {
893 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
894 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
895 }
896 authority.periodicSyncs.clear();
897 }
898 writeAccountInfoLocked();
899 }
900 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800901 }
902
Amith Yamasani04e0d262012-02-14 11:50:53 -0800903 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700904 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800905 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700906 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700907 return;
908 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800909 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700910 writeAccountInfoLocked();
911 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700912 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700913 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800914 new Bundle(),
915 /*exemptFromAppStandby=*/ false); // Or the caller FG state?
Joe Onorato8294fad2009-07-15 16:08:44 -0700916 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700917 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800918 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800919 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921
Amith Yamasani04e0d262012-02-14 11:50:53 -0800922 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700923 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800924 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800925 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700926 }
927 }
Costin Manolache360e4542009-09-04 13:36:04 -0700928
Makoto Onukib47e8942017-09-18 14:03:03 -0700929 public int getAuthorityCount() {
930 synchronized (mAuthorities) {
931 return mAuthorities.size();
932 }
933 }
934
Dianne Hackborn231cc602009-04-27 17:10:36 -0700935 public AuthorityInfo getAuthority(int authorityId) {
936 synchronized (mAuthorities) {
937 return mAuthorities.get(authorityId);
938 }
939 }
Costin Manolache360e4542009-09-04 13:36:04 -0700940
Dianne Hackborn231cc602009-04-27 17:10:36 -0700941 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700942 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700943 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700944 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700945 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700947 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700948 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700949 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 return true;
951 }
952 }
953 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 return false;
955 }
Costin Manolache360e4542009-09-04 13:36:04 -0700956
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000957 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000959 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
960 -1 /* desired identifier */,
961 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700962 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000963 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700964 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700965 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000966 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700968 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 }
Costin Manolache360e4542009-09-04 13:36:04 -0700970
Dianne Hackborn231cc602009-04-27 17:10:36 -0700971 /**
972 * Called when the set of account has changed, given the new array of
973 * active accounts.
974 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800975 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700976 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700977 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000978 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700979 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700980 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
981 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
982 while (accIt.hasNext()) {
983 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800984 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
985 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700986 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700987 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000988 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700989 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700990 for (AuthorityInfo auth : acc.authorities.values()) {
991 removing.put(auth.ident, auth);
992 }
993 accIt.remove();
994 }
995 }
Costin Manolache360e4542009-09-04 13:36:04 -0700996
Dianne Hackborn231cc602009-04-27 17:10:36 -0700997 // Clean out all data structures.
998 int i = removing.size();
999 if (i > 0) {
1000 while (i > 0) {
1001 i--;
1002 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001003 AuthorityInfo auth = removing.valueAt(i);
1004 if (mAuthorityRemovedListener != null) {
1005 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1006 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001007 mAuthorities.remove(ident);
1008 int j = mSyncStatus.size();
1009 while (j > 0) {
1010 j--;
1011 if (mSyncStatus.keyAt(j) == ident) {
1012 mSyncStatus.remove(mSyncStatus.keyAt(j));
1013 }
1014 }
1015 j = mSyncHistory.size();
1016 while (j > 0) {
1017 j--;
1018 if (mSyncHistory.get(j).authorityId == ident) {
1019 mSyncHistory.remove(j);
1020 }
1021 }
1022 }
1023 writeAccountInfoLocked();
1024 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 writeStatisticsLocked();
1026 }
1027 }
1028 }
1029
1030 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001031 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1032 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 */
Fred Quintana918339a2010-10-05 14:00:39 -07001034 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1035 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001036 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001037 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001038 Slog.v(TAG, "setActiveSync: account="
1039 + " auth=" + activeSyncContext.mSyncOperation.target
1040 + " src=" + activeSyncContext.mSyncOperation.syncSource
1041 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001043 final EndPoint info = activeSyncContext.mSyncOperation.target;
1044 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1045 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001046 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001047 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001048 syncInfo = new SyncInfo(
1049 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001050 authorityInfo.target.account,
1051 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001052 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001053 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001054 }
Fred Quintana918339a2010-10-05 14:00:39 -07001055 reportActiveChange();
1056 return syncInfo;
1057 }
1058
1059 /**
1060 * Called to indicate that a previously active sync is no longer active.
1061 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001062 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001063 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001064 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001065 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001066 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001067 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001068 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001069 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001070 }
1071
1072 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001073 }
1074
1075 /**
1076 * To allow others to send active change reports, to poke clients.
1077 */
1078 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001079 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001080 }
Costin Manolache360e4542009-09-04 13:36:04 -07001081
Dianne Hackborn231cc602009-04-27 17:10:36 -07001082 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001083 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001085 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001086 long id;
1087 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001088 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001089 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001090 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001091 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001092 if (authority == null) {
1093 return -1;
1094 }
1095 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001096 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001097 item.authorityId = authority.ident;
1098 item.historyId = mNextHistoryId++;
1099 if (mNextHistoryId < 0) mNextHistoryId = 0;
1100 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001101 item.source = op.syncSource;
1102 item.reason = op.reason;
1103 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 item.event = EVENT_START;
1105 mSyncHistory.add(0, item);
1106 while (mSyncHistory.size() > MAX_HISTORY) {
1107 mSyncHistory.remove(mSyncHistory.size()-1);
1108 }
1109 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001110 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001111 }
Costin Manolache360e4542009-09-04 13:36:04 -07001112
Fred Quintanaac9385e2009-06-22 18:00:59 -07001113 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001114 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 }
1116
Fred Quintana77c560f2010-03-29 22:20:26 -07001117 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001118 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001120 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001121 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001122 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 SyncHistoryItem item = null;
1124 int i = mSyncHistory.size();
1125 while (i > 0) {
1126 i--;
1127 item = mSyncHistory.get(i);
1128 if (item.historyId == historyId) {
1129 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 }
Costin Manolache360e4542009-09-04 13:36:04 -07001133
Dianne Hackborn231cc602009-04-27 17:10:36 -07001134 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001135 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001136 return;
1137 }
Costin Manolache360e4542009-09-04 13:36:04 -07001138
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 item.elapsedTime = elapsedTime;
1140 item.event = EVENT_STOP;
1141 item.mesg = resultMessage;
1142 item.downstreamActivity = downstreamActivity;
1143 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001144
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001146
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 status.numSyncs++;
1148 status.totalElapsedTime += elapsedTime;
1149 switch (item.source) {
1150 case SOURCE_LOCAL:
1151 status.numSourceLocal++;
1152 break;
1153 case SOURCE_POLL:
1154 status.numSourcePoll++;
1155 break;
1156 case SOURCE_USER:
1157 status.numSourceUser++;
1158 break;
1159 case SOURCE_SERVER:
1160 status.numSourceServer++;
1161 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001162 case SOURCE_PERIODIC:
1163 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001164 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 }
Costin Manolache360e4542009-09-04 13:36:04 -07001166
Dianne Hackborn231cc602009-04-27 17:10:36 -07001167 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001168 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 if (mDayStats[0] == null) {
1170 mDayStats[0] = new DayStats(day);
1171 } else if (day != mDayStats[0].day) {
1172 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1173 mDayStats[0] = new DayStats(day);
1174 writeStatisticsNow = true;
1175 } else if (mDayStats[0] == null) {
1176 }
1177 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001178
Dianne Hackborn231cc602009-04-27 17:10:36 -07001179 final long lastSyncTime = (item.eventTime + elapsedTime);
1180 boolean writeStatusNow = false;
1181 if (MESG_SUCCESS.equals(resultMessage)) {
1182 // - if successful, update the successful columns
1183 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1184 writeStatusNow = true;
1185 }
1186 status.lastSuccessTime = lastSyncTime;
1187 status.lastSuccessSource = item.source;
1188 status.lastFailureTime = 0;
1189 status.lastFailureSource = -1;
1190 status.lastFailureMesg = null;
1191 status.initialFailureTime = 0;
1192 ds.successCount++;
1193 ds.successTime += elapsedTime;
1194 } else if (!MESG_CANCELED.equals(resultMessage)) {
1195 if (status.lastFailureTime == 0) {
1196 writeStatusNow = true;
1197 }
1198 status.lastFailureTime = lastSyncTime;
1199 status.lastFailureSource = item.source;
1200 status.lastFailureMesg = resultMessage;
1201 if (status.initialFailureTime == 0) {
1202 status.initialFailureTime = lastSyncTime;
1203 }
1204 ds.failureCount++;
1205 ds.failureTime += elapsedTime;
1206 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001207 final StringBuilder event = new StringBuilder();
1208 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1209 + " Elapsed=");
1210 SyncManager.formatDurationHMS(event, elapsedTime);
1211 event.append(" Reason=");
1212 event.append(SyncOperation.reasonToString(null, item.reason));
1213 event.append(" Extras=");
1214 SyncOperation.extrasToStringBuilder(item.extras, event);
1215
1216 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001217
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 if (writeStatusNow) {
1219 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001220 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1221 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001222 WRITE_STATUS_DELAY);
1223 }
1224 if (writeStatisticsNow) {
1225 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001226 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1227 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001229 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001230 }
Costin Manolache360e4542009-09-04 13:36:04 -07001231
Fred Quintanaac9385e2009-06-22 18:00:59 -07001232 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 }
1234
1235 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001236 * Return a list of the currently active syncs. Note that the returned
1237 * items are the real, live active sync objects, so be careful what you do
1238 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001239 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001240 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001241 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001242 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001243 }
1244 }
Costin Manolache360e4542009-09-04 13:36:04 -07001245
Dianne Hackborn231cc602009-04-27 17:10:36 -07001246 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001247 * @param userId Id of user to return current sync info.
1248 * @param canAccessAccounts Determines whether to redact Account information from the result.
1249 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001250 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001251 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001252 synchronized (mAuthorities) {
1253 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1254 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1255 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001256 SyncInfo copy;
1257 if (!canAccessAccounts) {
1258 copy = SyncInfo.createAccountRedacted(
1259 sync.authorityId, sync.authority, sync.startTime);
1260 } else {
1261 copy = new SyncInfo(sync);
1262 }
1263 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001264 }
1265 return syncsCopy;
1266 }
1267 }
1268
1269 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1270 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1271 if (syncs == null) {
1272 syncs = new ArrayList<SyncInfo>();
1273 mCurrentSyncs.put(userId, syncs);
1274 }
1275 return syncs;
1276 }
1277
1278 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001279 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001280 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001281 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001282 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001283 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001284 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001285 true /* write to storage if this results in a change */);
1286 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1287 }
1288 }
1289
1290 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001291 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001292 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001293 * @param info the endpoint target we are querying status info for.
1294 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001295 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001296 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001297 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001298 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001299 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001302 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001303 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001304 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001305 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001306 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001307 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 }
1309 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001310 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 }
1312 }
Costin Manolache360e4542009-09-04 13:36:04 -07001313
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001314 /** Return true if the pending status is true of any matching authorities. */
1315 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001316 synchronized (mAuthorities) {
1317 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001318 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001319 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001320 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1321 if (ainfo == null) {
1322 continue;
1323 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001324 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001325 continue;
1326 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001327 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001328 return true;
1329 }
1330 }
1331 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
1333 }
1334
1335 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001336 * Return an array of the current sync status for all authorities. Note
1337 * that the objects inside the array are the real, live status objects,
1338 * so be careful what you do with them.
1339 */
1340 public ArrayList<SyncHistoryItem> getSyncHistory() {
1341 synchronized (mAuthorities) {
1342 final int N = mSyncHistory.size();
1343 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1344 for (int i=0; i<N; i++) {
1345 items.add(mSyncHistory.get(i));
1346 }
1347 return items;
1348 }
1349 }
Costin Manolache360e4542009-09-04 13:36:04 -07001350
Dianne Hackborn231cc602009-04-27 17:10:36 -07001351 /**
1352 * Return an array of the current per-day statistics. Note
1353 * that the objects inside the array are the real, live status objects,
1354 * so be careful what you do with them.
1355 */
1356 public DayStats[] getDayStatistics() {
1357 synchronized (mAuthorities) {
1358 DayStats[] ds = new DayStats[mDayStats.length];
1359 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1360 return ds;
1361 }
1362 }
Costin Manolache360e4542009-09-04 13:36:04 -07001363
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001364 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1365 AuthorityInfo authorityInfo) {
1366 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1367 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1368 }
1369
Dianne Hackborn55280a92009-05-07 15:53:46 -07001370 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001371 mCal.setTimeInMillis(System.currentTimeMillis());
1372 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1373 if (mYear != mCal.get(Calendar.YEAR)) {
1374 mYear = mCal.get(Calendar.YEAR);
1375 mCal.clear();
1376 mCal.set(Calendar.YEAR, mYear);
1377 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1378 }
1379 return dayOfYear + mYearInDays;
1380 }
Costin Manolache360e4542009-09-04 13:36:04 -07001381
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001383 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001384 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001385 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001387 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001389 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001390 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1391 AccountInfo accountInfo = mAccounts.get(au);
1392 if (accountInfo == null) {
1393 if (tag != null) {
1394 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1395 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001396 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001397 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 return null;
1399 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001400 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1401 if (authority == null) {
1402 if (tag != null) {
1403 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1404 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1405 }
1406 }
1407 return null;
1408 }
1409 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001410 }
Costin Manolache360e4542009-09-04 13:36:04 -07001411
Matthew Williamsfa774182013-06-18 15:44:11 -07001412 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001413 * @param info info identifying target.
1414 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001415 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001416 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001417 * exists.
1418 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001419 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1420 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001421 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1422 AccountInfo account = mAccounts.get(au);
1423 if (account == null) {
1424 account = new AccountInfo(au);
1425 mAccounts.put(au, account);
1426 }
1427 authority = account.authorities.get(info.provider);
1428 if (authority == null) {
1429 authority = createAuthorityLocked(info, ident, doWrite);
1430 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001431 }
1432 return authority;
1433 }
1434
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001435 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1436 AuthorityInfo authority;
1437 if (ident < 0) {
1438 ident = mNextAuthorityId;
1439 mNextAuthorityId++;
1440 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001442 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001443 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001444 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001445 authority = new AuthorityInfo(info, ident);
1446 mAuthorities.put(ident, authority);
1447 if (doWrite) {
1448 writeAccountInfoLocked();
1449 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001450 return authority;
1451 }
Costin Manolache360e4542009-09-04 13:36:04 -07001452
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001453 public void removeAuthority(EndPoint info) {
1454 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001455 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001456 }
1457 }
1458
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001459
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001460 /**
1461 * Remove an authority associated with a provider. Needs to be a standalone function for
1462 * backward compatibility.
1463 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001464 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001465 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001466 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001467 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001468 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1469 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001470 if (mAuthorityRemovedListener != null) {
1471 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1472 }
Fred Quintanafb084402010-03-23 17:57:03 -07001473 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001474 if (doWrite) {
1475 writeAccountInfoLocked();
1476 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001477 }
1478 }
1479 }
1480
Dianne Hackborn231cc602009-04-27 17:10:36 -07001481 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1482 SyncStatusInfo status = mSyncStatus.get(authorityId);
1483 if (status == null) {
1484 status = new SyncStatusInfo(authorityId);
1485 mSyncStatus.put(authorityId, status);
1486 }
1487 return status;
1488 }
Costin Manolache360e4542009-09-04 13:36:04 -07001489
Dianne Hackborn55280a92009-05-07 15:53:46 -07001490 public void writeAllState() {
1491 synchronized (mAuthorities) {
1492 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001493 writeStatusLocked();
1494 writeStatisticsLocked();
1495 }
1496 }
Costin Manolache360e4542009-09-04 13:36:04 -07001497
Svet Ganov65712b02016-09-01 10:24:11 -07001498 public boolean shouldGrantSyncAdaptersAccountAccess() {
1499 return mGrantSyncAdaptersAccountAccess;
1500 }
1501
Dianne Hackborn231cc602009-04-27 17:10:36 -07001502 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001503 * public for testing
1504 */
1505 public void clearAndReadState() {
1506 synchronized (mAuthorities) {
1507 mAuthorities.clear();
1508 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001509 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001510 mSyncStatus.clear();
1511 mSyncHistory.clear();
1512
1513 readAccountInfoLocked();
1514 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001515 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001516 readAndDeleteLegacyAccountInfoLocked();
1517 writeAccountInfoLocked();
1518 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001519 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001520 }
1521 }
1522
1523 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 * Read all account information back in to the initial engine state.
1525 */
1526 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001527 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001528 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001531 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001532 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001533 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001534 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001535 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001536 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001537 while (eventType != XmlPullParser.START_TAG &&
1538 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001539 eventType = parser.next();
1540 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001541 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001542 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001543 return;
1544 }
1545
Dianne Hackborn231cc602009-04-27 17:10:36 -07001546 String tagName = parser.getName();
1547 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001548 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001549 String versionString = parser.getAttributeValue(null, "version");
1550 int version;
1551 try {
1552 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1553 } catch (NumberFormatException e) {
1554 version = 0;
1555 }
Svet Ganov65712b02016-09-01 10:24:11 -07001556
1557 if (version < 3) {
1558 mGrantSyncAdaptersAccountAccess = true;
1559 }
1560
Amith Yamasani04e0d262012-02-14 11:50:53 -08001561 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001562 try {
1563 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1564 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1565 } catch (NumberFormatException e) {
1566 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001567 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001568 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1569 try {
1570 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1571 } catch (NumberFormatException e) {
1572 mSyncRandomOffset = 0;
1573 }
1574 if (mSyncRandomOffset == 0) {
1575 Random random = new Random(System.currentTimeMillis());
1576 mSyncRandomOffset = random.nextInt(86400);
1577 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001578 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001579 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001580 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001581 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001582 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001583 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001584 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001586 if (parser.getDepth() == 2) {
1587 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001588 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001589 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001590 if (authority != null) {
1591 if (authority.ident > highestAuthorityId) {
1592 highestAuthorityId = authority.ident;
1593 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001594 } else {
1595 EventLog.writeEvent(0x534e4554, "26513719", -1,
1596 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001597 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001598 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1599 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001600 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001601 } else if (parser.getDepth() == 3) {
1602 if ("periodicSync".equals(tagName) && authority != null) {
1603 periodicSync = parsePeriodicSync(parser, authority);
1604 }
1605 } else if (parser.getDepth() == 4 && periodicSync != null) {
1606 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001607 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001608 }
1609 }
1610 }
1611 eventType = parser.next();
1612 } while (eventType != XmlPullParser.END_DOCUMENT);
1613 }
1614 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001615 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001616 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001617 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001618 if (fis == null) Slog.i(TAG, "No initial accounts");
1619 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001620 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001621 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001622 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001623 if (fis != null) {
1624 try {
1625 fis.close();
1626 } catch (java.io.IOException e1) {
1627 }
1628 }
1629 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001630
Fred Quintana77c560f2010-03-29 22:20:26 -07001631 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001632 }
Costin Manolache360e4542009-09-04 13:36:04 -07001633
Fred Quintanafb084402010-03-23 17:57:03 -07001634 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001635 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1636 * pending.xml was used starting in KLP.
1637 * @param syncDir directory where the sync files are located.
1638 */
1639 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1640 File file = new File(syncDir, "pending.bin");
1641 if (!file.exists()) {
1642 return;
1643 } else {
1644 file.delete();
1645 }
1646 }
1647
1648 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001649 * some authority names have changed. copy over their settings and delete the old ones
1650 * @return true if a change was made
1651 */
1652 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1653 boolean writeNeeded = false;
1654
1655 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1656 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001657 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001658 AuthorityInfo authority = mAuthorities.valueAt(i);
1659 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001660 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001661 if (newAuthorityName == null) {
1662 continue;
1663 }
1664
1665 // remember this authority so we can remove it later. we can't remove it
1666 // now without messing up this loop iteration
1667 authoritiesToRemove.add(authority);
1668
1669 // this authority isn't enabled, no need to copy it to the new authority name since
1670 // the default is "disabled"
1671 if (!authority.enabled) {
1672 continue;
1673 }
1674
1675 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001676 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001677 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001678 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001679 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001680 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001681 continue;
1682 }
1683
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001684 AuthorityInfo newAuthority =
1685 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001686 newAuthority.enabled = true;
1687 writeNeeded = true;
1688 }
1689
1690 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001691 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001692 authorityInfo.target.account,
1693 authorityInfo.target.userId,
1694 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001695 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001696 writeNeeded = true;
1697 }
1698
1699 return writeNeeded;
1700 }
1701
Amith Yamasani04e0d262012-02-14 11:50:53 -08001702 private void parseListenForTickles(XmlPullParser parser) {
1703 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1704 int userId = 0;
1705 try {
1706 userId = Integer.parseInt(user);
1707 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001708 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001709 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001710 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001711 }
1712 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1713 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1714 mMasterSyncAutomatically.put(userId, listen);
1715 }
1716
Suprabh Shukla042a4782017-05-12 15:26:54 -07001717 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1718 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001719 AuthorityInfo authority = null;
1720 int id = -1;
1721 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001722 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001723 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001724 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001725 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001726 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001727 }
1728 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001729 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001730 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001731 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001732 String accountName = parser.getAttributeValue(null, "account");
1733 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001734 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001735 String packageName = parser.getAttributeValue(null, "package");
1736 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001737 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001738 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001739 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001740 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001741 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001742 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001743 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001744 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001745 + " account=" + accountName
1746 + " accountType=" + accountType
1747 + " auth=" + authorityName
1748 + " package=" + packageName
1749 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001750 + " user=" + userId
1751 + " enabled=" + enabled
1752 + " syncable=" + syncable);
1753 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001754 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001755 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001756 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001757 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001758 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001759 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001760 new Account(accountName, accountType),
1761 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001762 if (validator.isAccountValid(info.account, userId)
1763 && validator.isAuthorityValid(authorityName, userId)) {
1764 authority = getOrCreateAuthorityLocked(info, id, false);
1765 // If the version is 0 then we are upgrading from a file format that did not
1766 // know about periodic syncs. In that case don't clear the list since we
1767 // want the default, which is a daily periodic sync.
1768 // Otherwise clear out this default list since we will populate it later
1769 // with
1770 // the periodic sync descriptions that are read from the configuration file.
1771 if (version > 0) {
1772 authority.periodicSyncs.clear();
1773 }
1774 } else {
1775 EventLog.writeEvent(0x534e4554, "35028827", -1,
1776 "account:" + info.account + " provider:" + authorityName + " user:"
1777 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001778 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001779 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001780 }
1781 if (authority != null) {
1782 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001783 try {
1784 authority.syncable = (syncable == null) ?
1785 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1786 } catch (NumberFormatException e) {
1787 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1788 // format.
1789 if ("unknown".equals(syncable)) {
1790 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1791 } else {
1792 authority.syncable = Boolean.parseBoolean(syncable) ?
1793 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1794 }
1795
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001796 }
1797 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001798 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001799 + accountName + " auth=" + authorityName
1800 + " enabled=" + enabled
1801 + " syncable=" + syncable);
1802 }
1803 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001804 return authority;
1805 }
1806
Matthew Williamsfa774182013-06-18 15:44:11 -07001807 /**
1808 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1809 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001810 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001811 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001812 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001813 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001814 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001815 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001816 try {
1817 period = Long.parseLong(periodValue);
1818 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001819 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001820 return null;
1821 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001822 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001823 return null;
1824 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001825 try {
1826 flextime = Long.parseLong(flexValue);
1827 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001828 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001829 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001830 + ", using default: "
1831 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001832 } catch (NullPointerException expected) {
1833 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001834 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1835 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001836 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001837 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001838 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001839 new PeriodicSync(authorityInfo.target.account,
1840 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001841 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001842 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001843 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001844 return periodicSync;
1845 }
1846
Matthew Williamsfa774182013-06-18 15:44:11 -07001847 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001848 String name = parser.getAttributeValue(null, "name");
1849 String type = parser.getAttributeValue(null, "type");
1850 String value1 = parser.getAttributeValue(null, "value1");
1851 String value2 = parser.getAttributeValue(null, "value2");
1852
1853 try {
1854 if ("long".equals(type)) {
1855 extras.putLong(name, Long.parseLong(value1));
1856 } else if ("integer".equals(type)) {
1857 extras.putInt(name, Integer.parseInt(value1));
1858 } else if ("double".equals(type)) {
1859 extras.putDouble(name, Double.parseDouble(value1));
1860 } else if ("float".equals(type)) {
1861 extras.putFloat(name, Float.parseFloat(value1));
1862 } else if ("boolean".equals(type)) {
1863 extras.putBoolean(name, Boolean.parseBoolean(value1));
1864 } else if ("string".equals(type)) {
1865 extras.putString(name, value1);
1866 } else if ("account".equals(type)) {
1867 extras.putParcelable(name, new Account(value1, value2));
1868 }
1869 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001870 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001871 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001872 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001873 }
1874 }
1875
Dianne Hackborn231cc602009-04-27 17:10:36 -07001876 /**
1877 * Write all account information to the account file.
1878 */
1879 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001880 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001881 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001882 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001883 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001884
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 try {
1886 fos = mAccountInfoFile.startWrite();
1887 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001888 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001889 out.startDocument(null, true);
1890 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001891
Dianne Hackborn231cc602009-04-27 17:10:36 -07001892 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001893 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001894 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001895 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001896
1897 // Write the Sync Automatically flags for each user
1898 final int M = mMasterSyncAutomatically.size();
1899 for (int m = 0; m < M; m++) {
1900 int userId = mMasterSyncAutomatically.keyAt(m);
1901 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1902 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1903 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1904 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1905 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001906 }
Costin Manolache360e4542009-09-04 13:36:04 -07001907
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001909 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001910 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001911 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001912 out.startTag(null, "authority");
1913 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001914 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001915 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001916 out.attribute(null, "account", info.account.name);
1917 out.attribute(null, "type", info.account.type);
1918 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001919 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001920 out.endTag(null, "authority");
1921 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001922 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001924 mAccountInfoFile.finishWrite(fos);
1925 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001926 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001927 if (fos != null) {
1928 mAccountInfoFile.failWrite(fos);
1929 }
1930 }
1931 }
Costin Manolache360e4542009-09-04 13:36:04 -07001932
Dianne Hackborn231cc602009-04-27 17:10:36 -07001933 static int getIntColumn(Cursor c, String name) {
1934 return c.getInt(c.getColumnIndex(name));
1935 }
Costin Manolache360e4542009-09-04 13:36:04 -07001936
Dianne Hackborn231cc602009-04-27 17:10:36 -07001937 static long getLongColumn(Cursor c, String name) {
1938 return c.getLong(c.getColumnIndex(name));
1939 }
Costin Manolache360e4542009-09-04 13:36:04 -07001940
Dianne Hackborn231cc602009-04-27 17:10:36 -07001941 /**
1942 * Load sync engine state from the old syncmanager database, and then
1943 * erase it. Note that we don't deal with pending operations, active
1944 * sync, or history.
1945 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001946 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001947 // Look for old database to initialize from.
1948 File file = mContext.getDatabasePath("syncmanager.db");
1949 if (!file.exists()) {
1950 return;
1951 }
1952 String path = file.getPath();
1953 SQLiteDatabase db = null;
1954 try {
1955 db = SQLiteDatabase.openDatabase(path, null,
1956 SQLiteDatabase.OPEN_READONLY);
1957 } catch (SQLiteException e) {
1958 }
Costin Manolache360e4542009-09-04 13:36:04 -07001959
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001961 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001962
Dianne Hackborn231cc602009-04-27 17:10:36 -07001963 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001964 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001965 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001966 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1968 qb.setTables("stats, status");
1969 HashMap<String,String> map = new HashMap<String,String>();
1970 map.put("_id", "status._id as _id");
1971 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001972 if (hasType) {
1973 map.put("account_type", "stats.account_type as account_type");
1974 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 map.put("authority", "stats.authority as authority");
1976 map.put("totalElapsedTime", "totalElapsedTime");
1977 map.put("numSyncs", "numSyncs");
1978 map.put("numSourceLocal", "numSourceLocal");
1979 map.put("numSourcePoll", "numSourcePoll");
1980 map.put("numSourceServer", "numSourceServer");
1981 map.put("numSourceUser", "numSourceUser");
1982 map.put("lastSuccessSource", "lastSuccessSource");
1983 map.put("lastSuccessTime", "lastSuccessTime");
1984 map.put("lastFailureSource", "lastFailureSource");
1985 map.put("lastFailureTime", "lastFailureTime");
1986 map.put("lastFailureMesg", "lastFailureMesg");
1987 map.put("pending", "pending");
1988 qb.setProjectionMap(map);
1989 qb.appendWhere("stats._id = status.stats_id");
1990 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001992 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001993 String accountType = hasType
1994 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001995 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001996 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001998 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001999 AuthorityInfo authority =
2000 this.getOrCreateAuthorityLocked(
2001 new EndPoint(new Account(accountName, accountType),
2002 authorityName,
2003 0 /* legacy is single-user */)
2004 , -1,
2005 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 if (authority != null) {
2007 int i = mSyncStatus.size();
2008 boolean found = false;
2009 SyncStatusInfo st = null;
2010 while (i > 0) {
2011 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002012 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 if (st.authorityId == authority.ident) {
2014 found = true;
2015 break;
2016 }
2017 }
2018 if (!found) {
2019 st = new SyncStatusInfo(authority.ident);
2020 mSyncStatus.put(authority.ident, st);
2021 }
2022 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2023 st.numSyncs = getIntColumn(c, "numSyncs");
2024 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
2025 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
2026 st.numSourceServer = getIntColumn(c, "numSourceServer");
2027 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08002028 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002029 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2030 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2031 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2032 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2033 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2034 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036 }
Costin Manolache360e4542009-09-04 13:36:04 -07002037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002039
Dianne Hackborn231cc602009-04-27 17:10:36 -07002040 // Retrieve the settings.
2041 qb = new SQLiteQueryBuilder();
2042 qb.setTables("settings");
2043 c = qb.query(db, null, null, null, null, null, null);
2044 while (c.moveToNext()) {
2045 String name = c.getString(c.getColumnIndex("name"));
2046 String value = c.getString(c.getColumnIndex("value"));
2047 if (name == null) continue;
2048 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002049 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002050 } else if (name.startsWith("sync_provider_")) {
2051 String provider = name.substring("sync_provider_".length(),
2052 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002053 int i = mAuthorities.size();
2054 while (i > 0) {
2055 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002056 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002057 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002058 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002059 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002060 }
2061 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 }
Costin Manolache360e4542009-09-04 13:36:04 -07002064
Dianne Hackborn231cc602009-04-27 17:10:36 -07002065 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002066
Dianne Hackborn231cc602009-04-27 17:10:36 -07002067 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002068
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 (new File(path)).delete();
2070 }
2071 }
Costin Manolache360e4542009-09-04 13:36:04 -07002072
Dianne Hackborn231cc602009-04-27 17:10:36 -07002073 public static final int STATUS_FILE_END = 0;
2074 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002075
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 /**
2077 * Read all sync status back in to the initial engine state.
2078 */
2079 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002080 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002081 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002082 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002083 try {
2084 byte[] data = mStatusFile.readFully();
2085 Parcel in = Parcel.obtain();
2086 in.unmarshall(data, 0, data.length);
2087 in.setDataPosition(0);
2088 int token;
2089 while ((token=in.readInt()) != STATUS_FILE_END) {
2090 if (token == STATUS_FILE_ITEM) {
2091 SyncStatusInfo status = new SyncStatusInfo(in);
2092 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2093 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002094 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002095 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002096 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002097 mSyncStatus.put(status.authorityId, status);
2098 }
2099 } else {
2100 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002101 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002102 break;
2103 }
2104 }
2105 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002106 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002107 }
2108 }
Costin Manolache360e4542009-09-04 13:36:04 -07002109
Dianne Hackborn231cc602009-04-27 17:10:36 -07002110 /**
2111 * Write all sync status to the sync status file.
2112 */
2113 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002114 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002115 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002116 }
Costin Manolache360e4542009-09-04 13:36:04 -07002117
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 // The file is being written, so we don't need to have a scheduled
2119 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002120 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002121
Dianne Hackborn231cc602009-04-27 17:10:36 -07002122 FileOutputStream fos = null;
2123 try {
2124 fos = mStatusFile.startWrite();
2125 Parcel out = Parcel.obtain();
2126 final int N = mSyncStatus.size();
2127 for (int i=0; i<N; i++) {
2128 SyncStatusInfo status = mSyncStatus.valueAt(i);
2129 out.writeInt(STATUS_FILE_ITEM);
2130 status.writeToParcel(out, 0);
2131 }
2132 out.writeInt(STATUS_FILE_END);
2133 fos.write(out.marshall());
2134 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002135
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 mStatusFile.finishWrite(fos);
2137 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002138 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002139 if (fos != null) {
2140 mStatusFile.failWrite(fos);
2141 }
2142 }
2143 }
Costin Manolache360e4542009-09-04 13:36:04 -07002144
Makoto Onuki61283ec2018-01-31 17:22:36 -08002145 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
2146 boolean exemptFromAppStandby) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002147 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2148 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002149 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
2150 exemptFromAppStandby);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002151 } else {
2152 SyncRequest.Builder req =
2153 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002154 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002155 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002156 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002157 ContentResolver.requestSync(req.build());
2158 }
2159 }
2160
Alon Albert57286f92012-10-09 14:21:38 -07002161 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onuki61283ec2018-01-31 17:22:36 -08002162 Bundle extras, boolean exemptFromAppStandby) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002163 // If this is happening in the system process, then call the syncrequest listener
2164 // to make a request back to the SyncManager directly.
2165 // If this is probably a test instance, then call back through the ContentResolver
2166 // which will know which userId to apply based on the Binder id.
2167 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2168 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002169 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002170 new EndPoint(account, authority, userId),
Makoto Onuki61283ec2018-01-31 17:22:36 -08002171 reason, extras, exemptFromAppStandby);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002172 } else {
2173 ContentResolver.requestSync(account, authority, extras);
2174 }
2175 }
2176
Dianne Hackborn231cc602009-04-27 17:10:36 -07002177 public static final int STATISTICS_FILE_END = 0;
2178 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2179 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002180
Dianne Hackborn231cc602009-04-27 17:10:36 -07002181 /**
2182 * Read all sync statistics back in to the initial engine state.
2183 */
2184 private void readStatisticsLocked() {
2185 try {
2186 byte[] data = mStatisticsFile.readFully();
2187 Parcel in = Parcel.obtain();
2188 in.unmarshall(data, 0, data.length);
2189 in.setDataPosition(0);
2190 int token;
2191 int index = 0;
2192 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2193 if (token == STATISTICS_FILE_ITEM
2194 || token == STATISTICS_FILE_ITEM_OLD) {
2195 int day = in.readInt();
2196 if (token == STATISTICS_FILE_ITEM_OLD) {
2197 day = day - 2009 + 14245; // Magic!
2198 }
2199 DayStats ds = new DayStats(day);
2200 ds.successCount = in.readInt();
2201 ds.successTime = in.readLong();
2202 ds.failureCount = in.readInt();
2203 ds.failureTime = in.readLong();
2204 if (index < mDayStats.length) {
2205 mDayStats[index] = ds;
2206 index++;
2207 }
2208 } else {
2209 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002210 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002211 break;
2212 }
2213 }
2214 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002215 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002216 }
2217 }
Costin Manolache360e4542009-09-04 13:36:04 -07002218
Dianne Hackborn231cc602009-04-27 17:10:36 -07002219 /**
2220 * Write all sync statistics to the sync status file.
2221 */
2222 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002223 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002224 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002225 }
Costin Manolache360e4542009-09-04 13:36:04 -07002226
Dianne Hackborn231cc602009-04-27 17:10:36 -07002227 // The file is being written, so we don't need to have a scheduled
2228 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002229 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002230
Dianne Hackborn231cc602009-04-27 17:10:36 -07002231 FileOutputStream fos = null;
2232 try {
2233 fos = mStatisticsFile.startWrite();
2234 Parcel out = Parcel.obtain();
2235 final int N = mDayStats.length;
2236 for (int i=0; i<N; i++) {
2237 DayStats ds = mDayStats[i];
2238 if (ds == null) {
2239 break;
2240 }
2241 out.writeInt(STATISTICS_FILE_ITEM);
2242 out.writeInt(ds.day);
2243 out.writeInt(ds.successCount);
2244 out.writeLong(ds.successTime);
2245 out.writeInt(ds.failureCount);
2246 out.writeLong(ds.failureTime);
2247 }
2248 out.writeInt(STATISTICS_FILE_END);
2249 fos.write(out.marshall());
2250 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002251
Dianne Hackborn231cc602009-04-27 17:10:36 -07002252 mStatisticsFile.finishWrite(fos);
2253 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002254 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002255 if (fos != null) {
2256 mStatisticsFile.failWrite(fos);
2257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002260
2261 /**
Marvin Paula6533252014-11-24 12:57:48 -08002262 * Let the BackupManager know that account sync settings have changed. This will trigger
2263 * {@link com.android.server.backup.SystemBackupAgent} to run.
2264 */
2265 public void queueBackup() {
2266 BackupManager.dataChanged("android");
2267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268}