blob: f54a9a0c006a37f7e646a45d4a3b8d4bb016a705 [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
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 /** String names for the sync source types. */
Makoto Onuki94986212018-04-11 16:24:46 -0700132 public static final String[] SOURCES = { "OTHER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000133 "LOCAL",
134 "POLL",
135 "USER",
136 "PERIODIC",
Makoto Onuki94986212018-04-11 16:24:46 -0700137 "FEED"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138
Dianne Hackborn231cc602009-04-27 17:10:36 -0700139 // The MESG column will contain one of these or one of the Error types.
140 public static final String MESG_SUCCESS = "success";
141 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700143 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700144
Dianne Hackborn231cc602009-04-27 17:10:36 -0700145 private static final int MSG_WRITE_STATUS = 1;
146 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700147
Dianne Hackborn231cc602009-04-27 17:10:36 -0700148 private static final int MSG_WRITE_STATISTICS = 2;
149 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700150
151 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700152
Fred Quintanac2e46912010-03-15 16:10:44 -0700153 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700154 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700155
156 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000157 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700158
Makoto Onuki94986212018-04-11 16:24:46 -0700159 private volatile boolean mIsClockValid;
160
Fred Quintanafb084402010-03-23 17:57:03 -0700161 static {
162 sAuthorityRenames = new HashMap<String, String>();
163 sAuthorityRenames.put("contacts", "com.android.contacts");
164 sAuthorityRenames.put("calendar", "com.android.calendar");
165 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700166
Dianne Hackborn231cc602009-04-27 17:10:36 -0700167 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800168 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700169 final HashMap<String, AuthorityInfo> authorities =
170 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700171
Amith Yamasani04e0d262012-02-14 11:50:53 -0800172 AccountInfo(AccountAndUser accountAndUser) {
173 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700174 }
175 }
Costin Manolache360e4542009-09-04 13:36:04 -0700176
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700177 /** Bare bones representation of a sync target. */
178 public static class EndPoint {
179 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
180 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700181 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800182 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700184
185 public EndPoint(Account account, String provider, int userId) {
186 this.account = account;
187 this.provider = provider;
188 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700189 }
190
191 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700192 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
193 *
194 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000195 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700196 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700197 public boolean matchesSpec(EndPoint spec) {
198 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700199 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700200 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700201 return false;
202 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000203 boolean accountsMatch;
204 if (spec.account == null) {
205 accountsMatch = true;
206 } else {
207 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000209 boolean providersMatch;
210 if (spec.provider == null) {
211 providersMatch = true;
212 } else {
213 providersMatch = provider.equals(spec.provider);
214 }
215 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700216 }
217
218 public String toString() {
219 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000220 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700221 .append("/")
222 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700223 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700224 return sb.toString();
225 }
226 }
227
228 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700229 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700230
231 /**
232 * The syncable state is undefined.
233 */
234 public static final int UNDEFINED = -2;
235
Matthew Williams53abfdb2015-06-10 20:06:37 -0700236 /**
237 * Default state for a newly installed adapter. An uninitialized adapter will receive an
238 * initialization sync which are governed by a different set of rules to that of regular
239 * syncs.
240 */
241 public static final int NOT_INITIALIZED = -1;
242 /**
243 * The adapter will not receive any syncs. This is behaviourally equivalent to
244 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
245 * while this is generally meant to be controlled by the developer.
246 */
247 public static final int NOT_SYNCABLE = 0;
248 /**
249 * The adapter is initialized and functioning. This is the normal state for an adapter.
250 */
251 public static final int SYNCABLE = 1;
252 /**
253 * The adapter is syncable but still requires an initialization sync. For example an adapter
254 * than has been restored from a previous device will be in this state. Not meant for
255 * external use.
256 */
257 public static final int SYNCABLE_NOT_INITIALIZED = 2;
258
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700259 /**
260 * The adapter is syncable but does not have access to the synced account and needs a
261 * user access approval.
262 */
263 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
264
Matthew Williams8ef22042013-07-26 12:56:39 -0700265 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700266 final int ident;
267 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700268 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700269 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800270 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800272 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700273 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800274 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275
Matthew Williamsfa774182013-06-18 15:44:11 -0700276 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700277
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700278 /**
279 * Copy constructor for making deep-ish copies. Only the bundles stored
280 * in periodic syncs can make unexpected changes.
281 *
282 * @param toCopy AuthorityInfo to be copied.
283 */
284 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700285 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700286 ident = toCopy.ident;
287 enabled = toCopy.enabled;
288 syncable = toCopy.syncable;
289 backoffTime = toCopy.backoffTime;
290 backoffDelay = toCopy.backoffDelay;
291 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700292 periodicSyncs = new ArrayList<PeriodicSync>();
293 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700294 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700295 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700296 }
297 }
298
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700299 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700300 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700301 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000302 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700303 periodicSyncs = new ArrayList<PeriodicSync>();
304 defaultInitialisation();
305 }
306
307 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700308 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800309 backoffTime = -1; // if < 0 then we aren't in backoff mode
310 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000311
312 if (mPeriodicSyncAddedListener != null) {
313 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
314 DEFAULT_POLL_FREQUENCY_SECONDS,
315 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700316 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700317 }
Matthew Williams06485a72013-07-26 12:56:39 -0700318
319 @Override
320 public String toString() {
321 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
322 + backoffTime + ", delay=" + delayUntil;
323 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700324 }
Costin Manolache360e4542009-09-04 13:36:04 -0700325
Dianne Hackborn231cc602009-04-27 17:10:36 -0700326 public static class SyncHistoryItem {
327 int authorityId;
328 int historyId;
329 long eventTime;
330 long elapsedTime;
331 int source;
332 int event;
333 long upstreamActivity;
334 long downstreamActivity;
335 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700336 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700337 Bundle extras;
338 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700339 }
Costin Manolache360e4542009-09-04 13:36:04 -0700340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 public static class DayStats {
342 public final int day;
343 public int successCount;
344 public long successTime;
345 public int failureCount;
346 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700347
Dianne Hackborn231cc602009-04-27 17:10:36 -0700348 public DayStats(int day) {
349 this.day = day;
350 }
351 }
Costin Manolache360e4542009-09-04 13:36:04 -0700352
Amith Yamasani04e0d262012-02-14 11:50:53 -0800353 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700354
355 /** Called when a sync is needed on an account(s) due to some change in state. */
Makoto Onuki61283ec2018-01-31 17:22:36 -0800356 public void onSyncRequest(EndPoint info, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -0700357 @SyncExemption int syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800358 }
359
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000360 interface PeriodicSyncAddedListener {
361 /** Called when a periodic sync is added. */
362 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
363 }
364
365 interface OnAuthorityRemovedListener {
366 /** Called when an authority is removed. */
367 void onAuthorityRemoved(EndPoint removedAuthority);
368 }
369
Suprabh Shukla042a4782017-05-12 15:26:54 -0700370 /**
371 * Validator that maintains a lazy cache of accounts and providers to tell if an authority or
372 * account is valid.
373 */
374 private static class AccountAuthorityValidator {
375 final private AccountManager mAccountManager;
376 final private PackageManager mPackageManager;
377 final private SparseArray<Account[]> mAccountsCache;
378 final private SparseArray<ArrayMap<String, Boolean>> mProvidersPerUserCache;
379
380 AccountAuthorityValidator(Context context) {
381 mAccountManager = context.getSystemService(AccountManager.class);
382 mPackageManager = context.getPackageManager();
383 mAccountsCache = new SparseArray<>();
384 mProvidersPerUserCache = new SparseArray<>();
385 }
386
387 // An account is valid if an installed authenticator has previously created that account
388 // on the device
389 boolean isAccountValid(Account account, int userId) {
390 Account[] accountsForUser = mAccountsCache.get(userId);
391 if (accountsForUser == null) {
392 accountsForUser = mAccountManager.getAccountsAsUser(userId);
393 mAccountsCache.put(userId, accountsForUser);
394 }
395 return ArrayUtils.contains(accountsForUser, account);
396 }
397
398 // An authority is only valid if it has a content provider installed on the system
399 boolean isAuthorityValid(String authority, int userId) {
400 ArrayMap<String, Boolean> authorityMap = mProvidersPerUserCache.get(userId);
401 if (authorityMap == null) {
402 authorityMap = new ArrayMap<>();
403 mProvidersPerUserCache.put(userId, authorityMap);
404 }
405 if (!authorityMap.containsKey(authority)) {
406 authorityMap.put(authority, mPackageManager.resolveContentProviderAsUser(authority,
407 PackageManager.MATCH_DIRECT_BOOT_AWARE
408 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userId) != null);
409 }
410 return authorityMap.get(authority);
411 }
412 }
413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 // Primary list of all syncable authorities. Also our global lock.
415 private final SparseArray<AuthorityInfo> mAuthorities =
416 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700417
Amith Yamasani04e0d262012-02-14 11:50:53 -0800418 private final HashMap<AccountAndUser, AccountInfo> mAccounts
419 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420
Amith Yamasani04e0d262012-02-14 11:50:53 -0800421 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
422 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 private final SparseArray<SyncStatusInfo> mSyncStatus =
425 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700426
Dianne Hackborn231cc602009-04-27 17:10:36 -0700427 private final ArrayList<SyncHistoryItem> mSyncHistory =
428 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700429
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
431 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700432
Matthew Williams8ef22042013-07-26 12:56:39 -0700433 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700434 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
435 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700436
Fred Quintana77c560f2010-03-29 22:20:26 -0700437 private int mNextAuthorityId = 0;
438
Dianne Hackborn231cc602009-04-27 17:10:36 -0700439 // We keep 4 weeks of stats.
440 private final DayStats[] mDayStats = new DayStats[7*4];
441 private final Calendar mCal;
442 private int mYear;
443 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700444
Dianne Hackborn231cc602009-04-27 17:10:36 -0700445 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800446
Dianne Hackborn231cc602009-04-27 17:10:36 -0700447 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700448
Ashish Sharma69d95de2012-04-11 17:27:24 -0700449 private int mSyncRandomOffset;
450
Dianne Hackborn231cc602009-04-27 17:10:36 -0700451 /**
452 * This file contains the core engine state: all accounts and the
453 * settings for them. It must never be lost, and should be changed
454 * infrequently, so it is stored as an XML file.
455 */
456 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700457
Dianne Hackborn231cc602009-04-27 17:10:36 -0700458 /**
459 * This file contains the current sync status. We would like to retain
460 * it across boots, but its loss is not the end of the world, so we store
461 * this information as binary data.
462 */
463 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700464
Dianne Hackborn231cc602009-04-27 17:10:36 -0700465 /**
466 * This file contains sync statistics. This is purely debugging information
467 * so is written infrequently and can be thrown away at any time.
468 */
469 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700470
Dianne Hackborn231cc602009-04-27 17:10:36 -0700471 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800472 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800473 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800474
475 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000476 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700477
Svet Ganov65712b02016-09-01 10:24:11 -0700478 private boolean mGrantSyncAdaptersAccountAccess;
479
Makoto Onuki6963bea72017-12-12 10:42:39 -0800480 private final MyHandler mHandler;
Makoto Onukid4764302018-03-30 17:32:57 -0700481 private final SyncLogger mLogger;
Makoto Onuki6963bea72017-12-12 10:42:39 -0800482
483 private SyncStorageEngine(Context context, File dataDir, Looper looper) {
484 mHandler = new MyHandler(looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800485 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 sSyncStorageEngine = this;
Makoto Onukid4764302018-03-30 17:32:57 -0700487 mLogger = SyncLogger.getInstance();
Costin Manolache360e4542009-09-04 13:36:04 -0700488
Dianne Hackborn231cc602009-04-27 17:10:36 -0700489 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700490
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800491 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000492 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800493
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 File systemDir = new File(dataDir, "system");
495 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800496 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700497
498 maybeDeleteLegacyPendingInfoLocked(syncDir);
499
Dianne Hackborne17b4452018-01-10 13:15:40 -0800500 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"), "sync-accounts");
501 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"), "sync-status");
502 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"), "sync-stats");
Costin Manolache360e4542009-09-04 13:36:04 -0700503
Dianne Hackborn231cc602009-04-27 17:10:36 -0700504 readAccountInfoLocked();
505 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700506 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700507 readAndDeleteLegacyAccountInfoLocked();
508 writeAccountInfoLocked();
509 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700510 writeStatisticsLocked();
Makoto Onukid4764302018-03-30 17:32:57 -0700511
512 if (mLogger.enabled()) {
513 final int size = mAuthorities.size();
514 mLogger.log("Loaded ", size, " items");
515 for (int i = 0; i < size; i++) {
516 mLogger.log(mAuthorities.valueAt(i));
517 }
518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 }
520
521 public static SyncStorageEngine newTestInstance(Context context) {
Makoto Onuki6963bea72017-12-12 10:42:39 -0800522 return new SyncStorageEngine(context, context.getFilesDir(), Looper.getMainLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800523 }
524
Makoto Onuki6963bea72017-12-12 10:42:39 -0800525 public static void init(Context context, Looper looper) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800527 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700529 File dataDir = Environment.getDataDirectory();
Makoto Onuki6963bea72017-12-12 10:42:39 -0800530 sSyncStorageEngine = new SyncStorageEngine(context, dataDir, looper);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800531 }
532
533 public static SyncStorageEngine getSingleton() {
534 if (sSyncStorageEngine == null) {
535 throw new IllegalStateException("not initialized");
536 }
537 return sSyncStorageEngine;
538 }
539
Amith Yamasani04e0d262012-02-14 11:50:53 -0800540 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
541 if (mSyncRequestListener == null) {
542 mSyncRequestListener = listener;
543 }
544 }
545
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000546 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
547 if (mAuthorityRemovedListener == null) {
548 mAuthorityRemovedListener = listener;
549 }
550 }
551
552 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
553 if (mPeriodicSyncAddedListener == null) {
554 mPeriodicSyncAddedListener = listener;
555 }
556 }
557
Makoto Onuki6963bea72017-12-12 10:42:39 -0800558 private class MyHandler extends Handler {
559 public MyHandler(Looper looper) {
560 super(looper);
561 }
562
563 @Override
564 public void handleMessage(Message msg) {
565 if (msg.what == MSG_WRITE_STATUS) {
566 synchronized (mAuthorities) {
567 writeStatusLocked();
568 }
569 } else if (msg.what == MSG_WRITE_STATISTICS) {
570 synchronized (mAuthorities) {
571 writeStatisticsLocked();
572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 }
574 }
575 }
Costin Manolache360e4542009-09-04 13:36:04 -0700576
Ashish Sharma69d95de2012-04-11 17:27:24 -0700577 public int getSyncRandomOffset() {
578 return mSyncRandomOffset;
579 }
580
Dianne Hackborn231cc602009-04-27 17:10:36 -0700581 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
582 synchronized (mAuthorities) {
583 mChangeListeners.register(callback, mask);
584 }
585 }
Costin Manolache360e4542009-09-04 13:36:04 -0700586
Dianne Hackborn231cc602009-04-27 17:10:36 -0700587 public void removeStatusChangeListener(ISyncStatusObserver callback) {
588 synchronized (mAuthorities) {
589 mChangeListeners.unregister(callback);
590 }
591 }
Costin Manolache360e4542009-09-04 13:36:04 -0700592
Matthew Williamsfa774182013-06-18 15:44:11 -0700593 /**
594 * Figure out a reasonable flex time for cases where none is provided (old api calls).
595 * @param syncTimeSeconds requested sync time from now.
596 * @return amount of seconds before syncTimeSeconds that the sync can occur.
597 * I.e.
598 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700599 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700600 */
601 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
602 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
603 // Small enough sync request time that we don't add flex time - developer probably
604 // wants to wait for an operation to occur before syncing so we honour the
605 // request time.
606 return 0L;
607 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
608 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
609 } else {
610 // Large enough sync request time that we cap the flex time.
611 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
612 }
613 }
614
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000615 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700616 ArrayList<ISyncStatusObserver> reports = null;
617 synchronized (mAuthorities) {
618 int i = mChangeListeners.beginBroadcast();
619 while (i > 0) {
620 i--;
621 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
622 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800623 continue;
624 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700625 if (reports == null) {
626 reports = new ArrayList<ISyncStatusObserver>(i);
627 }
628 reports.add(mChangeListeners.getBroadcastItem(i));
629 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700630 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700631 }
Costin Manolache360e4542009-09-04 13:36:04 -0700632
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700633 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000634 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700635 }
Costin Manolache360e4542009-09-04 13:36:04 -0700636
Dianne Hackborn231cc602009-04-27 17:10:36 -0700637 if (reports != null) {
638 int i = reports.size();
639 while (i > 0) {
640 i--;
641 try {
642 reports.get(i).onStatusChanged(which);
643 } catch (RemoteException e) {
644 // The remote callback list will take care of this for us.
645 }
646 }
647 }
648 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700649
Amith Yamasani04e0d262012-02-14 11:50:53 -0800650 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700651 synchronized (mAuthorities) {
652 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700653 AuthorityInfo authority = getAuthorityLocked(
654 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700655 "getSyncAutomatically");
656 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700657 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700658
Dianne Hackborn231cc602009-04-27 17:10:36 -0700659 int i = mAuthorities.size();
660 while (i > 0) {
661 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700662 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700663 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700664 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700665 return true;
666 }
667 }
668 return false;
669 }
670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
Amith Yamasani04e0d262012-02-14 11:50:53 -0800672 public void setSyncAutomatically(Account account, int userId, String providerName,
Makoto Onukid4764302018-03-30 17:32:57 -0700673 boolean sync, @SyncExemption int syncExemptionFlag, int callingUid) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700674 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000675 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800676 + ", user " + userId + " -> " + sync);
677 }
Makoto Onukid4764302018-03-30 17:32:57 -0700678 mLogger.log("Set sync auto account=", account,
679 " user=", userId,
680 " authority=", providerName,
681 " value=", Boolean.toString(sync),
682 " callingUid=", callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700683 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700684 AuthorityInfo authority =
685 getOrCreateAuthorityLocked(
686 new EndPoint(account, providerName, userId),
687 -1 /* ident */,
688 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700689 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000691 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800692 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700693 return;
694 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700695 // If the adapter was syncable but missing its initialization sync, set it to
696 // uninitialized now. This is to give it a chance to run any one-time initialization
697 // logic.
698 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
699 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
700 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700701 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700702 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700704
Fred Quintana77c560f2010-03-29 22:20:26 -0700705 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700706 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800707 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700708 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700709 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700710 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800711 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800712 }
713
Amith Yamasani04e0d262012-02-14 11:50:53 -0800714 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700715 synchronized (mAuthorities) {
716 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700717 AuthorityInfo authority = getAuthorityLocked(
718 new EndPoint(account, providerName, userId),
719 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700720 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700721 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700722 }
723 return authority.syncable;
724 }
725
726 int i = mAuthorities.size();
727 while (i > 0) {
728 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700729 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700730 if (authorityInfo.target != null
731 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700732 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700733 }
734 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700735 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700736 }
737 }
738
Makoto Onukid4764302018-03-30 17:32:57 -0700739 public void setIsSyncable(Account account, int userId, String providerName, int syncable,
740 int callingUid) {
741 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable,
742 callingUid);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700743 }
744
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700745 /**
746 * An enabled sync service and a syncable provider's adapter both get resolved to the same
747 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700748 * @param target target to set value for.
749 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700750 */
Makoto Onukid4764302018-03-30 17:32:57 -0700751 private void setSyncableStateForEndPoint(EndPoint target, int syncable, int callingUid) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700752 AuthorityInfo aInfo;
Makoto Onukid4764302018-03-30 17:32:57 -0700753 mLogger.log("Set syncable ", target, " value=", Integer.toString(syncable),
754 " callingUid=", callingUid);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700755 synchronized (mAuthorities) {
756 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700757 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
758 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700759 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700760 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000761 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700762 }
763 if (aInfo.syncable == syncable) {
764 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000765 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700766 }
767 return;
768 }
769 aInfo.syncable = syncable;
770 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700771 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700772 if (syncable == AuthorityInfo.SYNCABLE) {
Makoto Onuki61283ec2018-01-31 17:22:36 -0800773 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700774 ContentResolver.SYNC_EXEMPTION_NONE);
Fred Quintana5e787c42009-08-16 23:13:53 -0700775 }
776 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
777 }
778
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700779 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800780 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700781 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
782 if (authority != null) {
783 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800784 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700785 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800786 }
787 }
788
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700789 /**
790 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
791 * the account or provider info be null, which signifies all accounts or providers.
792 */
793 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
794 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000795 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800796 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
797 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000800 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700801 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000802 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700803 changed = setBackoffLocked(
804 info.account /* may be null */,
805 info.userId,
806 info.provider /* may be null */,
807 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800808 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700809 AuthorityInfo authorityInfo =
810 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
811 if (authorityInfo.backoffTime == nextSyncTime
812 && authorityInfo.backoffDelay == nextDelay) {
813 changed = false;
814 } else {
815 authorityInfo.backoffTime = nextSyncTime;
816 authorityInfo.backoffDelay = nextDelay;
817 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800818 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800819 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800820 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800821 if (changed) {
822 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
823 }
824 }
825
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700826 /**
827 * Either set backoff for a specific authority, or set backoff for all the
828 * accounts on a specific adapter/all adapters.
829 *
830 * @param account account for which to set backoff. Null to specify all accounts.
831 * @param userId id of the user making this request.
832 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700833 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700834 */
835 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000836 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700837 boolean changed = false;
838 for (AccountInfo accountInfo : mAccounts.values()) {
839 if (account != null && !account.equals(accountInfo.accountAndUser.account)
840 && userId != accountInfo.accountAndUser.userId) {
841 continue;
842 }
843 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
844 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700845 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700846 continue;
847 }
848 if (authorityInfo.backoffTime != nextSyncTime
849 || authorityInfo.backoffDelay != nextDelay) {
850 authorityInfo.backoffTime = nextSyncTime;
851 authorityInfo.backoffDelay = nextDelay;
852 changed = true;
853 }
854 }
855 }
856 return changed;
857 }
858
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000859 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800860 boolean changed = false;
861 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000862 // Clear backoff for all sync adapters.
863 for (AccountInfo accountInfo : mAccounts.values()) {
864 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
865 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
866 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
867 if (Log.isLoggable(TAG, Log.VERBOSE)) {
868 Slog.v(TAG, "clearAllBackoffsLocked:"
869 + " authority:" + authorityInfo.target
870 + " account:" + accountInfo.accountAndUser.account.name
871 + " user:" + accountInfo.accountAndUser.userId
872 + " backoffTime was: " + authorityInfo.backoffTime
873 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800874 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000875 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
876 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
877 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800878 }
879 }
880 }
881 }
882
883 if (changed) {
884 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
885 }
886 }
887
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700888 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800889 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700890 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800891 if (authority == null) {
892 return 0;
893 }
894 return authority.delayUntil;
895 }
896 }
897
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700898 public void setDelayUntilTime(EndPoint info, long delayUntil) {
899 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000900 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700901 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800902 }
903 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700904 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
905 if (authority.delayUntil == delayUntil) {
906 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700907 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700908 authority.delayUntil = delayUntil;
909 }
910 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
911 }
912
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700913 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000914 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
915 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700916 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000917 boolean restoreAllPeriodicSyncs() {
918 if (mPeriodicSyncAddedListener == null) {
919 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800920 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000921 synchronized (mAuthorities) {
922 for (int i=0; i<mAuthorities.size(); i++) {
923 AuthorityInfo authority = mAuthorities.valueAt(i);
924 for (PeriodicSync periodicSync: authority.periodicSyncs) {
925 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
926 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
927 }
928 authority.periodicSyncs.clear();
929 }
930 writeAccountInfoLocked();
931 }
932 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800933 }
934
Makoto Onuki75ad2492018-03-28 14:42:42 -0700935 public void setMasterSyncAutomatically(boolean flag, int userId,
Makoto Onukid4764302018-03-30 17:32:57 -0700936 @SyncExemption int syncExemptionFlag, int callingUid) {
937 mLogger.log("Set master enabled=", flag, " user=", userId,
938 " caller=" + callingUid);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700939 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800940 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700941 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700942 return;
943 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800944 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700945 writeAccountInfoLocked();
946 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700947 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700948 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
Makoto Onuki61283ec2018-01-31 17:22:36 -0800949 new Bundle(),
Makoto Onuki75ad2492018-03-28 14:42:42 -0700950 syncExemptionFlag);
Joe Onorato8294fad2009-07-15 16:08:44 -0700951 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700952 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800953 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800954 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956
Amith Yamasani04e0d262012-02-14 11:50:53 -0800957 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800959 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800960 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 }
962 }
Costin Manolache360e4542009-09-04 13:36:04 -0700963
Makoto Onukib47e8942017-09-18 14:03:03 -0700964 public int getAuthorityCount() {
965 synchronized (mAuthorities) {
966 return mAuthorities.size();
967 }
968 }
969
Dianne Hackborn231cc602009-04-27 17:10:36 -0700970 public AuthorityInfo getAuthority(int authorityId) {
971 synchronized (mAuthorities) {
972 return mAuthorities.get(authorityId);
973 }
974 }
Costin Manolache360e4542009-09-04 13:36:04 -0700975
Dianne Hackborn231cc602009-04-27 17:10:36 -0700976 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700977 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700978 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700979 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700980 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700981 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700982 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700983 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700984 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700985 return true;
986 }
987 }
988 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700989 return false;
990 }
Costin Manolache360e4542009-09-04 13:36:04 -0700991
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000992 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700993 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000994 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
995 -1 /* desired identifier */,
996 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700997 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000998 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001001 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001002 }
Fred Quintanaac9385e2009-06-22 18:00:59 -07001003 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001004 }
Costin Manolache360e4542009-09-04 13:36:04 -07001005
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 /**
1007 * Called when the set of account has changed, given the new array of
1008 * active accounts.
1009 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001010 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -07001012 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001013 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -07001014 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001015 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
1016 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
1017 while (accIt.hasNext()) {
1018 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -08001019 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
1020 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001022 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001023 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -07001024 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 for (AuthorityInfo auth : acc.authorities.values()) {
1026 removing.put(auth.ident, auth);
1027 }
1028 accIt.remove();
1029 }
1030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 // Clean out all data structures.
1033 int i = removing.size();
1034 if (i > 0) {
1035 while (i > 0) {
1036 i--;
1037 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001038 AuthorityInfo auth = removing.valueAt(i);
1039 if (mAuthorityRemovedListener != null) {
1040 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
1041 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 mAuthorities.remove(ident);
1043 int j = mSyncStatus.size();
1044 while (j > 0) {
1045 j--;
1046 if (mSyncStatus.keyAt(j) == ident) {
1047 mSyncStatus.remove(mSyncStatus.keyAt(j));
1048 }
1049 }
1050 j = mSyncHistory.size();
1051 while (j > 0) {
1052 j--;
1053 if (mSyncHistory.get(j).authorityId == ident) {
1054 mSyncHistory.remove(j);
1055 }
1056 }
1057 }
1058 writeAccountInfoLocked();
1059 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 writeStatisticsLocked();
1061 }
1062 }
1063 }
1064
1065 /**
Fred Quintana918339a2010-10-05 14:00:39 -07001066 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
1067 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 */
Fred Quintana918339a2010-10-05 14:00:39 -07001069 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
1070 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001071 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001072 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001073 Slog.v(TAG, "setActiveSync: account="
1074 + " auth=" + activeSyncContext.mSyncOperation.target
1075 + " src=" + activeSyncContext.mSyncOperation.syncSource
1076 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001077 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001078 final EndPoint info = activeSyncContext.mSyncOperation.target;
1079 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
1080 info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001081 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -07001082 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001083 syncInfo = new SyncInfo(
1084 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -07001085 authorityInfo.target.account,
1086 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -07001087 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -07001088 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001089 }
Fred Quintana918339a2010-10-05 14:00:39 -07001090 reportActiveChange();
1091 return syncInfo;
1092 }
1093
1094 /**
1095 * Called to indicate that a previously active sync is no longer active.
1096 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001097 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001098 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001099 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001100 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -08001101 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001102 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001103 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001104 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001105 }
1106
1107 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 }
1109
1110 /**
1111 * To allow others to send active change reports, to poke clients.
1112 */
1113 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001114 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001115 }
Costin Manolache360e4542009-09-04 13:36:04 -07001116
Dianne Hackborn231cc602009-04-27 17:10:36 -07001117 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001118 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001119 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001120 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001121 long id;
1122 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001123 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001124 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001125 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001126 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 if (authority == null) {
1128 return -1;
1129 }
1130 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001131 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001132 item.authorityId = authority.ident;
1133 item.historyId = mNextHistoryId++;
1134 if (mNextHistoryId < 0) mNextHistoryId = 0;
1135 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001136 item.source = op.syncSource;
1137 item.reason = op.reason;
1138 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 item.event = EVENT_START;
1140 mSyncHistory.add(0, item);
1141 while (mSyncHistory.size() > MAX_HISTORY) {
1142 mSyncHistory.remove(mSyncHistory.size()-1);
1143 }
1144 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001145 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001146 }
Costin Manolache360e4542009-09-04 13:36:04 -07001147
Fred Quintanaac9385e2009-06-22 18:00:59 -07001148 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 }
1151
Fred Quintana77c560f2010-03-29 22:20:26 -07001152 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001153 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001154 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001155 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001156 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001157 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001158 SyncHistoryItem item = null;
1159 int i = mSyncHistory.size();
1160 while (i > 0) {
1161 i--;
1162 item = mSyncHistory.get(i);
1163 if (item.historyId == historyId) {
1164 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
Costin Manolache360e4542009-09-04 13:36:04 -07001168
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001170 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001171 return;
1172 }
Costin Manolache360e4542009-09-04 13:36:04 -07001173
Dianne Hackborn231cc602009-04-27 17:10:36 -07001174 item.elapsedTime = elapsedTime;
1175 item.event = EVENT_STOP;
1176 item.mesg = resultMessage;
1177 item.downstreamActivity = downstreamActivity;
1178 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001179
Dianne Hackborn231cc602009-04-27 17:10:36 -07001180 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001181
Makoto Onuki94986212018-04-11 16:24:46 -07001182 status.maybeResetTodayStats(isClockValid(), /*force=*/ false);
1183
1184 status.totalStats.numSyncs++;
1185 status.todayStats.numSyncs++;
1186 status.totalStats.totalElapsedTime += elapsedTime;
1187 status.todayStats.totalElapsedTime += elapsedTime;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001188 switch (item.source) {
1189 case SOURCE_LOCAL:
Makoto Onuki94986212018-04-11 16:24:46 -07001190 status.totalStats.numSourceLocal++;
1191 status.todayStats.numSourceLocal++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001192 break;
1193 case SOURCE_POLL:
Makoto Onuki94986212018-04-11 16:24:46 -07001194 status.totalStats.numSourcePoll++;
1195 status.todayStats.numSourcePoll++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001196 break;
1197 case SOURCE_USER:
Makoto Onuki94986212018-04-11 16:24:46 -07001198 status.totalStats.numSourceUser++;
1199 status.todayStats.numSourceUser++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001200 break;
Makoto Onuki94986212018-04-11 16:24:46 -07001201 case SOURCE_OTHER:
1202 status.totalStats.numSourceOther++;
1203 status.todayStats.numSourceOther++;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001204 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001205 case SOURCE_PERIODIC:
Makoto Onuki94986212018-04-11 16:24:46 -07001206 status.totalStats.numSourcePeriodic++;
1207 status.todayStats.numSourcePeriodic++;
1208 break;
1209 case SOURCE_FEED:
1210 status.totalStats.numSourceFeed++;
1211 status.todayStats.numSourceFeed++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001212 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001213 }
Costin Manolache360e4542009-09-04 13:36:04 -07001214
Dianne Hackborn231cc602009-04-27 17:10:36 -07001215 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001216 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 if (mDayStats[0] == null) {
1218 mDayStats[0] = new DayStats(day);
1219 } else if (day != mDayStats[0].day) {
1220 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1221 mDayStats[0] = new DayStats(day);
1222 writeStatisticsNow = true;
1223 } else if (mDayStats[0] == null) {
1224 }
1225 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001226
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 final long lastSyncTime = (item.eventTime + elapsedTime);
1228 boolean writeStatusNow = false;
1229 if (MESG_SUCCESS.equals(resultMessage)) {
1230 // - if successful, update the successful columns
1231 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1232 writeStatusNow = true;
1233 }
1234 status.lastSuccessTime = lastSyncTime;
1235 status.lastSuccessSource = item.source;
1236 status.lastFailureTime = 0;
1237 status.lastFailureSource = -1;
1238 status.lastFailureMesg = null;
1239 status.initialFailureTime = 0;
1240 ds.successCount++;
1241 ds.successTime += elapsedTime;
1242 } else if (!MESG_CANCELED.equals(resultMessage)) {
1243 if (status.lastFailureTime == 0) {
1244 writeStatusNow = true;
1245 }
Makoto Onuki94986212018-04-11 16:24:46 -07001246 status.totalStats.numFailures++;
1247 status.todayStats.numFailures++;
1248
Dianne Hackborn231cc602009-04-27 17:10:36 -07001249 status.lastFailureTime = lastSyncTime;
1250 status.lastFailureSource = item.source;
1251 status.lastFailureMesg = resultMessage;
1252 if (status.initialFailureTime == 0) {
1253 status.initialFailureTime = lastSyncTime;
1254 }
1255 ds.failureCount++;
1256 ds.failureTime += elapsedTime;
Makoto Onuki94986212018-04-11 16:24:46 -07001257 } else {
1258 // Cancel
1259 status.totalStats.numCancels++;
1260 status.todayStats.numCancels++;
1261 writeStatusNow = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001262 }
Makoto Onuki15e7a252017-06-08 17:12:05 -07001263 final StringBuilder event = new StringBuilder();
1264 event.append("" + resultMessage + " Source=" + SyncStorageEngine.SOURCES[item.source]
1265 + " Elapsed=");
1266 SyncManager.formatDurationHMS(event, elapsedTime);
1267 event.append(" Reason=");
1268 event.append(SyncOperation.reasonToString(null, item.reason));
1269 event.append(" Extras=");
1270 SyncOperation.extrasToStringBuilder(item.extras, event);
1271
1272 status.addEvent(event.toString());
Costin Manolache360e4542009-09-04 13:36:04 -07001273
Dianne Hackborn231cc602009-04-27 17:10:36 -07001274 if (writeStatusNow) {
1275 writeStatusLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001276 } else if (!mHandler.hasMessages(MSG_WRITE_STATUS)) {
1277 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATUS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001278 WRITE_STATUS_DELAY);
1279 }
1280 if (writeStatisticsNow) {
1281 writeStatisticsLocked();
Makoto Onuki6963bea72017-12-12 10:42:39 -08001282 } else if (!mHandler.hasMessages(MSG_WRITE_STATISTICS)) {
1283 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_WRITE_STATISTICS),
Dianne Hackborn231cc602009-04-27 17:10:36 -07001284 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001285 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 }
Costin Manolache360e4542009-09-04 13:36:04 -07001287
Fred Quintanaac9385e2009-06-22 18:00:59 -07001288 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001289 }
1290
1291 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001292 * Return a list of the currently active syncs. Note that the returned
1293 * items are the real, live active sync objects, so be careful what you do
1294 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001295 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001296 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001297 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001298 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001299 }
1300 }
Costin Manolache360e4542009-09-04 13:36:04 -07001301
Dianne Hackborn231cc602009-04-27 17:10:36 -07001302 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001303 * @param userId Id of user to return current sync info.
1304 * @param canAccessAccounts Determines whether to redact Account information from the result.
1305 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001306 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001307 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001308 synchronized (mAuthorities) {
1309 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1310 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1311 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001312 SyncInfo copy;
1313 if (!canAccessAccounts) {
1314 copy = SyncInfo.createAccountRedacted(
1315 sync.authorityId, sync.authority, sync.startTime);
1316 } else {
1317 copy = new SyncInfo(sync);
1318 }
1319 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001320 }
1321 return syncsCopy;
1322 }
1323 }
1324
1325 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1326 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1327 if (syncs == null) {
1328 syncs = new ArrayList<SyncInfo>();
1329 mCurrentSyncs.put(userId, syncs);
1330 }
1331 return syncs;
1332 }
1333
1334 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001335 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001336 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001337 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001338 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001339 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001340 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001341 true /* write to storage if this results in a change */);
1342 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1343 }
1344 }
1345
1346 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001347 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001348 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001349 * @param info the endpoint target we are querying status info for.
1350 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001351 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001352 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001353 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001354 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001355 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001357 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001358 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001359 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001361 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001362 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001363 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 }
1365 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001366 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001367 }
1368 }
Costin Manolache360e4542009-09-04 13:36:04 -07001369
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001370 /** Return true if the pending status is true of any matching authorities. */
1371 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001372 synchronized (mAuthorities) {
1373 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001374 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001375 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001376 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1377 if (ainfo == null) {
1378 continue;
1379 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001380 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 continue;
1382 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001383 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001384 return true;
1385 }
1386 }
1387 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388 }
1389 }
1390
1391 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001392 * Return an array of the current sync status for all authorities. Note
1393 * that the objects inside the array are the real, live status objects,
1394 * so be careful what you do with them.
1395 */
1396 public ArrayList<SyncHistoryItem> getSyncHistory() {
1397 synchronized (mAuthorities) {
1398 final int N = mSyncHistory.size();
1399 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1400 for (int i=0; i<N; i++) {
1401 items.add(mSyncHistory.get(i));
1402 }
1403 return items;
1404 }
1405 }
Costin Manolache360e4542009-09-04 13:36:04 -07001406
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 /**
1408 * Return an array of the current per-day statistics. Note
1409 * that the objects inside the array are the real, live status objects,
1410 * so be careful what you do with them.
1411 */
1412 public DayStats[] getDayStatistics() {
1413 synchronized (mAuthorities) {
1414 DayStats[] ds = new DayStats[mDayStats.length];
1415 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1416 return ds;
1417 }
1418 }
Costin Manolache360e4542009-09-04 13:36:04 -07001419
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001420 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1421 AuthorityInfo authorityInfo) {
1422 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1423 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1424 }
1425
Dianne Hackborn55280a92009-05-07 15:53:46 -07001426 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001427 mCal.setTimeInMillis(System.currentTimeMillis());
1428 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1429 if (mYear != mCal.get(Calendar.YEAR)) {
1430 mYear = mCal.get(Calendar.YEAR);
1431 mCal.clear();
1432 mCal.set(Calendar.YEAR, mYear);
1433 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1434 }
1435 return dayOfYear + mYearInDays;
1436 }
Costin Manolache360e4542009-09-04 13:36:04 -07001437
Dianne Hackborn231cc602009-04-27 17:10:36 -07001438 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001439 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001440 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001441 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001442 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001443 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001444 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001445 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001446 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1447 AccountInfo accountInfo = mAccounts.get(au);
1448 if (accountInfo == null) {
1449 if (tag != null) {
1450 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1451 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001452 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001453 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 return null;
1455 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001456 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1457 if (authority == null) {
1458 if (tag != null) {
1459 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1460 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1461 }
1462 }
1463 return null;
1464 }
1465 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001466 }
Costin Manolache360e4542009-09-04 13:36:04 -07001467
Matthew Williamsfa774182013-06-18 15:44:11 -07001468 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001469 * @param info info identifying target.
1470 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001471 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001472 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001473 * exists.
1474 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001475 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1476 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001477 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1478 AccountInfo account = mAccounts.get(au);
1479 if (account == null) {
1480 account = new AccountInfo(au);
1481 mAccounts.put(au, account);
1482 }
1483 authority = account.authorities.get(info.provider);
1484 if (authority == null) {
1485 authority = createAuthorityLocked(info, ident, doWrite);
1486 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001487 }
1488 return authority;
1489 }
1490
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001491 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1492 AuthorityInfo authority;
1493 if (ident < 0) {
1494 ident = mNextAuthorityId;
1495 mNextAuthorityId++;
1496 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001497 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001498 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001499 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001500 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001501 authority = new AuthorityInfo(info, ident);
1502 mAuthorities.put(ident, authority);
1503 if (doWrite) {
1504 writeAccountInfoLocked();
1505 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001506 return authority;
1507 }
Costin Manolache360e4542009-09-04 13:36:04 -07001508
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001509 public void removeAuthority(EndPoint info) {
1510 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001511 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001512 }
1513 }
1514
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001515
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001516 /**
1517 * Remove an authority associated with a provider. Needs to be a standalone function for
1518 * backward compatibility.
1519 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001520 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001521 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001522 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001523 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001524 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1525 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001526 if (mAuthorityRemovedListener != null) {
1527 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1528 }
Fred Quintanafb084402010-03-23 17:57:03 -07001529 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001530 if (doWrite) {
1531 writeAccountInfoLocked();
1532 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001533 }
1534 }
1535 }
1536
Dianne Hackborn231cc602009-04-27 17:10:36 -07001537 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1538 SyncStatusInfo status = mSyncStatus.get(authorityId);
1539 if (status == null) {
1540 status = new SyncStatusInfo(authorityId);
1541 mSyncStatus.put(authorityId, status);
1542 }
1543 return status;
1544 }
Costin Manolache360e4542009-09-04 13:36:04 -07001545
Dianne Hackborn55280a92009-05-07 15:53:46 -07001546 public void writeAllState() {
1547 synchronized (mAuthorities) {
1548 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001549 writeStatusLocked();
1550 writeStatisticsLocked();
1551 }
1552 }
Costin Manolache360e4542009-09-04 13:36:04 -07001553
Svet Ganov65712b02016-09-01 10:24:11 -07001554 public boolean shouldGrantSyncAdaptersAccountAccess() {
1555 return mGrantSyncAdaptersAccountAccess;
1556 }
1557
Dianne Hackborn231cc602009-04-27 17:10:36 -07001558 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001559 * public for testing
1560 */
1561 public void clearAndReadState() {
1562 synchronized (mAuthorities) {
1563 mAuthorities.clear();
1564 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001565 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001566 mSyncStatus.clear();
1567 mSyncHistory.clear();
1568
1569 readAccountInfoLocked();
1570 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001571 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001572 readAndDeleteLegacyAccountInfoLocked();
1573 writeAccountInfoLocked();
1574 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001575 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001576 }
1577 }
1578
1579 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001580 * Read all account information back in to the initial engine state.
1581 */
1582 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001583 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001584 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001586 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001587 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001588 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001589 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001590 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001591 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001592 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001593 while (eventType != XmlPullParser.START_TAG &&
1594 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001595 eventType = parser.next();
1596 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001597 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001598 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001599 return;
1600 }
1601
Dianne Hackborn231cc602009-04-27 17:10:36 -07001602 String tagName = parser.getName();
1603 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001604 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001605 String versionString = parser.getAttributeValue(null, "version");
1606 int version;
1607 try {
1608 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1609 } catch (NumberFormatException e) {
1610 version = 0;
1611 }
Svet Ganov65712b02016-09-01 10:24:11 -07001612
1613 if (version < 3) {
1614 mGrantSyncAdaptersAccountAccess = true;
1615 }
1616
Amith Yamasani04e0d262012-02-14 11:50:53 -08001617 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001618 try {
1619 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1620 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1621 } catch (NumberFormatException e) {
1622 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001623 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001624 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1625 try {
1626 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1627 } catch (NumberFormatException e) {
1628 mSyncRandomOffset = 0;
1629 }
1630 if (mSyncRandomOffset == 0) {
1631 Random random = new Random(System.currentTimeMillis());
1632 mSyncRandomOffset = random.nextInt(86400);
1633 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001634 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001635 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001636 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001637 PeriodicSync periodicSync = null;
Suprabh Shukla042a4782017-05-12 15:26:54 -07001638 AccountAuthorityValidator validator = new AccountAuthorityValidator(mContext);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001639 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001641 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001642 if (parser.getDepth() == 2) {
1643 if ("authority".equals(tagName)) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001644 authority = parseAuthority(parser, version, validator);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001645 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001646 if (authority != null) {
1647 if (authority.ident > highestAuthorityId) {
1648 highestAuthorityId = authority.ident;
1649 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001650 } else {
1651 EventLog.writeEvent(0x534e4554, "26513719", -1,
1652 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001653 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001654 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1655 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001656 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001657 } else if (parser.getDepth() == 3) {
1658 if ("periodicSync".equals(tagName) && authority != null) {
1659 periodicSync = parsePeriodicSync(parser, authority);
1660 }
1661 } else if (parser.getDepth() == 4 && periodicSync != null) {
1662 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001663 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001664 }
1665 }
1666 }
1667 eventType = parser.next();
1668 } while (eventType != XmlPullParser.END_DOCUMENT);
1669 }
1670 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001671 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001672 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001673 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001674 if (fis == null) Slog.i(TAG, "No initial accounts");
1675 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001676 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001677 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001678 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001679 if (fis != null) {
1680 try {
1681 fis.close();
1682 } catch (java.io.IOException e1) {
1683 }
1684 }
1685 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001686
Fred Quintana77c560f2010-03-29 22:20:26 -07001687 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001688 }
Costin Manolache360e4542009-09-04 13:36:04 -07001689
Fred Quintanafb084402010-03-23 17:57:03 -07001690 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001691 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1692 * pending.xml was used starting in KLP.
1693 * @param syncDir directory where the sync files are located.
1694 */
1695 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1696 File file = new File(syncDir, "pending.bin");
1697 if (!file.exists()) {
1698 return;
1699 } else {
1700 file.delete();
1701 }
1702 }
1703
1704 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001705 * some authority names have changed. copy over their settings and delete the old ones
1706 * @return true if a change was made
1707 */
1708 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1709 boolean writeNeeded = false;
1710
1711 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1712 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001713 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001714 AuthorityInfo authority = mAuthorities.valueAt(i);
1715 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001716 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001717 if (newAuthorityName == null) {
1718 continue;
1719 }
1720
1721 // remember this authority so we can remove it later. we can't remove it
1722 // now without messing up this loop iteration
1723 authoritiesToRemove.add(authority);
1724
1725 // this authority isn't enabled, no need to copy it to the new authority name since
1726 // the default is "disabled"
1727 if (!authority.enabled) {
1728 continue;
1729 }
1730
1731 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001732 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001733 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001734 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001735 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001736 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001737 continue;
1738 }
1739
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001740 AuthorityInfo newAuthority =
1741 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001742 newAuthority.enabled = true;
1743 writeNeeded = true;
1744 }
1745
1746 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001747 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001748 authorityInfo.target.account,
1749 authorityInfo.target.userId,
1750 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001751 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001752 writeNeeded = true;
1753 }
1754
1755 return writeNeeded;
1756 }
1757
Amith Yamasani04e0d262012-02-14 11:50:53 -08001758 private void parseListenForTickles(XmlPullParser parser) {
1759 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1760 int userId = 0;
1761 try {
1762 userId = Integer.parseInt(user);
1763 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001764 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001765 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001766 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001767 }
1768 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1769 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1770 mMasterSyncAutomatically.put(userId, listen);
1771 }
1772
Suprabh Shukla042a4782017-05-12 15:26:54 -07001773 private AuthorityInfo parseAuthority(XmlPullParser parser, int version,
1774 AccountAuthorityValidator validator) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001775 AuthorityInfo authority = null;
1776 int id = -1;
1777 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001778 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001779 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001780 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001781 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001782 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001783 }
1784 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001785 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001787 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001788 String accountName = parser.getAttributeValue(null, "account");
1789 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001790 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001791 String packageName = parser.getAttributeValue(null, "package");
1792 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001793 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001794 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001795 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001796 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001797 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001798 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001799 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001800 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001801 + " account=" + accountName
1802 + " accountType=" + accountType
1803 + " auth=" + authorityName
1804 + " package=" + packageName
1805 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001806 + " user=" + userId
1807 + " enabled=" + enabled
1808 + " syncable=" + syncable);
1809 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001810 if (authority == null) {
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, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001813 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001814 if (accountName != null && authorityName != null) {
Suprabh Shukla042a4782017-05-12 15:26:54 -07001815 EndPoint info = new EndPoint(
Matthew Williams8ef22042013-07-26 12:56:39 -07001816 new Account(accountName, accountType),
1817 authorityName, userId);
Suprabh Shukla042a4782017-05-12 15:26:54 -07001818 if (validator.isAccountValid(info.account, userId)
1819 && validator.isAuthorityValid(authorityName, userId)) {
1820 authority = getOrCreateAuthorityLocked(info, id, false);
1821 // If the version is 0 then we are upgrading from a file format that did not
1822 // know about periodic syncs. In that case don't clear the list since we
1823 // want the default, which is a daily periodic sync.
1824 // Otherwise clear out this default list since we will populate it later
1825 // with
1826 // the periodic sync descriptions that are read from the configuration file.
1827 if (version > 0) {
1828 authority.periodicSyncs.clear();
1829 }
1830 } else {
1831 EventLog.writeEvent(0x534e4554, "35028827", -1,
1832 "account:" + info.account + " provider:" + authorityName + " user:"
1833 + userId);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001834 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001835 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001836 }
1837 if (authority != null) {
1838 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001839 try {
1840 authority.syncable = (syncable == null) ?
1841 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1842 } catch (NumberFormatException e) {
1843 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1844 // format.
1845 if ("unknown".equals(syncable)) {
1846 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1847 } else {
1848 authority.syncable = Boolean.parseBoolean(syncable) ?
1849 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1850 }
1851
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001852 }
1853 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001854 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001855 + accountName + " auth=" + authorityName
1856 + " enabled=" + enabled
1857 + " syncable=" + syncable);
1858 }
1859 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001860 return authority;
1861 }
1862
Matthew Williamsfa774182013-06-18 15:44:11 -07001863 /**
1864 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1865 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001866 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001867 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001868 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001869 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001870 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001871 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001872 try {
1873 period = Long.parseLong(periodValue);
1874 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001875 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001876 return null;
1877 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001878 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001879 return null;
1880 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001881 try {
1882 flextime = Long.parseLong(flexValue);
1883 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001884 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001885 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001886 + ", using default: "
1887 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001888 } catch (NullPointerException expected) {
1889 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001890 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1891 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001892 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001893 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001894 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001895 new PeriodicSync(authorityInfo.target.account,
1896 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001897 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001898 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001899 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001900 return periodicSync;
1901 }
1902
Matthew Williamsfa774182013-06-18 15:44:11 -07001903 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001904 String name = parser.getAttributeValue(null, "name");
1905 String type = parser.getAttributeValue(null, "type");
1906 String value1 = parser.getAttributeValue(null, "value1");
1907 String value2 = parser.getAttributeValue(null, "value2");
1908
1909 try {
1910 if ("long".equals(type)) {
1911 extras.putLong(name, Long.parseLong(value1));
1912 } else if ("integer".equals(type)) {
1913 extras.putInt(name, Integer.parseInt(value1));
1914 } else if ("double".equals(type)) {
1915 extras.putDouble(name, Double.parseDouble(value1));
1916 } else if ("float".equals(type)) {
1917 extras.putFloat(name, Float.parseFloat(value1));
1918 } else if ("boolean".equals(type)) {
1919 extras.putBoolean(name, Boolean.parseBoolean(value1));
1920 } else if ("string".equals(type)) {
1921 extras.putString(name, value1);
1922 } else if ("account".equals(type)) {
1923 extras.putParcelable(name, new Account(value1, value2));
1924 }
1925 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001926 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001927 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001928 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001929 }
1930 }
1931
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 /**
1933 * Write all account information to the account file.
1934 */
1935 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001936 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001937 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001938 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001940
Dianne Hackborn231cc602009-04-27 17:10:36 -07001941 try {
1942 fos = mAccountInfoFile.startWrite();
1943 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001944 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001945 out.startDocument(null, true);
1946 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001947
Dianne Hackborn231cc602009-04-27 17:10:36 -07001948 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001949 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001950 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001951 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001952
1953 // Write the Sync Automatically flags for each user
1954 final int M = mMasterSyncAutomatically.size();
1955 for (int m = 0; m < M; m++) {
1956 int userId = mMasterSyncAutomatically.keyAt(m);
1957 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1958 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1959 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1960 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1961 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 }
Costin Manolache360e4542009-09-04 13:36:04 -07001963
Dianne Hackborn231cc602009-04-27 17:10:36 -07001964 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001965 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001966 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001967 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 out.startTag(null, "authority");
1969 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001970 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001971 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001972 out.attribute(null, "account", info.account.name);
1973 out.attribute(null, "type", info.account.type);
1974 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001975 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 out.endTag(null, "authority");
1977 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001978 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001979 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001980 mAccountInfoFile.finishWrite(fos);
1981 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001982 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 if (fos != null) {
1984 mAccountInfoFile.failWrite(fos);
1985 }
1986 }
1987 }
Costin Manolache360e4542009-09-04 13:36:04 -07001988
Dianne Hackborn231cc602009-04-27 17:10:36 -07001989 static int getIntColumn(Cursor c, String name) {
1990 return c.getInt(c.getColumnIndex(name));
1991 }
Costin Manolache360e4542009-09-04 13:36:04 -07001992
Dianne Hackborn231cc602009-04-27 17:10:36 -07001993 static long getLongColumn(Cursor c, String name) {
1994 return c.getLong(c.getColumnIndex(name));
1995 }
Costin Manolache360e4542009-09-04 13:36:04 -07001996
Dianne Hackborn231cc602009-04-27 17:10:36 -07001997 /**
Makoto Onuki94986212018-04-11 16:24:46 -07001998 * TODO Remove it. It's super old code that was used to migrate the information from a sqlite
1999 * database that we used a long time ago, and is no longer relevant.
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 */
Fred Quintana77c560f2010-03-29 22:20:26 -07002001 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 // Look for old database to initialize from.
2003 File file = mContext.getDatabasePath("syncmanager.db");
2004 if (!file.exists()) {
2005 return;
2006 }
2007 String path = file.getPath();
2008 SQLiteDatabase db = null;
2009 try {
2010 db = SQLiteDatabase.openDatabase(path, null,
2011 SQLiteDatabase.OPEN_READONLY);
2012 } catch (SQLiteException e) {
2013 }
Costin Manolache360e4542009-09-04 13:36:04 -07002014
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002016 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07002017
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07002019 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002020 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07002021 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002022 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
2023 qb.setTables("stats, status");
2024 HashMap<String,String> map = new HashMap<String,String>();
2025 map.put("_id", "status._id as _id");
2026 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002027 if (hasType) {
2028 map.put("account_type", "stats.account_type as account_type");
2029 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002030 map.put("authority", "stats.authority as authority");
2031 map.put("totalElapsedTime", "totalElapsedTime");
2032 map.put("numSyncs", "numSyncs");
2033 map.put("numSourceLocal", "numSourceLocal");
2034 map.put("numSourcePoll", "numSourcePoll");
2035 map.put("numSourceServer", "numSourceServer");
2036 map.put("numSourceUser", "numSourceUser");
2037 map.put("lastSuccessSource", "lastSuccessSource");
2038 map.put("lastSuccessTime", "lastSuccessTime");
2039 map.put("lastFailureSource", "lastFailureSource");
2040 map.put("lastFailureTime", "lastFailureTime");
2041 map.put("lastFailureMesg", "lastFailureMesg");
2042 map.put("pending", "pending");
2043 qb.setProjectionMap(map);
2044 qb.appendWhere("stats._id = status.stats_id");
2045 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002046 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07002047 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07002048 String accountType = hasType
2049 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07002050 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07002051 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002053 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002054 AuthorityInfo authority =
2055 this.getOrCreateAuthorityLocked(
2056 new EndPoint(new Account(accountName, accountType),
2057 authorityName,
2058 0 /* legacy is single-user */)
2059 , -1,
2060 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002061 if (authority != null) {
2062 int i = mSyncStatus.size();
2063 boolean found = false;
2064 SyncStatusInfo st = null;
2065 while (i > 0) {
2066 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002067 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002068 if (st.authorityId == authority.ident) {
2069 found = true;
2070 break;
2071 }
2072 }
2073 if (!found) {
2074 st = new SyncStatusInfo(authority.ident);
2075 mSyncStatus.put(authority.ident, st);
2076 }
Makoto Onuki94986212018-04-11 16:24:46 -07002077 st.totalStats.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
2078 st.totalStats.numSyncs = getIntColumn(c, "numSyncs");
2079 st.totalStats.numSourceLocal = getIntColumn(c, "numSourceLocal");
2080 st.totalStats.numSourcePoll = getIntColumn(c, "numSourcePoll");
2081 st.totalStats.numSourceOther = getIntColumn(c, "numSourceServer");
2082 st.totalStats.numSourceUser = getIntColumn(c, "numSourceUser");
2083 st.totalStats.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07002084 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
2085 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
2086 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
2087 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
2088 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
2089 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
Costin Manolache360e4542009-09-04 13:36:04 -07002092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002094
Dianne Hackborn231cc602009-04-27 17:10:36 -07002095 // Retrieve the settings.
2096 qb = new SQLiteQueryBuilder();
2097 qb.setTables("settings");
2098 c = qb.query(db, null, null, null, null, null, null);
2099 while (c.moveToNext()) {
2100 String name = c.getString(c.getColumnIndex("name"));
2101 String value = c.getString(c.getColumnIndex("value"));
2102 if (name == null) continue;
2103 if (name.equals("listen_for_tickles")) {
Makoto Onuki75ad2492018-03-28 14:42:42 -07002104 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0,
Makoto Onukid4764302018-03-30 17:32:57 -07002105 ContentResolver.SYNC_EXEMPTION_NONE, SyncLogger.CALLING_UID_SELF);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002106 } else if (name.startsWith("sync_provider_")) {
2107 String provider = name.substring("sync_provider_".length(),
2108 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07002109 int i = mAuthorities.size();
2110 while (i > 0) {
2111 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07002112 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07002113 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07002114 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07002115 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07002116 }
2117 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
Costin Manolache360e4542009-09-04 13:36:04 -07002120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002122
Dianne Hackborn231cc602009-04-27 17:10:36 -07002123 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07002124
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 (new File(path)).delete();
2126 }
2127 }
Costin Manolache360e4542009-09-04 13:36:04 -07002128
Dianne Hackborn231cc602009-04-27 17:10:36 -07002129 public static final int STATUS_FILE_END = 0;
2130 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07002131
Dianne Hackborn231cc602009-04-27 17:10:36 -07002132 /**
2133 * Read all sync status back in to the initial engine state.
2134 */
2135 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002136 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002137 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002138 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002139 try {
2140 byte[] data = mStatusFile.readFully();
2141 Parcel in = Parcel.obtain();
2142 in.unmarshall(data, 0, data.length);
2143 in.setDataPosition(0);
2144 int token;
2145 while ((token=in.readInt()) != STATUS_FILE_END) {
2146 if (token == STATUS_FILE_ITEM) {
2147 SyncStatusInfo status = new SyncStatusInfo(in);
2148 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2149 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002150 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002151 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002152 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002153 mSyncStatus.put(status.authorityId, status);
2154 }
2155 } else {
2156 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002157 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002158 break;
2159 }
2160 }
2161 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002162 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002163 }
2164 }
Costin Manolache360e4542009-09-04 13:36:04 -07002165
Dianne Hackborn231cc602009-04-27 17:10:36 -07002166 /**
2167 * Write all sync status to the sync status file.
2168 */
2169 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002170 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002171 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002172 }
Costin Manolache360e4542009-09-04 13:36:04 -07002173
Dianne Hackborn231cc602009-04-27 17:10:36 -07002174 // The file is being written, so we don't need to have a scheduled
2175 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002176 mHandler.removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002177
Dianne Hackborn231cc602009-04-27 17:10:36 -07002178 FileOutputStream fos = null;
2179 try {
2180 fos = mStatusFile.startWrite();
2181 Parcel out = Parcel.obtain();
2182 final int N = mSyncStatus.size();
2183 for (int i=0; i<N; i++) {
2184 SyncStatusInfo status = mSyncStatus.valueAt(i);
2185 out.writeInt(STATUS_FILE_ITEM);
2186 status.writeToParcel(out, 0);
2187 }
2188 out.writeInt(STATUS_FILE_END);
2189 fos.write(out.marshall());
2190 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002191
Dianne Hackborn231cc602009-04-27 17:10:36 -07002192 mStatusFile.finishWrite(fos);
2193 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002194 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002195 if (fos != null) {
2196 mStatusFile.failWrite(fos);
2197 }
2198 }
2199 }
Costin Manolache360e4542009-09-04 13:36:04 -07002200
Makoto Onuki61283ec2018-01-31 17:22:36 -08002201 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002202 @SyncExemption int syncExemptionFlag) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002203 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2204 && mSyncRequestListener != null) {
Makoto Onuki61283ec2018-01-31 17:22:36 -08002205 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002206 syncExemptionFlag);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002207 } else {
2208 SyncRequest.Builder req =
2209 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002210 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002211 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002212 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002213 ContentResolver.requestSync(req.build());
2214 }
2215 }
2216
Alon Albert57286f92012-10-09 14:21:38 -07002217 private void requestSync(Account account, int userId, int reason, String authority,
Makoto Onuki75ad2492018-03-28 14:42:42 -07002218 Bundle extras, @SyncExemption int syncExemptionFlag) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002219 // If this is happening in the system process, then call the syncrequest listener
2220 // to make a request back to the SyncManager directly.
2221 // If this is probably a test instance, then call back through the ContentResolver
2222 // which will know which userId to apply based on the Binder id.
2223 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2224 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002225 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002226 new EndPoint(account, authority, userId),
Makoto Onuki75ad2492018-03-28 14:42:42 -07002227 reason, extras, syncExemptionFlag);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002228 } else {
2229 ContentResolver.requestSync(account, authority, extras);
2230 }
2231 }
2232
Dianne Hackborn231cc602009-04-27 17:10:36 -07002233 public static final int STATISTICS_FILE_END = 0;
2234 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2235 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002236
Dianne Hackborn231cc602009-04-27 17:10:36 -07002237 /**
2238 * Read all sync statistics back in to the initial engine state.
2239 */
2240 private void readStatisticsLocked() {
2241 try {
2242 byte[] data = mStatisticsFile.readFully();
2243 Parcel in = Parcel.obtain();
2244 in.unmarshall(data, 0, data.length);
2245 in.setDataPosition(0);
2246 int token;
2247 int index = 0;
2248 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2249 if (token == STATISTICS_FILE_ITEM
2250 || token == STATISTICS_FILE_ITEM_OLD) {
2251 int day = in.readInt();
2252 if (token == STATISTICS_FILE_ITEM_OLD) {
2253 day = day - 2009 + 14245; // Magic!
2254 }
2255 DayStats ds = new DayStats(day);
2256 ds.successCount = in.readInt();
2257 ds.successTime = in.readLong();
2258 ds.failureCount = in.readInt();
2259 ds.failureTime = in.readLong();
2260 if (index < mDayStats.length) {
2261 mDayStats[index] = ds;
2262 index++;
2263 }
2264 } else {
2265 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002266 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002267 break;
2268 }
2269 }
2270 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002271 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002272 }
2273 }
Costin Manolache360e4542009-09-04 13:36:04 -07002274
Dianne Hackborn231cc602009-04-27 17:10:36 -07002275 /**
2276 * Write all sync statistics to the sync status file.
2277 */
2278 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002279 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002280 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002281 }
Costin Manolache360e4542009-09-04 13:36:04 -07002282
Dianne Hackborn231cc602009-04-27 17:10:36 -07002283 // The file is being written, so we don't need to have a scheduled
2284 // write until the next change.
Makoto Onuki6963bea72017-12-12 10:42:39 -08002285 mHandler.removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002286
Dianne Hackborn231cc602009-04-27 17:10:36 -07002287 FileOutputStream fos = null;
2288 try {
2289 fos = mStatisticsFile.startWrite();
2290 Parcel out = Parcel.obtain();
2291 final int N = mDayStats.length;
2292 for (int i=0; i<N; i++) {
2293 DayStats ds = mDayStats[i];
2294 if (ds == null) {
2295 break;
2296 }
2297 out.writeInt(STATISTICS_FILE_ITEM);
2298 out.writeInt(ds.day);
2299 out.writeInt(ds.successCount);
2300 out.writeLong(ds.successTime);
2301 out.writeInt(ds.failureCount);
2302 out.writeLong(ds.failureTime);
2303 }
2304 out.writeInt(STATISTICS_FILE_END);
2305 fos.write(out.marshall());
2306 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002307
Dianne Hackborn231cc602009-04-27 17:10:36 -07002308 mStatisticsFile.finishWrite(fos);
2309 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002310 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002311 if (fos != null) {
2312 mStatisticsFile.failWrite(fos);
2313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002316
2317 /**
Marvin Paula6533252014-11-24 12:57:48 -08002318 * Let the BackupManager know that account sync settings have changed. This will trigger
2319 * {@link com.android.server.backup.SystemBackupAgent} to run.
2320 */
2321 public void queueBackup() {
2322 BackupManager.dataChanged("android");
2323 }
Makoto Onuki94986212018-04-11 16:24:46 -07002324
2325 public void setClockValid() {
2326 if (!mIsClockValid) {
2327 mIsClockValid = true;
2328 Slog.w(TAG, "Clock is valid now.");
2329 }
2330 }
2331
2332 public boolean isClockValid() {
2333 return mIsClockValid;
2334 }
2335
2336 public void resetTodayStats(boolean force) {
2337 if (force) {
2338 Log.w(TAG, "Force resetting today stats.");
2339 }
2340 synchronized (mAuthorities) {
2341 final int N = mSyncStatus.size();
2342 for (int i = 0; i < N; i++) {
2343 SyncStatusInfo cur = mSyncStatus.valueAt(i);
2344 cur.maybeResetTodayStats(isClockValid(), force);
2345 }
2346 writeStatusLocked();
2347 }
2348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349}