blob: 391e3b01da08c972dc93115b5ad4777577180853 [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;
Makoto Onuki3ab77812018-07-09 14:29:33 -070022import android.annotation.Nullable;
Marvin Paula6533252014-11-24 12:57:48 -080023import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070024import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080025import android.content.ContentResolver;
Makoto Onuki75ad2492018-03-28 14:42:42 -070026import android.content.ContentResolver.SyncExemption;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.content.Context;
28import android.content.ISyncStatusObserver;
29import android.content.PeriodicSync;
30import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070031import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080032import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070033import android.content.pm.PackageManager;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080037import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070038import android.os.Message;
39import android.os.Parcel;
40import android.os.RemoteCallbackList;
41import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070042import android.os.UserHandle;
Makoto Onukid4764302018-03-30 17:32:57 -070043import android.util.ArrayMap;
44import android.util.AtomicFile;
45import android.util.EventLog;
46import android.util.Log;
47import android.util.Pair;
48import android.util.Slog;
49import android.util.SparseArray;
50import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080051
52import com.android.internal.annotations.VisibleForTesting;
53import com.android.internal.util.ArrayUtils;
54import com.android.internal.util.FastXmlSerializer;
55
56import org.xmlpull.v1.XmlPullParser;
57import org.xmlpull.v1.XmlPullParserException;
58import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
Dianne Hackborn231cc602009-04-27 17:10:36 -070060import java.io.File;
61import java.io.FileInputStream;
62import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010063import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070065import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070067import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080068import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070069import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060070import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070073 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070075 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * @hide
77 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080078public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070081 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070082
Amith Yamasani04e0d262012-02-14 11:50:53 -080083 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
84 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070085 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080086 private static final String XML_ATTR_ENABLED = "enabled";
87 private static final String XML_ATTR_USER = "user";
88 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
89
Matthew Williamsfa774182013-06-18 15:44:11 -070090 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000091 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080092
Shreyas Basarge8c834c02016-01-07 13:53:16 +000093 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070094 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
95
96 /** Lower bound on sync time from which we assign a default flex time. */
97 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
98
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080099 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 /** Enum value for a sync start event. */
103 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Dianne Hackborn231cc602009-04-27 17:10:36 -0700105 /** Enum value for a sync stop event. */
106 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Makoto Onuki94986212018-04-11 16:24:46 -0700108 /** Enum value for a sync with other sources. */
109 public static final int SOURCE_OTHER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Dianne Hackborn231cc602009-04-27 17:10:36 -0700111 /** Enum value for a local-initiated sync. */
112 public static final int SOURCE_LOCAL = 1;
Makoto Onuki94986212018-04-11 16:24:46 -0700113
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700114 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700115 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Dianne Hackborn231cc602009-04-27 17:10:36 -0700117 /** Enum value for a user-initiated sync. */
118 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800120 /** Enum value for a periodic sync. */
121 public static final int SOURCE_PERIODIC = 4;
122
Makoto Onuki94986212018-04-11 16:24:46 -0700123 /** Enum a sync with a "feed" extra */
124 public static final int SOURCE_FEED = 5;
125
Fred Quintana307da1a2010-01-21 14:24:20 -0800126 public static final long NOT_IN_BACKOFF_MODE = -1;
127
Makoto Onukif74cf942018-04-16 17:04:58 -0700128 /**
129 * String names for the sync source types.
130 *
131 * KEEP THIS AND {@link SyncStatusInfo#SOURCE_COUNT} IN SYNC.
132 */
133 public static final String[] SOURCES = {
134 "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000135 "LOCAL",
136 "POLL",
137 "USER",
138 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700139 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140
Dianne Hackborn231cc602009-04-27 17:10:36 -0700141 // The MESG column will contain one of these or one of the Error types.
142 public static final String MESG_SUCCESS = "success";
143 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700145 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700146
Dianne Hackborn231cc602009-04-27 17:10:36 -0700147 private static final int MSG_WRITE_STATUS = 1;
148 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700149
Dianne Hackborn231cc602009-04-27 17:10:36 -0700150 private static final int MSG_WRITE_STATISTICS = 2;
151 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700152
153 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700154
Fred Quintanac2e46912010-03-15 16:10:44 -0700155 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700156 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700157
158 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000159 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700160
Makoto Onuki94986212018-04-11 16:24:46 -0700161 private volatile boolean mIsClockValid;
162
Fred Quintanafb084402010-03-23 17:57:03 -0700163 static {
164 sAuthorityRenames = new HashMap<String, String>();
165 sAuthorityRenames.put("contacts", "com.android.contacts");
166 sAuthorityRenames.put("calendar", "com.android.calendar");
167 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700168
Dianne Hackborn231cc602009-04-27 17:10:36 -0700169 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800170 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 final HashMap<String, AuthorityInfo> authorities =
172 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700173
Amith Yamasani04e0d262012-02-14 11:50:53 -0800174 AccountInfo(AccountAndUser accountAndUser) {
175 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700176 }
177 }
Costin Manolache360e4542009-09-04 13:36:04 -0700178
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700179 /** Bare bones representation of a sync target. */
180 public static class EndPoint {
181 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
182 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700183 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800184 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700185 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700186
187 public EndPoint(Account account, String provider, int userId) {
188 this.account = account;
189 this.provider = provider;
190 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700191 }
192
193 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700194 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
195 *
196 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000197 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700198 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700199 public boolean matchesSpec(EndPoint spec) {
200 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700201 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700202 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700203 return false;
204 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000205 boolean accountsMatch;
206 if (spec.account == null) {
207 accountsMatch = true;
208 } else {
209 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700210 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000211 boolean providersMatch;
212 if (spec.provider == null) {
213 providersMatch = true;
214 } else {
215 providersMatch = provider.equals(spec.provider);
216 }
217 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700218 }
219
220 public String toString() {
221 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000222 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700223 .append("/")
224 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700225 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700226 return sb.toString();
227 }
228 }
229
230 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700231 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700232
233 /**
234 * The syncable state is undefined.
235 */
236 public static final int UNDEFINED = -2;
237
Matthew Williams53abfdb2015-06-10 20:06:37 -0700238 /**
239 * Default state for a newly installed adapter. An uninitialized adapter will receive an
240 * initialization sync which are governed by a different set of rules to that of regular
241 * syncs.
242 */
243 public static final int NOT_INITIALIZED = -1;
244 /**
245 * The adapter will not receive any syncs. This is behaviourally equivalent to
246 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
247 * while this is generally meant to be controlled by the developer.
248 */
249 public static final int NOT_SYNCABLE = 0;
250 /**
251 * The adapter is initialized and functioning. This is the normal state for an adapter.
252 */
253 public static final int SYNCABLE = 1;
254 /**
255 * The adapter is syncable but still requires an initialization sync. For example an adapter
256 * than has been restored from a previous device will be in this state. Not meant for
257 * external use.
258 */
259 public static final int SYNCABLE_NOT_INITIALIZED = 2;
260
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700261 /**
262 * The adapter is syncable but does not have access to the synced account and needs a
263 * user access approval.
264 */
265 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
266
Matthew Williams8ef22042013-07-26 12:56:39 -0700267 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700268 final int ident;
269 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700270 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800272 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700273 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800274 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700275 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800276 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700277
Matthew Williamsfa774182013-06-18 15:44:11 -0700278 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700279
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700280 /**
281 * Copy constructor for making deep-ish copies. Only the bundles stored
282 * in periodic syncs can make unexpected changes.
283 *
284 * @param toCopy AuthorityInfo to be copied.
285 */
286 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700287 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700288 ident = toCopy.ident;
289 enabled = toCopy.enabled;
290 syncable = toCopy.syncable;
291 backoffTime = toCopy.backoffTime;
292 backoffDelay = toCopy.backoffDelay;
293 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700294 periodicSyncs = new ArrayList<PeriodicSync>();
295 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700296 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700297 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700298 }
299 }
300
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700301 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700302 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700303 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000304 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700305 periodicSyncs = new ArrayList<PeriodicSync>();
306 defaultInitialisation();
307 }
308
309 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700310 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800311 backoffTime = -1; // if < 0 then we aren't in backoff mode
312 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000313
314 if (mPeriodicSyncAddedListener != null) {
315 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
316 DEFAULT_POLL_FREQUENCY_SECONDS,
317 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700318 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700319 }
Matthew Williams06485a72013-07-26 12:56:39 -0700320
321 @Override
322 public String toString() {
323 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
324 + backoffTime + ", delay=" + delayUntil;
325 }
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 SyncHistoryItem {
329 int authorityId;
330 int historyId;
331 long eventTime;
332 long elapsedTime;
333 int source;
334 int event;
335 long upstreamActivity;
336 long downstreamActivity;
337 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700338 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700339 Bundle extras;
340 int reason;
Makoto Onukid5f25d22018-05-22 16:02:17 -0700341 int syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700342 }
Costin Manolache360e4542009-09-04 13:36:04 -0700343
Dianne Hackborn231cc602009-04-27 17:10:36 -0700344 public static class DayStats {
345 public final int day;
346 public int successCount;
347 public long successTime;
348 public int failureCount;
349 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 public DayStats(int day) {
352 this.day = day;
353 }
354 }
Costin Manolache360e4542009-09-04 13:36:04 -0700355
Amith Yamasani04e0d262012-02-14 11:50:53 -0800356 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700357
358 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800359 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -0700360 @SyncExemption int syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800361 }
362
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000363 interface PeriodicSyncAddedListener {
364 /** Called when a periodic sync is added. */
365 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
366 }
367
368 interface OnAuthorityRemovedListener {
369 /** Called when an authority is removed. */
370 void onAuthorityRemoved(EndPoint removedAuthority);
371 }
372
Suprabh Shukla042a4782017-05-12 15:26:54 -0700373 /**
374 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
375 * account is valid.
376 */
377 private static class AccountAuthorityValidator {
378 final private AccountManager mAccountManager;
379 final private PackageManager mPackageManager;
380 final private SparseArray<Account[]> mAccountsCache;
381 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
382
383 AccountAuthorityValidator(Context context) {
384 mAccountManager = context.getSystemService(AccountManager.class);
385 mPackageManager = context.getPackageManager();
386 mAccountsCache = new SparseArray<>();
387 mProvidersPerUserCache = new SparseArray<>();
388 }
389
390 // An account is valid if an installed authenticator has previously created that account
391 // on the device
392 boolean isAccountValid(Account account, int userId) {
393 Account[] accountsForUser = mAccountsCache.get(userId);
394 if (accountsForUser == null) {
395 accountsForUser = mAccountManager.getAccountsAsUser(userId);
396 mAccountsCache.put(userId, accountsForUser);
397 }
398 return ArrayUtils.contains(accountsForUser, account);
399 }
400
401 // An authority is only valid if it has a content provider installed on the system
402 boolean isAuthorityValid(String authority, int userId) {
403 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
404 if (authorityMap == null) {
405 authorityMap = new ArrayMap<>();
406 mProvidersPerUserCache.put(userId, authorityMap);
407 }
408 if (!authorityMap.containsKey(authority)) {
409 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
410 PackageManager.MATCH_DIRECT_BOOT_AWARE
411 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
412 }
413 return authorityMap.get(authority);
414 }
415 }
416
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 // Primary list of all syncable authorities. Also our global lock.
418 private final SparseArray<AuthorityInfo> mAuthorities =
419 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700420
Amith Yamasani04e0d262012-02-14 11:50:53 -0800421 private final HashMap<AccountAndUser, AccountInfo> mAccounts
422 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
425 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 private final SparseArray<SyncStatusInfo> mSyncStatus =
428 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700429
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 private final ArrayList<SyncHistoryItem> mSyncHistory =
431 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
434 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700435
Matthew Williams8ef22042013-07-26 12:56:39 -0700436 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700437 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
438 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700439
Fred Quintana77c560f2010-03-29 22:20:26 -0700440 private int mNextAuthorityId = 0;
441
Dianne Hackborn231cc602009-04-27 17:10:36 -0700442 // We keep 4 weeks of stats.
443 private final DayStats[] mDayStats = new DayStats[7*4];
444 private final Calendar mCal;
445 private int mYear;
446 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700447
Dianne Hackborn231cc602009-04-27 17:10:36 -0700448 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800449
Dianne Hackborn231cc602009-04-27 17:10:36 -0700450 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700451
Ashish Sharma69d95de2012-04-11 17:27:24 -0700452 private int mSyncRandomOffset;
453
Dianne Hackborn231cc602009-04-27 17:10:36 -0700454 /**
455 * This file contains the core engine state: all accounts and the
456 * settings for them. It must never be lost, and should be changed
457 * infrequently, so it is stored as an XML file.
458 */
459 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 /**
462 * This file contains the current sync status. We would like to retain
463 * it across boots, but its loss is not the end of the world, so we store
464 * this information as binary data.
465 */
466 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700467
Dianne Hackborn231cc602009-04-27 17:10:36 -0700468 /**
469 * This file contains sync statistics. This is purely debugging information
470 * so is written infrequently and can be thrown away at any time.
471 */
472 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700473
Dianne Hackborn231cc602009-04-27 17:10:36 -0700474 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800475 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800476 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800477
478 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000479 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700480
Svet Ganov65712b02016-09-01 10:24:11 -0700481 private boolean mGrantSyncAdaptersAccountAccess;
482
Makoto Onuki6963bea72017-12-12 10:42:39 -0800483 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700484 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800485
486 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
487 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800488 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700490 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700491
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700493
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800494 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000495 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800496
Dianne Hackborn231cc602009-04-27 17:10:36 -0700497 File systemDir = new File(dataDir, "system");
498 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800499 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700500
501 maybeDeleteLegacyPendingInfoLocked(syncDir);
502
Dianne Hackborne17b4452018-01-10 13:15:40 -0800503 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
504 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
505 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700506
Dianne Hackborn231cc602009-04-27 17:10:36 -0700507 readAccountInfoLocked();
508 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700509 readStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700510
511 if (mLogger.enabled()) {
512 final int size = mAuthorities.size();
513 mLogger.log("Loaded ", size, " items");
514 for (int i = 0; i < size; i++) {
515 mLogger.log(mAuthorities.valueAt(i));
516 }
517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518 }
519
520 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800521 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800522 }
523
Makoto Onuki6963bea72017-12-12 10:42:39 -0800524 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800526 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800527 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700528 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800529 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
531
532 public static SyncStorageEngine getSingleton() {
533 if (sSyncStorageEngine == null) {
534 throw new IllegalStateException("not initialized");
535 }
536 return sSyncStorageEngine;
537 }
538
Amith Yamasani04e0d262012-02-14 11:50:53 -0800539 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
540 if (mSyncRequestListener == null) {
541 mSyncRequestListener = listener;
542 }
543 }
544
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000545 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
546 if (mAuthorityRemovedListener == null) {
547 mAuthorityRemovedListener = listener;
548 }
549 }
550
551 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
552 if (mPeriodicSyncAddedListener == null) {
553 mPeriodicSyncAddedListener = listener;
554 }
555 }
556
Makoto Onuki6963bea72017-12-12 10:42:39 -0800557 private class MyHandler extends Handler {
558 public MyHandler(Looper looper) {
559 super(looper);
560 }
561
562 @Override
563 public void handleMessage(Message msg) {
564 if (msg.what == MSG_WRITE_STATUS) {
565 synchronized (mAuthorities) {
566 writeStatusLocked();
567 }
568 } else if (msg.what == MSG_WRITE_STATISTICS) {
569 synchronized (mAuthorities) {
570 writeStatisticsLocked();
571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
573 }
574 }
Costin Manolache360e4542009-09-04 13:36:04 -0700575
Ashish Sharma69d95de2012-04-11 17:27:24 -0700576 public int getSyncRandomOffset() {
577 return mSyncRandomOffset;
578 }
579
Dianne Hackborn231cc602009-04-27 17:10:36 -0700580 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
581 synchronized (mAuthorities) {
582 mChangeListeners.register(callback, mask);
583 }
584 }
Costin Manolache360e4542009-09-04 13:36:04 -0700585
Dianne Hackborn231cc602009-04-27 17:10:36 -0700586 public void removeStatusChangeListener(ISyncStatusObserver callback) {
587 synchronized (mAuthorities) {
588 mChangeListeners.unregister(callback);
589 }
590 }
Costin Manolache360e4542009-09-04 13:36:04 -0700591
Matthew Williamsfa774182013-06-18 15:44:11 -0700592 /**
593 * Figure out a reasonable flex time for cases where none is provided (old api calls).
594 * @param syncTimeSeconds requested sync time from now.
595 * @return amount of seconds before syncTimeSeconds that the sync can occur.
596 * I.e.
597 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700598 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700599 */
600 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
601 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
602 // Small enough sync request time that we don't add flex time - developer probably
603 // wants to wait for an operation to occur before syncing so we honour the
604 // request time.
605 return 0L;
606 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
607 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
608 } else {
609 // Large enough sync request time that we cap the flex time.
610 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
611 }
612 }
613
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000614 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700615 ArrayList<ISyncStatusObserver> reports = null;
616 synchronized (mAuthorities) {
617 int i = mChangeListeners.beginBroadcast();
618 while (i > 0) {
619 i--;
620 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
621 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 continue;
623 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700624 if (reports == null) {
625 reports = new ArrayList<ISyncStatusObserver>(i);
626 }
627 reports.add(mChangeListeners.getBroadcastItem(i));
628 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700629 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700630 }
Costin Manolache360e4542009-09-04 13:36:04 -0700631
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700632 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000633 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700634 }
Costin Manolache360e4542009-09-04 13:36:04 -0700635
Dianne Hackborn231cc602009-04-27 17:10:36 -0700636 if (reports != null) {
637 int i = reports.size();
638 while (i > 0) {
639 i--;
640 try {
641 reports.get(i).onStatusChanged(which);
642 } catch (RemoteException e) {
643 // The remote callback list will take care of this for us.
644 }
645 }
646 }
647 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700648
Amith Yamasani04e0d262012-02-14 11:50:53 -0800649 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700650 synchronized (mAuthorities) {
651 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700652 AuthorityInfo authority = getAuthorityLocked(
653 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700654 "getSyncAutomatically");
655 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700656 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700657
Dianne Hackborn231cc602009-04-27 17:10:36 -0700658 int i = mAuthorities.size();
659 while (i > 0) {
660 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700661 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700662 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700663 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700664 return true;
665 }
666 }
667 return false;
668 }
669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670
Amith Yamasani04e0d262012-02-14 11:50:53 -0800671 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukid4764302018-03-30 17:32:57 -0700672 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000674 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800675 + ", user " + userId + " -> " + sync);
676 }
Makoto Onukid4764302018-03-30 17:32:57 -0700677 mLogger.log("Set sync auto account=", account,
678 " user=", userId,
679 " authority=", providerName,
680 " value=", Boolean.toString(sync),
681 " callingUid=", callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700682 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700683 AuthorityInfo authority =
684 getOrCreateAuthorityLocked(
685 new EndPoint(account, providerName, userId),
686 -1 /* ident */,
687 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700688 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000690 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800691 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700692 return;
693 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700694 // If the adapter was syncable but missing its initialization sync, set it to
695 // uninitialized now. This is to give it a chance to run any one-time initialization
696 // logic.
697 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
698 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
699 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700700 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700701 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700703
Fred Quintana77c560f2010-03-29 22:20:26 -0700704 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700705 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800706 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700707 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700708 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700709 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800710 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800711 }
712
Amith Yamasani04e0d262012-02-14 11:50:53 -0800713 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700714 synchronized (mAuthorities) {
715 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700716 AuthorityInfo authority = getAuthorityLocked(
717 new EndPoint(account, providerName, userId),
718 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700719 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700720 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700721 }
722 return authority.syncable;
723 }
724
725 int i = mAuthorities.size();
726 while (i > 0) {
727 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700729 if (authorityInfo.target != null
730 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700731 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700732 }
733 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700734 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700735 }
736 }
737
Makoto Onukid4764302018-03-30 17:32:57 -0700738 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
739 int callingUid) {
740 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
741 callingUid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700742 }
743
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700744 /**
745 * An enabled sync service and a syncable provider's adapter both get resolved to the same
746 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700747 * @param target target to set value for.
748 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 */
Makoto Onukid4764302018-03-30 17:32:57 -0700750 private void setSyncableStateForEndPoint(EndPoint target, int syncable, int callingUid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700751 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700752 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
753 " callingUid=", callingUid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700754 synchronized (mAuthorities) {
755 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700756 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
757 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700758 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700759 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000760 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700761 }
762 if (aInfo.syncable == syncable) {
763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000764 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700765 }
766 return;
767 }
768 aInfo.syncable = syncable;
769 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700770 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700771 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800772 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700773 ContentResolver.SYNC_EXEMPTION_NONE);
Fred Quintana5e787c42009-08-16 23:13:53 -0700774 }
775 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
776 }
777
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700778 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800779 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700780 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
781 if (authority != null) {
782 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800783 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700784 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800785 }
786 }
787
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700788 /**
789 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
790 * the account or provider info be null, which signifies all accounts or providers.
791 */
792 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000794 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800795 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
796 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700797 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800798 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000799 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700800 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000801 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700802 changed = setBackoffLocked(
803 info.account /* may be null */,
804 info.userId,
805 info.provider /* may be null */,
806 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800807 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700808 AuthorityInfo authorityInfo =
809 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
810 if (authorityInfo.backoffTime == nextSyncTime
811 && authorityInfo.backoffDelay == nextDelay) {
812 changed = false;
813 } else {
814 authorityInfo.backoffTime = nextSyncTime;
815 authorityInfo.backoffDelay = nextDelay;
816 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800817 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800818 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800819 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800820 if (changed) {
821 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
822 }
823 }
824
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700825 /**
826 * Either set backoff for a specific authority, or set backoff for all the
827 * accounts on a specific adapter/all adapters.
828 *
829 * @param account account for which to set backoff. Null to specify all accounts.
830 * @param userId id of the user making this request.
831 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700832 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700833 */
834 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000835 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700836 boolean changed = false;
837 for (AccountInfo accountInfo : mAccounts.values()) {
838 if (account != null && !account.equals(accountInfo.accountAndUser.account)
839 && userId != accountInfo.accountAndUser.userId) {
840 continue;
841 }
842 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
843 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700844 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700845 continue;
846 }
847 if (authorityInfo.backoffTime != nextSyncTime
848 || authorityInfo.backoffDelay != nextDelay) {
849 authorityInfo.backoffTime = nextSyncTime;
850 authorityInfo.backoffDelay = nextDelay;
851 changed = true;
852 }
853 }
854 }
855 return changed;
856 }
857
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000858 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800859 boolean changed = false;
860 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000861 // Clear backoff for all sync adapters.
862 for (AccountInfo accountInfo : mAccounts.values()) {
863 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
864 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
865 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
866 if (Log.isLoggable(TAG, Log.VERBOSE)) {
867 Slog.v(TAG, "clearAllBackoffsLocked:"
868 + " authority:" + authorityInfo.target
869 + " account:" + accountInfo.accountAndUser.account.name
870 + " user:" + accountInfo.accountAndUser.userId
871 + " backoffTime was: " + authorityInfo.backoffTime
872 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800873 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000874 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
875 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
876 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800877 }
878 }
879 }
880 }
881
882 if (changed) {
883 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
884 }
885 }
886
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700887 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800888 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700889 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800890 if (authority == null) {
891 return 0;
892 }
893 return authority.delayUntil;
894 }
895 }
896
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700897 public void setDelayUntilTime(EndPoint info, long delayUntil) {
898 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000899 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700900 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800901 }
902 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700903 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
904 if (authority.delayUntil == delayUntil) {
905 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700906 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700907 authority.delayUntil = delayUntil;
908 }
909 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
910 }
911
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700912 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000913 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
914 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700915 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000916 boolean restoreAllPeriodicSyncs() {
917 if (mPeriodicSyncAddedListener == null) {
918 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800919 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000920 synchronized (mAuthorities) {
921 for (int i=0; i<mAuthorities.size(); i++) {
922 AuthorityInfo authority = mAuthorities.valueAt(i);
923 for (PeriodicSync periodicSync: authority.periodicSyncs) {
924 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
925 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
926 }
927 authority.periodicSyncs.clear();
928 }
929 writeAccountInfoLocked();
930 }
931 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800932 }
933
Makoto Onuki75ad2492018-03-28 14:42:42 -0700934 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukid4764302018-03-30 17:32:57 -0700935 @SyncExemption int syncExemptionFlag, int callingUid) {
936 mLogger.log("Set master enabled=", flag, " user=", userId,
937 " caller=" + callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700938 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800939 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700940 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700941 return;
942 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800943 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700944 writeAccountInfoLocked();
945 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700946 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700947 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800948 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700949 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700950 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700951 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800952 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800953 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955
Amith Yamasani04e0d262012-02-14 11:50:53 -0800956 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700957 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800958 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800959 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 }
961 }
Costin Manolache360e4542009-09-04 13:36:04 -0700962
Makoto Onukib47e8942017-09-18 14:03:03 -0700963 public int getAuthorityCount() {
964 synchronized (mAuthorities) {
965 return mAuthorities.size();
966 }
967 }
968
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 public AuthorityInfo getAuthority(int authorityId) {
970 synchronized (mAuthorities) {
971 return mAuthorities.get(authorityId);
972 }
973 }
Costin Manolache360e4542009-09-04 13:36:04 -0700974
Dianne Hackborn231cc602009-04-27 17:10:36 -0700975 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700976 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700977 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700978 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700979 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700980 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700981 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700982 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700983 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700984 return true;
985 }
986 }
987 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700988 return false;
989 }
Costin Manolache360e4542009-09-04 13:36:04 -0700990
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000991 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700992 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000993 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
994 -1 /* desired identifier */,
995 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700996 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000997 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700998 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001000 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001002 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 }
Costin Manolache360e4542009-09-04 13:36:04 -07001004
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 /**
1006 * Called when the set of account has changed, given the new array of
1007 * active accounts.
1008 */
Makoto Onuki3ab77812018-07-09 14:29:33 -07001009 public void removeStaleAccounts(@Nullable Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001010 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001011 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001012 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001013 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001014 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1015 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1016 while (accIt.hasNext()) {
1017 AccountInfo acc = accIt.next();
Makoto Onuki3ab77812018-07-09 14:29:33 -07001018 if ((accounts == null) || (
1019 (acc.accountAndUser.userId == userId)
1020 && !ArrayUtils.contains(accounts, acc.accountAndUser.account))) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001022 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001023 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001024 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 for (AuthorityInfo auth : acc.authorities.values()) {
1026 removing.put(auth.ident, auth);
1027 }
1028 accIt.remove();
1029 }
1030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 // Clean out all data structures.
1033 int i = removing.size();
1034 if (i > 0) {
1035 while (i > 0) {
1036 i--;
1037 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001038 AuthorityInfo auth = removing.valueAt(i);
1039 if (mAuthorityRemovedListener != null) {
1040 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1041 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 mAuthorities.remove(ident);
1043 int j = mSyncStatus.size();
1044 while (j > 0) {
1045 j--;
1046 if (mSyncStatus.keyAt(j) == ident) {
1047 mSyncStatus.remove(mSyncStatus.keyAt(j));
1048 }
1049 }
1050 j = mSyncHistory.size();
1051 while (j > 0) {
1052 j--;
1053 if (mSyncHistory.get(j).authorityId == ident) {
1054 mSyncHistory.remove(j);
1055 }
1056 }
1057 }
1058 writeAccountInfoLocked();
1059 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 writeStatisticsLocked();
1061 }
1062 }
1063 }
1064
1065 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001066 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1067 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 */
Fred Quintana918339a2010-10-05 14:00:39 -07001069 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1070 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001073 Slog.v(TAG, "setActiveSync: account="
1074 + " auth=" + activeSyncContext.mSyncOperation.target
1075 + " src=" + activeSyncContext.mSyncOperation.syncSource
1076 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001077 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001078 final EndPoint info = activeSyncContext.mSyncOperation.target;
1079 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1080 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001081 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001082 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001083 syncInfo = new SyncInfo(
1084 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001085 authorityInfo.target.account,
1086 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001087 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001088 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001089 }
Fred Quintana918339a2010-10-05 14:00:39 -07001090 reportActiveChange();
1091 return syncInfo;
1092 }
1093
1094 /**
1095 * Called to indicate that a previously active sync is no longer active.
1096 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001097 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001098 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001100 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001101 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001102 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001103 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001104 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001105 }
1106
1107 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 }
1109
1110 /**
1111 * To allow others to send active change reports, to poke clients.
1112 */
1113 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001114 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 }
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001118 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001120 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 long id;
1122 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001124 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001125 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001126 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 if (authority == null) {
1128 return -1;
1129 }
1130 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001131 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 item.authorityId = authority.ident;
1133 item.historyId = mNextHistoryId++;
1134 if (mNextHistoryId < 0) mNextHistoryId = 0;
1135 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001136 item.source = op.syncSource;
1137 item.reason = op.reason;
1138 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001140 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 mSyncHistory.add(0, item);
1142 while (mSyncHistory.size() > MAX_HISTORY) {
1143 mSyncHistory.remove(mSyncHistory.size()-1);
1144 }
1145 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001146 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 }
Costin Manolache360e4542009-09-04 13:36:04 -07001148
Fred Quintanaac9385e2009-06-22 18:00:59 -07001149 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
1152
Fred Quintana77c560f2010-03-29 22:20:26 -07001153 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001154 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001155 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001156 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001157 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001158 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001159 SyncHistoryItem item = null;
1160 int i = mSyncHistory.size();
1161 while (i > 0) {
1162 i--;
1163 item = mSyncHistory.get(i);
1164 if (item.historyId == historyId) {
1165 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001167 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 }
Costin Manolache360e4542009-09-04 13:36:04 -07001169
Dianne Hackborn231cc602009-04-27 17:10:36 -07001170 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001171 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001172 return;
1173 }
Costin Manolache360e4542009-09-04 13:36:04 -07001174
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 item.elapsedTime = elapsedTime;
1176 item.event = EVENT_STOP;
1177 item.mesg = resultMessage;
1178 item.downstreamActivity = downstreamActivity;
1179 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001180
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001182
Makoto Onuki94986212018-04-11 16:24:46 -07001183 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1184
1185 status.totalStats.numSyncs++;
1186 status.todayStats.numSyncs++;
1187 status.totalStats.totalElapsedTime += elapsedTime;
1188 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001189 switch (item.source) {
1190 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001191 status.totalStats.numSourceLocal++;
1192 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001193 break;
1194 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001195 status.totalStats.numSourcePoll++;
1196 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 break;
1198 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001199 status.totalStats.numSourceUser++;
1200 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001201 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001202 case SOURCE_OTHER:
1203 status.totalStats.numSourceOther++;
1204 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001205 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001206 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001207 status.totalStats.numSourcePeriodic++;
1208 status.todayStats.numSourcePeriodic++;
1209 break;
1210 case SOURCE_FEED:
1211 status.totalStats.numSourceFeed++;
1212 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001213 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 }
Costin Manolache360e4542009-09-04 13:36:04 -07001215
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001217 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 if (mDayStats[0] == null) {
1219 mDayStats[0] = new DayStats(day);
1220 } else if (day != mDayStats[0].day) {
1221 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1222 mDayStats[0] = new DayStats(day);
1223 writeStatisticsNow = true;
1224 } else if (mDayStats[0] == null) {
1225 }
1226 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001227
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 final long lastSyncTime = (item.eventTime + elapsedTime);
1229 boolean writeStatusNow = false;
1230 if (MESG_SUCCESS.equals(resultMessage)) {
1231 // - if successful, update the successful columns
1232 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1233 writeStatusNow = true;
1234 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001235 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001236 ds.successCount++;
1237 ds.successTime += elapsedTime;
1238 } else if (!MESG_CANCELED.equals(resultMessage)) {
1239 if (status.lastFailureTime == 0) {
1240 writeStatusNow = true;
1241 }
Makoto Onuki94986212018-04-11 16:24:46 -07001242 status.totalStats.numFailures++;
1243 status.todayStats.numFailures++;
1244
Makoto Onukif74cf942018-04-16 17:04:58 -07001245 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1246
Dianne Hackborn231cc602009-04-27 17:10:36 -07001247 ds.failureCount++;
1248 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001249 } else {
1250 // Cancel
1251 status.totalStats.numCancels++;
1252 status.todayStats.numCancels++;
1253 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001254 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001255 final StringBuilder event = new StringBuilder();
1256 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1257 + " Elapsed=");
1258 SyncManager.formatDurationHMS(event, elapsedTime);
1259 event.append(" Reason=");
1260 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001261 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1262 event.append(" Exemption=");
1263 switch (item.syncExemptionFlag) {
1264 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1265 event.append("fg");
1266 break;
1267 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1268 event.append("top");
1269 break;
1270 default:
1271 event.append(item.syncExemptionFlag);
1272 break;
1273 }
1274 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001275 event.append(" Extras=");
1276 SyncOperation.extrasToStringBuilder(item.extras, event);
1277
1278 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001279
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 if (writeStatusNow) {
1281 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001282 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1283 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 WRITE_STATUS_DELAY);
1285 }
1286 if (writeStatisticsNow) {
1287 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001288 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1289 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001290 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001291 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001292 }
Costin Manolache360e4542009-09-04 13:36:04 -07001293
Fred Quintanaac9385e2009-06-22 18:00:59 -07001294 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001295 }
1296
1297 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001298 * Return a list of the currently active syncs. Note that the returned
1299 * items are the real, live active sync objects, so be careful what you do
1300 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001301 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001302 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001303 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001304 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 }
1306 }
Costin Manolache360e4542009-09-04 13:36:04 -07001307
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001309 * @param userId Id of user to return current sync info.
1310 * @param canAccessAccounts Determines whether to redact Account information from the result.
1311 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001312 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001313 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001314 synchronized (mAuthorities) {
1315 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1316 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1317 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001318 SyncInfo copy;
1319 if (!canAccessAccounts) {
1320 copy = SyncInfo.createAccountRedacted(
1321 sync.authorityId, sync.authority, sync.startTime);
1322 } else {
1323 copy = new SyncInfo(sync);
1324 }
1325 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001326 }
1327 return syncsCopy;
1328 }
1329 }
1330
1331 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1332 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1333 if (syncs == null) {
1334 syncs = new ArrayList<SyncInfo>();
1335 mCurrentSyncs.put(userId, syncs);
1336 }
1337 return syncs;
1338 }
1339
1340 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001341 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001342 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001343 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001344 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001345 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001346 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001347 true /* write to storage if this results in a change */);
1348 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1349 }
1350 }
1351
1352 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001353 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001354 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001355 * @param info the endpoint target we are querying status info for.
1356 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001358 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001359 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001360 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001361 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001362 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001364 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001365 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001366 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001367 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001368 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001369 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001370 }
1371 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001372 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 }
1374 }
Costin Manolache360e4542009-09-04 13:36:04 -07001375
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001376 /** Return true if the pending status is true of any matching authorities. */
1377 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 synchronized (mAuthorities) {
1379 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001380 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001381 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001382 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1383 if (ainfo == null) {
1384 continue;
1385 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001386 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 continue;
1388 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001389 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001390 return true;
1391 }
1392 }
1393 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
1395 }
1396
1397 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 * Return an array of the current sync status for all authorities. Note
1399 * that the objects inside the array are the real, live status objects,
1400 * so be careful what you do with them.
1401 */
1402 public ArrayList<SyncHistoryItem> getSyncHistory() {
1403 synchronized (mAuthorities) {
1404 final int N = mSyncHistory.size();
1405 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1406 for (int i=0; i<N; i++) {
1407 items.add(mSyncHistory.get(i));
1408 }
1409 return items;
1410 }
1411 }
Costin Manolache360e4542009-09-04 13:36:04 -07001412
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 /**
1414 * Return an array of the current per-day statistics. Note
1415 * that the objects inside the array are the real, live status objects,
1416 * so be careful what you do with them.
1417 */
1418 public DayStats[] getDayStatistics() {
1419 synchronized (mAuthorities) {
1420 DayStats[] ds = new DayStats[mDayStats.length];
1421 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1422 return ds;
1423 }
1424 }
Costin Manolache360e4542009-09-04 13:36:04 -07001425
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001426 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1427 AuthorityInfo authorityInfo) {
1428 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1429 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1430 }
1431
Dianne Hackborn55280a92009-05-07 15:53:46 -07001432 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001433 mCal.setTimeInMillis(System.currentTimeMillis());
1434 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1435 if (mYear != mCal.get(Calendar.YEAR)) {
1436 mYear = mCal.get(Calendar.YEAR);
1437 mCal.clear();
1438 mCal.set(Calendar.YEAR, mYear);
1439 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1440 }
1441 return dayOfYear + mYearInDays;
1442 }
Costin Manolache360e4542009-09-04 13:36:04 -07001443
Dianne Hackborn231cc602009-04-27 17:10:36 -07001444 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001445 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001446 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001447 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001448 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001449 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001450 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001451 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001452 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1453 AccountInfo accountInfo = mAccounts.get(au);
1454 if (accountInfo == null) {
1455 if (tag != null) {
1456 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1457 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001458 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001459 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001460 return null;
1461 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001462 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1463 if (authority == null) {
1464 if (tag != null) {
1465 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1466 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1467 }
1468 }
1469 return null;
1470 }
1471 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001472 }
Costin Manolache360e4542009-09-04 13:36:04 -07001473
Matthew Williamsfa774182013-06-18 15:44:11 -07001474 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001475 * @param info info identifying target.
1476 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001477 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001478 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001479 * exists.
1480 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001481 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1482 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001483 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1484 AccountInfo account = mAccounts.get(au);
1485 if (account == null) {
1486 account = new AccountInfo(au);
1487 mAccounts.put(au, account);
1488 }
1489 authority = account.authorities.get(info.provider);
1490 if (authority == null) {
1491 authority = createAuthorityLocked(info, ident, doWrite);
1492 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001493 }
1494 return authority;
1495 }
1496
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001497 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1498 AuthorityInfo authority;
1499 if (ident < 0) {
1500 ident = mNextAuthorityId;
1501 mNextAuthorityId++;
1502 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001503 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001504 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001505 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001506 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001507 authority = new AuthorityInfo(info, ident);
1508 mAuthorities.put(ident, authority);
1509 if (doWrite) {
1510 writeAccountInfoLocked();
1511 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001512 return authority;
1513 }
Costin Manolache360e4542009-09-04 13:36:04 -07001514
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001515 public void removeAuthority(EndPoint info) {
1516 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001517 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001518 }
1519 }
1520
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001521
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001522 /**
1523 * Remove an authority associated with a provider. Needs to be a standalone function for
1524 * backward compatibility.
1525 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001526 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001527 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001528 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001529 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001530 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1531 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001532 if (mAuthorityRemovedListener != null) {
1533 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1534 }
Fred Quintanafb084402010-03-23 17:57:03 -07001535 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001536 if (doWrite) {
1537 writeAccountInfoLocked();
1538 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001539 }
1540 }
1541 }
1542
Dianne Hackborn231cc602009-04-27 17:10:36 -07001543 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1544 SyncStatusInfo status = mSyncStatus.get(authorityId);
1545 if (status == null) {
1546 status = new SyncStatusInfo(authorityId);
1547 mSyncStatus.put(authorityId, status);
1548 }
1549 return status;
1550 }
Costin Manolache360e4542009-09-04 13:36:04 -07001551
Dianne Hackborn55280a92009-05-07 15:53:46 -07001552 public void writeAllState() {
1553 synchronized (mAuthorities) {
1554 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001555 writeStatusLocked();
1556 writeStatisticsLocked();
1557 }
1558 }
Costin Manolache360e4542009-09-04 13:36:04 -07001559
Svet Ganov65712b02016-09-01 10:24:11 -07001560 public boolean shouldGrantSyncAdaptersAccountAccess() {
1561 return mGrantSyncAdaptersAccountAccess;
1562 }
1563
Dianne Hackborn231cc602009-04-27 17:10:36 -07001564 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001565 * public for testing
1566 */
1567 public void clearAndReadState() {
1568 synchronized (mAuthorities) {
1569 mAuthorities.clear();
1570 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001571 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001572 mSyncStatus.clear();
1573 mSyncHistory.clear();
1574
1575 readAccountInfoLocked();
1576 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001577 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001578 writeAccountInfoLocked();
1579 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001580 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001581 }
1582 }
1583
1584 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001585 * Read all account information back in to the initial engine state.
1586 */
1587 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001588 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001589 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001590 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001591 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001592 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001593 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001594 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001595 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001596 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001597 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001598 while (eventType != XmlPullParser.START_TAG &&
1599 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001600 eventType = parser.next();
1601 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001602 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001603 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001604 return;
1605 }
1606
Dianne Hackborn231cc602009-04-27 17:10:36 -07001607 String tagName = parser.getName();
1608 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001609 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001610 String versionString = parser.getAttributeValue(null, "version");
1611 int version;
1612 try {
1613 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1614 } catch (NumberFormatException e) {
1615 version = 0;
1616 }
Svet Ganov65712b02016-09-01 10:24:11 -07001617
1618 if (version < 3) {
1619 mGrantSyncAdaptersAccountAccess = true;
1620 }
1621
Amith Yamasani04e0d262012-02-14 11:50:53 -08001622 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001623 try {
1624 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1625 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1626 } catch (NumberFormatException e) {
1627 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001628 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001629 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1630 try {
1631 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1632 } catch (NumberFormatException e) {
1633 mSyncRandomOffset = 0;
1634 }
1635 if (mSyncRandomOffset == 0) {
1636 Random random = new Random(System.currentTimeMillis());
1637 mSyncRandomOffset = random.nextInt(86400);
1638 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001639 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001640 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001641 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001642 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001643 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001644 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001645 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001646 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 if (parser.getDepth() == 2) {
1648 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001649 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001650 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001651 if (authority != null) {
1652 if (authority.ident > highestAuthorityId) {
1653 highestAuthorityId = authority.ident;
1654 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001655 } else {
1656 EventLog.writeEvent(0x534e4554, "26513719", -1,
1657 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001658 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001659 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1660 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001661 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001662 } else if (parser.getDepth() == 3) {
1663 if ("periodicSync".equals(tagName) && authority != null) {
1664 periodicSync = parsePeriodicSync(parser, authority);
1665 }
1666 } else if (parser.getDepth() == 4 && periodicSync != null) {
1667 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001668 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001669 }
1670 }
1671 }
1672 eventType = parser.next();
1673 } while (eventType != XmlPullParser.END_DOCUMENT);
1674 }
1675 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001676 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001677 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001678 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001679 if (fis == null) Slog.i(TAG, "No initial accounts");
1680 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001681 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001682 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001683 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001684 if (fis != null) {
1685 try {
1686 fis.close();
1687 } catch (java.io.IOException e1) {
1688 }
1689 }
1690 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001691
Fred Quintana77c560f2010-03-29 22:20:26 -07001692 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001693 }
Costin Manolache360e4542009-09-04 13:36:04 -07001694
Fred Quintanafb084402010-03-23 17:57:03 -07001695 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001696 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1697 * pending.xml was used starting in KLP.
1698 * @param syncDir directory where the sync files are located.
1699 */
1700 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1701 File file = new File(syncDir, "pending.bin");
1702 if (!file.exists()) {
1703 return;
1704 } else {
1705 file.delete();
1706 }
1707 }
1708
1709 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001710 * some authority names have changed. copy over their settings and delete the old ones
1711 * @return true if a change was made
1712 */
1713 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1714 boolean writeNeeded = false;
1715
1716 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1717 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001718 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001719 AuthorityInfo authority = mAuthorities.valueAt(i);
1720 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001721 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001722 if (newAuthorityName == null) {
1723 continue;
1724 }
1725
1726 // remember this authority so we can remove it later. we can't remove it
1727 // now without messing up this loop iteration
1728 authoritiesToRemove.add(authority);
1729
1730 // this authority isn't enabled, no need to copy it to the new authority name since
1731 // the default is "disabled"
1732 if (!authority.enabled) {
1733 continue;
1734 }
1735
1736 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001737 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001738 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001739 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001740 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001741 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001742 continue;
1743 }
1744
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001745 AuthorityInfo newAuthority =
1746 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001747 newAuthority.enabled = true;
1748 writeNeeded = true;
1749 }
1750
1751 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001752 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001753 authorityInfo.target.account,
1754 authorityInfo.target.userId,
1755 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001756 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001757 writeNeeded = true;
1758 }
1759
1760 return writeNeeded;
1761 }
1762
Amith Yamasani04e0d262012-02-14 11:50:53 -08001763 private void parseListenForTickles(XmlPullParser parser) {
1764 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1765 int userId = 0;
1766 try {
1767 userId = Integer.parseInt(user);
1768 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001769 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001770 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001771 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001772 }
1773 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1774 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1775 mMasterSyncAutomatically.put(userId, listen);
1776 }
1777
Suprabh Shukla042a4782017-05-12 15:26:54 -07001778 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1779 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001780 AuthorityInfo authority = null;
1781 int id = -1;
1782 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001783 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001784 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001785 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001786 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001787 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001788 }
1789 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001790 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001791 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001792 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001793 String accountName = parser.getAttributeValue(null, "account");
1794 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001795 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001796 String packageName = parser.getAttributeValue(null, "package");
1797 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001798 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001799 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001800 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001801 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001802 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001803 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001804 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001805 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001806 + " account=" + accountName
1807 + " accountType=" + accountType
1808 + " auth=" + authorityName
1809 + " package=" + packageName
1810 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001811 + " user=" + userId
1812 + " enabled=" + enabled
1813 + " syncable=" + syncable);
1814 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001815 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001816 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001817 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001818 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001819 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001820 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001821 new Account(accountName, accountType),
1822 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001823 if (validator.isAccountValid(info.account, userId)
1824 && validator.isAuthorityValid(authorityName, userId)) {
1825 authority = getOrCreateAuthorityLocked(info, id, false);
1826 // If the version is 0 then we are upgrading from a file format that did not
1827 // know about periodic syncs. In that case don't clear the list since we
1828 // want the default, which is a daily periodic sync.
1829 // Otherwise clear out this default list since we will populate it later
1830 // with
1831 // the periodic sync descriptions that are read from the configuration file.
1832 if (version > 0) {
1833 authority.periodicSyncs.clear();
1834 }
1835 } else {
1836 EventLog.writeEvent(0x534e4554, "35028827", -1,
1837 "account:" + info.account + " provider:" + authorityName + " user:"
1838 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001839 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001840 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001841 }
1842 if (authority != null) {
1843 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001844 try {
1845 authority.syncable = (syncable == null) ?
1846 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1847 } catch (NumberFormatException e) {
1848 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1849 // format.
1850 if ("unknown".equals(syncable)) {
1851 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1852 } else {
1853 authority.syncable = Boolean.parseBoolean(syncable) ?
1854 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1855 }
1856
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001857 }
1858 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001859 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001860 + accountName + " auth=" + authorityName
1861 + " enabled=" + enabled
1862 + " syncable=" + syncable);
1863 }
1864 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001865 return authority;
1866 }
1867
Matthew Williamsfa774182013-06-18 15:44:11 -07001868 /**
1869 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1870 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001871 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001872 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001873 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001874 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001875 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001876 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001877 try {
1878 period = Long.parseLong(periodValue);
1879 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001880 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001881 return null;
1882 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001883 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001884 return null;
1885 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001886 try {
1887 flextime = Long.parseLong(flexValue);
1888 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001889 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001890 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001891 + ", using default: "
1892 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001893 } catch (NullPointerException expected) {
1894 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001895 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1896 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001897 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001898 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001899 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001900 new PeriodicSync(authorityInfo.target.account,
1901 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001902 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001903 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001904 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001905 return periodicSync;
1906 }
1907
Matthew Williamsfa774182013-06-18 15:44:11 -07001908 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001909 String name = parser.getAttributeValue(null, "name");
1910 String type = parser.getAttributeValue(null, "type");
1911 String value1 = parser.getAttributeValue(null, "value1");
1912 String value2 = parser.getAttributeValue(null, "value2");
1913
1914 try {
1915 if ("long".equals(type)) {
1916 extras.putLong(name, Long.parseLong(value1));
1917 } else if ("integer".equals(type)) {
1918 extras.putInt(name, Integer.parseInt(value1));
1919 } else if ("double".equals(type)) {
1920 extras.putDouble(name, Double.parseDouble(value1));
1921 } else if ("float".equals(type)) {
1922 extras.putFloat(name, Float.parseFloat(value1));
1923 } else if ("boolean".equals(type)) {
1924 extras.putBoolean(name, Boolean.parseBoolean(value1));
1925 } else if ("string".equals(type)) {
1926 extras.putString(name, value1);
1927 } else if ("account".equals(type)) {
1928 extras.putParcelable(name, new Account(value1, value2));
1929 }
1930 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001931 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001932 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001933 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001934 }
1935 }
1936
Dianne Hackborn231cc602009-04-27 17:10:36 -07001937 /**
1938 * Write all account information to the account file.
1939 */
1940 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001941 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001942 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001943 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001944 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001945
Dianne Hackborn231cc602009-04-27 17:10:36 -07001946 try {
1947 fos = mAccountInfoFile.startWrite();
1948 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001949 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001950 out.startDocument(null, true);
1951 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001952
Dianne Hackborn231cc602009-04-27 17:10:36 -07001953 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001954 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001955 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001956 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001957
1958 // Write the Sync Automatically flags for each user
1959 final int M = mMasterSyncAutomatically.size();
1960 for (int m = 0; m < M; m++) {
1961 int userId = mMasterSyncAutomatically.keyAt(m);
1962 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1963 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1964 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1965 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1966 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001967 }
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001970 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001971 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001972 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001973 out.startTag(null, "authority");
1974 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001975 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001976 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001977 out.attribute(null, "account", info.account.name);
1978 out.attribute(null, "type", info.account.type);
1979 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001980 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001981 out.endTag(null, "authority");
1982 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001984 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001985 mAccountInfoFile.finishWrite(fos);
1986 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001987 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001988 if (fos != null) {
1989 mAccountInfoFile.failWrite(fos);
1990 }
1991 }
1992 }
Costin Manolache360e4542009-09-04 13:36:04 -07001993
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 public static final int STATUS_FILE_END = 0;
1995 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001996
Dianne Hackborn231cc602009-04-27 17:10:36 -07001997 /**
1998 * Read all sync status back in to the initial engine state.
1999 */
2000 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002001 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002002 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002003 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 try {
2005 byte[] data = mStatusFile.readFully();
2006 Parcel in = Parcel.obtain();
2007 in.unmarshall(data, 0, data.length);
2008 in.setDataPosition(0);
2009 int token;
2010 while ((token=in.readInt()) != STATUS_FILE_END) {
2011 if (token == STATUS_FILE_ITEM) {
2012 SyncStatusInfo status = new SyncStatusInfo(in);
2013 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2014 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002015 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002016 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002017 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 mSyncStatus.put(status.authorityId, status);
2019 }
2020 } else {
2021 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002022 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002023 break;
2024 }
2025 }
2026 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002027 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 }
2029 }
Costin Manolache360e4542009-09-04 13:36:04 -07002030
Dianne Hackborn231cc602009-04-27 17:10:36 -07002031 /**
2032 * Write all sync status to the sync status file.
2033 */
2034 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002035 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002036 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002037 }
Costin Manolache360e4542009-09-04 13:36:04 -07002038
Dianne Hackborn231cc602009-04-27 17:10:36 -07002039 // The file is being written, so we don't need to have a scheduled
2040 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002041 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002042
Dianne Hackborn231cc602009-04-27 17:10:36 -07002043 FileOutputStream fos = null;
2044 try {
2045 fos = mStatusFile.startWrite();
2046 Parcel out = Parcel.obtain();
2047 final int N = mSyncStatus.size();
2048 for (int i=0; i<N; i++) {
2049 SyncStatusInfo status = mSyncStatus.valueAt(i);
2050 out.writeInt(STATUS_FILE_ITEM);
2051 status.writeToParcel(out, 0);
2052 }
2053 out.writeInt(STATUS_FILE_END);
2054 fos.write(out.marshall());
2055 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002056
Dianne Hackborn231cc602009-04-27 17:10:36 -07002057 mStatusFile.finishWrite(fos);
2058 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002059 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002060 if (fos != null) {
2061 mStatusFile.failWrite(fos);
2062 }
2063 }
2064 }
Costin Manolache360e4542009-09-04 13:36:04 -07002065
Makoto Onuki61283ec2018-01-31 17:22:36 -08002066 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002067 @SyncExemption int syncExemptionFlag) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002068 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2069 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002070 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002071 syncExemptionFlag);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002072 } else {
2073 SyncRequest.Builder req =
2074 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002075 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002076 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002077 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002078 ContentResolver.requestSync(req.build());
2079 }
2080 }
2081
Alon Albert57286f92012-10-09 14:21:38 -07002082 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002083 Bundle extras, @SyncExemption int syncExemptionFlag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002084 // If this is happening in the system process, then call the syncrequest listener
2085 // to make a request back to the SyncManager directly.
2086 // If this is probably a test instance, then call back through the ContentResolver
2087 // which will know which userId to apply based on the Binder id.
2088 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2089 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002090 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002091 new EndPoint(account, authority, userId),
Makoto Onuki75ad2492018-03-28 14:42:42 -07002092 reason, extras, syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002093 } else {
2094 ContentResolver.requestSync(account, authority, extras);
2095 }
2096 }
2097
Dianne Hackborn231cc602009-04-27 17:10:36 -07002098 public static final int STATISTICS_FILE_END = 0;
2099 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2100 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002101
Dianne Hackborn231cc602009-04-27 17:10:36 -07002102 /**
2103 * Read all sync statistics back in to the initial engine state.
2104 */
2105 private void readStatisticsLocked() {
2106 try {
2107 byte[] data = mStatisticsFile.readFully();
2108 Parcel in = Parcel.obtain();
2109 in.unmarshall(data, 0, data.length);
2110 in.setDataPosition(0);
2111 int token;
2112 int index = 0;
2113 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2114 if (token == STATISTICS_FILE_ITEM
2115 || token == STATISTICS_FILE_ITEM_OLD) {
2116 int day = in.readInt();
2117 if (token == STATISTICS_FILE_ITEM_OLD) {
2118 day = day - 2009 + 14245; // Magic!
2119 }
2120 DayStats ds = new DayStats(day);
2121 ds.successCount = in.readInt();
2122 ds.successTime = in.readLong();
2123 ds.failureCount = in.readInt();
2124 ds.failureTime = in.readLong();
2125 if (index < mDayStats.length) {
2126 mDayStats[index] = ds;
2127 index++;
2128 }
2129 } else {
2130 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002131 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002132 break;
2133 }
2134 }
2135 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002136 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002137 }
2138 }
Costin Manolache360e4542009-09-04 13:36:04 -07002139
Dianne Hackborn231cc602009-04-27 17:10:36 -07002140 /**
2141 * Write all sync statistics to the sync status file.
2142 */
2143 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002144 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002145 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002146 }
Costin Manolache360e4542009-09-04 13:36:04 -07002147
Dianne Hackborn231cc602009-04-27 17:10:36 -07002148 // The file is being written, so we don't need to have a scheduled
2149 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002150 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002151
Dianne Hackborn231cc602009-04-27 17:10:36 -07002152 FileOutputStream fos = null;
2153 try {
2154 fos = mStatisticsFile.startWrite();
2155 Parcel out = Parcel.obtain();
2156 final int N = mDayStats.length;
2157 for (int i=0; i<N; i++) {
2158 DayStats ds = mDayStats[i];
2159 if (ds == null) {
2160 break;
2161 }
2162 out.writeInt(STATISTICS_FILE_ITEM);
2163 out.writeInt(ds.day);
2164 out.writeInt(ds.successCount);
2165 out.writeLong(ds.successTime);
2166 out.writeInt(ds.failureCount);
2167 out.writeLong(ds.failureTime);
2168 }
2169 out.writeInt(STATISTICS_FILE_END);
2170 fos.write(out.marshall());
2171 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002172
Dianne Hackborn231cc602009-04-27 17:10:36 -07002173 mStatisticsFile.finishWrite(fos);
2174 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002175 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002176 if (fos != null) {
2177 mStatisticsFile.failWrite(fos);
2178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002181
2182 /**
Marvin Paula6533252014-11-24 12:57:48 -08002183 * Let the BackupManager know that account sync settings have changed. This will trigger
2184 * {@link com.android.server.backup.SystemBackupAgent} to run.
2185 */
2186 public void queueBackup() {
2187 BackupManager.dataChanged("android");
2188 }
Makoto Onuki94986212018-04-11 16:24:46 -07002189
2190 public void setClockValid() {
2191 if (!mIsClockValid) {
2192 mIsClockValid = true;
2193 Slog.w(TAG, "Clock is valid now.");
2194 }
2195 }
2196
2197 public boolean isClockValid() {
2198 return mIsClockValid;
2199 }
2200
2201 public void resetTodayStats(boolean force) {
2202 if (force) {
2203 Log.w(TAG, "Force resetting today stats.");
2204 }
2205 synchronized (mAuthorities) {
2206 final int N = mSyncStatus.size();
2207 for (int i = 0; i < N; i++) {
2208 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2209 cur.maybeResetTodayStats(isClockValid(), force);
2210 }
2211 writeStatusLocked();
2212 }
2213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214}