blob: 11f07015ef12403b54355bbb699e629683ef033f [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Suprabh Shukla042a4782017-05-12 15:26:54 -070021import android.accounts.AccountManager;
Marvin Paula6533252014-11-24 12:57:48 -080022import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070023import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080024import android.content.ContentResolver;
Makoto Onuki75ad2492018-03-28 14:42:42 -070025import android.content.ContentResolver.SyncExemption;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080026import android.content.Context;
27import android.content.ISyncStatusObserver;
28import android.content.PeriodicSync;
29import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070030import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080031import android.content.SyncStatusInfo;
Suprabh Shukla042a4782017-05-12 15:26:54 -070032import android.content.pm.PackageManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070035import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070037import android.os.Bundle;
38import android.os.Environment;
39import android.os.Handler;
Makoto Onuki6963bea72017-12-12 10:42:39 -080040import android.os.Looper;
Dianne Hackborn231cc602009-04-27 17:10:36 -070041import android.os.Message;
42import android.os.Parcel;
43import android.os.RemoteCallbackList;
44import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070045import android.os.UserHandle;
Makoto Onukid4764302018-03-30 17:32:57 -070046import android.util.ArrayMap;
47import android.util.AtomicFile;
48import android.util.EventLog;
49import android.util.Log;
50import android.util.Pair;
51import android.util.Slog;
52import android.util.SparseArray;
53import android.util.Xml;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080054
55import com.android.internal.annotations.VisibleForTesting;
56import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastXmlSerializer;
58
59import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062
Dianne Hackborn231cc602009-04-27 17:10:36 -070063import java.io.File;
64import java.io.FileInputStream;
65import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010066import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070068import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070070import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080071import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070072import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060073import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074
75/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070076 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070078 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079 * @hide
80 */
Makoto Onuki6963bea72017-12-12 10:42:39 -080081public class SyncStorageEngine {
Amith Yamasani04e0d262012-02-14 11:50:53 -080082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070084 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070085
Amith Yamasani04e0d262012-02-14 11:50:53 -080086 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
87 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070088 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080089 private static final String XML_ATTR_ENABLED = "enabled";
90 private static final String XML_ATTR_USER = "user";
91 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
92
Matthew Williamsfa774182013-06-18 15:44:11 -070093 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000094 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080095
Shreyas Basarge8c834c02016-01-07 13:53:16 +000096 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070097 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
98
99 /** Lower bound on sync time from which we assign a default flex time. */
100 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
101
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800102 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Dianne Hackborn231cc602009-04-27 17:10:36 -0700105 /** Enum value for a sync start event. */
106 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a sync stop event. */
109 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Makoto Onuki94986212018-04-11 16:24:46 -0700111 /** Enum value for a sync with other sources. */
112 public static final int SOURCE_OTHER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Dianne Hackborn231cc602009-04-27 17:10:36 -0700114 /** Enum value for a local-initiated sync. */
115 public static final int SOURCE_LOCAL = 1;
Makoto Onuki94986212018-04-11 16:24:46 -0700116
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700117 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700118 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Dianne Hackborn231cc602009-04-27 17:10:36 -0700120 /** Enum value for a user-initiated sync. */
121 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800123 /** Enum value for a periodic sync. */
124 public static final int SOURCE_PERIODIC = 4;
125
Makoto Onuki94986212018-04-11 16:24:46 -0700126 /** Enum a sync with a "feed" extra */
127 public static final int SOURCE_FEED = 5;
128
Fred Quintana307da1a2010-01-21 14:24:20 -0800129 public static final long NOT_IN_BACKOFF_MODE = -1;
130
Makoto Onukif74cf942018-04-16 17:04:58 -0700131 /**
132 * String names for the sync source types.
133 *
134 * KEEP THIS AND {@link SyncStatusInfo#SOURCE_COUNT} IN SYNC.
135 */
136 public static final String[] SOURCES = {
137 "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000138 "LOCAL",
139 "POLL",
140 "USER",
141 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700142 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Dianne Hackborn231cc602009-04-27 17:10:36 -0700144 // The MESG column will contain one of these or one of the Error types.
145 public static final String MESG_SUCCESS = "success";
146 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700148 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700149
Dianne Hackborn231cc602009-04-27 17:10:36 -0700150 private static final int MSG_WRITE_STATUS = 1;
151 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700152
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 private static final int MSG_WRITE_STATISTICS = 2;
154 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700155
156 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700157
Fred Quintanac2e46912010-03-15 16:10:44 -0700158 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700159 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700160
161 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000162 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700163
Makoto Onuki94986212018-04-11 16:24:46 -0700164 private volatile boolean mIsClockValid;
165
Fred Quintanafb084402010-03-23 17:57:03 -0700166 static {
167 sAuthorityRenames = new HashMap<String, String>();
168 sAuthorityRenames.put("contacts", "com.android.contacts");
169 sAuthorityRenames.put("calendar", "com.android.calendar");
170 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700171
Dianne Hackborn231cc602009-04-27 17:10:36 -0700172 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800173 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700174 final HashMap<String, AuthorityInfo> authorities =
175 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700176
Amith Yamasani04e0d262012-02-14 11:50:53 -0800177 AccountInfo(AccountAndUser accountAndUser) {
178 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700179 }
180 }
Costin Manolache360e4542009-09-04 13:36:04 -0700181
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700182 /** Bare bones representation of a sync target. */
183 public static class EndPoint {
184 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
185 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700186 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800187 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700188 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700189
190 public EndPoint(Account account, String provider, int userId) {
191 this.account = account;
192 this.provider = provider;
193 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700194 }
195
196 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700197 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
198 *
199 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000200 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700201 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700202 public boolean matchesSpec(EndPoint spec) {
203 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700204 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700205 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700206 return false;
207 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000208 boolean accountsMatch;
209 if (spec.account == null) {
210 accountsMatch = true;
211 } else {
212 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700213 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000214 boolean providersMatch;
215 if (spec.provider == null) {
216 providersMatch = true;
217 } else {
218 providersMatch = provider.equals(spec.provider);
219 }
220 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700221 }
222
223 public String toString() {
224 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000225 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700226 .append("/")
227 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700228 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700229 return sb.toString();
230 }
231 }
232
233 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700234 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700235
236 /**
237 * The syncable state is undefined.
238 */
239 public static final int UNDEFINED = -2;
240
Matthew Williams53abfdb2015-06-10 20:06:37 -0700241 /**
242 * Default state for a newly installed adapter. An uninitialized adapter will receive an
243 * initialization sync which are governed by a different set of rules to that of regular
244 * syncs.
245 */
246 public static final int NOT_INITIALIZED = -1;
247 /**
248 * The adapter will not receive any syncs. This is behaviourally equivalent to
249 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
250 * while this is generally meant to be controlled by the developer.
251 */
252 public static final int NOT_SYNCABLE = 0;
253 /**
254 * The adapter is initialized and functioning. This is the normal state for an adapter.
255 */
256 public static final int SYNCABLE = 1;
257 /**
258 * The adapter is syncable but still requires an initialization sync. For example an adapter
259 * than has been restored from a previous device will be in this state. Not meant for
260 * external use.
261 */
262 public static final int SYNCABLE_NOT_INITIALIZED = 2;
263
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700264 /**
265 * The adapter is syncable but does not have access to the synced account and needs a
266 * user access approval.
267 */
268 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
269
Matthew Williams8ef22042013-07-26 12:56:39 -0700270 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700271 final int ident;
272 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700273 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700274 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800275 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700276 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800277 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700278 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800279 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700280
Matthew Williamsfa774182013-06-18 15:44:11 -0700281 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700282
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700283 /**
284 * Copy constructor for making deep-ish copies. Only the bundles stored
285 * in periodic syncs can make unexpected changes.
286 *
287 * @param toCopy AuthorityInfo to be copied.
288 */
289 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700290 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700291 ident = toCopy.ident;
292 enabled = toCopy.enabled;
293 syncable = toCopy.syncable;
294 backoffTime = toCopy.backoffTime;
295 backoffDelay = toCopy.backoffDelay;
296 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700297 periodicSyncs = new ArrayList<PeriodicSync>();
298 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700299 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700300 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700301 }
302 }
303
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700304 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700305 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700306 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000307 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700308 periodicSyncs = new ArrayList<PeriodicSync>();
309 defaultInitialisation();
310 }
311
312 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700313 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800314 backoffTime = -1; // if < 0 then we aren't in backoff mode
315 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000316
317 if (mPeriodicSyncAddedListener != null) {
318 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
319 DEFAULT_POLL_FREQUENCY_SECONDS,
320 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700321 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700322 }
Matthew Williams06485a72013-07-26 12:56:39 -0700323
324 @Override
325 public String toString() {
326 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
327 + backoffTime + ", delay=" + delayUntil;
328 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700329 }
Costin Manolache360e4542009-09-04 13:36:04 -0700330
Dianne Hackborn231cc602009-04-27 17:10:36 -0700331 public static class SyncHistoryItem {
332 int authorityId;
333 int historyId;
334 long eventTime;
335 long elapsedTime;
336 int source;
337 int event;
338 long upstreamActivity;
339 long downstreamActivity;
340 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700341 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700342 Bundle extras;
343 int reason;
Makoto Onukid5f25d22018-05-22 16:02:17 -0700344 int syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700345 }
Costin Manolache360e4542009-09-04 13:36:04 -0700346
Dianne Hackborn231cc602009-04-27 17:10:36 -0700347 public static class DayStats {
348 public final int day;
349 public int successCount;
350 public long successTime;
351 public int failureCount;
352 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 public DayStats(int day) {
355 this.day = day;
356 }
357 }
Costin Manolache360e4542009-09-04 13:36:04 -0700358
Amith Yamasani04e0d262012-02-14 11:50:53 -0800359 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700360
361 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800362 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -0700363 @SyncExemption int syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800364 }
365
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000366 interface PeriodicSyncAddedListener {
367 /** Called when a periodic sync is added. */
368 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
369 }
370
371 interface OnAuthorityRemovedListener {
372 /** Called when an authority is removed. */
373 void onAuthorityRemoved(EndPoint removedAuthority);
374 }
375
Suprabh Shukla042a4782017-05-12 15:26:54 -0700376 /**
377 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
378 * account is valid.
379 */
380 private static class AccountAuthorityValidator {
381 final private AccountManager mAccountManager;
382 final private PackageManager mPackageManager;
383 final private SparseArray<Account[]> mAccountsCache;
384 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
385
386 AccountAuthorityValidator(Context context) {
387 mAccountManager = context.getSystemService(AccountManager.class);
388 mPackageManager = context.getPackageManager();
389 mAccountsCache = new SparseArray<>();
390 mProvidersPerUserCache = new SparseArray<>();
391 }
392
393 // An account is valid if an installed authenticator has previously created that account
394 // on the device
395 boolean isAccountValid(Account account, int userId) {
396 Account[] accountsForUser = mAccountsCache.get(userId);
397 if (accountsForUser == null) {
398 accountsForUser = mAccountManager.getAccountsAsUser(userId);
399 mAccountsCache.put(userId, accountsForUser);
400 }
401 return ArrayUtils.contains(accountsForUser, account);
402 }
403
404 // An authority is only valid if it has a content provider installed on the system
405 boolean isAuthorityValid(String authority, int userId) {
406 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
407 if (authorityMap == null) {
408 authorityMap = new ArrayMap<>();
409 mProvidersPerUserCache.put(userId, authorityMap);
410 }
411 if (!authorityMap.containsKey(authority)) {
412 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
413 PackageManager.MATCH_DIRECT_BOOT_AWARE
414 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
415 }
416 return authorityMap.get(authority);
417 }
418 }
419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 // Primary list of all syncable authorities. Also our global lock.
421 private final SparseArray<AuthorityInfo> mAuthorities =
422 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Amith Yamasani04e0d262012-02-14 11:50:53 -0800424 private final HashMap<AccountAndUser, AccountInfo> mAccounts
425 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426
Amith Yamasani04e0d262012-02-14 11:50:53 -0800427 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
428 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700429
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 private final SparseArray<SyncStatusInfo> mSyncStatus =
431 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Dianne Hackborn231cc602009-04-27 17:10:36 -0700433 private final ArrayList<SyncHistoryItem> mSyncHistory =
434 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700435
Dianne Hackborn231cc602009-04-27 17:10:36 -0700436 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
437 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700438
Matthew Williams8ef22042013-07-26 12:56:39 -0700439 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700440 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
441 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700442
Fred Quintana77c560f2010-03-29 22:20:26 -0700443 private int mNextAuthorityId = 0;
444
Dianne Hackborn231cc602009-04-27 17:10:36 -0700445 // We keep 4 weeks of stats.
446 private final DayStats[] mDayStats = new DayStats[7*4];
447 private final Calendar mCal;
448 private int mYear;
449 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700450
Dianne Hackborn231cc602009-04-27 17:10:36 -0700451 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800452
Dianne Hackborn231cc602009-04-27 17:10:36 -0700453 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700454
Ashish Sharma69d95de2012-04-11 17:27:24 -0700455 private int mSyncRandomOffset;
456
Dianne Hackborn231cc602009-04-27 17:10:36 -0700457 /**
458 * This file contains the core engine state: all accounts and the
459 * settings for them. It must never be lost, and should be changed
460 * infrequently, so it is stored as an XML file.
461 */
462 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700463
Dianne Hackborn231cc602009-04-27 17:10:36 -0700464 /**
465 * This file contains the current sync status. We would like to retain
466 * it across boots, but its loss is not the end of the world, so we store
467 * this information as binary data.
468 */
469 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700470
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 /**
472 * This file contains sync statistics. This is purely debugging information
473 * so is written infrequently and can be thrown away at any time.
474 */
475 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700476
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800478 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800479 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800480
481 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000482 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700483
Svet Ganov65712b02016-09-01 10:24:11 -0700484 private boolean mGrantSyncAdaptersAccountAccess;
485
Makoto Onuki6963bea72017-12-12 10:42:39 -0800486 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700487 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800488
489 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
490 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700493 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700494
Dianne Hackborn231cc602009-04-27 17:10:36 -0700495 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700496
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800497 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000498 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800499
Dianne Hackborn231cc602009-04-27 17:10:36 -0700500 File systemDir = new File(dataDir, "system");
501 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800502 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700503
504 maybeDeleteLegacyPendingInfoLocked(syncDir);
505
Dianne Hackborne17b4452018-01-10 13:15:40 -0800506 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
507 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
508 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700509
Dianne Hackborn231cc602009-04-27 17:10:36 -0700510 readAccountInfoLocked();
511 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700512 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700513 readAndDeleteLegacyAccountInfoLocked();
514 writeAccountInfoLocked();
515 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700516 writeStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700517
518 if (mLogger.enabled()) {
519 final int size = mAuthorities.size();
520 mLogger.log("Loaded ", size, " items");
521 for (int i = 0; i < size; i++) {
522 mLogger.log(mAuthorities.valueAt(i));
523 }
524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 }
526
527 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800528 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 }
530
Makoto Onuki6963bea72017-12-12 10:42:39 -0800531 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800533 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700535 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800536 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537 }
538
539 public static SyncStorageEngine getSingleton() {
540 if (sSyncStorageEngine == null) {
541 throw new IllegalStateException("not initialized");
542 }
543 return sSyncStorageEngine;
544 }
545
Amith Yamasani04e0d262012-02-14 11:50:53 -0800546 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
547 if (mSyncRequestListener == null) {
548 mSyncRequestListener = listener;
549 }
550 }
551
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000552 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
553 if (mAuthorityRemovedListener == null) {
554 mAuthorityRemovedListener = listener;
555 }
556 }
557
558 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
559 if (mPeriodicSyncAddedListener == null) {
560 mPeriodicSyncAddedListener = listener;
561 }
562 }
563
Makoto Onuki6963bea72017-12-12 10:42:39 -0800564 private class MyHandler extends Handler {
565 public MyHandler(Looper looper) {
566 super(looper);
567 }
568
569 @Override
570 public void handleMessage(Message msg) {
571 if (msg.what == MSG_WRITE_STATUS) {
572 synchronized (mAuthorities) {
573 writeStatusLocked();
574 }
575 } else if (msg.what == MSG_WRITE_STATISTICS) {
576 synchronized (mAuthorities) {
577 writeStatisticsLocked();
578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 }
580 }
581 }
Costin Manolache360e4542009-09-04 13:36:04 -0700582
Ashish Sharma69d95de2012-04-11 17:27:24 -0700583 public int getSyncRandomOffset() {
584 return mSyncRandomOffset;
585 }
586
Dianne Hackborn231cc602009-04-27 17:10:36 -0700587 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
588 synchronized (mAuthorities) {
589 mChangeListeners.register(callback, mask);
590 }
591 }
Costin Manolache360e4542009-09-04 13:36:04 -0700592
Dianne Hackborn231cc602009-04-27 17:10:36 -0700593 public void removeStatusChangeListener(ISyncStatusObserver callback) {
594 synchronized (mAuthorities) {
595 mChangeListeners.unregister(callback);
596 }
597 }
Costin Manolache360e4542009-09-04 13:36:04 -0700598
Matthew Williamsfa774182013-06-18 15:44:11 -0700599 /**
600 * Figure out a reasonable flex time for cases where none is provided (old api calls).
601 * @param syncTimeSeconds requested sync time from now.
602 * @return amount of seconds before syncTimeSeconds that the sync can occur.
603 * I.e.
604 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700605 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700606 */
607 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
608 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
609 // Small enough sync request time that we don't add flex time - developer probably
610 // wants to wait for an operation to occur before syncing so we honour the
611 // request time.
612 return 0L;
613 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
614 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
615 } else {
616 // Large enough sync request time that we cap the flex time.
617 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
618 }
619 }
620
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000621 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700622 ArrayList<ISyncStatusObserver> reports = null;
623 synchronized (mAuthorities) {
624 int i = mChangeListeners.beginBroadcast();
625 while (i > 0) {
626 i--;
627 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
628 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800629 continue;
630 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700631 if (reports == null) {
632 reports = new ArrayList<ISyncStatusObserver>(i);
633 }
634 reports.add(mChangeListeners.getBroadcastItem(i));
635 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700636 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700637 }
Costin Manolache360e4542009-09-04 13:36:04 -0700638
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700639 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000640 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700641 }
Costin Manolache360e4542009-09-04 13:36:04 -0700642
Dianne Hackborn231cc602009-04-27 17:10:36 -0700643 if (reports != null) {
644 int i = reports.size();
645 while (i > 0) {
646 i--;
647 try {
648 reports.get(i).onStatusChanged(which);
649 } catch (RemoteException e) {
650 // The remote callback list will take care of this for us.
651 }
652 }
653 }
654 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700655
Amith Yamasani04e0d262012-02-14 11:50:53 -0800656 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700657 synchronized (mAuthorities) {
658 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700659 AuthorityInfo authority = getAuthorityLocked(
660 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700661 "getSyncAutomatically");
662 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700663 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700664
Dianne Hackborn231cc602009-04-27 17:10:36 -0700665 int i = mAuthorities.size();
666 while (i > 0) {
667 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700668 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700669 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700670 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700671 return true;
672 }
673 }
674 return false;
675 }
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677
Amith Yamasani04e0d262012-02-14 11:50:53 -0800678 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukid4764302018-03-30 17:32:57 -0700679 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700680 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000681 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800682 + ", user " + userId + " -> " + sync);
683 }
Makoto Onukid4764302018-03-30 17:32:57 -0700684 mLogger.log("Set sync auto account=", account,
685 " user=", userId,
686 " authority=", providerName,
687 " value=", Boolean.toString(sync),
688 " callingUid=", callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700689 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700690 AuthorityInfo authority =
691 getOrCreateAuthorityLocked(
692 new EndPoint(account, providerName, userId),
693 -1 /* ident */,
694 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700695 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700696 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000697 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800698 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700699 return;
700 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700701 // If the adapter was syncable but missing its initialization sync, set it to
702 // uninitialized now. This is to give it a chance to run any one-time initialization
703 // logic.
704 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
705 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
706 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700707 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700708 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700710
Fred Quintana77c560f2010-03-29 22:20:26 -0700711 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700712 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800713 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700714 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700715 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700716 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800717 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 }
719
Amith Yamasani04e0d262012-02-14 11:50:53 -0800720 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700721 synchronized (mAuthorities) {
722 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700723 AuthorityInfo authority = getAuthorityLocked(
724 new EndPoint(account, providerName, userId),
725 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700726 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700727 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700728 }
729 return authority.syncable;
730 }
731
732 int i = mAuthorities.size();
733 while (i > 0) {
734 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700735 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700736 if (authorityInfo.target != null
737 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700738 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700739 }
740 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700741 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700742 }
743 }
744
Makoto Onukid4764302018-03-30 17:32:57 -0700745 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
746 int callingUid) {
747 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
748 callingUid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700749 }
750
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700751 /**
752 * An enabled sync service and a syncable provider's adapter both get resolved to the same
753 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700754 * @param target target to set value for.
755 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700756 */
Makoto Onukid4764302018-03-30 17:32:57 -0700757 private void setSyncableStateForEndPoint(EndPoint target, int syncable, int callingUid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700758 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700759 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
760 " callingUid=", callingUid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700761 synchronized (mAuthorities) {
762 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700763 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
764 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700765 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700766 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000767 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700768 }
769 if (aInfo.syncable == syncable) {
770 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000771 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700772 }
773 return;
774 }
775 aInfo.syncable = syncable;
776 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700777 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700778 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800779 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700780 ContentResolver.SYNC_EXEMPTION_NONE);
Fred Quintana5e787c42009-08-16 23:13:53 -0700781 }
782 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
783 }
784
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700785 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800786 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700787 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
788 if (authority != null) {
789 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800790 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700791 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800792 }
793 }
794
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700795 /**
796 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
797 * the account or provider info be null, which signifies all accounts or providers.
798 */
799 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
800 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000801 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800802 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
803 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800805 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000806 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700807 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000808 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700809 changed = setBackoffLocked(
810 info.account /* may be null */,
811 info.userId,
812 info.provider /* may be null */,
813 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800814 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700815 AuthorityInfo authorityInfo =
816 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
817 if (authorityInfo.backoffTime == nextSyncTime
818 && authorityInfo.backoffDelay == nextDelay) {
819 changed = false;
820 } else {
821 authorityInfo.backoffTime = nextSyncTime;
822 authorityInfo.backoffDelay = nextDelay;
823 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800824 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800825 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800826 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800827 if (changed) {
828 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
829 }
830 }
831
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700832 /**
833 * Either set backoff for a specific authority, or set backoff for all the
834 * accounts on a specific adapter/all adapters.
835 *
836 * @param account account for which to set backoff. Null to specify all accounts.
837 * @param userId id of the user making this request.
838 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700839 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700840 */
841 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000842 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700843 boolean changed = false;
844 for (AccountInfo accountInfo : mAccounts.values()) {
845 if (account != null && !account.equals(accountInfo.accountAndUser.account)
846 && userId != accountInfo.accountAndUser.userId) {
847 continue;
848 }
849 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
850 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700851 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700852 continue;
853 }
854 if (authorityInfo.backoffTime != nextSyncTime
855 || authorityInfo.backoffDelay != nextDelay) {
856 authorityInfo.backoffTime = nextSyncTime;
857 authorityInfo.backoffDelay = nextDelay;
858 changed = true;
859 }
860 }
861 }
862 return changed;
863 }
864
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000865 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800866 boolean changed = false;
867 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000868 // Clear backoff for all sync adapters.
869 for (AccountInfo accountInfo : mAccounts.values()) {
870 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
871 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
872 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
873 if (Log.isLoggable(TAG, Log.VERBOSE)) {
874 Slog.v(TAG, "clearAllBackoffsLocked:"
875 + " authority:" + authorityInfo.target
876 + " account:" + accountInfo.accountAndUser.account.name
877 + " user:" + accountInfo.accountAndUser.userId
878 + " backoffTime was: " + authorityInfo.backoffTime
879 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800880 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000881 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
882 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
883 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800884 }
885 }
886 }
887 }
888
889 if (changed) {
890 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
891 }
892 }
893
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700894 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800895 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700896 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800897 if (authority == null) {
898 return 0;
899 }
900 return authority.delayUntil;
901 }
902 }
903
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700904 public void setDelayUntilTime(EndPoint info, long delayUntil) {
905 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000906 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700907 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800908 }
909 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700910 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
911 if (authority.delayUntil == delayUntil) {
912 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700913 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700914 authority.delayUntil = delayUntil;
915 }
916 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
917 }
918
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700919 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000920 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
921 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700922 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000923 boolean restoreAllPeriodicSyncs() {
924 if (mPeriodicSyncAddedListener == null) {
925 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800926 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000927 synchronized (mAuthorities) {
928 for (int i=0; i<mAuthorities.size(); i++) {
929 AuthorityInfo authority = mAuthorities.valueAt(i);
930 for (PeriodicSync periodicSync: authority.periodicSyncs) {
931 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
932 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
933 }
934 authority.periodicSyncs.clear();
935 }
936 writeAccountInfoLocked();
937 }
938 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800939 }
940
Makoto Onuki75ad2492018-03-28 14:42:42 -0700941 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukid4764302018-03-30 17:32:57 -0700942 @SyncExemption int syncExemptionFlag, int callingUid) {
943 mLogger.log("Set master enabled=", flag, " user=", userId,
944 " caller=" + callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700945 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800946 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700947 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700948 return;
949 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800950 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700951 writeAccountInfoLocked();
952 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700953 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700954 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800955 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700956 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700957 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700958 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800959 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800960 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962
Amith Yamasani04e0d262012-02-14 11:50:53 -0800963 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700964 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800965 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800966 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 }
968 }
Costin Manolache360e4542009-09-04 13:36:04 -0700969
Makoto Onukib47e8942017-09-18 14:03:03 -0700970 public int getAuthorityCount() {
971 synchronized (mAuthorities) {
972 return mAuthorities.size();
973 }
974 }
975
Dianne Hackborn231cc602009-04-27 17:10:36 -0700976 public AuthorityInfo getAuthority(int authorityId) {
977 synchronized (mAuthorities) {
978 return mAuthorities.get(authorityId);
979 }
980 }
Costin Manolache360e4542009-09-04 13:36:04 -0700981
Dianne Hackborn231cc602009-04-27 17:10:36 -0700982 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700983 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700984 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700985 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700986 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700987 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700988 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700989 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700990 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700991 return true;
992 }
993 }
994 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700995 return false;
996 }
Costin Manolache360e4542009-09-04 13:36:04 -0700997
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000998 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001000 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
1001 -1 /* desired identifier */,
1002 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001004 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001007 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001008 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001009 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001010 }
Costin Manolache360e4542009-09-04 13:36:04 -07001011
Dianne Hackborn231cc602009-04-27 17:10:36 -07001012 /**
1013 * Called when the set of account has changed, given the new array of
1014 * active accounts.
1015 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001016 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001018 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001019 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001020 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1022 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1023 while (accIt.hasNext()) {
1024 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001025 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1026 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001027 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001028 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001029 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001030 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001031 for (AuthorityInfo auth : acc.authorities.values()) {
1032 removing.put(auth.ident, auth);
1033 }
1034 accIt.remove();
1035 }
1036 }
Costin Manolache360e4542009-09-04 13:36:04 -07001037
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 // Clean out all data structures.
1039 int i = removing.size();
1040 if (i > 0) {
1041 while (i > 0) {
1042 i--;
1043 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001044 AuthorityInfo auth = removing.valueAt(i);
1045 if (mAuthorityRemovedListener != null) {
1046 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1047 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 mAuthorities.remove(ident);
1049 int j = mSyncStatus.size();
1050 while (j > 0) {
1051 j--;
1052 if (mSyncStatus.keyAt(j) == ident) {
1053 mSyncStatus.remove(mSyncStatus.keyAt(j));
1054 }
1055 }
1056 j = mSyncHistory.size();
1057 while (j > 0) {
1058 j--;
1059 if (mSyncHistory.get(j).authorityId == ident) {
1060 mSyncHistory.remove(j);
1061 }
1062 }
1063 }
1064 writeAccountInfoLocked();
1065 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 writeStatisticsLocked();
1067 }
1068 }
1069 }
1070
1071 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001072 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1073 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 */
Fred Quintana918339a2010-10-05 14:00:39 -07001075 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1076 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001077 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001078 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001079 Slog.v(TAG, "setActiveSync: account="
1080 + " auth=" + activeSyncContext.mSyncOperation.target
1081 + " src=" + activeSyncContext.mSyncOperation.syncSource
1082 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001083 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001084 final EndPoint info = activeSyncContext.mSyncOperation.target;
1085 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1086 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001087 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001088 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001089 syncInfo = new SyncInfo(
1090 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001091 authorityInfo.target.account,
1092 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001093 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001094 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001095 }
Fred Quintana918339a2010-10-05 14:00:39 -07001096 reportActiveChange();
1097 return syncInfo;
1098 }
1099
1100 /**
1101 * Called to indicate that a previously active sync is no longer active.
1102 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001103 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001104 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001105 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001106 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001107 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001108 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001109 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001110 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001111 }
1112
1113 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001114 }
1115
1116 /**
1117 * To allow others to send active change reports, to poke clients.
1118 */
1119 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001120 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 }
Costin Manolache360e4542009-09-04 13:36:04 -07001122
Dianne Hackborn231cc602009-04-27 17:10:36 -07001123 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001124 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001125 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001126 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 long id;
1128 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001129 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001130 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001131 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001132 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 if (authority == null) {
1134 return -1;
1135 }
1136 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001137 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001138 item.authorityId = authority.ident;
1139 item.historyId = mNextHistoryId++;
1140 if (mNextHistoryId < 0) mNextHistoryId = 0;
1141 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001142 item.source = op.syncSource;
1143 item.reason = op.reason;
1144 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 item.event = EVENT_START;
Makoto Onukid5f25d22018-05-22 16:02:17 -07001146 item.syncExemptionFlag = op.syncExemptionFlag;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 mSyncHistory.add(0, item);
1148 while (mSyncHistory.size() > MAX_HISTORY) {
1149 mSyncHistory.remove(mSyncHistory.size()-1);
1150 }
1151 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001152 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 }
Costin Manolache360e4542009-09-04 13:36:04 -07001154
Fred Quintanaac9385e2009-06-22 18:00:59 -07001155 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
1158
Fred Quintana77c560f2010-03-29 22:20:26 -07001159 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001160 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001162 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001163 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001164 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 SyncHistoryItem item = null;
1166 int i = mSyncHistory.size();
1167 while (i > 0) {
1168 i--;
1169 item = mSyncHistory.get(i);
1170 if (item.historyId == historyId) {
1171 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001173 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
Costin Manolache360e4542009-09-04 13:36:04 -07001175
Dianne Hackborn231cc602009-04-27 17:10:36 -07001176 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001177 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001178 return;
1179 }
Costin Manolache360e4542009-09-04 13:36:04 -07001180
Dianne Hackborn231cc602009-04-27 17:10:36 -07001181 item.elapsedTime = elapsedTime;
1182 item.event = EVENT_STOP;
1183 item.mesg = resultMessage;
1184 item.downstreamActivity = downstreamActivity;
1185 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001186
Dianne Hackborn231cc602009-04-27 17:10:36 -07001187 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001188
Makoto Onuki94986212018-04-11 16:24:46 -07001189 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1190
1191 status.totalStats.numSyncs++;
1192 status.todayStats.numSyncs++;
1193 status.totalStats.totalElapsedTime += elapsedTime;
1194 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001195 switch (item.source) {
1196 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001197 status.totalStats.numSourceLocal++;
1198 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001199 break;
1200 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001201 status.totalStats.numSourcePoll++;
1202 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001203 break;
1204 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001205 status.totalStats.numSourceUser++;
1206 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001207 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001208 case SOURCE_OTHER:
1209 status.totalStats.numSourceOther++;
1210 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001211 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001212 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001213 status.totalStats.numSourcePeriodic++;
1214 status.todayStats.numSourcePeriodic++;
1215 break;
1216 case SOURCE_FEED:
1217 status.totalStats.numSourceFeed++;
1218 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001219 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001220 }
Costin Manolache360e4542009-09-04 13:36:04 -07001221
Dianne Hackborn231cc602009-04-27 17:10:36 -07001222 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001223 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 if (mDayStats[0] == null) {
1225 mDayStats[0] = new DayStats(day);
1226 } else if (day != mDayStats[0].day) {
1227 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1228 mDayStats[0] = new DayStats(day);
1229 writeStatisticsNow = true;
1230 } else if (mDayStats[0] == null) {
1231 }
1232 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001233
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 final long lastSyncTime = (item.eventTime + elapsedTime);
1235 boolean writeStatusNow = false;
1236 if (MESG_SUCCESS.equals(resultMessage)) {
1237 // - if successful, update the successful columns
1238 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1239 writeStatusNow = true;
1240 }
Makoto Onukif74cf942018-04-16 17:04:58 -07001241 status.setLastSuccess(item.source, lastSyncTime);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001242 ds.successCount++;
1243 ds.successTime += elapsedTime;
1244 } else if (!MESG_CANCELED.equals(resultMessage)) {
1245 if (status.lastFailureTime == 0) {
1246 writeStatusNow = true;
1247 }
Makoto Onuki94986212018-04-11 16:24:46 -07001248 status.totalStats.numFailures++;
1249 status.todayStats.numFailures++;
1250
Makoto Onukif74cf942018-04-16 17:04:58 -07001251 status.setLastFailure(item.source, lastSyncTime, resultMessage);
1252
Dianne Hackborn231cc602009-04-27 17:10:36 -07001253 ds.failureCount++;
1254 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001255 } else {
1256 // Cancel
1257 status.totalStats.numCancels++;
1258 status.todayStats.numCancels++;
1259 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001260 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001261 final StringBuilder event = new StringBuilder();
1262 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1263 + " Elapsed=");
1264 SyncManager.formatDurationHMS(event, elapsedTime);
1265 event.append(" Reason=");
1266 event.append(SyncOperation.reasonToString(null, item.reason));
Makoto Onukid5f25d22018-05-22 16:02:17 -07001267 if (item.syncExemptionFlag != ContentResolver.SYNC_EXEMPTION_NONE) {
1268 event.append(" Exemption=");
1269 switch (item.syncExemptionFlag) {
1270 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET:
1271 event.append("fg");
1272 break;
1273 case ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP:
1274 event.append("top");
1275 break;
1276 default:
1277 event.append(item.syncExemptionFlag);
1278 break;
1279 }
1280 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001281 event.append(" Extras=");
1282 SyncOperation.extrasToStringBuilder(item.extras, event);
1283
1284 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001285
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 if (writeStatusNow) {
1287 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001288 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1289 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001290 WRITE_STATUS_DELAY);
1291 }
1292 if (writeStatisticsNow) {
1293 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001294 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1295 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001296 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001297 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001298 }
Costin Manolache360e4542009-09-04 13:36:04 -07001299
Fred Quintanaac9385e2009-06-22 18:00:59 -07001300 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 }
1302
1303 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001304 * Return a list of the currently active syncs. Note that the returned
1305 * items are the real, live active sync objects, so be careful what you do
1306 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001307 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001308 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001309 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001310 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 }
1312 }
Costin Manolache360e4542009-09-04 13:36:04 -07001313
Dianne Hackborn231cc602009-04-27 17:10:36 -07001314 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001315 * @param userId Id of user to return current sync info.
1316 * @param canAccessAccounts Determines whether to redact Account information from the result.
1317 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001318 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001319 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001320 synchronized (mAuthorities) {
1321 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1322 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1323 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001324 SyncInfo copy;
1325 if (!canAccessAccounts) {
1326 copy = SyncInfo.createAccountRedacted(
1327 sync.authorityId, sync.authority, sync.startTime);
1328 } else {
1329 copy = new SyncInfo(sync);
1330 }
1331 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001332 }
1333 return syncsCopy;
1334 }
1335 }
1336
1337 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1338 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1339 if (syncs == null) {
1340 syncs = new ArrayList<SyncInfo>();
1341 mCurrentSyncs.put(userId, syncs);
1342 }
1343 return syncs;
1344 }
1345
1346 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001347 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001348 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001349 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001350 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001351 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001352 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001353 true /* write to storage if this results in a change */);
1354 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1355 }
1356 }
1357
1358 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001359 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001360 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001361 * @param info the endpoint target we are querying status info for.
1362 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001364 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001365 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001366 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001367 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001368 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001370 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001371 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001372 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001373 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001374 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001375 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001376 }
1377 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001378 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001379 }
1380 }
Costin Manolache360e4542009-09-04 13:36:04 -07001381
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001382 /** Return true if the pending status is true of any matching authorities. */
1383 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 synchronized (mAuthorities) {
1385 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001386 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001387 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001388 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1389 if (ainfo == null) {
1390 continue;
1391 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001392 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001393 continue;
1394 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001395 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001396 return true;
1397 }
1398 }
1399 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 }
1401 }
1402
1403 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001404 * Return an array of the current sync status for all authorities. Note
1405 * that the objects inside the array are the real, live status objects,
1406 * so be careful what you do with them.
1407 */
1408 public ArrayList<SyncHistoryItem> getSyncHistory() {
1409 synchronized (mAuthorities) {
1410 final int N = mSyncHistory.size();
1411 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1412 for (int i=0; i<N; i++) {
1413 items.add(mSyncHistory.get(i));
1414 }
1415 return items;
1416 }
1417 }
Costin Manolache360e4542009-09-04 13:36:04 -07001418
Dianne Hackborn231cc602009-04-27 17:10:36 -07001419 /**
1420 * Return an array of the current per-day statistics. Note
1421 * that the objects inside the array are the real, live status objects,
1422 * so be careful what you do with them.
1423 */
1424 public DayStats[] getDayStatistics() {
1425 synchronized (mAuthorities) {
1426 DayStats[] ds = new DayStats[mDayStats.length];
1427 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1428 return ds;
1429 }
1430 }
Costin Manolache360e4542009-09-04 13:36:04 -07001431
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001432 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1433 AuthorityInfo authorityInfo) {
1434 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1435 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1436 }
1437
Dianne Hackborn55280a92009-05-07 15:53:46 -07001438 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001439 mCal.setTimeInMillis(System.currentTimeMillis());
1440 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1441 if (mYear != mCal.get(Calendar.YEAR)) {
1442 mYear = mCal.get(Calendar.YEAR);
1443 mCal.clear();
1444 mCal.set(Calendar.YEAR, mYear);
1445 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1446 }
1447 return dayOfYear + mYearInDays;
1448 }
Costin Manolache360e4542009-09-04 13:36:04 -07001449
Dianne Hackborn231cc602009-04-27 17:10:36 -07001450 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001451 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001452 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001453 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001455 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001456 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001457 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001458 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1459 AccountInfo accountInfo = mAccounts.get(au);
1460 if (accountInfo == null) {
1461 if (tag != null) {
1462 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1463 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001464 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001465 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 return null;
1467 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001468 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1469 if (authority == null) {
1470 if (tag != null) {
1471 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1472 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1473 }
1474 }
1475 return null;
1476 }
1477 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001478 }
Costin Manolache360e4542009-09-04 13:36:04 -07001479
Matthew Williamsfa774182013-06-18 15:44:11 -07001480 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001481 * @param info info identifying target.
1482 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001483 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001484 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001485 * exists.
1486 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001487 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1488 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001489 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1490 AccountInfo account = mAccounts.get(au);
1491 if (account == null) {
1492 account = new AccountInfo(au);
1493 mAccounts.put(au, account);
1494 }
1495 authority = account.authorities.get(info.provider);
1496 if (authority == null) {
1497 authority = createAuthorityLocked(info, ident, doWrite);
1498 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001499 }
1500 return authority;
1501 }
1502
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001503 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1504 AuthorityInfo authority;
1505 if (ident < 0) {
1506 ident = mNextAuthorityId;
1507 mNextAuthorityId++;
1508 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001509 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001510 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001511 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001512 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001513 authority = new AuthorityInfo(info, ident);
1514 mAuthorities.put(ident, authority);
1515 if (doWrite) {
1516 writeAccountInfoLocked();
1517 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001518 return authority;
1519 }
Costin Manolache360e4542009-09-04 13:36:04 -07001520
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001521 public void removeAuthority(EndPoint info) {
1522 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001523 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001524 }
1525 }
1526
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001527
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001528 /**
1529 * Remove an authority associated with a provider. Needs to be a standalone function for
1530 * backward compatibility.
1531 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001532 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001533 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001534 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001535 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001536 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1537 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001538 if (mAuthorityRemovedListener != null) {
1539 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1540 }
Fred Quintanafb084402010-03-23 17:57:03 -07001541 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001542 if (doWrite) {
1543 writeAccountInfoLocked();
1544 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001545 }
1546 }
1547 }
1548
Dianne Hackborn231cc602009-04-27 17:10:36 -07001549 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1550 SyncStatusInfo status = mSyncStatus.get(authorityId);
1551 if (status == null) {
1552 status = new SyncStatusInfo(authorityId);
1553 mSyncStatus.put(authorityId, status);
1554 }
1555 return status;
1556 }
Costin Manolache360e4542009-09-04 13:36:04 -07001557
Dianne Hackborn55280a92009-05-07 15:53:46 -07001558 public void writeAllState() {
1559 synchronized (mAuthorities) {
1560 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001561 writeStatusLocked();
1562 writeStatisticsLocked();
1563 }
1564 }
Costin Manolache360e4542009-09-04 13:36:04 -07001565
Svet Ganov65712b02016-09-01 10:24:11 -07001566 public boolean shouldGrantSyncAdaptersAccountAccess() {
1567 return mGrantSyncAdaptersAccountAccess;
1568 }
1569
Dianne Hackborn231cc602009-04-27 17:10:36 -07001570 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001571 * public for testing
1572 */
1573 public void clearAndReadState() {
1574 synchronized (mAuthorities) {
1575 mAuthorities.clear();
1576 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001577 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001578 mSyncStatus.clear();
1579 mSyncHistory.clear();
1580
1581 readAccountInfoLocked();
1582 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001583 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001584 readAndDeleteLegacyAccountInfoLocked();
1585 writeAccountInfoLocked();
1586 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001587 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001588 }
1589 }
1590
1591 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001592 * Read all account information back in to the initial engine state.
1593 */
1594 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001595 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001596 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001598 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001599 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001600 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001601 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001602 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001603 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001604 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001605 while (eventType != XmlPullParser.START_TAG &&
1606 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001607 eventType = parser.next();
1608 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001609 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001610 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001611 return;
1612 }
1613
Dianne Hackborn231cc602009-04-27 17:10:36 -07001614 String tagName = parser.getName();
1615 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001617 String versionString = parser.getAttributeValue(null, "version");
1618 int version;
1619 try {
1620 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1621 } catch (NumberFormatException e) {
1622 version = 0;
1623 }
Svet Ganov65712b02016-09-01 10:24:11 -07001624
1625 if (version < 3) {
1626 mGrantSyncAdaptersAccountAccess = true;
1627 }
1628
Amith Yamasani04e0d262012-02-14 11:50:53 -08001629 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001630 try {
1631 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1632 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1633 } catch (NumberFormatException e) {
1634 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001635 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001636 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1637 try {
1638 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1639 } catch (NumberFormatException e) {
1640 mSyncRandomOffset = 0;
1641 }
1642 if (mSyncRandomOffset == 0) {
1643 Random random = new Random(System.currentTimeMillis());
1644 mSyncRandomOffset = random.nextInt(86400);
1645 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001646 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001647 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001648 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001649 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001650 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001651 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001652 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001653 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001654 if (parser.getDepth() == 2) {
1655 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001656 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001657 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001658 if (authority != null) {
1659 if (authority.ident > highestAuthorityId) {
1660 highestAuthorityId = authority.ident;
1661 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001662 } else {
1663 EventLog.writeEvent(0x534e4554, "26513719", -1,
1664 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001665 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001666 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1667 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001668 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001669 } else if (parser.getDepth() == 3) {
1670 if ("periodicSync".equals(tagName) && authority != null) {
1671 periodicSync = parsePeriodicSync(parser, authority);
1672 }
1673 } else if (parser.getDepth() == 4 && periodicSync != null) {
1674 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001675 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001676 }
1677 }
1678 }
1679 eventType = parser.next();
1680 } while (eventType != XmlPullParser.END_DOCUMENT);
1681 }
1682 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001683 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001684 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001685 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001686 if (fis == null) Slog.i(TAG, "No initial accounts");
1687 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001688 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001689 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001690 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001691 if (fis != null) {
1692 try {
1693 fis.close();
1694 } catch (java.io.IOException e1) {
1695 }
1696 }
1697 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001698
Fred Quintana77c560f2010-03-29 22:20:26 -07001699 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001700 }
Costin Manolache360e4542009-09-04 13:36:04 -07001701
Fred Quintanafb084402010-03-23 17:57:03 -07001702 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001703 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1704 * pending.xml was used starting in KLP.
1705 * @param syncDir directory where the sync files are located.
1706 */
1707 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1708 File file = new File(syncDir, "pending.bin");
1709 if (!file.exists()) {
1710 return;
1711 } else {
1712 file.delete();
1713 }
1714 }
1715
1716 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001717 * some authority names have changed. copy over their settings and delete the old ones
1718 * @return true if a change was made
1719 */
1720 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1721 boolean writeNeeded = false;
1722
1723 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1724 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001725 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001726 AuthorityInfo authority = mAuthorities.valueAt(i);
1727 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001728 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001729 if (newAuthorityName == null) {
1730 continue;
1731 }
1732
1733 // remember this authority so we can remove it later. we can't remove it
1734 // now without messing up this loop iteration
1735 authoritiesToRemove.add(authority);
1736
1737 // this authority isn't enabled, no need to copy it to the new authority name since
1738 // the default is "disabled"
1739 if (!authority.enabled) {
1740 continue;
1741 }
1742
1743 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001744 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001745 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001746 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001747 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001748 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001749 continue;
1750 }
1751
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001752 AuthorityInfo newAuthority =
1753 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001754 newAuthority.enabled = true;
1755 writeNeeded = true;
1756 }
1757
1758 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001759 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001760 authorityInfo.target.account,
1761 authorityInfo.target.userId,
1762 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001763 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001764 writeNeeded = true;
1765 }
1766
1767 return writeNeeded;
1768 }
1769
Amith Yamasani04e0d262012-02-14 11:50:53 -08001770 private void parseListenForTickles(XmlPullParser parser) {
1771 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1772 int userId = 0;
1773 try {
1774 userId = Integer.parseInt(user);
1775 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001776 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001777 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001778 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001779 }
1780 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1781 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1782 mMasterSyncAutomatically.put(userId, listen);
1783 }
1784
Suprabh Shukla042a4782017-05-12 15:26:54 -07001785 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1786 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001787 AuthorityInfo authority = null;
1788 int id = -1;
1789 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001790 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001791 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001792 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001793 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001794 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001795 }
1796 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001797 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001798 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001799 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001800 String accountName = parser.getAttributeValue(null, "account");
1801 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001802 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001803 String packageName = parser.getAttributeValue(null, "package");
1804 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001805 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001806 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001807 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001808 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001809 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001810 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001811 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001812 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001813 + " account=" + accountName
1814 + " accountType=" + accountType
1815 + " auth=" + authorityName
1816 + " package=" + packageName
1817 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001818 + " user=" + userId
1819 + " enabled=" + enabled
1820 + " syncable=" + syncable);
1821 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001822 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001823 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001824 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001825 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001826 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001827 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001828 new Account(accountName, accountType),
1829 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001830 if (validator.isAccountValid(info.account, userId)
1831 && validator.isAuthorityValid(authorityName, userId)) {
1832 authority = getOrCreateAuthorityLocked(info, id, false);
1833 // If the version is 0 then we are upgrading from a file format that did not
1834 // know about periodic syncs. In that case don't clear the list since we
1835 // want the default, which is a daily periodic sync.
1836 // Otherwise clear out this default list since we will populate it later
1837 // with
1838 // the periodic sync descriptions that are read from the configuration file.
1839 if (version > 0) {
1840 authority.periodicSyncs.clear();
1841 }
1842 } else {
1843 EventLog.writeEvent(0x534e4554, "35028827", -1,
1844 "account:" + info.account + " provider:" + authorityName + " user:"
1845 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001846 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001847 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001848 }
1849 if (authority != null) {
1850 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001851 try {
1852 authority.syncable = (syncable == null) ?
1853 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1854 } catch (NumberFormatException e) {
1855 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1856 // format.
1857 if ("unknown".equals(syncable)) {
1858 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1859 } else {
1860 authority.syncable = Boolean.parseBoolean(syncable) ?
1861 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1862 }
1863
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001864 }
1865 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001866 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001867 + accountName + " auth=" + authorityName
1868 + " enabled=" + enabled
1869 + " syncable=" + syncable);
1870 }
1871 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001872 return authority;
1873 }
1874
Matthew Williamsfa774182013-06-18 15:44:11 -07001875 /**
1876 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1877 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001878 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001879 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001880 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001881 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001882 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001883 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001884 try {
1885 period = Long.parseLong(periodValue);
1886 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001887 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001888 return null;
1889 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001890 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001891 return null;
1892 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001893 try {
1894 flextime = Long.parseLong(flexValue);
1895 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001896 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001897 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001898 + ", using default: "
1899 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001900 } catch (NullPointerException expected) {
1901 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001902 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1903 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001904 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001905 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001906 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001907 new PeriodicSync(authorityInfo.target.account,
1908 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001909 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001910 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001911 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001912 return periodicSync;
1913 }
1914
Matthew Williamsfa774182013-06-18 15:44:11 -07001915 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001916 String name = parser.getAttributeValue(null, "name");
1917 String type = parser.getAttributeValue(null, "type");
1918 String value1 = parser.getAttributeValue(null, "value1");
1919 String value2 = parser.getAttributeValue(null, "value2");
1920
1921 try {
1922 if ("long".equals(type)) {
1923 extras.putLong(name, Long.parseLong(value1));
1924 } else if ("integer".equals(type)) {
1925 extras.putInt(name, Integer.parseInt(value1));
1926 } else if ("double".equals(type)) {
1927 extras.putDouble(name, Double.parseDouble(value1));
1928 } else if ("float".equals(type)) {
1929 extras.putFloat(name, Float.parseFloat(value1));
1930 } else if ("boolean".equals(type)) {
1931 extras.putBoolean(name, Boolean.parseBoolean(value1));
1932 } else if ("string".equals(type)) {
1933 extras.putString(name, value1);
1934 } else if ("account".equals(type)) {
1935 extras.putParcelable(name, new Account(value1, value2));
1936 }
1937 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001938 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001939 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001940 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001941 }
1942 }
1943
Dianne Hackborn231cc602009-04-27 17:10:36 -07001944 /**
1945 * Write all account information to the account file.
1946 */
1947 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001948 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001949 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001950 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001951 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001952
Dianne Hackborn231cc602009-04-27 17:10:36 -07001953 try {
1954 fos = mAccountInfoFile.startWrite();
1955 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001956 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001957 out.startDocument(null, true);
1958 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001959
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001961 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001962 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001963 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001964
1965 // Write the Sync Automatically flags for each user
1966 final int M = mMasterSyncAutomatically.size();
1967 for (int m = 0; m < M; m++) {
1968 int userId = mMasterSyncAutomatically.keyAt(m);
1969 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1970 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1971 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1972 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1973 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001974 }
Costin Manolache360e4542009-09-04 13:36:04 -07001975
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001977 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001978 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001979 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001980 out.startTag(null, "authority");
1981 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001982 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001983 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001984 out.attribute(null, "account", info.account.name);
1985 out.attribute(null, "type", info.account.type);
1986 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001987 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001988 out.endTag(null, "authority");
1989 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001990 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001991 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001992 mAccountInfoFile.finishWrite(fos);
1993 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001994 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001995 if (fos != null) {
1996 mAccountInfoFile.failWrite(fos);
1997 }
1998 }
1999 }
Costin Manolache360e4542009-09-04 13:36:04 -07002000
Dianne Hackborn231cc602009-04-27 17:10:36 -07002001 static int getIntColumn(Cursor c, String name) {
2002 return c.getInt(c.getColumnIndex(name));
2003 }
Costin Manolache360e4542009-09-04 13:36:04 -07002004
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 static long getLongColumn(Cursor c, String name) {
2006 return c.getLong(c.getColumnIndex(name));
2007 }
Costin Manolache360e4542009-09-04 13:36:04 -07002008
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 /**
Makoto Onuki94986212018-04-11 16:24:46 -07002010 * TODO Remove it. It's super old code that was used to migrate the information from a sqlite
2011 * database that we used a long time ago, and is no longer relevant.
Dianne Hackborn231cc602009-04-27 17:10:36 -07002012 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002013 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002014 // Look for old database to initialize from.
2015 File file = mContext.getDatabasePath("syncmanager.db");
2016 if (!file.exists()) {
2017 return;
2018 }
2019 String path = file.getPath();
2020 SQLiteDatabase db = null;
2021 try {
2022 db = SQLiteDatabase.openDatabase(path, null,
2023 SQLiteDatabase.OPEN_READONLY);
2024 } catch (SQLiteException e) {
2025 }
Costin Manolache360e4542009-09-04 13:36:04 -07002026
Dianne Hackborn231cc602009-04-27 17:10:36 -07002027 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002028 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002029
Dianne Hackborn231cc602009-04-27 17:10:36 -07002030 // Copy in all of the status information, as well as accounts.
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, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002033 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002034 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2035 qb.setTables("stats, status");
2036 HashMap<String,String> map = new HashMap<String,String>();
2037 map.put("_id", "status._id as _id");
2038 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002039 if (hasType) {
2040 map.put("account_type", "stats.account_type as account_type");
2041 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 map.put("authority", "stats.authority as authority");
2043 map.put("totalElapsedTime", "totalElapsedTime");
2044 map.put("numSyncs", "numSyncs");
2045 map.put("numSourceLocal", "numSourceLocal");
2046 map.put("numSourcePoll", "numSourcePoll");
2047 map.put("numSourceServer", "numSourceServer");
2048 map.put("numSourceUser", "numSourceUser");
2049 map.put("lastSuccessSource", "lastSuccessSource");
2050 map.put("lastSuccessTime", "lastSuccessTime");
2051 map.put("lastFailureSource", "lastFailureSource");
2052 map.put("lastFailureTime", "lastFailureTime");
2053 map.put("lastFailureMesg", "lastFailureMesg");
2054 map.put("pending", "pending");
2055 qb.setProjectionMap(map);
2056 qb.appendWhere("stats._id = status.stats_id");
2057 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002059 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002060 String accountType = hasType
2061 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002062 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002063 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002065 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002066 AuthorityInfo authority =
2067 this.getOrCreateAuthorityLocked(
2068 new EndPoint(new Account(accountName, accountType),
2069 authorityName,
2070 0 /* legacy is single-user */)
2071 , -1,
2072 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002073 if (authority != null) {
2074 int i = mSyncStatus.size();
2075 boolean found = false;
2076 SyncStatusInfo st = null;
2077 while (i > 0) {
2078 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002079 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002080 if (st.authorityId == authority.ident) {
2081 found = true;
2082 break;
2083 }
2084 }
2085 if (!found) {
2086 st = new SyncStatusInfo(authority.ident);
2087 mSyncStatus.put(authority.ident, st);
2088 }
Makoto Onuki94986212018-04-11 16:24:46 -07002089 st.totalStats.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2090 st.totalStats.numSyncs = getIntColumn(c, "numSyncs");
2091 st.totalStats.numSourceLocal = getIntColumn(c, "numSourceLocal");
2092 st.totalStats.numSourcePoll = getIntColumn(c, "numSourcePoll");
2093 st.totalStats.numSourceOther = getIntColumn(c, "numSourceServer");
2094 st.totalStats.numSourceUser = getIntColumn(c, "numSourceUser");
2095 st.totalStats.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002096 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2097 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2098 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2099 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2100 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2101 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 }
Costin Manolache360e4542009-09-04 13:36:04 -07002104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002106
Dianne Hackborn231cc602009-04-27 17:10:36 -07002107 // Retrieve the settings.
2108 qb = new SQLiteQueryBuilder();
2109 qb.setTables("settings");
2110 c = qb.query(db, null, null, null, null, null, null);
2111 while (c.moveToNext()) {
2112 String name = c.getString(c.getColumnIndex("name"));
2113 String value = c.getString(c.getColumnIndex("value"));
2114 if (name == null) continue;
2115 if (name.equals("listen_for_tickles")) {
Makoto Onuki75ad2492018-03-28 14:42:42 -07002116 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0,
Makoto Onukid4764302018-03-30 17:32:57 -07002117 ContentResolver.SYNC_EXEMPTION_NONE, SyncLogger.CALLING_UID_SELF);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 } else if (name.startsWith("sync_provider_")) {
2119 String provider = name.substring("sync_provider_".length(),
2120 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002121 int i = mAuthorities.size();
2122 while (i > 0) {
2123 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002124 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002125 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002126 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002127 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002128 }
2129 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
Costin Manolache360e4542009-09-04 13:36:04 -07002132
Dianne Hackborn231cc602009-04-27 17:10:36 -07002133 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002134
Dianne Hackborn231cc602009-04-27 17:10:36 -07002135 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002136
Dianne Hackborn231cc602009-04-27 17:10:36 -07002137 (new File(path)).delete();
2138 }
2139 }
Costin Manolache360e4542009-09-04 13:36:04 -07002140
Dianne Hackborn231cc602009-04-27 17:10:36 -07002141 public static final int STATUS_FILE_END = 0;
2142 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002143
Dianne Hackborn231cc602009-04-27 17:10:36 -07002144 /**
2145 * Read all sync status back in to the initial engine state.
2146 */
2147 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002148 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002149 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002150 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002151 try {
2152 byte[] data = mStatusFile.readFully();
2153 Parcel in = Parcel.obtain();
2154 in.unmarshall(data, 0, data.length);
2155 in.setDataPosition(0);
2156 int token;
2157 while ((token=in.readInt()) != STATUS_FILE_END) {
2158 if (token == STATUS_FILE_ITEM) {
2159 SyncStatusInfo status = new SyncStatusInfo(in);
2160 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2161 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002162 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002163 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002164 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002165 mSyncStatus.put(status.authorityId, status);
2166 }
2167 } else {
2168 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002169 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002170 break;
2171 }
2172 }
2173 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002174 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002175 }
2176 }
Costin Manolache360e4542009-09-04 13:36:04 -07002177
Dianne Hackborn231cc602009-04-27 17:10:36 -07002178 /**
2179 * Write all sync status to the sync status file.
2180 */
2181 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002182 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002183 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002184 }
Costin Manolache360e4542009-09-04 13:36:04 -07002185
Dianne Hackborn231cc602009-04-27 17:10:36 -07002186 // The file is being written, so we don't need to have a scheduled
2187 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002188 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002189
Dianne Hackborn231cc602009-04-27 17:10:36 -07002190 FileOutputStream fos = null;
2191 try {
2192 fos = mStatusFile.startWrite();
2193 Parcel out = Parcel.obtain();
2194 final int N = mSyncStatus.size();
2195 for (int i=0; i<N; i++) {
2196 SyncStatusInfo status = mSyncStatus.valueAt(i);
2197 out.writeInt(STATUS_FILE_ITEM);
2198 status.writeToParcel(out, 0);
2199 }
2200 out.writeInt(STATUS_FILE_END);
2201 fos.write(out.marshall());
2202 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002203
Dianne Hackborn231cc602009-04-27 17:10:36 -07002204 mStatusFile.finishWrite(fos);
2205 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002206 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002207 if (fos != null) {
2208 mStatusFile.failWrite(fos);
2209 }
2210 }
2211 }
Costin Manolache360e4542009-09-04 13:36:04 -07002212
Makoto Onuki61283ec2018-01-31 17:22:36 -08002213 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002214 @SyncExemption int syncExemptionFlag) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002215 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2216 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002217 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002218 syncExemptionFlag);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002219 } else {
2220 SyncRequest.Builder req =
2221 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002222 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002223 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002224 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002225 ContentResolver.requestSync(req.build());
2226 }
2227 }
2228
Alon Albert57286f92012-10-09 14:21:38 -07002229 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002230 Bundle extras, @SyncExemption int syncExemptionFlag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002231 // If this is happening in the system process, then call the syncrequest listener
2232 // to make a request back to the SyncManager directly.
2233 // If this is probably a test instance, then call back through the ContentResolver
2234 // which will know which userId to apply based on the Binder id.
2235 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2236 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002237 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002238 new EndPoint(account, authority, userId),
Makoto Onuki75ad2492018-03-28 14:42:42 -07002239 reason, extras, syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002240 } else {
2241 ContentResolver.requestSync(account, authority, extras);
2242 }
2243 }
2244
Dianne Hackborn231cc602009-04-27 17:10:36 -07002245 public static final int STATISTICS_FILE_END = 0;
2246 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2247 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002248
Dianne Hackborn231cc602009-04-27 17:10:36 -07002249 /**
2250 * Read all sync statistics back in to the initial engine state.
2251 */
2252 private void readStatisticsLocked() {
2253 try {
2254 byte[] data = mStatisticsFile.readFully();
2255 Parcel in = Parcel.obtain();
2256 in.unmarshall(data, 0, data.length);
2257 in.setDataPosition(0);
2258 int token;
2259 int index = 0;
2260 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2261 if (token == STATISTICS_FILE_ITEM
2262 || token == STATISTICS_FILE_ITEM_OLD) {
2263 int day = in.readInt();
2264 if (token == STATISTICS_FILE_ITEM_OLD) {
2265 day = day - 2009 + 14245; // Magic!
2266 }
2267 DayStats ds = new DayStats(day);
2268 ds.successCount = in.readInt();
2269 ds.successTime = in.readLong();
2270 ds.failureCount = in.readInt();
2271 ds.failureTime = in.readLong();
2272 if (index < mDayStats.length) {
2273 mDayStats[index] = ds;
2274 index++;
2275 }
2276 } else {
2277 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002278 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002279 break;
2280 }
2281 }
2282 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002283 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002284 }
2285 }
Costin Manolache360e4542009-09-04 13:36:04 -07002286
Dianne Hackborn231cc602009-04-27 17:10:36 -07002287 /**
2288 * Write all sync statistics to the sync status file.
2289 */
2290 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002291 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002292 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002293 }
Costin Manolache360e4542009-09-04 13:36:04 -07002294
Dianne Hackborn231cc602009-04-27 17:10:36 -07002295 // The file is being written, so we don't need to have a scheduled
2296 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002297 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002298
Dianne Hackborn231cc602009-04-27 17:10:36 -07002299 FileOutputStream fos = null;
2300 try {
2301 fos = mStatisticsFile.startWrite();
2302 Parcel out = Parcel.obtain();
2303 final int N = mDayStats.length;
2304 for (int i=0; i<N; i++) {
2305 DayStats ds = mDayStats[i];
2306 if (ds == null) {
2307 break;
2308 }
2309 out.writeInt(STATISTICS_FILE_ITEM);
2310 out.writeInt(ds.day);
2311 out.writeInt(ds.successCount);
2312 out.writeLong(ds.successTime);
2313 out.writeInt(ds.failureCount);
2314 out.writeLong(ds.failureTime);
2315 }
2316 out.writeInt(STATISTICS_FILE_END);
2317 fos.write(out.marshall());
2318 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002319
Dianne Hackborn231cc602009-04-27 17:10:36 -07002320 mStatisticsFile.finishWrite(fos);
2321 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002322 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002323 if (fos != null) {
2324 mStatisticsFile.failWrite(fos);
2325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002326 }
2327 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002328
2329 /**
Marvin Paula6533252014-11-24 12:57:48 -08002330 * Let the BackupManager know that account sync settings have changed. This will trigger
2331 * {@link com.android.server.backup.SystemBackupAgent} to run.
2332 */
2333 public void queueBackup() {
2334 BackupManager.dataChanged("android");
2335 }
Makoto Onuki94986212018-04-11 16:24:46 -07002336
2337 public void setClockValid() {
2338 if (!mIsClockValid) {
2339 mIsClockValid = true;
2340 Slog.w(TAG, "Clock is valid now.");
2341 }
2342 }
2343
2344 public boolean isClockValid() {
2345 return mIsClockValid;
2346 }
2347
2348 public void resetTodayStats(boolean force) {
2349 if (force) {
2350 Log.w(TAG, "Force resetting today stats.");
2351 }
2352 synchronized (mAuthorities) {
2353 final int N = mSyncStatus.size();
2354 for (int i = 0; i < N; i++) {
2355 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2356 cur.maybeResetTodayStats(isClockValid(), force);
2357 }
2358 writeStatusLocked();
2359 }
2360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002361}