blob: 6b441a0d0f30b84bd0d32a42a3b8ab6b2e21021f [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Makoto Onukidecc5ba2019-01-15 09:34:05 -080019import static com.android.server.content.SyncLogger.logSafe;
20
Fred Quintanad9d2f112009-04-23 13:36:27 -070021import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070022import android.accounts.AccountAndUser;
Suprabh Shukla042a4782017-05-12 15:26:54 -070023import android.accounts.AccountManager;
Makoto Onuki3ab77812018-07-09 14:29:33 -070024import android.annotation.Nullable;
Marvin Paula6533252014-11-24 12:57:48 -080025import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070026import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080027import android.content.ContentResolver;
Makoto Onuki75ad2492018-03-28 14:42:42 -070028import android.content.ContentResolver.SyncExemption;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.Context;
30import android.content.ISyncStatusObserver;
31import android.content.PeriodicSync;
32import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070033import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080034import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070035import android.content.pm.PackageManager;
Dianne Hackborn231cc602009-04-27 17:10:36 -070036import android.os.Bundle;
37import android.os.Environment;
38import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080039import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070040import android.os.Message;
41import android.os.Parcel;
42import android.os.RemoteCallbackList;
43import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070044import android.os.UserHandle;
Makoto Onukid4764302018-03-30 17:32:57 -070045import android.util.ArrayMap;
46import android.util.AtomicFile;
47import android.util.EventLog;
48import android.util.Log;
49import android.util.Pair;
50import android.util.Slog;
51import android.util.SparseArray;
52import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080053
54import com.android.internal.annotations.VisibleForTesting;
55import com.android.internal.util.ArrayUtils;
56import com.android.internal.util.FastXmlSerializer;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
Dianne Hackborn231cc602009-04-27 17:10:36 -070062import java.io.File;
63import java.io.FileInputStream;
64import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010065import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070067import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070069import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080070import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070071import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060072import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073
74/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070075 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070077 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078 * @hide
79 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080080public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070083 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070084
Amith Yamasani04e0d262012-02-14 11:50:53 -080085 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
86 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070087 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080088 private static final String XML_ATTR_ENABLED = "enabled";
89 private static final String XML_ATTR_USER = "user";
90 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
91
Matthew Williamsfa774182013-06-18 15:44:11 -070092 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000093 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080094
Shreyas Basarge8c834c02016-01-07 13:53:16 +000095 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070096 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
97
98 /** Lower bound on sync time from which we assign a default flex time. */
99 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
100
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800101 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700102 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Dianne Hackborn231cc602009-04-27 17:10:36 -0700104 /** Enum value for a sync start event. */
105 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
Dianne Hackborn231cc602009-04-27 17:10:36 -0700107 /** Enum value for a sync stop event. */
108 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Makoto Onuki94986212018-04-11 16:24:46 -0700110 /** Enum value for a sync with other sources. */
111 public static final int SOURCE_OTHER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Dianne Hackborn231cc602009-04-27 17:10:36 -0700113 /** Enum value for a local-initiated sync. */
114 public static final int SOURCE_LOCAL = 1;
Makoto Onuki94986212018-04-11 16:24:46 -0700115
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700116 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700117 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Dianne Hackborn231cc602009-04-27 17:10:36 -0700119 /** Enum value for a user-initiated sync. */
120 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800122 /** Enum value for a periodic sync. */
123 public static final int SOURCE_PERIODIC = 4;
124
Makoto Onuki94986212018-04-11 16:24:46 -0700125 /** Enum a sync with a "feed" extra */
126 public static final int SOURCE_FEED = 5;
127
Fred Quintana307da1a2010-01-21 14:24:20 -0800128 public static final long NOT_IN_BACKOFF_MODE = -1;
129
Makoto Onukif74cf942018-04-16 17:04:58 -0700130 /**
131 * String names for the sync source types.
132 *
133 * KEEP THIS AND {@link SyncStatusInfo#SOURCE_COUNT} IN SYNC.
134 */
135 public static final String[] SOURCES = {
136 "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000137 "LOCAL",
138 "POLL",
139 "USER",
140 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700141 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Dianne Hackborn231cc602009-04-27 17:10:36 -0700143 // The MESG column will contain one of these or one of the Error types.
144 public static final String MESG_SUCCESS = "success";
145 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700147 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700148
Dianne Hackborn231cc602009-04-27 17:10:36 -0700149 private static final int MSG_WRITE_STATUS = 1;
150 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700151
Dianne Hackborn231cc602009-04-27 17:10:36 -0700152 private static final int MSG_WRITE_STATISTICS = 2;
153 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700154
155 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700156
Fred Quintanac2e46912010-03-15 16:10:44 -0700157 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700158 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700159
160 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000161 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700162
Makoto Onuki94986212018-04-11 16:24:46 -0700163 private volatile boolean mIsClockValid;
164
Fred Quintanafb084402010-03-23 17:57:03 -0700165 static {
166 sAuthorityRenames = new HashMap<String, String>();
167 sAuthorityRenames.put("contacts", "com.android.contacts");
168 sAuthorityRenames.put("calendar", "com.android.calendar");
169 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700170
Dianne Hackborn231cc602009-04-27 17:10:36 -0700171 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800172 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700173 final HashMap<String, AuthorityInfo> authorities =
174 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700175
Amith Yamasani04e0d262012-02-14 11:50:53 -0800176 AccountInfo(AccountAndUser accountAndUser) {
177 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700178 }
179 }
Costin Manolache360e4542009-09-04 13:36:04 -0700180
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700181 /** Bare bones representation of a sync target. */
182 public static class EndPoint {
183 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
184 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700185 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800186 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700187 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700188
189 public EndPoint(Account account, String provider, int userId) {
190 this.account = account;
191 this.provider = provider;
192 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700193 }
194
195 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700196 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
197 *
198 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000199 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700201 public boolean matchesSpec(EndPoint spec) {
202 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700203 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700204 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 return false;
206 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000207 boolean accountsMatch;
208 if (spec.account == null) {
209 accountsMatch = true;
210 } else {
211 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700212 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000213 boolean providersMatch;
214 if (spec.provider == null) {
215 providersMatch = true;
216 } else {
217 providersMatch = provider.equals(spec.provider);
218 }
219 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700220 }
221
222 public String toString() {
223 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000224 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700225 .append("/")
226 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700227 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700228 return sb.toString();
229 }
Makoto Onukidecc5ba2019-01-15 09:34:05 -0800230
231 public String toSafeString() {
232 StringBuilder sb = new StringBuilder();
233 sb.append(account == null ? "ALL ACCS" : logSafe(account))
234 .append("/")
235 .append(provider == null ? "ALL PDRS" : provider);
236 sb.append(":u" + userId);
237 return sb.toString();
238 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700239 }
240
241 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700242 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700243
244 /**
245 * The syncable state is undefined.
246 */
247 public static final int UNDEFINED = -2;
248
Matthew Williams53abfdb2015-06-10 20:06:37 -0700249 /**
250 * Default state for a newly installed adapter. An uninitialized adapter will receive an
251 * initialization sync which are governed by a different set of rules to that of regular
252 * syncs.
253 */
254 public static final int NOT_INITIALIZED = -1;
255 /**
256 * The adapter will not receive any syncs. This is behaviourally equivalent to
257 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
258 * while this is generally meant to be controlled by the developer.
259 */
260 public static final int NOT_SYNCABLE = 0;
261 /**
262 * The adapter is initialized and functioning. This is the normal state for an adapter.
263 */
264 public static final int SYNCABLE = 1;
265 /**
266 * The adapter is syncable but still requires an initialization sync. For example an adapter
267 * than has been restored from a previous device will be in this state. Not meant for
268 * external use.
269 */
270 public static final int SYNCABLE_NOT_INITIALIZED = 2;
271
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700272 /**
273 * The adapter is syncable but does not have access to the synced account and needs a
274 * user access approval.
275 */
276 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
277
Matthew Williams8ef22042013-07-26 12:56:39 -0700278 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700279 final int ident;
280 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700281 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700282 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800283 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700284 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800285 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700286 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800287 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700288
Matthew Williamsfa774182013-06-18 15:44:11 -0700289 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700290
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700291 /**
292 * Copy constructor for making deep-ish copies. Only the bundles stored
293 * in periodic syncs can make unexpected changes.
294 *
295 * @param toCopy AuthorityInfo to be copied.
296 */
297 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700298 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700299 ident = toCopy.ident;
300 enabled = toCopy.enabled;
301 syncable = toCopy.syncable;
302 backoffTime = toCopy.backoffTime;
303 backoffDelay = toCopy.backoffDelay;
304 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700305 periodicSyncs = new ArrayList<PeriodicSync>();
306 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700307 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700308 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700309 }
310 }
311
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700312 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700313 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700314 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000315 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700316 periodicSyncs = new ArrayList<PeriodicSync>();
317 defaultInitialisation();
318 }
319
320 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700321 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800322 backoffTime = -1; // if < 0 then we aren't in backoff mode
323 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000324
325 if (mPeriodicSyncAddedListener != null) {
326 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
327 DEFAULT_POLL_FREQUENCY_SECONDS,
328 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700329 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700330 }
Matthew Williams06485a72013-07-26 12:56:39 -0700331
332 @Override
333 public String toString() {
334 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
335 + backoffTime + ", delay=" + delayUntil;
336 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700337 }
Costin Manolache360e4542009-09-04 13:36:04 -0700338
Dianne Hackborn231cc602009-04-27 17:10:36 -0700339 public static class SyncHistoryItem {
340 int authorityId;
341 int historyId;
342 long eventTime;
343 long elapsedTime;
344 int source;
345 int event;
346 long upstreamActivity;
347 long downstreamActivity;
348 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700349 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700350 Bundle extras;
351 int reason;
Makoto Onukid5f25d22018-05-22 16:02:17 -0700352 int syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700353 }
Costin Manolache360e4542009-09-04 13:36:04 -0700354
Dianne Hackborn231cc602009-04-27 17:10:36 -0700355 public static class DayStats {
356 public final int day;
357 public int successCount;
358 public long successTime;
359 public int failureCount;
360 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700361
Dianne Hackborn231cc602009-04-27 17:10:36 -0700362 public DayStats(int day) {
363 this.day = day;
364 }
365 }
Costin Manolache360e4542009-09-04 13:36:04 -0700366
Amith Yamasani04e0d262012-02-14 11:50:53 -0800367 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700368
369 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800370 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -0700371 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800372 }
373
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000374 interface PeriodicSyncAddedListener {
375 /** Called when a periodic sync is added. */
376 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
377 }
378
379 interface OnAuthorityRemovedListener {
380 /** Called when an authority is removed. */
381 void onAuthorityRemoved(EndPoint removedAuthority);
382 }
383
Suprabh Shukla042a4782017-05-12 15:26:54 -0700384 /**
385 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
386 * account is valid.
387 */
388 private static class AccountAuthorityValidator {
389 final private AccountManager mAccountManager;
390 final private PackageManager mPackageManager;
391 final private SparseArray<Account[]> mAccountsCache;
392 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
393
394 AccountAuthorityValidator(Context context) {
395 mAccountManager = context.getSystemService(AccountManager.class);
396 mPackageManager = context.getPackageManager();
397 mAccountsCache = new SparseArray<>();
398 mProvidersPerUserCache = new SparseArray<>();
399 }
400
401 // An account is valid if an installed authenticator has previously created that account
402 // on the device
403 boolean isAccountValid(Account account, int userId) {
404 Account[] accountsForUser = mAccountsCache.get(userId);
405 if (accountsForUser == null) {
406 accountsForUser = mAccountManager.getAccountsAsUser(userId);
407 mAccountsCache.put(userId, accountsForUser);
408 }
409 return ArrayUtils.contains(accountsForUser, account);
410 }
411
412 // An authority is only valid if it has a content provider installed on the system
413 boolean isAuthorityValid(String authority, int userId) {
414 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
415 if (authorityMap == null) {
416 authorityMap = new ArrayMap<>();
417 mProvidersPerUserCache.put(userId, authorityMap);
418 }
419 if (!authorityMap.containsKey(authority)) {
420 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
421 PackageManager.MATCH_DIRECT_BOOT_AWARE
422 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
423 }
424 return authorityMap.get(authority);
425 }
426 }
427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 // Primary list of all syncable authorities. Also our global lock.
429 private final SparseArray<AuthorityInfo> mAuthorities =
430 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700431
Amith Yamasani04e0d262012-02-14 11:50:53 -0800432 private final HashMap<AccountAndUser, AccountInfo> mAccounts
433 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434
Amith Yamasani04e0d262012-02-14 11:50:53 -0800435 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
436 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 private final SparseArray<SyncStatusInfo> mSyncStatus =
439 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700440
Dianne Hackborn231cc602009-04-27 17:10:36 -0700441 private final ArrayList<SyncHistoryItem> mSyncHistory =
442 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700443
Dianne Hackborn231cc602009-04-27 17:10:36 -0700444 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
445 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700446
Matthew Williams8ef22042013-07-26 12:56:39 -0700447 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700448 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
449 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700450
Fred Quintana77c560f2010-03-29 22:20:26 -0700451 private int mNextAuthorityId = 0;
452
Dianne Hackborn231cc602009-04-27 17:10:36 -0700453 // We keep 4 weeks of stats.
454 private final DayStats[] mDayStats = new DayStats[7*4];
455 private final Calendar mCal;
456 private int mYear;
457 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700458
Dianne Hackborn231cc602009-04-27 17:10:36 -0700459 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800460
Dianne Hackborn231cc602009-04-27 17:10:36 -0700461 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700462
Ashish Sharma69d95de2012-04-11 17:27:24 -0700463 private int mSyncRandomOffset;
464
Dianne Hackborn231cc602009-04-27 17:10:36 -0700465 /**
466 * This file contains the core engine state: all accounts and the
467 * settings for them. It must never be lost, and should be changed
468 * infrequently, so it is stored as an XML file.
469 */
470 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700471
Dianne Hackborn231cc602009-04-27 17:10:36 -0700472 /**
473 * This file contains the current sync status. We would like to retain
474 * it across boots, but its loss is not the end of the world, so we store
475 * this information as binary data.
476 */
477 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700478
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 /**
480 * This file contains sync statistics. This is purely debugging information
481 * so is written infrequently and can be thrown away at any time.
482 */
483 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700484
Dianne Hackborn231cc602009-04-27 17:10:36 -0700485 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800486 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800487 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800488
489 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000490 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700491
Svet Ganov65712b02016-09-01 10:24:11 -0700492 private boolean mGrantSyncAdaptersAccountAccess;
493
Makoto Onuki6963bea72017-12-12 10:42:39 -0800494 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700495 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800496
497 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
498 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800500 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700501 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700502
Dianne Hackborn231cc602009-04-27 17:10:36 -0700503 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700504
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800505 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000506 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800507
Dianne Hackborn231cc602009-04-27 17:10:36 -0700508 File systemDir = new File(dataDir, "system");
509 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800510 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700511
512 maybeDeleteLegacyPendingInfoLocked(syncDir);
513
Dianne Hackborne17b4452018-01-10 13:15:40 -0800514 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
515 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
516 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700517
Dianne Hackborn231cc602009-04-27 17:10:36 -0700518 readAccountInfoLocked();
519 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700520 readStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700521
522 if (mLogger.enabled()) {
523 final int size = mAuthorities.size();
524 mLogger.log("Loaded ", size, " items");
525 for (int i = 0; i < size; i++) {
526 mLogger.log(mAuthorities.valueAt(i));
527 }
528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 }
530
531 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800532 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 }
534
Makoto Onuki6963bea72017-12-12 10:42:39 -0800535 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800537 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700539 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800540 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 }
542
543 public static SyncStorageEngine getSingleton() {
544 if (sSyncStorageEngine == null) {
545 throw new IllegalStateException("not initialized");
546 }
547 return sSyncStorageEngine;
548 }
549
Amith Yamasani04e0d262012-02-14 11:50:53 -0800550 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
551 if (mSyncRequestListener == null) {
552 mSyncRequestListener = listener;
553 }
554 }
555
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000556 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
557 if (mAuthorityRemovedListener == null) {
558 mAuthorityRemovedListener = listener;
559 }
560 }
561
562 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
563 if (mPeriodicSyncAddedListener == null) {
564 mPeriodicSyncAddedListener = listener;
565 }
566 }
567
Makoto Onuki6963bea72017-12-12 10:42:39 -0800568 private class MyHandler extends Handler {
569 public MyHandler(Looper looper) {
570 super(looper);
571 }
572
573 @Override
574 public void handleMessage(Message msg) {
575 if (msg.what == MSG_WRITE_STATUS) {
576 synchronized (mAuthorities) {
577 writeStatusLocked();
578 }
579 } else if (msg.what == MSG_WRITE_STATISTICS) {
580 synchronized (mAuthorities) {
581 writeStatisticsLocked();
582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800583 }
584 }
585 }
Costin Manolache360e4542009-09-04 13:36:04 -0700586
Ashish Sharma69d95de2012-04-11 17:27:24 -0700587 public int getSyncRandomOffset() {
588 return mSyncRandomOffset;
589 }
590
Dianne Hackborn231cc602009-04-27 17:10:36 -0700591 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
592 synchronized (mAuthorities) {
593 mChangeListeners.register(callback, mask);
594 }
595 }
Costin Manolache360e4542009-09-04 13:36:04 -0700596
Dianne Hackborn231cc602009-04-27 17:10:36 -0700597 public void removeStatusChangeListener(ISyncStatusObserver callback) {
598 synchronized (mAuthorities) {
599 mChangeListeners.unregister(callback);
600 }
601 }
Costin Manolache360e4542009-09-04 13:36:04 -0700602
Matthew Williamsfa774182013-06-18 15:44:11 -0700603 /**
604 * Figure out a reasonable flex time for cases where none is provided (old api calls).
605 * @param syncTimeSeconds requested sync time from now.
606 * @return amount of seconds before syncTimeSeconds that the sync can occur.
607 * I.e.
608 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700609 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700610 */
611 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
612 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
613 // Small enough sync request time that we don't add flex time - developer probably
614 // wants to wait for an operation to occur before syncing so we honour the
615 // request time.
616 return 0L;
617 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
618 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
619 } else {
620 // Large enough sync request time that we cap the flex time.
621 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
622 }
623 }
624
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000625 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700626 ArrayList<ISyncStatusObserver> reports = null;
627 synchronized (mAuthorities) {
628 int i = mChangeListeners.beginBroadcast();
629 while (i > 0) {
630 i--;
631 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
632 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 continue;
634 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700635 if (reports == null) {
636 reports = new ArrayList<ISyncStatusObserver>(i);
637 }
638 reports.add(mChangeListeners.getBroadcastItem(i));
639 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700640 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700641 }
Costin Manolache360e4542009-09-04 13:36:04 -0700642
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700643 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000644 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700645 }
Costin Manolache360e4542009-09-04 13:36:04 -0700646
Dianne Hackborn231cc602009-04-27 17:10:36 -0700647 if (reports != null) {
648 int i = reports.size();
649 while (i > 0) {
650 i--;
651 try {
652 reports.get(i).onStatusChanged(which);
653 } catch (RemoteException e) {
654 // The remote callback list will take care of this for us.
655 }
656 }
657 }
658 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700659
Amith Yamasani04e0d262012-02-14 11:50:53 -0800660 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700661 synchronized (mAuthorities) {
662 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700663 AuthorityInfo authority = getAuthorityLocked(
664 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700665 "getSyncAutomatically");
666 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700667 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700668
Dianne Hackborn231cc602009-04-27 17:10:36 -0700669 int i = mAuthorities.size();
670 while (i > 0) {
671 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700672 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700673 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700674 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700675 return true;
676 }
677 }
678 return false;
679 }
680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800681
Amith Yamasani04e0d262012-02-14 11:50:53 -0800682 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukie183a402018-08-29 11:46:41 -0700683 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700684 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000685 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800686 + ", user " + userId + " -> " + sync);
687 }
Makoto Onukid4764302018-03-30 17:32:57 -0700688 mLogger.log("Set sync auto account=", account,
689 " user=", userId,
690 " authority=", providerName,
691 " value=", Boolean.toString(sync),
Makoto Onukie183a402018-08-29 11:46:41 -0700692 " cuid=", callingUid,
693 " cpid=", callingPid
694 );
Dianne Hackborn231cc602009-04-27 17:10:36 -0700695 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700696 AuthorityInfo authority =
697 getOrCreateAuthorityLocked(
698 new EndPoint(account, providerName, userId),
699 -1 /* ident */,
700 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700701 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700702 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000703 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800704 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700705 return;
706 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700707 // If the adapter was syncable but missing its initialization sync, set it to
708 // uninitialized now. This is to give it a chance to run any one-time initialization
709 // logic.
710 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
711 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
712 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700713 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700714 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700716
Fred Quintana77c560f2010-03-29 22:20:26 -0700717 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700718 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800719 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700720 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700721 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700722 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800723 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
725
Amith Yamasani04e0d262012-02-14 11:50:53 -0800726 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700727 synchronized (mAuthorities) {
728 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700729 AuthorityInfo authority = getAuthorityLocked(
730 new EndPoint(account, providerName, userId),
731 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700732 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700733 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700734 }
735 return authority.syncable;
736 }
737
738 int i = mAuthorities.size();
739 while (i > 0) {
740 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700741 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700742 if (authorityInfo.target != null
743 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700744 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700745 }
746 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700747 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700748 }
749 }
750
Makoto Onukid4764302018-03-30 17:32:57 -0700751 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700752 int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700753 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
Makoto Onukie183a402018-08-29 11:46:41 -0700754 callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700755 }
756
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700757 /**
758 * An enabled sync service and a syncable provider's adapter both get resolved to the same
759 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700760 * @param target target to set value for.
761 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700762 */
Makoto Onukie183a402018-08-29 11:46:41 -0700763 private void setSyncableStateForEndPoint(EndPoint target, int syncable,
764 int callingUid, int callingPid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700765 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700766 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
Makoto Onukie183a402018-08-29 11:46:41 -0700767 " cuid=", callingUid,
768 " cpid=", callingPid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700769 synchronized (mAuthorities) {
770 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700771 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
772 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700773 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000775 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700776 }
777 if (aInfo.syncable == syncable) {
778 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000779 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700780 }
781 return;
782 }
783 aInfo.syncable = syncable;
784 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700785 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700786 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800787 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700788 ContentResolver.SYNC_EXEMPTION_NONE, callingUid, callingPid);
Fred Quintana5e787c42009-08-16 23:13:53 -0700789 }
790 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
791 }
792
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700793 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800794 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700795 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
796 if (authority != null) {
797 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800798 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700799 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800800 }
801 }
802
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700803 /**
804 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
805 * the account or provider info be null, which signifies all accounts or providers.
806 */
807 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
808 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000809 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800810 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
811 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700812 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800813 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000814 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700815 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000816 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700817 changed = setBackoffLocked(
818 info.account /* may be null */,
819 info.userId,
820 info.provider /* may be null */,
821 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800822 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700823 AuthorityInfo authorityInfo =
824 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
825 if (authorityInfo.backoffTime == nextSyncTime
826 && authorityInfo.backoffDelay == nextDelay) {
827 changed = false;
828 } else {
829 authorityInfo.backoffTime = nextSyncTime;
830 authorityInfo.backoffDelay = nextDelay;
831 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800832 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800833 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800834 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800835 if (changed) {
836 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
837 }
838 }
839
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700840 /**
841 * Either set backoff for a specific authority, or set backoff for all the
842 * accounts on a specific adapter/all adapters.
843 *
844 * @param account account for which to set backoff. Null to specify all accounts.
845 * @param userId id of the user making this request.
846 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700847 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700848 */
849 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000850 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700851 boolean changed = false;
852 for (AccountInfo accountInfo : mAccounts.values()) {
853 if (account != null && !account.equals(accountInfo.accountAndUser.account)
854 && userId != accountInfo.accountAndUser.userId) {
855 continue;
856 }
857 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
858 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700859 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700860 continue;
861 }
862 if (authorityInfo.backoffTime != nextSyncTime
863 || authorityInfo.backoffDelay != nextDelay) {
864 authorityInfo.backoffTime = nextSyncTime;
865 authorityInfo.backoffDelay = nextDelay;
866 changed = true;
867 }
868 }
869 }
870 return changed;
871 }
872
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000873 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800874 boolean changed = false;
875 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000876 // Clear backoff for all sync adapters.
877 for (AccountInfo accountInfo : mAccounts.values()) {
878 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
879 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
880 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
881 if (Log.isLoggable(TAG, Log.VERBOSE)) {
882 Slog.v(TAG, "clearAllBackoffsLocked:"
883 + " authority:" + authorityInfo.target
884 + " account:" + accountInfo.accountAndUser.account.name
885 + " user:" + accountInfo.accountAndUser.userId
886 + " backoffTime was: " + authorityInfo.backoffTime
887 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800888 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000889 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
890 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
891 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800892 }
893 }
894 }
895 }
896
897 if (changed) {
898 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
899 }
900 }
901
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700902 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800903 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700904 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800905 if (authority == null) {
906 return 0;
907 }
908 return authority.delayUntil;
909 }
910 }
911
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700912 public void setDelayUntilTime(EndPoint info, long delayUntil) {
913 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000914 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700915 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800916 }
917 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700918 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
919 if (authority.delayUntil == delayUntil) {
920 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700921 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700922 authority.delayUntil = delayUntil;
923 }
924 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
925 }
926
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700927 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000928 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
929 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700930 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000931 boolean restoreAllPeriodicSyncs() {
932 if (mPeriodicSyncAddedListener == null) {
933 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800934 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000935 synchronized (mAuthorities) {
936 for (int i=0; i<mAuthorities.size(); i++) {
937 AuthorityInfo authority = mAuthorities.valueAt(i);
938 for (PeriodicSync periodicSync: authority.periodicSyncs) {
939 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
940 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
941 }
942 authority.periodicSyncs.clear();
943 }
944 writeAccountInfoLocked();
945 }
946 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800947 }
948
Makoto Onuki75ad2492018-03-28 14:42:42 -0700949 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700950 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Makoto Onukid4764302018-03-30 17:32:57 -0700951 mLogger.log("Set master enabled=", flag, " user=", userId,
Makoto Onukie183a402018-08-29 11:46:41 -0700952 " cuid=", callingUid,
953 " cpid=", callingPid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800955 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700956 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700957 return;
958 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800959 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 writeAccountInfoLocked();
961 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700962 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700963 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800964 new Bundle(),
Makoto Onukie183a402018-08-29 11:46:41 -0700965 syncExemptionFlag, callingUid, callingPid);
Joe Onorato8294fad2009-07-15 16:08:44 -0700966 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700967 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800968 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800969 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971
Amith Yamasani04e0d262012-02-14 11:50:53 -0800972 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800974 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800975 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700976 }
977 }
Costin Manolache360e4542009-09-04 13:36:04 -0700978
Makoto Onukib47e8942017-09-18 14:03:03 -0700979 public int getAuthorityCount() {
980 synchronized (mAuthorities) {
981 return mAuthorities.size();
982 }
983 }
984
Dianne Hackborn231cc602009-04-27 17:10:36 -0700985 public AuthorityInfo getAuthority(int authorityId) {
986 synchronized (mAuthorities) {
987 return mAuthorities.get(authorityId);
988 }
989 }
Costin Manolache360e4542009-09-04 13:36:04 -0700990
Dianne Hackborn231cc602009-04-27 17:10:36 -0700991 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700992 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700993 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700995 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700996 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700997 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700998 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700999 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 return true;
1001 }
1002 }
1003 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001004 return false;
1005 }
Costin Manolache360e4542009-09-04 13:36:04 -07001006
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001007 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001008 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001009 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
1010 -1 /* desired identifier */,
1011 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001012 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001013 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001014 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001015 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001016 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001018 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001019 }
Costin Manolache360e4542009-09-04 13:36:04 -07001020
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 /**
1022 * Called when the set of account has changed, given the new array of
1023 * active accounts.
1024 */
Makoto Onuki3ab77812018-07-09 14:29:33 -07001025 public void removeStaleAccounts(@Nullable Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001027 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001028 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001029 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1031 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1032 while (accIt.hasNext()) {
1033 AccountInfo acc = accIt.next();
Makoto Onuki3ab77812018-07-09 14:29:33 -07001034 if ((accounts == null) || (
1035 (acc.accountAndUser.userId == userId)
1036 && !ArrayUtils.contains(accounts, acc.accountAndUser.account))) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001037 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001038 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001039 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001040 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 for (AuthorityInfo auth : acc.authorities.values()) {
1042 removing.put(auth.ident, auth);
1043 }
1044 accIt.remove();
1045 }
1046 }
Costin Manolache360e4542009-09-04 13:36:04 -07001047
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 // Clean out all data structures.
1049 int i = removing.size();
1050 if (i > 0) {
1051 while (i > 0) {
1052 i--;
1053 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001054 AuthorityInfo auth = removing.valueAt(i);
1055 if (mAuthorityRemovedListener != null) {
1056 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1057 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 mAuthorities.remove(ident);
1059 int j = mSyncStatus.size();
1060 while (j > 0) {
1061 j--;
1062 if (mSyncStatus.keyAt(j) == ident) {
1063 mSyncStatus.remove(mSyncStatus.keyAt(j));
1064 }
1065 }
1066 j = mSyncHistory.size();
1067 while (j > 0) {
1068 j--;
1069 if (mSyncHistory.get(j).authorityId == ident) {
1070 mSyncHistory.remove(j);
1071 }
1072 }
1073 }
1074 writeAccountInfoLocked();
1075 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 writeStatisticsLocked();
1077 }
1078 }
1079 }
1080
1081 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001082 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1083 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 */
Fred Quintana918339a2010-10-05 14:00:39 -07001085 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1086 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001087 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001088 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001089 Slog.v(TAG, "setActiveSync: account="
1090 + " auth=" + activeSyncContext.mSyncOperation.target
1091 + " src=" + activeSyncContext.mSyncOperation.syncSource
1092 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001093 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001094 final EndPoint info = activeSyncContext.mSyncOperation.target;
1095 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1096 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001097 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001098 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001099 syncInfo = new SyncInfo(
1100 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001101 authorityInfo.target.account,
1102 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001103 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001104 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001105 }
Fred Quintana918339a2010-10-05 14:00:39 -07001106 reportActiveChange();
1107 return syncInfo;
1108 }
1109
1110 /**
1111 * Called to indicate that a previously active sync is no longer active.
1112 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001113 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001114 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001115 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001116 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001117 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001118 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001119 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001120 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001121 }
1122
1123 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001124 }
1125
1126 /**
1127 * To allow others to send active change reports, to poke clients.
1128 */
1129 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001130 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001131 }
Costin Manolache360e4542009-09-04 13:36:04 -07001132
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001134 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001135 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001136 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001137 long id;
1138 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001139 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001140 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001141 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001142 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001143 if (authority == null) {
1144 return -1;
1145 }
1146 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001147 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 item.authorityId = authority.ident;
1149 item.historyId = mNextHistoryId++;
1150 if (mNextHistoryId < 0) mNextHistoryId = 0;
1151 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001152 item.source = op.syncSource;
1153 item.reason = op.reason;
1154 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001155 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001156 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 mSyncHistory.add(0, item);
1158 while (mSyncHistory.size() > MAX_HISTORY) {
1159 mSyncHistory.remove(mSyncHistory.size()-1);
1160 }
1161 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001162 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 }
Costin Manolache360e4542009-09-04 13:36:04 -07001164
Fred Quintanaac9385e2009-06-22 18:00:59 -07001165 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168
Fred Quintana77c560f2010-03-29 22:20:26 -07001169 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001170 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001172 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001173 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001174 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001175 SyncHistoryItem item = null;
1176 int i = mSyncHistory.size();
1177 while (i > 0) {
1178 i--;
1179 item = mSyncHistory.get(i);
1180 if (item.historyId == historyId) {
1181 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001183 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 }
Costin Manolache360e4542009-09-04 13:36:04 -07001185
Dianne Hackborn231cc602009-04-27 17:10:36 -07001186 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001187 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001188 return;
1189 }
Costin Manolache360e4542009-09-04 13:36:04 -07001190
Dianne Hackborn231cc602009-04-27 17:10:36 -07001191 item.elapsedTime = elapsedTime;
1192 item.event = EVENT_STOP;
1193 item.mesg = resultMessage;
1194 item.downstreamActivity = downstreamActivity;
1195 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001196
Dianne Hackborn231cc602009-04-27 17:10:36 -07001197 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001198
Makoto Onuki94986212018-04-11 16:24:46 -07001199 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1200
1201 status.totalStats.numSyncs++;
1202 status.todayStats.numSyncs++;
1203 status.totalStats.totalElapsedTime += elapsedTime;
1204 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001205 switch (item.source) {
1206 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001207 status.totalStats.numSourceLocal++;
1208 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 break;
1210 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001211 status.totalStats.numSourcePoll++;
1212 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001213 break;
1214 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001215 status.totalStats.numSourceUser++;
1216 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001218 case SOURCE_OTHER:
1219 status.totalStats.numSourceOther++;
1220 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001221 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001222 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001223 status.totalStats.numSourcePeriodic++;
1224 status.todayStats.numSourcePeriodic++;
1225 break;
1226 case SOURCE_FEED:
1227 status.totalStats.numSourceFeed++;
1228 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001229 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001230 }
Costin Manolache360e4542009-09-04 13:36:04 -07001231
Dianne Hackborn231cc602009-04-27 17:10:36 -07001232 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001233 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 if (mDayStats[0] == null) {
1235 mDayStats[0] = new DayStats(day);
1236 } else if (day != mDayStats[0].day) {
1237 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1238 mDayStats[0] = new DayStats(day);
1239 writeStatisticsNow = true;
1240 } else if (mDayStats[0] == null) {
1241 }
1242 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001243
Dianne Hackborn231cc602009-04-27 17:10:36 -07001244 final long lastSyncTime = (item.eventTime + elapsedTime);
1245 boolean writeStatusNow = false;
1246 if (MESG_SUCCESS.equals(resultMessage)) {
1247 // - if successful, update the successful columns
1248 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1249 writeStatusNow = true;
1250 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001251 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001252 ds.successCount++;
1253 ds.successTime += elapsedTime;
1254 } else if (!MESG_CANCELED.equals(resultMessage)) {
1255 if (status.lastFailureTime == 0) {
1256 writeStatusNow = true;
1257 }
Makoto Onuki94986212018-04-11 16:24:46 -07001258 status.totalStats.numFailures++;
1259 status.todayStats.numFailures++;
1260
Makoto Onukif74cf942018-04-16 17:04:58 -07001261 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1262
Dianne Hackborn231cc602009-04-27 17:10:36 -07001263 ds.failureCount++;
1264 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001265 } else {
1266 // Cancel
1267 status.totalStats.numCancels++;
1268 status.todayStats.numCancels++;
1269 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001271 final StringBuilder event = new StringBuilder();
1272 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1273 + " Elapsed=");
1274 SyncManager.formatDurationHMS(event, elapsedTime);
1275 event.append(" Reason=");
1276 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001277 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1278 event.append(" Exemption=");
1279 switch (item.syncExemptionFlag) {
1280 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1281 event.append("fg");
1282 break;
1283 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1284 event.append("top");
1285 break;
1286 default:
1287 event.append(item.syncExemptionFlag);
1288 break;
1289 }
1290 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001291 event.append(" Extras=");
1292 SyncOperation.extrasToStringBuilder(item.extras, event);
1293
1294 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001295
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 if (writeStatusNow) {
1297 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001298 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1299 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001300 WRITE_STATUS_DELAY);
1301 }
1302 if (writeStatisticsNow) {
1303 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001304 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1305 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001306 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001307 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001308 }
Costin Manolache360e4542009-09-04 13:36:04 -07001309
Fred Quintanaac9385e2009-06-22 18:00:59 -07001310 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 }
1312
1313 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001314 * Return a list of the currently active syncs. Note that the returned
1315 * items are the real, live active sync objects, so be careful what you do
1316 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001317 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001318 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001319 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001320 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 }
1322 }
Costin Manolache360e4542009-09-04 13:36:04 -07001323
Dianne Hackborn231cc602009-04-27 17:10:36 -07001324 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001325 * @param userId Id of user to return current sync info.
1326 * @param canAccessAccounts Determines whether to redact Account information from the result.
1327 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001328 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001329 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001330 synchronized (mAuthorities) {
1331 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1332 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1333 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001334 SyncInfo copy;
1335 if (!canAccessAccounts) {
1336 copy = SyncInfo.createAccountRedacted(
1337 sync.authorityId, sync.authority, sync.startTime);
1338 } else {
1339 copy = new SyncInfo(sync);
1340 }
1341 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001342 }
1343 return syncsCopy;
1344 }
1345 }
1346
1347 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1348 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1349 if (syncs == null) {
1350 syncs = new ArrayList<SyncInfo>();
1351 mCurrentSyncs.put(userId, syncs);
1352 }
1353 return syncs;
1354 }
1355
1356 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001357 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001358 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001359 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001360 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001361 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001362 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001363 true /* write to storage if this results in a change */);
1364 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1365 }
1366 }
1367
1368 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001369 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001370 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001371 * @param info the endpoint target we are querying status info for.
1372 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001374 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001375 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001376 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001377 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001378 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 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);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001383 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001384 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001385 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001386 }
1387 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001388 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001389 }
1390 }
Costin Manolache360e4542009-09-04 13:36:04 -07001391
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001392 /** Return true if the pending status is true of any matching authorities. */
1393 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001394 synchronized (mAuthorities) {
1395 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001396 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001397 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1399 if (ainfo == null) {
1400 continue;
1401 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001402 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001403 continue;
1404 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001405 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001406 return true;
1407 }
1408 }
1409 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 }
1411 }
1412
1413 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001414 * Return an array of the current sync status for all authorities. 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 ArrayList<SyncHistoryItem> getSyncHistory() {
1419 synchronized (mAuthorities) {
1420 final int N = mSyncHistory.size();
1421 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1422 for (int i=0; i<N; i++) {
1423 items.add(mSyncHistory.get(i));
1424 }
1425 return items;
1426 }
1427 }
Costin Manolache360e4542009-09-04 13:36:04 -07001428
Dianne Hackborn231cc602009-04-27 17:10:36 -07001429 /**
1430 * Return an array of the current per-day statistics. Note
1431 * that the objects inside the array are the real, live status objects,
1432 * so be careful what you do with them.
1433 */
1434 public DayStats[] getDayStatistics() {
1435 synchronized (mAuthorities) {
1436 DayStats[] ds = new DayStats[mDayStats.length];
1437 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1438 return ds;
1439 }
1440 }
Costin Manolache360e4542009-09-04 13:36:04 -07001441
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001442 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1443 AuthorityInfo authorityInfo) {
1444 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1445 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1446 }
1447
Dianne Hackborn55280a92009-05-07 15:53:46 -07001448 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001449 mCal.setTimeInMillis(System.currentTimeMillis());
1450 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1451 if (mYear != mCal.get(Calendar.YEAR)) {
1452 mYear = mCal.get(Calendar.YEAR);
1453 mCal.clear();
1454 mCal.set(Calendar.YEAR, mYear);
1455 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1456 }
1457 return dayOfYear + mYearInDays;
1458 }
Costin Manolache360e4542009-09-04 13:36:04 -07001459
Dianne Hackborn231cc602009-04-27 17:10:36 -07001460 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001461 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001462 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001463 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001464 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001465 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001467 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001468 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1469 AccountInfo accountInfo = mAccounts.get(au);
1470 if (accountInfo == null) {
1471 if (tag != null) {
1472 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1473 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001474 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001475 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001476 return null;
1477 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001478 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1479 if (authority == null) {
1480 if (tag != null) {
1481 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1482 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1483 }
1484 }
1485 return null;
1486 }
1487 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001488 }
Costin Manolache360e4542009-09-04 13:36:04 -07001489
Matthew Williamsfa774182013-06-18 15:44:11 -07001490 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001491 * @param info info identifying target.
1492 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001493 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001494 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001495 * exists.
1496 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001497 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1498 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001499 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1500 AccountInfo account = mAccounts.get(au);
1501 if (account == null) {
1502 account = new AccountInfo(au);
1503 mAccounts.put(au, account);
1504 }
1505 authority = account.authorities.get(info.provider);
1506 if (authority == null) {
1507 authority = createAuthorityLocked(info, ident, doWrite);
1508 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001509 }
1510 return authority;
1511 }
1512
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001513 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1514 AuthorityInfo authority;
1515 if (ident < 0) {
1516 ident = mNextAuthorityId;
1517 mNextAuthorityId++;
1518 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001519 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001520 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001521 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001523 authority = new AuthorityInfo(info, ident);
1524 mAuthorities.put(ident, authority);
1525 if (doWrite) {
1526 writeAccountInfoLocked();
1527 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001528 return authority;
1529 }
Costin Manolache360e4542009-09-04 13:36:04 -07001530
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001531 public void removeAuthority(EndPoint info) {
1532 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001533 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001534 }
1535 }
1536
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001537
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001538 /**
1539 * Remove an authority associated with a provider. Needs to be a standalone function for
1540 * backward compatibility.
1541 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001542 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001543 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001544 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001545 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001546 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1547 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001548 if (mAuthorityRemovedListener != null) {
1549 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1550 }
Fred Quintanafb084402010-03-23 17:57:03 -07001551 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001552 if (doWrite) {
1553 writeAccountInfoLocked();
1554 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001555 }
1556 }
1557 }
1558
Dianne Hackborn231cc602009-04-27 17:10:36 -07001559 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1560 SyncStatusInfo status = mSyncStatus.get(authorityId);
1561 if (status == null) {
1562 status = new SyncStatusInfo(authorityId);
1563 mSyncStatus.put(authorityId, status);
1564 }
1565 return status;
1566 }
Costin Manolache360e4542009-09-04 13:36:04 -07001567
Dianne Hackborn55280a92009-05-07 15:53:46 -07001568 public void writeAllState() {
1569 synchronized (mAuthorities) {
1570 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001571 writeStatusLocked();
1572 writeStatisticsLocked();
1573 }
1574 }
Costin Manolache360e4542009-09-04 13:36:04 -07001575
Svet Ganov65712b02016-09-01 10:24:11 -07001576 public boolean shouldGrantSyncAdaptersAccountAccess() {
1577 return mGrantSyncAdaptersAccountAccess;
1578 }
1579
Dianne Hackborn231cc602009-04-27 17:10:36 -07001580 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001581 * public for testing
1582 */
1583 public void clearAndReadState() {
1584 synchronized (mAuthorities) {
1585 mAuthorities.clear();
1586 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001587 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001588 mSyncStatus.clear();
1589 mSyncHistory.clear();
1590
1591 readAccountInfoLocked();
1592 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001593 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001594 writeAccountInfoLocked();
1595 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001596 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001597 }
1598 }
1599
1600 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001601 * Read all account information back in to the initial engine state.
1602 */
1603 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001604 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001605 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001607 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001608 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001609 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001610 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001611 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001612 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001613 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001614 while (eventType != XmlPullParser.START_TAG &&
1615 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001616 eventType = parser.next();
1617 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001618 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001619 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001620 return;
1621 }
1622
Dianne Hackborn231cc602009-04-27 17:10:36 -07001623 String tagName = parser.getName();
1624 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001625 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001626 String versionString = parser.getAttributeValue(null, "version");
1627 int version;
1628 try {
1629 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1630 } catch (NumberFormatException e) {
1631 version = 0;
1632 }
Svet Ganov65712b02016-09-01 10:24:11 -07001633
1634 if (version < 3) {
1635 mGrantSyncAdaptersAccountAccess = true;
1636 }
1637
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001639 try {
1640 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1641 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1642 } catch (NumberFormatException e) {
1643 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001644 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001645 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1646 try {
1647 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1648 } catch (NumberFormatException e) {
1649 mSyncRandomOffset = 0;
1650 }
1651 if (mSyncRandomOffset == 0) {
1652 Random random = new Random(System.currentTimeMillis());
1653 mSyncRandomOffset = random.nextInt(86400);
1654 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001655 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001656 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001657 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001658 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001659 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001660 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001661 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001662 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001663 if (parser.getDepth() == 2) {
1664 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001665 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001666 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001667 if (authority != null) {
1668 if (authority.ident > highestAuthorityId) {
1669 highestAuthorityId = authority.ident;
1670 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001671 } else {
1672 EventLog.writeEvent(0x534e4554, "26513719", -1,
1673 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001674 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001675 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1676 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001677 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001678 } else if (parser.getDepth() == 3) {
1679 if ("periodicSync".equals(tagName) && authority != null) {
1680 periodicSync = parsePeriodicSync(parser, authority);
1681 }
1682 } else if (parser.getDepth() == 4 && periodicSync != null) {
1683 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001684 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001685 }
1686 }
1687 }
1688 eventType = parser.next();
1689 } while (eventType != XmlPullParser.END_DOCUMENT);
1690 }
1691 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001692 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001693 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001694 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001695 if (fis == null) Slog.i(TAG, "No initial accounts");
1696 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001697 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001698 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001699 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001700 if (fis != null) {
1701 try {
1702 fis.close();
1703 } catch (java.io.IOException e1) {
1704 }
1705 }
1706 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001707
Fred Quintana77c560f2010-03-29 22:20:26 -07001708 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001709 }
Costin Manolache360e4542009-09-04 13:36:04 -07001710
Fred Quintanafb084402010-03-23 17:57:03 -07001711 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001712 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1713 * pending.xml was used starting in KLP.
1714 * @param syncDir directory where the sync files are located.
1715 */
1716 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1717 File file = new File(syncDir, "pending.bin");
1718 if (!file.exists()) {
1719 return;
1720 } else {
1721 file.delete();
1722 }
1723 }
1724
1725 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001726 * some authority names have changed. copy over their settings and delete the old ones
1727 * @return true if a change was made
1728 */
1729 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1730 boolean writeNeeded = false;
1731
1732 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1733 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001734 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001735 AuthorityInfo authority = mAuthorities.valueAt(i);
1736 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001737 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001738 if (newAuthorityName == null) {
1739 continue;
1740 }
1741
1742 // remember this authority so we can remove it later. we can't remove it
1743 // now without messing up this loop iteration
1744 authoritiesToRemove.add(authority);
1745
1746 // this authority isn't enabled, no need to copy it to the new authority name since
1747 // the default is "disabled"
1748 if (!authority.enabled) {
1749 continue;
1750 }
1751
1752 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001753 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001754 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001755 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001756 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001757 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001758 continue;
1759 }
1760
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001761 AuthorityInfo newAuthority =
1762 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001763 newAuthority.enabled = true;
1764 writeNeeded = true;
1765 }
1766
1767 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001768 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001769 authorityInfo.target.account,
1770 authorityInfo.target.userId,
1771 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001772 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001773 writeNeeded = true;
1774 }
1775
1776 return writeNeeded;
1777 }
1778
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 private void parseListenForTickles(XmlPullParser parser) {
1780 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1781 int userId = 0;
1782 try {
1783 userId = Integer.parseInt(user);
1784 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001785 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001787 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001788 }
1789 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1790 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1791 mMasterSyncAutomatically.put(userId, listen);
1792 }
1793
Suprabh Shukla042a4782017-05-12 15:26:54 -07001794 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1795 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001796 AuthorityInfo authority = null;
1797 int id = -1;
1798 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001799 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001800 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001801 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001802 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001803 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001804 }
1805 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001806 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001807 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001808 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001809 String accountName = parser.getAttributeValue(null, "account");
1810 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001811 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001812 String packageName = parser.getAttributeValue(null, "package");
1813 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001815 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001816 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001817 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001818 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001819 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001820 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001821 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001822 + " account=" + accountName
1823 + " accountType=" + accountType
1824 + " auth=" + authorityName
1825 + " package=" + packageName
1826 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001827 + " user=" + userId
1828 + " enabled=" + enabled
1829 + " syncable=" + syncable);
1830 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001831 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001832 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001833 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001834 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001835 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001836 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001837 new Account(accountName, accountType),
1838 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001839 if (validator.isAccountValid(info.account, userId)
1840 && validator.isAuthorityValid(authorityName, userId)) {
1841 authority = getOrCreateAuthorityLocked(info, id, false);
1842 // If the version is 0 then we are upgrading from a file format that did not
1843 // know about periodic syncs. In that case don't clear the list since we
1844 // want the default, which is a daily periodic sync.
1845 // Otherwise clear out this default list since we will populate it later
1846 // with
1847 // the periodic sync descriptions that are read from the configuration file.
1848 if (version > 0) {
1849 authority.periodicSyncs.clear();
1850 }
1851 } else {
1852 EventLog.writeEvent(0x534e4554, "35028827", -1,
1853 "account:" + info.account + " provider:" + authorityName + " user:"
1854 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001855 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001856 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001857 }
1858 if (authority != null) {
1859 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001860 try {
1861 authority.syncable = (syncable == null) ?
1862 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1863 } catch (NumberFormatException e) {
1864 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1865 // format.
1866 if ("unknown".equals(syncable)) {
1867 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1868 } else {
1869 authority.syncable = Boolean.parseBoolean(syncable) ?
1870 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1871 }
1872
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001873 }
1874 } else {
Makoto Onukidecc5ba2019-01-15 09:34:05 -08001875 Slog.w(TAG, "Failure adding authority:"
1876 + " auth=" + authorityName
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001877 + " enabled=" + enabled
1878 + " syncable=" + syncable);
1879 }
1880 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001881 return authority;
1882 }
1883
Matthew Williamsfa774182013-06-18 15:44:11 -07001884 /**
1885 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1886 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001887 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001888 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001889 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001890 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001891 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001892 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001893 try {
1894 period = Long.parseLong(periodValue);
1895 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001896 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001897 return null;
1898 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001899 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001900 return null;
1901 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001902 try {
1903 flextime = Long.parseLong(flexValue);
1904 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001905 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001906 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001907 + ", using default: "
1908 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001909 } catch (NullPointerException expected) {
1910 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001911 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1912 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001913 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001914 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001915 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001916 new PeriodicSync(authorityInfo.target.account,
1917 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001918 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001919 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001920 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001921 return periodicSync;
1922 }
1923
Matthew Williamsfa774182013-06-18 15:44:11 -07001924 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001925 String name = parser.getAttributeValue(null, "name");
1926 String type = parser.getAttributeValue(null, "type");
1927 String value1 = parser.getAttributeValue(null, "value1");
1928 String value2 = parser.getAttributeValue(null, "value2");
1929
1930 try {
1931 if ("long".equals(type)) {
1932 extras.putLong(name, Long.parseLong(value1));
1933 } else if ("integer".equals(type)) {
1934 extras.putInt(name, Integer.parseInt(value1));
1935 } else if ("double".equals(type)) {
1936 extras.putDouble(name, Double.parseDouble(value1));
1937 } else if ("float".equals(type)) {
1938 extras.putFloat(name, Float.parseFloat(value1));
1939 } else if ("boolean".equals(type)) {
1940 extras.putBoolean(name, Boolean.parseBoolean(value1));
1941 } else if ("string".equals(type)) {
1942 extras.putString(name, value1);
1943 } else if ("account".equals(type)) {
1944 extras.putParcelable(name, new Account(value1, value2));
1945 }
1946 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001947 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001948 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001949 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001950 }
1951 }
1952
Dianne Hackborn231cc602009-04-27 17:10:36 -07001953 /**
1954 * Write all account information to the account file.
1955 */
1956 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001957 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001958 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001959 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001961
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 try {
1963 fos = mAccountInfoFile.startWrite();
1964 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001965 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 out.startDocument(null, true);
1967 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001970 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001971 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001972 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001973
1974 // Write the Sync Automatically flags for each user
1975 final int M = mMasterSyncAutomatically.size();
1976 for (int m = 0; m < M; m++) {
1977 int userId = mMasterSyncAutomatically.keyAt(m);
1978 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1979 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1980 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1981 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1982 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 }
Costin Manolache360e4542009-09-04 13:36:04 -07001984
Dianne Hackborn231cc602009-04-27 17:10:36 -07001985 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001986 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001987 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001988 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001989 out.startTag(null, "authority");
1990 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001991 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001992 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001993 out.attribute(null, "account", info.account.name);
1994 out.attribute(null, "type", info.account.type);
1995 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001996 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001997 out.endTag(null, "authority");
1998 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001999 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07002001 mAccountInfoFile.finishWrite(fos);
2002 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002003 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002004 if (fos != null) {
2005 mAccountInfoFile.failWrite(fos);
2006 }
2007 }
2008 }
Costin Manolache360e4542009-09-04 13:36:04 -07002009
Dianne Hackborn231cc602009-04-27 17:10:36 -07002010 public static final int STATUS_FILE_END = 0;
2011 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 /**
2014 * Read all sync status back in to the initial engine state.
2015 */
2016 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002017 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002018 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002019 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002020 try {
2021 byte[] data = mStatusFile.readFully();
2022 Parcel in = Parcel.obtain();
2023 in.unmarshall(data, 0, data.length);
2024 in.setDataPosition(0);
2025 int token;
2026 while ((token=in.readInt()) != STATUS_FILE_END) {
2027 if (token == STATUS_FILE_ITEM) {
2028 SyncStatusInfo status = new SyncStatusInfo(in);
2029 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2030 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002031 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002032 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002033 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002034 mSyncStatus.put(status.authorityId, status);
2035 }
2036 } else {
2037 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002038 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002039 break;
2040 }
2041 }
2042 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002043 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002044 }
2045 }
Costin Manolache360e4542009-09-04 13:36:04 -07002046
Dianne Hackborn231cc602009-04-27 17:10:36 -07002047 /**
2048 * Write all sync status to the sync status file.
2049 */
2050 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002051 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002052 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002053 }
Costin Manolache360e4542009-09-04 13:36:04 -07002054
Dianne Hackborn231cc602009-04-27 17:10:36 -07002055 // The file is being written, so we don't need to have a scheduled
2056 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002057 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002058
Dianne Hackborn231cc602009-04-27 17:10:36 -07002059 FileOutputStream fos = null;
2060 try {
2061 fos = mStatusFile.startWrite();
2062 Parcel out = Parcel.obtain();
2063 final int N = mSyncStatus.size();
2064 for (int i=0; i<N; i++) {
2065 SyncStatusInfo status = mSyncStatus.valueAt(i);
2066 out.writeInt(STATUS_FILE_ITEM);
2067 status.writeToParcel(out, 0);
2068 }
2069 out.writeInt(STATUS_FILE_END);
2070 fos.write(out.marshall());
2071 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002072
Dianne Hackborn231cc602009-04-27 17:10:36 -07002073 mStatusFile.finishWrite(fos);
2074 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002075 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002076 if (fos != null) {
2077 mStatusFile.failWrite(fos);
2078 }
2079 }
2080 }
Costin Manolache360e4542009-09-04 13:36:04 -07002081
Makoto Onuki61283ec2018-01-31 17:22:36 -08002082 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002083 @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002084 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2085 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002086 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onukie183a402018-08-29 11:46:41 -07002087 syncExemptionFlag, callingUid, callingPid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002088 } else {
2089 SyncRequest.Builder req =
2090 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002091 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002092 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002093 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002094 ContentResolver.requestSync(req.build());
2095 }
2096 }
2097
Alon Albert57286f92012-10-09 14:21:38 -07002098 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onukie183a402018-08-29 11:46:41 -07002099 Bundle extras, @SyncExemption int syncExemptionFlag, int callingUid, int callingPid) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002100 // If this is happening in the system process, then call the syncrequest listener
2101 // to make a request back to the SyncManager directly.
2102 // If this is probably a test instance, then call back through the ContentResolver
2103 // which will know which userId to apply based on the Binder id.
2104 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2105 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002106 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002107 new EndPoint(account, authority, userId),
Makoto Onukie183a402018-08-29 11:46:41 -07002108 reason, extras, syncExemptionFlag, callingUid, callingPid);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002109 } else {
2110 ContentResolver.requestSync(account, authority, extras);
2111 }
2112 }
2113
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 public static final int STATISTICS_FILE_END = 0;
2115 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2116 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002117
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 /**
2119 * Read all sync statistics back in to the initial engine state.
2120 */
2121 private void readStatisticsLocked() {
2122 try {
2123 byte[] data = mStatisticsFile.readFully();
2124 Parcel in = Parcel.obtain();
2125 in.unmarshall(data, 0, data.length);
2126 in.setDataPosition(0);
2127 int token;
2128 int index = 0;
2129 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2130 if (token == STATISTICS_FILE_ITEM
2131 || token == STATISTICS_FILE_ITEM_OLD) {
2132 int day = in.readInt();
2133 if (token == STATISTICS_FILE_ITEM_OLD) {
2134 day = day - 2009 + 14245; // Magic!
2135 }
2136 DayStats ds = new DayStats(day);
2137 ds.successCount = in.readInt();
2138 ds.successTime = in.readLong();
2139 ds.failureCount = in.readInt();
2140 ds.failureTime = in.readLong();
2141 if (index < mDayStats.length) {
2142 mDayStats[index] = ds;
2143 index++;
2144 }
2145 } else {
2146 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002147 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002148 break;
2149 }
2150 }
2151 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002152 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002153 }
2154 }
Costin Manolache360e4542009-09-04 13:36:04 -07002155
Dianne Hackborn231cc602009-04-27 17:10:36 -07002156 /**
2157 * Write all sync statistics to the sync status file.
2158 */
2159 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002160 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002161 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002162 }
Costin Manolache360e4542009-09-04 13:36:04 -07002163
Dianne Hackborn231cc602009-04-27 17:10:36 -07002164 // The file is being written, so we don't need to have a scheduled
2165 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002166 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002167
Dianne Hackborn231cc602009-04-27 17:10:36 -07002168 FileOutputStream fos = null;
2169 try {
2170 fos = mStatisticsFile.startWrite();
2171 Parcel out = Parcel.obtain();
2172 final int N = mDayStats.length;
2173 for (int i=0; i<N; i++) {
2174 DayStats ds = mDayStats[i];
2175 if (ds == null) {
2176 break;
2177 }
2178 out.writeInt(STATISTICS_FILE_ITEM);
2179 out.writeInt(ds.day);
2180 out.writeInt(ds.successCount);
2181 out.writeLong(ds.successTime);
2182 out.writeInt(ds.failureCount);
2183 out.writeLong(ds.failureTime);
2184 }
2185 out.writeInt(STATISTICS_FILE_END);
2186 fos.write(out.marshall());
2187 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002188
Dianne Hackborn231cc602009-04-27 17:10:36 -07002189 mStatisticsFile.finishWrite(fos);
2190 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002191 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002192 if (fos != null) {
2193 mStatisticsFile.failWrite(fos);
2194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 }
2196 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002197
2198 /**
Marvin Paula6533252014-11-24 12:57:48 -08002199 * Let the BackupManager know that account sync settings have changed. This will trigger
2200 * {@link com.android.server.backup.SystemBackupAgent} to run.
2201 */
2202 public void queueBackup() {
2203 BackupManager.dataChanged("android");
2204 }
Makoto Onuki94986212018-04-11 16:24:46 -07002205
2206 public void setClockValid() {
2207 if (!mIsClockValid) {
2208 mIsClockValid = true;
2209 Slog.w(TAG, "Clock is valid now.");
2210 }
2211 }
2212
2213 public boolean isClockValid() {
2214 return mIsClockValid;
2215 }
2216
2217 public void resetTodayStats(boolean force) {
2218 if (force) {
2219 Log.w(TAG, "Force resetting today stats.");
2220 }
2221 synchronized (mAuthorities) {
2222 final int N = mSyncStatus.size();
2223 for (int i = 0; i < N; i++) {
2224 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2225 cur.maybeResetTodayStats(isClockValid(), force);
2226 }
2227 writeStatusLocked();
2228 }
2229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230}