blob: 069ae739431975199b374e020a50c01977fa5508 [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;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Shreyas Basarge8c834c02016-01-07 13:53:16 +000042import android.util.*;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastXmlSerializer;
47
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Dianne Hackborn231cc602009-04-27 17:10:36 -070052import java.io.File;
53import java.io.FileInputStream;
54import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010055import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080060import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070061import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060062import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * @hide
69 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070070public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070073 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070074
Amith Yamasani04e0d262012-02-14 11:50:53 -080075 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
76 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070077 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080078 private static final String XML_ATTR_ENABLED = "enabled";
79 private static final String XML_ATTR_USER = "user";
80 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
81
Matthew Williamsfa774182013-06-18 15:44:11 -070082 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000083 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080084
Shreyas Basarge8c834c02016-01-07 13:53:16 +000085 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070086 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
87
88 /** Lower bound on sync time from which we assign a default flex time. */
89 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
90
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080091 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 /** Enum value for a sync start event. */
95 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a sync stop event. */
98 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a server-initiated sync. */
101 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a local-initiated sync. */
104 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700105 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a user-initiated sync. */
109 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800111 /** Enum value for a periodic sync. */
112 public static final int SOURCE_PERIODIC = 4;
113
Fred Quintana307da1a2010-01-21 14:24:20 -0800114 public static final long NOT_IN_BACKOFF_MODE = -1;
115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 // TODO: i18n -- grab these out of resources.
117 /** String names for the sync source types. */
118 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000119 "LOCAL",
120 "POLL",
121 "USER",
122 "PERIODIC",
123 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // The MESG column will contain one of these or one of the Error types.
126 public static final String MESG_SUCCESS = "success";
127 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700129 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 private static final int MSG_WRITE_STATUS = 1;
132 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATISTICS = 2;
135 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700136
137 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Fred Quintanac2e46912010-03-15 16:10:44 -0700139 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700140 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700141
142 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000143 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700144
145 static {
146 sAuthorityRenames = new HashMap<String, String>();
147 sAuthorityRenames.put("contacts", "com.android.contacts");
148 sAuthorityRenames.put("calendar", "com.android.calendar");
149 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700150
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800152 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 final HashMap<String, AuthorityInfo> authorities =
154 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 AccountInfo(AccountAndUser accountAndUser) {
157 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 }
159 }
Costin Manolache360e4542009-09-04 13:36:04 -0700160
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700161 /** Bare bones representation of a sync target. */
162 public static class EndPoint {
163 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
164 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700165 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800166 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700167 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168
169 public EndPoint(Account account, String provider, int userId) {
170 this.account = account;
171 this.provider = provider;
172 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 }
174
175 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700176 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
177 *
178 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000179 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700181 public boolean matchesSpec(EndPoint spec) {
182 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700184 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700185 return false;
186 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000187 boolean accountsMatch;
188 if (spec.account == null) {
189 accountsMatch = true;
190 } else {
191 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000193 boolean providersMatch;
194 if (spec.provider == null) {
195 providersMatch = true;
196 } else {
197 providersMatch = provider.equals(spec.provider);
198 }
199 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 }
201
202 public String toString() {
203 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000204 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 .append("/")
206 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700207 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 return sb.toString();
209 }
210 }
211
212 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700213 // Legal values of getIsSyncable
Svet Ganovf6d424f12016-09-20 20:18:53 -0700214
215 /**
216 * The syncable state is undefined.
217 */
218 public static final int UNDEFINED = -2;
219
Matthew Williams53abfdb2015-06-10 20:06:37 -0700220 /**
221 * Default state for a newly installed adapter. An uninitialized adapter will receive an
222 * initialization sync which are governed by a different set of rules to that of regular
223 * syncs.
224 */
225 public static final int NOT_INITIALIZED = -1;
226 /**
227 * The adapter will not receive any syncs. This is behaviourally equivalent to
228 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
229 * while this is generally meant to be controlled by the developer.
230 */
231 public static final int NOT_SYNCABLE = 0;
232 /**
233 * The adapter is initialized and functioning. This is the normal state for an adapter.
234 */
235 public static final int SYNCABLE = 1;
236 /**
237 * The adapter is syncable but still requires an initialization sync. For example an adapter
238 * than has been restored from a previous device will be in this state. Not meant for
239 * external use.
240 */
241 public static final int SYNCABLE_NOT_INITIALIZED = 2;
242
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700243 /**
244 * The adapter is syncable but does not have access to the synced account and needs a
245 * user access approval.
246 */
247 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
248
Matthew Williams8ef22042013-07-26 12:56:39 -0700249 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700250 final int ident;
251 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700252 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700253 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800254 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700255 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800256 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700257 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800258 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700259
Matthew Williamsfa774182013-06-18 15:44:11 -0700260 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700261
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700262 /**
263 * Copy constructor for making deep-ish copies. Only the bundles stored
264 * in periodic syncs can make unexpected changes.
265 *
266 * @param toCopy AuthorityInfo to be copied.
267 */
268 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700269 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700270 ident = toCopy.ident;
271 enabled = toCopy.enabled;
272 syncable = toCopy.syncable;
273 backoffTime = toCopy.backoffTime;
274 backoffDelay = toCopy.backoffDelay;
275 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700276 periodicSyncs = new ArrayList<PeriodicSync>();
277 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700278 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700279 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700280 }
281 }
282
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700283 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700284 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700285 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000286 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700287 periodicSyncs = new ArrayList<PeriodicSync>();
288 defaultInitialisation();
289 }
290
291 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700292 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800293 backoffTime = -1; // if < 0 then we aren't in backoff mode
294 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000295
296 if (mPeriodicSyncAddedListener != null) {
297 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
298 DEFAULT_POLL_FREQUENCY_SECONDS,
299 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700300 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700301 }
Matthew Williams06485a72013-07-26 12:56:39 -0700302
303 @Override
304 public String toString() {
305 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
306 + backoffTime + ", delay=" + delayUntil;
307 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700308 }
Costin Manolache360e4542009-09-04 13:36:04 -0700309
Dianne Hackborn231cc602009-04-27 17:10:36 -0700310 public static class SyncHistoryItem {
311 int authorityId;
312 int historyId;
313 long eventTime;
314 long elapsedTime;
315 int source;
316 int event;
317 long upstreamActivity;
318 long downstreamActivity;
319 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700320 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700321 Bundle extras;
322 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700323 }
Costin Manolache360e4542009-09-04 13:36:04 -0700324
Dianne Hackborn231cc602009-04-27 17:10:36 -0700325 public static class DayStats {
326 public final int day;
327 public int successCount;
328 public long successTime;
329 public int failureCount;
330 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700331
Dianne Hackborn231cc602009-04-27 17:10:36 -0700332 public DayStats(int day) {
333 this.day = day;
334 }
335 }
Costin Manolache360e4542009-09-04 13:36:04 -0700336
Amith Yamasani04e0d262012-02-14 11:50:53 -0800337 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700338
339 /** Called when a sync is needed on an account(s) due to some change in state. */
340 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800341 }
342
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000343 interface PeriodicSyncAddedListener {
344 /** Called when a periodic sync is added. */
345 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
346 }
347
348 interface OnAuthorityRemovedListener {
349 /** Called when an authority is removed. */
350 void onAuthorityRemoved(EndPoint removedAuthority);
351 }
352
Dianne Hackborn231cc602009-04-27 17:10:36 -0700353 // Primary list of all syncable authorities. Also our global lock.
354 private final SparseArray<AuthorityInfo> mAuthorities =
355 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Amith Yamasani04e0d262012-02-14 11:50:53 -0800357 private final HashMap<AccountAndUser, AccountInfo> mAccounts
358 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359
Amith Yamasani04e0d262012-02-14 11:50:53 -0800360 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
361 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700362
Dianne Hackborn231cc602009-04-27 17:10:36 -0700363 private final SparseArray<SyncStatusInfo> mSyncStatus =
364 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700365
Dianne Hackborn231cc602009-04-27 17:10:36 -0700366 private final ArrayList<SyncHistoryItem> mSyncHistory =
367 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700368
Dianne Hackborn231cc602009-04-27 17:10:36 -0700369 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
370 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700371
Matthew Williams8ef22042013-07-26 12:56:39 -0700372 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700373 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
374 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700375
Fred Quintana77c560f2010-03-29 22:20:26 -0700376 private int mNextAuthorityId = 0;
377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 // We keep 4 weeks of stats.
379 private final DayStats[] mDayStats = new DayStats[7*4];
380 private final Calendar mCal;
381 private int mYear;
382 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700383
Dianne Hackborn231cc602009-04-27 17:10:36 -0700384 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800385
Dianne Hackborn231cc602009-04-27 17:10:36 -0700386 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700387
Ashish Sharma69d95de2012-04-11 17:27:24 -0700388 private int mSyncRandomOffset;
389
Dianne Hackborn231cc602009-04-27 17:10:36 -0700390 /**
391 * This file contains the core engine state: all accounts and the
392 * settings for them. It must never be lost, and should be changed
393 * infrequently, so it is stored as an XML file.
394 */
395 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700396
Dianne Hackborn231cc602009-04-27 17:10:36 -0700397 /**
398 * This file contains the current sync status. We would like to retain
399 * it across boots, but its loss is not the end of the world, so we store
400 * this information as binary data.
401 */
402 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700403
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 /**
405 * This file contains sync statistics. This is purely debugging information
406 * so is written infrequently and can be thrown away at any time.
407 */
408 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700409
Dianne Hackborn231cc602009-04-27 17:10:36 -0700410 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800411 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800412 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800413
414 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000415 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Svet Ganov65712b02016-09-01 10:24:11 -0700417 private boolean mGrantSyncAdaptersAccountAccess;
418
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800419 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800420 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800421 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700422
Dianne Hackborn231cc602009-04-27 17:10:36 -0700423 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700424
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800425 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000426 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 File systemDir = new File(dataDir, "system");
429 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800430 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700431
432 maybeDeleteLegacyPendingInfoLocked(syncDir);
433
Dianne Hackborn231cc602009-04-27 17:10:36 -0700434 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
435 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700436 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700437
Dianne Hackborn231cc602009-04-27 17:10:36 -0700438 readAccountInfoLocked();
439 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700440 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700441 readAndDeleteLegacyAccountInfoLocked();
442 writeAccountInfoLocked();
443 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700444 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
447 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800448 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
451 public static void init(Context context) {
452 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800453 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800454 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700455 File dataDir = Environment.getDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800456 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
458
459 public static SyncStorageEngine getSingleton() {
460 if (sSyncStorageEngine == null) {
461 throw new IllegalStateException("not initialized");
462 }
463 return sSyncStorageEngine;
464 }
465
Amith Yamasani04e0d262012-02-14 11:50:53 -0800466 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
467 if (mSyncRequestListener == null) {
468 mSyncRequestListener = listener;
469 }
470 }
471
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000472 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
473 if (mAuthorityRemovedListener == null) {
474 mAuthorityRemovedListener = listener;
475 }
476 }
477
478 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
479 if (mPeriodicSyncAddedListener == null) {
480 mPeriodicSyncAddedListener = listener;
481 }
482 }
483
Dianne Hackborn231cc602009-04-27 17:10:36 -0700484 @Override public void handleMessage(Message msg) {
485 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700486 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700487 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700488 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700489 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700490 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700491 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493 }
494 }
Costin Manolache360e4542009-09-04 13:36:04 -0700495
Ashish Sharma69d95de2012-04-11 17:27:24 -0700496 public int getSyncRandomOffset() {
497 return mSyncRandomOffset;
498 }
499
Dianne Hackborn231cc602009-04-27 17:10:36 -0700500 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
501 synchronized (mAuthorities) {
502 mChangeListeners.register(callback, mask);
503 }
504 }
Costin Manolache360e4542009-09-04 13:36:04 -0700505
Dianne Hackborn231cc602009-04-27 17:10:36 -0700506 public void removeStatusChangeListener(ISyncStatusObserver callback) {
507 synchronized (mAuthorities) {
508 mChangeListeners.unregister(callback);
509 }
510 }
Costin Manolache360e4542009-09-04 13:36:04 -0700511
Matthew Williamsfa774182013-06-18 15:44:11 -0700512 /**
513 * Figure out a reasonable flex time for cases where none is provided (old api calls).
514 * @param syncTimeSeconds requested sync time from now.
515 * @return amount of seconds before syncTimeSeconds that the sync can occur.
516 * I.e.
517 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700518 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700519 */
520 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
521 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
522 // Small enough sync request time that we don't add flex time - developer probably
523 // wants to wait for an operation to occur before syncing so we honour the
524 // request time.
525 return 0L;
526 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
527 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
528 } else {
529 // Large enough sync request time that we cap the flex time.
530 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
531 }
532 }
533
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000534 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700535 ArrayList<ISyncStatusObserver> reports = null;
536 synchronized (mAuthorities) {
537 int i = mChangeListeners.beginBroadcast();
538 while (i > 0) {
539 i--;
540 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
541 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542 continue;
543 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 if (reports == null) {
545 reports = new ArrayList<ISyncStatusObserver>(i);
546 }
547 reports.add(mChangeListeners.getBroadcastItem(i));
548 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700549 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700550 }
Costin Manolache360e4542009-09-04 13:36:04 -0700551
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700552 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000553 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700554 }
Costin Manolache360e4542009-09-04 13:36:04 -0700555
Dianne Hackborn231cc602009-04-27 17:10:36 -0700556 if (reports != null) {
557 int i = reports.size();
558 while (i > 0) {
559 i--;
560 try {
561 reports.get(i).onStatusChanged(which);
562 } catch (RemoteException e) {
563 // The remote callback list will take care of this for us.
564 }
565 }
566 }
567 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700568
Amith Yamasani04e0d262012-02-14 11:50:53 -0800569 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700570 synchronized (mAuthorities) {
571 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700572 AuthorityInfo authority = getAuthorityLocked(
573 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700574 "getSyncAutomatically");
575 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700576 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700577
Dianne Hackborn231cc602009-04-27 17:10:36 -0700578 int i = mAuthorities.size();
579 while (i > 0) {
580 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700581 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700582 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700583 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700584 return true;
585 }
586 }
587 return false;
588 }
589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590
Amith Yamasani04e0d262012-02-14 11:50:53 -0800591 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000592 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700593 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000594 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800595 + ", user " + userId + " -> " + sync);
596 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700597 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700598 AuthorityInfo authority =
599 getOrCreateAuthorityLocked(
600 new EndPoint(account, providerName, userId),
601 -1 /* ident */,
602 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700603 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700604 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000605 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800606 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700607 return;
608 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700609 // If the adapter was syncable but missing its initialization sync, set it to
610 // uninitialized now. This is to give it a chance to run any one-time initialization
611 // logic.
612 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
613 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
614 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700615 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700616 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700618
Fred Quintana77c560f2010-03-29 22:20:26 -0700619 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700620 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
621 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700622 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700623 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800624 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 }
626
Amith Yamasani04e0d262012-02-14 11:50:53 -0800627 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700628 synchronized (mAuthorities) {
629 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700630 AuthorityInfo authority = getAuthorityLocked(
631 new EndPoint(account, providerName, userId),
632 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700633 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700634 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700635 }
636 return authority.syncable;
637 }
638
639 int i = mAuthorities.size();
640 while (i > 0) {
641 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700642 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700643 if (authorityInfo.target != null
644 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700645 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700646 }
647 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700648 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700649 }
650 }
651
Amith Yamasani04e0d262012-02-14 11:50:53 -0800652 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700653 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700654 }
655
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700656 /**
657 * An enabled sync service and a syncable provider's adapter both get resolved to the same
658 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700659 * @param target target to set value for.
660 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700661 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700662 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700663 AuthorityInfo aInfo;
664 synchronized (mAuthorities) {
665 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700666 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
667 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700668 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700669 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000670 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700671 }
672 if (aInfo.syncable == syncable) {
673 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000674 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700675 }
676 return;
677 }
678 aInfo.syncable = syncable;
679 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700680 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700681 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700682 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700683 }
684 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
685 }
686
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700687 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800688 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
690 if (authority != null) {
691 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800692 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700693 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800694 }
695 }
696
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700697 /**
698 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
699 * the account or provider info be null, which signifies all accounts or providers.
700 */
701 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
702 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000703 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800704 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
705 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700706 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800707 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000708 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700709 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000710 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700711 changed = setBackoffLocked(
712 info.account /* may be null */,
713 info.userId,
714 info.provider /* may be null */,
715 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800716 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700717 AuthorityInfo authorityInfo =
718 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
719 if (authorityInfo.backoffTime == nextSyncTime
720 && authorityInfo.backoffDelay == nextDelay) {
721 changed = false;
722 } else {
723 authorityInfo.backoffTime = nextSyncTime;
724 authorityInfo.backoffDelay = nextDelay;
725 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800726 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800727 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800728 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800729 if (changed) {
730 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
731 }
732 }
733
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700734 /**
735 * Either set backoff for a specific authority, or set backoff for all the
736 * accounts on a specific adapter/all adapters.
737 *
738 * @param account account for which to set backoff. Null to specify all accounts.
739 * @param userId id of the user making this request.
740 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700741 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700742 */
743 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000744 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700745 boolean changed = false;
746 for (AccountInfo accountInfo : mAccounts.values()) {
747 if (account != null && !account.equals(accountInfo.accountAndUser.account)
748 && userId != accountInfo.accountAndUser.userId) {
749 continue;
750 }
751 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
752 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700753 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700754 continue;
755 }
756 if (authorityInfo.backoffTime != nextSyncTime
757 || authorityInfo.backoffDelay != nextDelay) {
758 authorityInfo.backoffTime = nextSyncTime;
759 authorityInfo.backoffDelay = nextDelay;
760 changed = true;
761 }
762 }
763 }
764 return changed;
765 }
766
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000767 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800768 boolean changed = false;
769 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000770 // Clear backoff for all sync adapters.
771 for (AccountInfo accountInfo : mAccounts.values()) {
772 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
773 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
774 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
775 if (Log.isLoggable(TAG, Log.VERBOSE)) {
776 Slog.v(TAG, "clearAllBackoffsLocked:"
777 + " authority:" + authorityInfo.target
778 + " account:" + accountInfo.accountAndUser.account.name
779 + " user:" + accountInfo.accountAndUser.userId
780 + " backoffTime was: " + authorityInfo.backoffTime
781 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800782 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000783 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
784 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
785 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800786 }
787 }
788 }
789 }
790
791 if (changed) {
792 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
793 }
794 }
795
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700796 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800797 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800799 if (authority == null) {
800 return 0;
801 }
802 return authority.delayUntil;
803 }
804 }
805
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 public void setDelayUntilTime(EndPoint info, long delayUntil) {
807 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000808 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700809 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800810 }
811 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700812 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
813 if (authority.delayUntil == delayUntil) {
814 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700815 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700816 authority.delayUntil = delayUntil;
817 }
818 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
819 }
820
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700821 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000822 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
823 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700824 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000825 boolean restoreAllPeriodicSyncs() {
826 if (mPeriodicSyncAddedListener == null) {
827 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800828 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000829 synchronized (mAuthorities) {
830 for (int i=0; i<mAuthorities.size(); i++) {
831 AuthorityInfo authority = mAuthorities.valueAt(i);
832 for (PeriodicSync periodicSync: authority.periodicSyncs) {
833 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
834 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
835 }
836 authority.periodicSyncs.clear();
837 }
838 writeAccountInfoLocked();
839 }
840 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800841 }
842
Amith Yamasani04e0d262012-02-14 11:50:53 -0800843 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700844 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800845 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700846 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700847 return;
848 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800849 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700850 writeAccountInfoLocked();
851 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700852 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700853 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
854 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700855 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700856 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800857 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800858 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860
Amith Yamasani04e0d262012-02-14 11:50:53 -0800861 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700862 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800863 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800864 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700865 }
866 }
Costin Manolache360e4542009-09-04 13:36:04 -0700867
Dianne Hackborn231cc602009-04-27 17:10:36 -0700868 public AuthorityInfo getAuthority(int authorityId) {
869 synchronized (mAuthorities) {
870 return mAuthorities.get(authorityId);
871 }
872 }
Costin Manolache360e4542009-09-04 13:36:04 -0700873
Dianne Hackborn231cc602009-04-27 17:10:36 -0700874 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700875 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700876 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700877 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700878 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700879 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700880 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700881 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700882 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 return true;
884 }
885 }
886 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 return false;
888 }
Costin Manolache360e4542009-09-04 13:36:04 -0700889
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000890 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700891 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000892 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
893 -1 /* desired identifier */,
894 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000896 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700897 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000899 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700900 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700901 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700902 }
Costin Manolache360e4542009-09-04 13:36:04 -0700903
Dianne Hackborn231cc602009-04-27 17:10:36 -0700904 /**
905 * Called when the set of account has changed, given the new array of
906 * active accounts.
907 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800908 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700909 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700910 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000911 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700912 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700913 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
914 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
915 while (accIt.hasNext()) {
916 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800917 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
918 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700919 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700920 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000921 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700922 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700923 for (AuthorityInfo auth : acc.authorities.values()) {
924 removing.put(auth.ident, auth);
925 }
926 accIt.remove();
927 }
928 }
Costin Manolache360e4542009-09-04 13:36:04 -0700929
Dianne Hackborn231cc602009-04-27 17:10:36 -0700930 // Clean out all data structures.
931 int i = removing.size();
932 if (i > 0) {
933 while (i > 0) {
934 i--;
935 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000936 AuthorityInfo auth = removing.valueAt(i);
937 if (mAuthorityRemovedListener != null) {
938 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
939 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700940 mAuthorities.remove(ident);
941 int j = mSyncStatus.size();
942 while (j > 0) {
943 j--;
944 if (mSyncStatus.keyAt(j) == ident) {
945 mSyncStatus.remove(mSyncStatus.keyAt(j));
946 }
947 }
948 j = mSyncHistory.size();
949 while (j > 0) {
950 j--;
951 if (mSyncHistory.get(j).authorityId == ident) {
952 mSyncHistory.remove(j);
953 }
954 }
955 }
956 writeAccountInfoLocked();
957 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 writeStatisticsLocked();
959 }
960 }
961 }
962
963 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700964 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
965 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700966 */
Fred Quintana918339a2010-10-05 14:00:39 -0700967 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
968 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700970 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000971 Slog.v(TAG, "setActiveSync: account="
972 + " auth=" + activeSyncContext.mSyncOperation.target
973 + " src=" + activeSyncContext.mSyncOperation.syncSource
974 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700975 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700976 final EndPoint info = activeSyncContext.mSyncOperation.target;
977 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
978 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700979 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700980 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700981 syncInfo = new SyncInfo(
982 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700983 authorityInfo.target.account,
984 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700985 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700986 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700987 }
Fred Quintana918339a2010-10-05 14:00:39 -0700988 reportActiveChange();
989 return syncInfo;
990 }
991
992 /**
993 * Called to indicate that a previously active sync is no longer active.
994 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800995 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700996 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700997 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000998 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800999 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -07001000 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -07001001 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001002 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -07001003 }
1004
1005 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001006 }
1007
1008 /**
1009 * To allow others to send active change reports, to poke clients.
1010 */
1011 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001012 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 }
Costin Manolache360e4542009-09-04 13:36:04 -07001014
Dianne Hackborn231cc602009-04-27 17:10:36 -07001015 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001016 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001018 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001019 long id;
1020 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001021 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001022 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001023 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001024 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 if (authority == null) {
1026 return -1;
1027 }
1028 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001029 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 item.authorityId = authority.ident;
1031 item.historyId = mNextHistoryId++;
1032 if (mNextHistoryId < 0) mNextHistoryId = 0;
1033 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001034 item.source = op.syncSource;
1035 item.reason = op.reason;
1036 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001037 item.event = EVENT_START;
1038 mSyncHistory.add(0, item);
1039 while (mSyncHistory.size() > MAX_HISTORY) {
1040 mSyncHistory.remove(mSyncHistory.size()-1);
1041 }
1042 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001043 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 }
Costin Manolache360e4542009-09-04 13:36:04 -07001045
Fred Quintanaac9385e2009-06-22 18:00:59 -07001046 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001047 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049
Fred Quintana77c560f2010-03-29 22:20:26 -07001050 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001051 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001053 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001054 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001055 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 SyncHistoryItem item = null;
1057 int i = mSyncHistory.size();
1058 while (i > 0) {
1059 i--;
1060 item = mSyncHistory.get(i);
1061 if (item.historyId == historyId) {
1062 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001064 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
Costin Manolache360e4542009-09-04 13:36:04 -07001066
Dianne Hackborn231cc602009-04-27 17:10:36 -07001067 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001068 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001069 return;
1070 }
Costin Manolache360e4542009-09-04 13:36:04 -07001071
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 item.elapsedTime = elapsedTime;
1073 item.event = EVENT_STOP;
1074 item.mesg = resultMessage;
1075 item.downstreamActivity = downstreamActivity;
1076 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001077
Dianne Hackborn231cc602009-04-27 17:10:36 -07001078 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001079
Dianne Hackborn231cc602009-04-27 17:10:36 -07001080 status.numSyncs++;
1081 status.totalElapsedTime += elapsedTime;
1082 switch (item.source) {
1083 case SOURCE_LOCAL:
1084 status.numSourceLocal++;
1085 break;
1086 case SOURCE_POLL:
1087 status.numSourcePoll++;
1088 break;
1089 case SOURCE_USER:
1090 status.numSourceUser++;
1091 break;
1092 case SOURCE_SERVER:
1093 status.numSourceServer++;
1094 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001095 case SOURCE_PERIODIC:
1096 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001097 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 }
Costin Manolache360e4542009-09-04 13:36:04 -07001099
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001101 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001102 if (mDayStats[0] == null) {
1103 mDayStats[0] = new DayStats(day);
1104 } else if (day != mDayStats[0].day) {
1105 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1106 mDayStats[0] = new DayStats(day);
1107 writeStatisticsNow = true;
1108 } else if (mDayStats[0] == null) {
1109 }
1110 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001111
Dianne Hackborn231cc602009-04-27 17:10:36 -07001112 final long lastSyncTime = (item.eventTime + elapsedTime);
1113 boolean writeStatusNow = false;
1114 if (MESG_SUCCESS.equals(resultMessage)) {
1115 // - if successful, update the successful columns
1116 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1117 writeStatusNow = true;
1118 }
1119 status.lastSuccessTime = lastSyncTime;
1120 status.lastSuccessSource = item.source;
1121 status.lastFailureTime = 0;
1122 status.lastFailureSource = -1;
1123 status.lastFailureMesg = null;
1124 status.initialFailureTime = 0;
1125 ds.successCount++;
1126 ds.successTime += elapsedTime;
1127 } else if (!MESG_CANCELED.equals(resultMessage)) {
1128 if (status.lastFailureTime == 0) {
1129 writeStatusNow = true;
1130 }
1131 status.lastFailureTime = lastSyncTime;
1132 status.lastFailureSource = item.source;
1133 status.lastFailureMesg = resultMessage;
1134 if (status.initialFailureTime == 0) {
1135 status.initialFailureTime = lastSyncTime;
1136 }
1137 ds.failureCount++;
1138 ds.failureTime += elapsedTime;
1139 }
Costin Manolache360e4542009-09-04 13:36:04 -07001140
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 if (writeStatusNow) {
1142 writeStatusLocked();
1143 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1144 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1145 WRITE_STATUS_DELAY);
1146 }
1147 if (writeStatisticsNow) {
1148 writeStatisticsLocked();
1149 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1150 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1151 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001152 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001153 }
Costin Manolache360e4542009-09-04 13:36:04 -07001154
Fred Quintanaac9385e2009-06-22 18:00:59 -07001155 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001156 }
1157
1158 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001159 * Return a list of the currently active syncs. Note that the returned
1160 * items are the real, live active sync objects, so be careful what you do
1161 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001162 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001163 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001164 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001165 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001166 }
1167 }
Costin Manolache360e4542009-09-04 13:36:04 -07001168
Dianne Hackborn231cc602009-04-27 17:10:36 -07001169 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001170 * @param userId Id of user to return current sync info.
1171 * @param canAccessAccounts Determines whether to redact Account information from the result.
1172 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001173 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001174 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001175 synchronized (mAuthorities) {
1176 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1177 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1178 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001179 SyncInfo copy;
1180 if (!canAccessAccounts) {
1181 copy = SyncInfo.createAccountRedacted(
1182 sync.authorityId, sync.authority, sync.startTime);
1183 } else {
1184 copy = new SyncInfo(sync);
1185 }
1186 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001187 }
1188 return syncsCopy;
1189 }
1190 }
1191
1192 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1193 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1194 if (syncs == null) {
1195 syncs = new ArrayList<SyncInfo>();
1196 mCurrentSyncs.put(userId, syncs);
1197 }
1198 return syncs;
1199 }
1200
1201 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001202 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001203 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001204 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001205 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001206 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001207 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001208 true /* write to storage if this results in a change */);
1209 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1210 }
1211 }
1212
1213 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001214 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001215 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001216 * @param info the endpoint target we are querying status info for.
1217 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001219 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001220 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001221 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001222 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001223 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001224 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001225 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001226 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001228 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001229 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001230 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001231 }
1232 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001233 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001234 }
1235 }
Costin Manolache360e4542009-09-04 13:36:04 -07001236
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001237 /** Return true if the pending status is true of any matching authorities. */
1238 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 synchronized (mAuthorities) {
1240 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001241 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001242 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001243 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1244 if (ainfo == null) {
1245 continue;
1246 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001247 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001248 continue;
1249 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001250 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 return true;
1252 }
1253 }
1254 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 }
1257
1258 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001259 * Return an array of the current sync status for all authorities. Note
1260 * that the objects inside the array are the real, live status objects,
1261 * so be careful what you do with them.
1262 */
1263 public ArrayList<SyncHistoryItem> getSyncHistory() {
1264 synchronized (mAuthorities) {
1265 final int N = mSyncHistory.size();
1266 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1267 for (int i=0; i<N; i++) {
1268 items.add(mSyncHistory.get(i));
1269 }
1270 return items;
1271 }
1272 }
Costin Manolache360e4542009-09-04 13:36:04 -07001273
Dianne Hackborn231cc602009-04-27 17:10:36 -07001274 /**
1275 * Return an array of the current per-day statistics. Note
1276 * that the objects inside the array are the real, live status objects,
1277 * so be careful what you do with them.
1278 */
1279 public DayStats[] getDayStatistics() {
1280 synchronized (mAuthorities) {
1281 DayStats[] ds = new DayStats[mDayStats.length];
1282 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1283 return ds;
1284 }
1285 }
Costin Manolache360e4542009-09-04 13:36:04 -07001286
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001287 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1288 AuthorityInfo authorityInfo) {
1289 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1290 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1291 }
1292
Dianne Hackborn55280a92009-05-07 15:53:46 -07001293 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001294 mCal.setTimeInMillis(System.currentTimeMillis());
1295 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1296 if (mYear != mCal.get(Calendar.YEAR)) {
1297 mYear = mCal.get(Calendar.YEAR);
1298 mCal.clear();
1299 mCal.set(Calendar.YEAR, mYear);
1300 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1301 }
1302 return dayOfYear + mYearInDays;
1303 }
Costin Manolache360e4542009-09-04 13:36:04 -07001304
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001306 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001307 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001308 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001309 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001310 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001311 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001312 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001313 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1314 AccountInfo accountInfo = mAccounts.get(au);
1315 if (accountInfo == null) {
1316 if (tag != null) {
1317 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1318 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001319 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001320 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 return null;
1322 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001323 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1324 if (authority == null) {
1325 if (tag != null) {
1326 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1327 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1328 }
1329 }
1330 return null;
1331 }
1332 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001333 }
Costin Manolache360e4542009-09-04 13:36:04 -07001334
Matthew Williamsfa774182013-06-18 15:44:11 -07001335 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001336 * @param info info identifying target.
1337 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001338 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001339 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001340 * exists.
1341 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001342 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1343 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001344 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1345 AccountInfo account = mAccounts.get(au);
1346 if (account == null) {
1347 account = new AccountInfo(au);
1348 mAccounts.put(au, account);
1349 }
1350 authority = account.authorities.get(info.provider);
1351 if (authority == null) {
1352 authority = createAuthorityLocked(info, ident, doWrite);
1353 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001354 }
1355 return authority;
1356 }
1357
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001358 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1359 AuthorityInfo authority;
1360 if (ident < 0) {
1361 ident = mNextAuthorityId;
1362 mNextAuthorityId++;
1363 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001364 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001365 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001366 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001367 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001368 authority = new AuthorityInfo(info, ident);
1369 mAuthorities.put(ident, authority);
1370 if (doWrite) {
1371 writeAccountInfoLocked();
1372 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001373 return authority;
1374 }
Costin Manolache360e4542009-09-04 13:36:04 -07001375
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001376 public void removeAuthority(EndPoint info) {
1377 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001378 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001379 }
1380 }
1381
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001382
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001383 /**
1384 * Remove an authority associated with a provider. Needs to be a standalone function for
1385 * backward compatibility.
1386 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001387 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001388 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001389 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001390 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001391 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1392 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001393 if (mAuthorityRemovedListener != null) {
1394 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1395 }
Fred Quintanafb084402010-03-23 17:57:03 -07001396 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001397 if (doWrite) {
1398 writeAccountInfoLocked();
1399 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001400 }
1401 }
1402 }
1403
Dianne Hackborn231cc602009-04-27 17:10:36 -07001404 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1405 SyncStatusInfo status = mSyncStatus.get(authorityId);
1406 if (status == null) {
1407 status = new SyncStatusInfo(authorityId);
1408 mSyncStatus.put(authorityId, status);
1409 }
1410 return status;
1411 }
Costin Manolache360e4542009-09-04 13:36:04 -07001412
Dianne Hackborn55280a92009-05-07 15:53:46 -07001413 public void writeAllState() {
1414 synchronized (mAuthorities) {
1415 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001416 writeStatusLocked();
1417 writeStatisticsLocked();
1418 }
1419 }
Costin Manolache360e4542009-09-04 13:36:04 -07001420
Svet Ganov65712b02016-09-01 10:24:11 -07001421 public boolean shouldGrantSyncAdaptersAccountAccess() {
1422 return mGrantSyncAdaptersAccountAccess;
1423 }
1424
Dianne Hackborn231cc602009-04-27 17:10:36 -07001425 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001426 * public for testing
1427 */
1428 public void clearAndReadState() {
1429 synchronized (mAuthorities) {
1430 mAuthorities.clear();
1431 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001432 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001433 mSyncStatus.clear();
1434 mSyncHistory.clear();
1435
1436 readAccountInfoLocked();
1437 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001438 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001439 readAndDeleteLegacyAccountInfoLocked();
1440 writeAccountInfoLocked();
1441 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001442 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001443 }
1444 }
1445
1446 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 * Read all account information back in to the initial engine state.
1448 */
1449 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001450 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001451 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001453 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001454 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001455 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001456 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001457 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001458 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001459 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001460 while (eventType != XmlPullParser.START_TAG &&
1461 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001462 eventType = parser.next();
1463 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001464 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001465 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001466 return;
1467 }
1468
Dianne Hackborn231cc602009-04-27 17:10:36 -07001469 String tagName = parser.getName();
1470 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001471 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001472 String versionString = parser.getAttributeValue(null, "version");
1473 int version;
1474 try {
1475 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1476 } catch (NumberFormatException e) {
1477 version = 0;
1478 }
Svet Ganov65712b02016-09-01 10:24:11 -07001479
1480 if (version < 3) {
1481 mGrantSyncAdaptersAccountAccess = true;
1482 }
1483
Amith Yamasani04e0d262012-02-14 11:50:53 -08001484 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001485 try {
1486 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1487 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1488 } catch (NumberFormatException e) {
1489 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001490 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001491 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1492 try {
1493 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1494 } catch (NumberFormatException e) {
1495 mSyncRandomOffset = 0;
1496 }
1497 if (mSyncRandomOffset == 0) {
1498 Random random = new Random(System.currentTimeMillis());
1499 mSyncRandomOffset = random.nextInt(86400);
1500 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001501 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001502 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001503 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001504 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001505 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001506 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001507 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001508 if (parser.getDepth() == 2) {
1509 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001510 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001511 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001512 if (authority != null) {
1513 if (authority.ident > highestAuthorityId) {
1514 highestAuthorityId = authority.ident;
1515 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001516 } else {
1517 EventLog.writeEvent(0x534e4554, "26513719", -1,
1518 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001519 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001520 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1521 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001523 } else if (parser.getDepth() == 3) {
1524 if ("periodicSync".equals(tagName) && authority != null) {
1525 periodicSync = parsePeriodicSync(parser, authority);
1526 }
1527 } else if (parser.getDepth() == 4 && periodicSync != null) {
1528 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001529 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 }
1531 }
1532 }
1533 eventType = parser.next();
1534 } while (eventType != XmlPullParser.END_DOCUMENT);
1535 }
1536 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001537 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001538 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001539 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001540 if (fis == null) Slog.i(TAG, "No initial accounts");
1541 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001542 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001543 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001544 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001545 if (fis != null) {
1546 try {
1547 fis.close();
1548 } catch (java.io.IOException e1) {
1549 }
1550 }
1551 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001552
Fred Quintana77c560f2010-03-29 22:20:26 -07001553 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001554 }
Costin Manolache360e4542009-09-04 13:36:04 -07001555
Fred Quintanafb084402010-03-23 17:57:03 -07001556 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001557 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1558 * pending.xml was used starting in KLP.
1559 * @param syncDir directory where the sync files are located.
1560 */
1561 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1562 File file = new File(syncDir, "pending.bin");
1563 if (!file.exists()) {
1564 return;
1565 } else {
1566 file.delete();
1567 }
1568 }
1569
1570 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001571 * some authority names have changed. copy over their settings and delete the old ones
1572 * @return true if a change was made
1573 */
1574 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1575 boolean writeNeeded = false;
1576
1577 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1578 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001579 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001580 AuthorityInfo authority = mAuthorities.valueAt(i);
1581 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001582 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001583 if (newAuthorityName == null) {
1584 continue;
1585 }
1586
1587 // remember this authority so we can remove it later. we can't remove it
1588 // now without messing up this loop iteration
1589 authoritiesToRemove.add(authority);
1590
1591 // this authority isn't enabled, no need to copy it to the new authority name since
1592 // the default is "disabled"
1593 if (!authority.enabled) {
1594 continue;
1595 }
1596
1597 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001598 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001599 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001600 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001601 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001602 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001603 continue;
1604 }
1605
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001606 AuthorityInfo newAuthority =
1607 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001608 newAuthority.enabled = true;
1609 writeNeeded = true;
1610 }
1611
1612 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001613 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001614 authorityInfo.target.account,
1615 authorityInfo.target.userId,
1616 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001617 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001618 writeNeeded = true;
1619 }
1620
1621 return writeNeeded;
1622 }
1623
Amith Yamasani04e0d262012-02-14 11:50:53 -08001624 private void parseListenForTickles(XmlPullParser parser) {
1625 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1626 int userId = 0;
1627 try {
1628 userId = Integer.parseInt(user);
1629 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001630 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001631 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001632 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001633 }
1634 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1635 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1636 mMasterSyncAutomatically.put(userId, listen);
1637 }
1638
Fred Quintanac2e46912010-03-15 16:10:44 -07001639 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 AuthorityInfo authority = null;
1641 int id = -1;
1642 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001643 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001644 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001645 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001646 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001647 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001648 }
1649 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001650 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001651 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001652 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001653 String accountName = parser.getAttributeValue(null, "account");
1654 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001655 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001656 String packageName = parser.getAttributeValue(null, "package");
1657 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001658 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001659 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001660 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001661 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001662 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001663 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001664 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001665 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001666 + " account=" + accountName
1667 + " accountType=" + accountType
1668 + " auth=" + authorityName
1669 + " package=" + packageName
1670 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001671 + " user=" + userId
1672 + " enabled=" + enabled
1673 + " syncable=" + syncable);
1674 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001675 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001676 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001677 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001678 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001679 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001680 if (accountName != null && authorityName != null) {
1681 info = new EndPoint(
1682 new Account(accountName, accountType),
1683 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001684 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001685 if (info != null) {
1686 authority = getOrCreateAuthorityLocked(info, id, false);
1687 // If the version is 0 then we are upgrading from a file format that did not
1688 // know about periodic syncs. In that case don't clear the list since we
1689 // want the default, which is a daily periodic sync.
1690 // Otherwise clear out this default list since we will populate it later with
1691 // the periodic sync descriptions that are read from the configuration file.
1692 if (version > 0) {
1693 authority.periodicSyncs.clear();
1694 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001695 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001696 }
1697 if (authority != null) {
1698 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001699 try {
1700 authority.syncable = (syncable == null) ?
1701 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1702 } catch (NumberFormatException e) {
1703 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1704 // format.
1705 if ("unknown".equals(syncable)) {
1706 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1707 } else {
1708 authority.syncable = Boolean.parseBoolean(syncable) ?
1709 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1710 }
1711
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001712 }
1713 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001714 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 + accountName + " auth=" + authorityName
1716 + " enabled=" + enabled
1717 + " syncable=" + syncable);
1718 }
1719 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001720 return authority;
1721 }
1722
Matthew Williamsfa774182013-06-18 15:44:11 -07001723 /**
1724 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1725 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001726 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001727 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001728 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001729 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001730 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001731 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001732 try {
1733 period = Long.parseLong(periodValue);
1734 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001735 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001736 return null;
1737 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001738 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001739 return null;
1740 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001741 try {
1742 flextime = Long.parseLong(flexValue);
1743 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001744 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001745 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001746 + ", using default: "
1747 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001748 } catch (NullPointerException expected) {
1749 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001750 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1751 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001752 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001753 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001754 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001755 new PeriodicSync(authorityInfo.target.account,
1756 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001757 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001758 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001759 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001760 return periodicSync;
1761 }
1762
Matthew Williamsfa774182013-06-18 15:44:11 -07001763 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001764 String name = parser.getAttributeValue(null, "name");
1765 String type = parser.getAttributeValue(null, "type");
1766 String value1 = parser.getAttributeValue(null, "value1");
1767 String value2 = parser.getAttributeValue(null, "value2");
1768
1769 try {
1770 if ("long".equals(type)) {
1771 extras.putLong(name, Long.parseLong(value1));
1772 } else if ("integer".equals(type)) {
1773 extras.putInt(name, Integer.parseInt(value1));
1774 } else if ("double".equals(type)) {
1775 extras.putDouble(name, Double.parseDouble(value1));
1776 } else if ("float".equals(type)) {
1777 extras.putFloat(name, Float.parseFloat(value1));
1778 } else if ("boolean".equals(type)) {
1779 extras.putBoolean(name, Boolean.parseBoolean(value1));
1780 } else if ("string".equals(type)) {
1781 extras.putString(name, value1);
1782 } else if ("account".equals(type)) {
1783 extras.putParcelable(name, new Account(value1, value2));
1784 }
1785 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001786 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001787 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001788 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001789 }
1790 }
1791
Dianne Hackborn231cc602009-04-27 17:10:36 -07001792 /**
1793 * Write all account information to the account file.
1794 */
1795 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001796 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001797 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001798 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001799 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001800
Dianne Hackborn231cc602009-04-27 17:10:36 -07001801 try {
1802 fos = mAccountInfoFile.startWrite();
1803 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001804 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001805 out.startDocument(null, true);
1806 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001807
Dianne Hackborn231cc602009-04-27 17:10:36 -07001808 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001809 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001810 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001811 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001812
1813 // Write the Sync Automatically flags for each user
1814 final int M = mMasterSyncAutomatically.size();
1815 for (int m = 0; m < M; m++) {
1816 int userId = mMasterSyncAutomatically.keyAt(m);
1817 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1818 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1819 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1820 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1821 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 }
Costin Manolache360e4542009-09-04 13:36:04 -07001823
Dianne Hackborn231cc602009-04-27 17:10:36 -07001824 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001825 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001826 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001827 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001828 out.startTag(null, "authority");
1829 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001830 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001831 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001832 out.attribute(null, "account", info.account.name);
1833 out.attribute(null, "type", info.account.type);
1834 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001835 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 out.endTag(null, "authority");
1837 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001838 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001839 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 mAccountInfoFile.finishWrite(fos);
1841 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001842 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001843 if (fos != null) {
1844 mAccountInfoFile.failWrite(fos);
1845 }
1846 }
1847 }
Costin Manolache360e4542009-09-04 13:36:04 -07001848
Dianne Hackborn231cc602009-04-27 17:10:36 -07001849 static int getIntColumn(Cursor c, String name) {
1850 return c.getInt(c.getColumnIndex(name));
1851 }
Costin Manolache360e4542009-09-04 13:36:04 -07001852
Dianne Hackborn231cc602009-04-27 17:10:36 -07001853 static long getLongColumn(Cursor c, String name) {
1854 return c.getLong(c.getColumnIndex(name));
1855 }
Costin Manolache360e4542009-09-04 13:36:04 -07001856
Dianne Hackborn231cc602009-04-27 17:10:36 -07001857 /**
1858 * Load sync engine state from the old syncmanager database, and then
1859 * erase it. Note that we don't deal with pending operations, active
1860 * sync, or history.
1861 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001862 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001863 // Look for old database to initialize from.
1864 File file = mContext.getDatabasePath("syncmanager.db");
1865 if (!file.exists()) {
1866 return;
1867 }
1868 String path = file.getPath();
1869 SQLiteDatabase db = null;
1870 try {
1871 db = SQLiteDatabase.openDatabase(path, null,
1872 SQLiteDatabase.OPEN_READONLY);
1873 } catch (SQLiteException e) {
1874 }
Costin Manolache360e4542009-09-04 13:36:04 -07001875
Dianne Hackborn231cc602009-04-27 17:10:36 -07001876 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001877 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001878
Dianne Hackborn231cc602009-04-27 17:10:36 -07001879 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001880 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001881 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001882 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001883 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1884 qb.setTables("stats, status");
1885 HashMap<String,String> map = new HashMap<String,String>();
1886 map.put("_id", "status._id as _id");
1887 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001888 if (hasType) {
1889 map.put("account_type", "stats.account_type as account_type");
1890 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001891 map.put("authority", "stats.authority as authority");
1892 map.put("totalElapsedTime", "totalElapsedTime");
1893 map.put("numSyncs", "numSyncs");
1894 map.put("numSourceLocal", "numSourceLocal");
1895 map.put("numSourcePoll", "numSourcePoll");
1896 map.put("numSourceServer", "numSourceServer");
1897 map.put("numSourceUser", "numSourceUser");
1898 map.put("lastSuccessSource", "lastSuccessSource");
1899 map.put("lastSuccessTime", "lastSuccessTime");
1900 map.put("lastFailureSource", "lastFailureSource");
1901 map.put("lastFailureTime", "lastFailureTime");
1902 map.put("lastFailureMesg", "lastFailureMesg");
1903 map.put("pending", "pending");
1904 qb.setProjectionMap(map);
1905 qb.appendWhere("stats._id = status.stats_id");
1906 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001909 String accountType = hasType
1910 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001911 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001912 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001914 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001915 AuthorityInfo authority =
1916 this.getOrCreateAuthorityLocked(
1917 new EndPoint(new Account(accountName, accountType),
1918 authorityName,
1919 0 /* legacy is single-user */)
1920 , -1,
1921 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001922 if (authority != null) {
1923 int i = mSyncStatus.size();
1924 boolean found = false;
1925 SyncStatusInfo st = null;
1926 while (i > 0) {
1927 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001928 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001929 if (st.authorityId == authority.ident) {
1930 found = true;
1931 break;
1932 }
1933 }
1934 if (!found) {
1935 st = new SyncStatusInfo(authority.ident);
1936 mSyncStatus.put(authority.ident, st);
1937 }
1938 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1939 st.numSyncs = getIntColumn(c, "numSyncs");
1940 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1941 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1942 st.numSourceServer = getIntColumn(c, "numSourceServer");
1943 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001944 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001945 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1946 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1947 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1948 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1949 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1950 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
Costin Manolache360e4542009-09-04 13:36:04 -07001953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001955
Dianne Hackborn231cc602009-04-27 17:10:36 -07001956 // Retrieve the settings.
1957 qb = new SQLiteQueryBuilder();
1958 qb.setTables("settings");
1959 c = qb.query(db, null, null, null, null, null, null);
1960 while (c.moveToNext()) {
1961 String name = c.getString(c.getColumnIndex("name"));
1962 String value = c.getString(c.getColumnIndex("value"));
1963 if (name == null) continue;
1964 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001965 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 } else if (name.startsWith("sync_provider_")) {
1967 String provider = name.substring("sync_provider_".length(),
1968 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001969 int i = mAuthorities.size();
1970 while (i > 0) {
1971 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001972 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001973 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001974 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001975 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001976 }
1977 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 }
Costin Manolache360e4542009-09-04 13:36:04 -07001980
Dianne Hackborn231cc602009-04-27 17:10:36 -07001981 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001982
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001984
Dianne Hackborn231cc602009-04-27 17:10:36 -07001985 (new File(path)).delete();
1986 }
1987 }
Costin Manolache360e4542009-09-04 13:36:04 -07001988
Dianne Hackborn231cc602009-04-27 17:10:36 -07001989 public static final int STATUS_FILE_END = 0;
1990 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001991
Dianne Hackborn231cc602009-04-27 17:10:36 -07001992 /**
1993 * Read all sync status back in to the initial engine state.
1994 */
1995 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001996 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001997 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001998 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001999 try {
2000 byte[] data = mStatusFile.readFully();
2001 Parcel in = Parcel.obtain();
2002 in.unmarshall(data, 0, data.length);
2003 in.setDataPosition(0);
2004 int token;
2005 while ((token=in.readInt()) != STATUS_FILE_END) {
2006 if (token == STATUS_FILE_ITEM) {
2007 SyncStatusInfo status = new SyncStatusInfo(in);
2008 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2009 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002010 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002011 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002012 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 mSyncStatus.put(status.authorityId, status);
2014 }
2015 } else {
2016 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002017 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002018 break;
2019 }
2020 }
2021 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002022 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002023 }
2024 }
Costin Manolache360e4542009-09-04 13:36:04 -07002025
Dianne Hackborn231cc602009-04-27 17:10:36 -07002026 /**
2027 * Write all sync status to the sync status file.
2028 */
2029 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002030 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002031 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002032 }
Costin Manolache360e4542009-09-04 13:36:04 -07002033
Dianne Hackborn231cc602009-04-27 17:10:36 -07002034 // The file is being written, so we don't need to have a scheduled
2035 // write until the next change.
2036 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002037
Dianne Hackborn231cc602009-04-27 17:10:36 -07002038 FileOutputStream fos = null;
2039 try {
2040 fos = mStatusFile.startWrite();
2041 Parcel out = Parcel.obtain();
2042 final int N = mSyncStatus.size();
2043 for (int i=0; i<N; i++) {
2044 SyncStatusInfo status = mSyncStatus.valueAt(i);
2045 out.writeInt(STATUS_FILE_ITEM);
2046 status.writeToParcel(out, 0);
2047 }
2048 out.writeInt(STATUS_FILE_END);
2049 fos.write(out.marshall());
2050 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002051
Dianne Hackborn231cc602009-04-27 17:10:36 -07002052 mStatusFile.finishWrite(fos);
2053 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002054 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002055 if (fos != null) {
2056 mStatusFile.failWrite(fos);
2057 }
2058 }
2059 }
Costin Manolache360e4542009-09-04 13:36:04 -07002060
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002061 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2062 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2063 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002064 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002065 } else {
2066 SyncRequest.Builder req =
2067 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002068 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002069 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002070 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002071 ContentResolver.requestSync(req.build());
2072 }
2073 }
2074
Alon Albert57286f92012-10-09 14:21:38 -07002075 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002076 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002077 // If this is happening in the system process, then call the syncrequest listener
2078 // to make a request back to the SyncManager directly.
2079 // If this is probably a test instance, then call back through the ContentResolver
2080 // which will know which userId to apply based on the Binder id.
2081 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2082 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002083 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002084 new EndPoint(account, authority, userId),
2085 reason,
2086 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002087 } else {
2088 ContentResolver.requestSync(account, authority, extras);
2089 }
2090 }
2091
Dianne Hackborn231cc602009-04-27 17:10:36 -07002092 public static final int STATISTICS_FILE_END = 0;
2093 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2094 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002095
Dianne Hackborn231cc602009-04-27 17:10:36 -07002096 /**
2097 * Read all sync statistics back in to the initial engine state.
2098 */
2099 private void readStatisticsLocked() {
2100 try {
2101 byte[] data = mStatisticsFile.readFully();
2102 Parcel in = Parcel.obtain();
2103 in.unmarshall(data, 0, data.length);
2104 in.setDataPosition(0);
2105 int token;
2106 int index = 0;
2107 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2108 if (token == STATISTICS_FILE_ITEM
2109 || token == STATISTICS_FILE_ITEM_OLD) {
2110 int day = in.readInt();
2111 if (token == STATISTICS_FILE_ITEM_OLD) {
2112 day = day - 2009 + 14245; // Magic!
2113 }
2114 DayStats ds = new DayStats(day);
2115 ds.successCount = in.readInt();
2116 ds.successTime = in.readLong();
2117 ds.failureCount = in.readInt();
2118 ds.failureTime = in.readLong();
2119 if (index < mDayStats.length) {
2120 mDayStats[index] = ds;
2121 index++;
2122 }
2123 } else {
2124 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002125 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002126 break;
2127 }
2128 }
2129 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002130 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002131 }
2132 }
Costin Manolache360e4542009-09-04 13:36:04 -07002133
Dianne Hackborn231cc602009-04-27 17:10:36 -07002134 /**
2135 * Write all sync statistics to the sync status file.
2136 */
2137 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002138 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002139 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002140 }
Costin Manolache360e4542009-09-04 13:36:04 -07002141
Dianne Hackborn231cc602009-04-27 17:10:36 -07002142 // The file is being written, so we don't need to have a scheduled
2143 // write until the next change.
2144 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002145
Dianne Hackborn231cc602009-04-27 17:10:36 -07002146 FileOutputStream fos = null;
2147 try {
2148 fos = mStatisticsFile.startWrite();
2149 Parcel out = Parcel.obtain();
2150 final int N = mDayStats.length;
2151 for (int i=0; i<N; i++) {
2152 DayStats ds = mDayStats[i];
2153 if (ds == null) {
2154 break;
2155 }
2156 out.writeInt(STATISTICS_FILE_ITEM);
2157 out.writeInt(ds.day);
2158 out.writeInt(ds.successCount);
2159 out.writeLong(ds.successTime);
2160 out.writeInt(ds.failureCount);
2161 out.writeLong(ds.failureTime);
2162 }
2163 out.writeInt(STATISTICS_FILE_END);
2164 fos.write(out.marshall());
2165 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002166
Dianne Hackborn231cc602009-04-27 17:10:36 -07002167 mStatisticsFile.finishWrite(fos);
2168 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002169 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002170 if (fos != null) {
2171 mStatisticsFile.failWrite(fos);
2172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002175
2176 /**
Marvin Paula6533252014-11-24 12:57:48 -08002177 * Let the BackupManager know that account sync settings have changed. This will trigger
2178 * {@link com.android.server.backup.SystemBackupAgent} to run.
2179 */
2180 public void queueBackup() {
2181 BackupManager.dataChanged("android");
2182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183}