blob: 64849aa321da101e1b051582b2488b2f7dfa1d5a [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
Fred Quintanafb084402010-03-23 17:57:03 -0700140 private static final int ACCOUNTS_VERSION = 2;
141
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
214 /**
215 * Default state for a newly installed adapter. An uninitialized adapter will receive an
216 * initialization sync which are governed by a different set of rules to that of regular
217 * syncs.
218 */
219 public static final int NOT_INITIALIZED = -1;
220 /**
221 * The adapter will not receive any syncs. This is behaviourally equivalent to
222 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
223 * while this is generally meant to be controlled by the developer.
224 */
225 public static final int NOT_SYNCABLE = 0;
226 /**
227 * The adapter is initialized and functioning. This is the normal state for an adapter.
228 */
229 public static final int SYNCABLE = 1;
230 /**
231 * The adapter is syncable but still requires an initialization sync. For example an adapter
232 * than has been restored from a previous device will be in this state. Not meant for
233 * external use.
234 */
235 public static final int SYNCABLE_NOT_INITIALIZED = 2;
236
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700237 /**
238 * The adapter is syncable but does not have access to the synced account and needs a
239 * user access approval.
240 */
241 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
242
Matthew Williams8ef22042013-07-26 12:56:39 -0700243 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700244 final int ident;
245 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700246 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700247 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800248 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700249 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800250 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700251 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800252 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700253
Matthew Williamsfa774182013-06-18 15:44:11 -0700254 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700255
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700256 /**
257 * Copy constructor for making deep-ish copies. Only the bundles stored
258 * in periodic syncs can make unexpected changes.
259 *
260 * @param toCopy AuthorityInfo to be copied.
261 */
262 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700263 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700264 ident = toCopy.ident;
265 enabled = toCopy.enabled;
266 syncable = toCopy.syncable;
267 backoffTime = toCopy.backoffTime;
268 backoffDelay = toCopy.backoffDelay;
269 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700270 periodicSyncs = new ArrayList<PeriodicSync>();
271 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700272 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700273 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700274 }
275 }
276
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700277 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700278 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700279 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000280 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700281 periodicSyncs = new ArrayList<PeriodicSync>();
282 defaultInitialisation();
283 }
284
285 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700286 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800287 backoffTime = -1; // if < 0 then we aren't in backoff mode
288 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000289
290 if (mPeriodicSyncAddedListener != null) {
291 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
292 DEFAULT_POLL_FREQUENCY_SECONDS,
293 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700294 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700295 }
Matthew Williams06485a72013-07-26 12:56:39 -0700296
297 @Override
298 public String toString() {
299 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
300 + backoffTime + ", delay=" + delayUntil;
301 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700302 }
Costin Manolache360e4542009-09-04 13:36:04 -0700303
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 public static class SyncHistoryItem {
305 int authorityId;
306 int historyId;
307 long eventTime;
308 long elapsedTime;
309 int source;
310 int event;
311 long upstreamActivity;
312 long downstreamActivity;
313 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700314 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700315 Bundle extras;
316 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700317 }
Costin Manolache360e4542009-09-04 13:36:04 -0700318
Dianne Hackborn231cc602009-04-27 17:10:36 -0700319 public static class DayStats {
320 public final int day;
321 public int successCount;
322 public long successTime;
323 public int failureCount;
324 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700325
Dianne Hackborn231cc602009-04-27 17:10:36 -0700326 public DayStats(int day) {
327 this.day = day;
328 }
329 }
Costin Manolache360e4542009-09-04 13:36:04 -0700330
Amith Yamasani04e0d262012-02-14 11:50:53 -0800331 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700332
333 /** Called when a sync is needed on an account(s) due to some change in state. */
334 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800335 }
336
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000337 interface PeriodicSyncAddedListener {
338 /** Called when a periodic sync is added. */
339 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
340 }
341
342 interface OnAuthorityRemovedListener {
343 /** Called when an authority is removed. */
344 void onAuthorityRemoved(EndPoint removedAuthority);
345 }
346
Dianne Hackborn231cc602009-04-27 17:10:36 -0700347 // Primary list of all syncable authorities. Also our global lock.
348 private final SparseArray<AuthorityInfo> mAuthorities =
349 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Amith Yamasani04e0d262012-02-14 11:50:53 -0800351 private final HashMap<AccountAndUser, AccountInfo> mAccounts
352 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353
Amith Yamasani04e0d262012-02-14 11:50:53 -0800354 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
355 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private final SparseArray<SyncStatusInfo> mSyncStatus =
358 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Dianne Hackborn231cc602009-04-27 17:10:36 -0700360 private final ArrayList<SyncHistoryItem> mSyncHistory =
361 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700362
Dianne Hackborn231cc602009-04-27 17:10:36 -0700363 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
364 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700365
Matthew Williams8ef22042013-07-26 12:56:39 -0700366 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700367 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
368 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700369
Fred Quintana77c560f2010-03-29 22:20:26 -0700370 private int mNextAuthorityId = 0;
371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 // We keep 4 weeks of stats.
373 private final DayStats[] mDayStats = new DayStats[7*4];
374 private final Calendar mCal;
375 private int mYear;
376 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800379
Dianne Hackborn231cc602009-04-27 17:10:36 -0700380 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700381
Ashish Sharma69d95de2012-04-11 17:27:24 -0700382 private int mSyncRandomOffset;
383
Dianne Hackborn231cc602009-04-27 17:10:36 -0700384 /**
385 * This file contains the core engine state: all accounts and the
386 * settings for them. It must never be lost, and should be changed
387 * infrequently, so it is stored as an XML file.
388 */
389 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700390
Dianne Hackborn231cc602009-04-27 17:10:36 -0700391 /**
392 * This file contains the current sync status. We would like to retain
393 * it across boots, but its loss is not the end of the world, so we store
394 * this information as binary data.
395 */
396 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 /**
399 * This file contains sync statistics. This is purely debugging information
400 * so is written infrequently and can be thrown away at any time.
401 */
402 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700403
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800406 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407
408 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000409 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800411 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700414
Dianne Hackborn231cc602009-04-27 17:10:36 -0700415 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800417 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000418 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 File systemDir = new File(dataDir, "system");
421 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800422 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700423
424 maybeDeleteLegacyPendingInfoLocked(syncDir);
425
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
427 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700429
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 readAccountInfoLocked();
431 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700433 readAndDeleteLegacyAccountInfoLocked();
434 writeAccountInfoLocked();
435 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700436 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 }
438
439 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800440 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800441 }
442
443 public static void init(Context context) {
444 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800445 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700447 File dataDir = Environment.getDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800448 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 }
450
451 public static SyncStorageEngine getSingleton() {
452 if (sSyncStorageEngine == null) {
453 throw new IllegalStateException("not initialized");
454 }
455 return sSyncStorageEngine;
456 }
457
Amith Yamasani04e0d262012-02-14 11:50:53 -0800458 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
459 if (mSyncRequestListener == null) {
460 mSyncRequestListener = listener;
461 }
462 }
463
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000464 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
465 if (mAuthorityRemovedListener == null) {
466 mAuthorityRemovedListener = listener;
467 }
468 }
469
470 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
471 if (mPeriodicSyncAddedListener == null) {
472 mPeriodicSyncAddedListener = listener;
473 }
474 }
475
Dianne Hackborn231cc602009-04-27 17:10:36 -0700476 @Override public void handleMessage(Message msg) {
477 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700478 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700480 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700481 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700482 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700483 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800484 }
485 }
486 }
Costin Manolache360e4542009-09-04 13:36:04 -0700487
Ashish Sharma69d95de2012-04-11 17:27:24 -0700488 public int getSyncRandomOffset() {
489 return mSyncRandomOffset;
490 }
491
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
493 synchronized (mAuthorities) {
494 mChangeListeners.register(callback, mask);
495 }
496 }
Costin Manolache360e4542009-09-04 13:36:04 -0700497
Dianne Hackborn231cc602009-04-27 17:10:36 -0700498 public void removeStatusChangeListener(ISyncStatusObserver callback) {
499 synchronized (mAuthorities) {
500 mChangeListeners.unregister(callback);
501 }
502 }
Costin Manolache360e4542009-09-04 13:36:04 -0700503
Matthew Williamsfa774182013-06-18 15:44:11 -0700504 /**
505 * Figure out a reasonable flex time for cases where none is provided (old api calls).
506 * @param syncTimeSeconds requested sync time from now.
507 * @return amount of seconds before syncTimeSeconds that the sync can occur.
508 * I.e.
509 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700510 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700511 */
512 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
513 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
514 // Small enough sync request time that we don't add flex time - developer probably
515 // wants to wait for an operation to occur before syncing so we honour the
516 // request time.
517 return 0L;
518 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
519 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
520 } else {
521 // Large enough sync request time that we cap the flex time.
522 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
523 }
524 }
525
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000526 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700527 ArrayList<ISyncStatusObserver> reports = null;
528 synchronized (mAuthorities) {
529 int i = mChangeListeners.beginBroadcast();
530 while (i > 0) {
531 i--;
532 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
533 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 continue;
535 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700536 if (reports == null) {
537 reports = new ArrayList<ISyncStatusObserver>(i);
538 }
539 reports.add(mChangeListeners.getBroadcastItem(i));
540 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700541 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700542 }
Costin Manolache360e4542009-09-04 13:36:04 -0700543
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700544 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000545 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700546 }
Costin Manolache360e4542009-09-04 13:36:04 -0700547
Dianne Hackborn231cc602009-04-27 17:10:36 -0700548 if (reports != null) {
549 int i = reports.size();
550 while (i > 0) {
551 i--;
552 try {
553 reports.get(i).onStatusChanged(which);
554 } catch (RemoteException e) {
555 // The remote callback list will take care of this for us.
556 }
557 }
558 }
559 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700560
Amith Yamasani04e0d262012-02-14 11:50:53 -0800561 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700562 synchronized (mAuthorities) {
563 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700564 AuthorityInfo authority = getAuthorityLocked(
565 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700566 "getSyncAutomatically");
567 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700568 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700569
Dianne Hackborn231cc602009-04-27 17:10:36 -0700570 int i = mAuthorities.size();
571 while (i > 0) {
572 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700573 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700574 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700575 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700576 return true;
577 }
578 }
579 return false;
580 }
581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582
Amith Yamasani04e0d262012-02-14 11:50:53 -0800583 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000584 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700585 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000586 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800587 + ", user " + userId + " -> " + sync);
588 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700589 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700590 AuthorityInfo authority =
591 getOrCreateAuthorityLocked(
592 new EndPoint(account, providerName, userId),
593 -1 /* ident */,
594 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700595 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700596 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000597 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800598 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700599 return;
600 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700601 // If the adapter was syncable but missing its initialization sync, set it to
602 // uninitialized now. This is to give it a chance to run any one-time initialization
603 // logic.
604 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
605 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
606 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700607 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700608 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700610
Fred Quintana77c560f2010-03-29 22:20:26 -0700611 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700612 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
613 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700614 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700615 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800616 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800617 }
618
Amith Yamasani04e0d262012-02-14 11:50:53 -0800619 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700620 synchronized (mAuthorities) {
621 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700622 AuthorityInfo authority = getAuthorityLocked(
623 new EndPoint(account, providerName, userId),
624 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700625 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700626 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700627 }
628 return authority.syncable;
629 }
630
631 int i = mAuthorities.size();
632 while (i > 0) {
633 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700634 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700635 if (authorityInfo.target != null
636 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700637 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700638 }
639 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700640 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700641 }
642 }
643
Amith Yamasani04e0d262012-02-14 11:50:53 -0800644 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700645 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700646 }
647
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700648 /**
649 * An enabled sync service and a syncable provider's adapter both get resolved to the same
650 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700651 * @param target target to set value for.
652 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700653 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700654 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700655 AuthorityInfo aInfo;
656 synchronized (mAuthorities) {
657 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700658 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
659 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700660 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000662 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700663 }
664 if (aInfo.syncable == syncable) {
665 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000666 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700667 }
668 return;
669 }
670 aInfo.syncable = syncable;
671 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700672 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700673 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700674 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700675 }
676 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
677 }
678
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700679 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800680 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700681 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
682 if (authority != null) {
683 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800684 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700685 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800686 }
687 }
688
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700689 /**
690 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
691 * the account or provider info be null, which signifies all accounts or providers.
692 */
693 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
694 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000695 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800696 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
697 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700698 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800699 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000700 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700701 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000702 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700703 changed = setBackoffLocked(
704 info.account /* may be null */,
705 info.userId,
706 info.provider /* may be null */,
707 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800708 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700709 AuthorityInfo authorityInfo =
710 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
711 if (authorityInfo.backoffTime == nextSyncTime
712 && authorityInfo.backoffDelay == nextDelay) {
713 changed = false;
714 } else {
715 authorityInfo.backoffTime = nextSyncTime;
716 authorityInfo.backoffDelay = nextDelay;
717 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800718 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800719 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800720 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800721 if (changed) {
722 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
723 }
724 }
725
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700726 /**
727 * Either set backoff for a specific authority, or set backoff for all the
728 * accounts on a specific adapter/all adapters.
729 *
730 * @param account account for which to set backoff. Null to specify all accounts.
731 * @param userId id of the user making this request.
732 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700733 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700734 */
735 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000736 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700737 boolean changed = false;
738 for (AccountInfo accountInfo : mAccounts.values()) {
739 if (account != null && !account.equals(accountInfo.accountAndUser.account)
740 && userId != accountInfo.accountAndUser.userId) {
741 continue;
742 }
743 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
744 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700745 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700746 continue;
747 }
748 if (authorityInfo.backoffTime != nextSyncTime
749 || authorityInfo.backoffDelay != nextDelay) {
750 authorityInfo.backoffTime = nextSyncTime;
751 authorityInfo.backoffDelay = nextDelay;
752 changed = true;
753 }
754 }
755 }
756 return changed;
757 }
758
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000759 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800760 boolean changed = false;
761 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000762 // Clear backoff for all sync adapters.
763 for (AccountInfo accountInfo : mAccounts.values()) {
764 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
765 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
766 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
767 if (Log.isLoggable(TAG, Log.VERBOSE)) {
768 Slog.v(TAG, "clearAllBackoffsLocked:"
769 + " authority:" + authorityInfo.target
770 + " account:" + accountInfo.accountAndUser.account.name
771 + " user:" + accountInfo.accountAndUser.userId
772 + " backoffTime was: " + authorityInfo.backoffTime
773 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800774 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000775 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
776 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
777 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800778 }
779 }
780 }
781 }
782
783 if (changed) {
784 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
785 }
786 }
787
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700788 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800789 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700790 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800791 if (authority == null) {
792 return 0;
793 }
794 return authority.delayUntil;
795 }
796 }
797
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 public void setDelayUntilTime(EndPoint info, long delayUntil) {
799 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000800 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700801 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800802 }
803 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
805 if (authority.delayUntil == delayUntil) {
806 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700807 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700808 authority.delayUntil = delayUntil;
809 }
810 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
811 }
812
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700813 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000814 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
815 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700816 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000817 boolean restoreAllPeriodicSyncs() {
818 if (mPeriodicSyncAddedListener == null) {
819 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800820 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000821 synchronized (mAuthorities) {
822 for (int i=0; i<mAuthorities.size(); i++) {
823 AuthorityInfo authority = mAuthorities.valueAt(i);
824 for (PeriodicSync periodicSync: authority.periodicSyncs) {
825 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
826 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
827 }
828 authority.periodicSyncs.clear();
829 }
830 writeAccountInfoLocked();
831 }
832 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800833 }
834
Amith Yamasani04e0d262012-02-14 11:50:53 -0800835 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700836 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700838 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700839 return;
840 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800841 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700842 writeAccountInfoLocked();
843 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700844 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700845 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
846 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700847 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700848 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800849 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800850 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852
Amith Yamasani04e0d262012-02-14 11:50:53 -0800853 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700854 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800855 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800856 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700857 }
858 }
Costin Manolache360e4542009-09-04 13:36:04 -0700859
Dianne Hackborn231cc602009-04-27 17:10:36 -0700860 public AuthorityInfo getAuthority(int authorityId) {
861 synchronized (mAuthorities) {
862 return mAuthorities.get(authorityId);
863 }
864 }
Costin Manolache360e4542009-09-04 13:36:04 -0700865
Dianne Hackborn231cc602009-04-27 17:10:36 -0700866 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700867 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700868 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700869 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700870 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700871 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700872 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700873 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700874 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 return true;
876 }
877 }
878 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700879 return false;
880 }
Costin Manolache360e4542009-09-04 13:36:04 -0700881
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000882 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000884 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
885 -1 /* desired identifier */,
886 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000888 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700889 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700890 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000891 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700893 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 }
Costin Manolache360e4542009-09-04 13:36:04 -0700895
Dianne Hackborn231cc602009-04-27 17:10:36 -0700896 /**
897 * Called when the set of account has changed, given the new array of
898 * active accounts.
899 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800900 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700902 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000903 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700904 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
906 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
907 while (accIt.hasNext()) {
908 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800909 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
910 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700911 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700912 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000913 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700914 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700915 for (AuthorityInfo auth : acc.authorities.values()) {
916 removing.put(auth.ident, auth);
917 }
918 accIt.remove();
919 }
920 }
Costin Manolache360e4542009-09-04 13:36:04 -0700921
Dianne Hackborn231cc602009-04-27 17:10:36 -0700922 // Clean out all data structures.
923 int i = removing.size();
924 if (i > 0) {
925 while (i > 0) {
926 i--;
927 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000928 AuthorityInfo auth = removing.valueAt(i);
929 if (mAuthorityRemovedListener != null) {
930 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
931 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700932 mAuthorities.remove(ident);
933 int j = mSyncStatus.size();
934 while (j > 0) {
935 j--;
936 if (mSyncStatus.keyAt(j) == ident) {
937 mSyncStatus.remove(mSyncStatus.keyAt(j));
938 }
939 }
940 j = mSyncHistory.size();
941 while (j > 0) {
942 j--;
943 if (mSyncHistory.get(j).authorityId == ident) {
944 mSyncHistory.remove(j);
945 }
946 }
947 }
948 writeAccountInfoLocked();
949 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700950 writeStatisticsLocked();
951 }
952 }
953 }
954
955 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700956 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
957 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700958 */
Fred Quintana918339a2010-10-05 14:00:39 -0700959 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
960 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700962 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000963 Slog.v(TAG, "setActiveSync: account="
964 + " auth=" + activeSyncContext.mSyncOperation.target
965 + " src=" + activeSyncContext.mSyncOperation.syncSource
966 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700967 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700968 final EndPoint info = activeSyncContext.mSyncOperation.target;
969 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
970 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700971 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700972 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700973 syncInfo = new SyncInfo(
974 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700975 authorityInfo.target.account,
976 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700977 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700978 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700979 }
Fred Quintana918339a2010-10-05 14:00:39 -0700980 reportActiveChange();
981 return syncInfo;
982 }
983
984 /**
985 * Called to indicate that a previously active sync is no longer active.
986 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800987 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700988 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700989 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000990 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800991 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -0700992 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -0700993 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800994 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -0700995 }
996
997 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700998 }
999
1000 /**
1001 * To allow others to send active change reports, to poke clients.
1002 */
1003 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001004 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 }
Costin Manolache360e4542009-09-04 13:36:04 -07001006
Dianne Hackborn231cc602009-04-27 17:10:36 -07001007 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001008 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001010 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 long id;
1012 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001013 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001014 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001015 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001016 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001017 if (authority == null) {
1018 return -1;
1019 }
1020 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001021 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001022 item.authorityId = authority.ident;
1023 item.historyId = mNextHistoryId++;
1024 if (mNextHistoryId < 0) mNextHistoryId = 0;
1025 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001026 item.source = op.syncSource;
1027 item.reason = op.reason;
1028 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001029 item.event = EVENT_START;
1030 mSyncHistory.add(0, item);
1031 while (mSyncHistory.size() > MAX_HISTORY) {
1032 mSyncHistory.remove(mSyncHistory.size()-1);
1033 }
1034 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001035 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001036 }
Costin Manolache360e4542009-09-04 13:36:04 -07001037
Fred Quintanaac9385e2009-06-22 18:00:59 -07001038 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001039 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041
Fred Quintana77c560f2010-03-29 22:20:26 -07001042 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001043 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001045 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001046 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001047 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 SyncHistoryItem item = null;
1049 int i = mSyncHistory.size();
1050 while (i > 0) {
1051 i--;
1052 item = mSyncHistory.get(i);
1053 if (item.historyId == historyId) {
1054 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001056 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
Costin Manolache360e4542009-09-04 13:36:04 -07001058
Dianne Hackborn231cc602009-04-27 17:10:36 -07001059 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001060 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 return;
1062 }
Costin Manolache360e4542009-09-04 13:36:04 -07001063
Dianne Hackborn231cc602009-04-27 17:10:36 -07001064 item.elapsedTime = elapsedTime;
1065 item.event = EVENT_STOP;
1066 item.mesg = resultMessage;
1067 item.downstreamActivity = downstreamActivity;
1068 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001069
Dianne Hackborn231cc602009-04-27 17:10:36 -07001070 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001071
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 status.numSyncs++;
1073 status.totalElapsedTime += elapsedTime;
1074 switch (item.source) {
1075 case SOURCE_LOCAL:
1076 status.numSourceLocal++;
1077 break;
1078 case SOURCE_POLL:
1079 status.numSourcePoll++;
1080 break;
1081 case SOURCE_USER:
1082 status.numSourceUser++;
1083 break;
1084 case SOURCE_SERVER:
1085 status.numSourceServer++;
1086 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001087 case SOURCE_PERIODIC:
1088 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001089 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 }
Costin Manolache360e4542009-09-04 13:36:04 -07001091
Dianne Hackborn231cc602009-04-27 17:10:36 -07001092 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001093 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 if (mDayStats[0] == null) {
1095 mDayStats[0] = new DayStats(day);
1096 } else if (day != mDayStats[0].day) {
1097 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1098 mDayStats[0] = new DayStats(day);
1099 writeStatisticsNow = true;
1100 } else if (mDayStats[0] == null) {
1101 }
1102 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001103
Dianne Hackborn231cc602009-04-27 17:10:36 -07001104 final long lastSyncTime = (item.eventTime + elapsedTime);
1105 boolean writeStatusNow = false;
1106 if (MESG_SUCCESS.equals(resultMessage)) {
1107 // - if successful, update the successful columns
1108 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1109 writeStatusNow = true;
1110 }
1111 status.lastSuccessTime = lastSyncTime;
1112 status.lastSuccessSource = item.source;
1113 status.lastFailureTime = 0;
1114 status.lastFailureSource = -1;
1115 status.lastFailureMesg = null;
1116 status.initialFailureTime = 0;
1117 ds.successCount++;
1118 ds.successTime += elapsedTime;
1119 } else if (!MESG_CANCELED.equals(resultMessage)) {
1120 if (status.lastFailureTime == 0) {
1121 writeStatusNow = true;
1122 }
1123 status.lastFailureTime = lastSyncTime;
1124 status.lastFailureSource = item.source;
1125 status.lastFailureMesg = resultMessage;
1126 if (status.initialFailureTime == 0) {
1127 status.initialFailureTime = lastSyncTime;
1128 }
1129 ds.failureCount++;
1130 ds.failureTime += elapsedTime;
1131 }
Costin Manolache360e4542009-09-04 13:36:04 -07001132
Dianne Hackborn231cc602009-04-27 17:10:36 -07001133 if (writeStatusNow) {
1134 writeStatusLocked();
1135 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1136 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1137 WRITE_STATUS_DELAY);
1138 }
1139 if (writeStatisticsNow) {
1140 writeStatisticsLocked();
1141 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1142 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1143 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001144 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001145 }
Costin Manolache360e4542009-09-04 13:36:04 -07001146
Fred Quintanaac9385e2009-06-22 18:00:59 -07001147 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001148 }
1149
1150 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001151 * Return a list of the currently active syncs. Note that the returned
1152 * items are the real, live active sync objects, so be careful what you do
1153 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001154 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001155 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001156 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001157 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001158 }
1159 }
Costin Manolache360e4542009-09-04 13:36:04 -07001160
Dianne Hackborn231cc602009-04-27 17:10:36 -07001161 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001162 * @param userId Id of user to return current sync info.
1163 * @param canAccessAccounts Determines whether to redact Account information from the result.
1164 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001165 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001166 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001167 synchronized (mAuthorities) {
1168 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1169 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1170 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001171 SyncInfo copy;
1172 if (!canAccessAccounts) {
1173 copy = SyncInfo.createAccountRedacted(
1174 sync.authorityId, sync.authority, sync.startTime);
1175 } else {
1176 copy = new SyncInfo(sync);
1177 }
1178 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001179 }
1180 return syncsCopy;
1181 }
1182 }
1183
1184 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1185 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1186 if (syncs == null) {
1187 syncs = new ArrayList<SyncInfo>();
1188 mCurrentSyncs.put(userId, syncs);
1189 }
1190 return syncs;
1191 }
1192
1193 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001194 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001195 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001196 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001197 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001198 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001199 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001200 true /* write to storage if this results in a change */);
1201 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1202 }
1203 }
1204
1205 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001206 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001207 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001208 * @param info the endpoint target we are querying status info for.
1209 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001210 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001211 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001212 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001213 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001214 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001215 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001216 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001217 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001218 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001220 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001221 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001222 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001223 }
1224 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001225 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001226 }
1227 }
Costin Manolache360e4542009-09-04 13:36:04 -07001228
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001229 /** Return true if the pending status is true of any matching authorities. */
1230 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001231 synchronized (mAuthorities) {
1232 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001233 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001234 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1236 if (ainfo == null) {
1237 continue;
1238 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001239 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001240 continue;
1241 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001242 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001243 return true;
1244 }
1245 }
1246 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 }
1248 }
1249
1250 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001251 * Return an array of the current sync status for all authorities. Note
1252 * that the objects inside the array are the real, live status objects,
1253 * so be careful what you do with them.
1254 */
1255 public ArrayList<SyncHistoryItem> getSyncHistory() {
1256 synchronized (mAuthorities) {
1257 final int N = mSyncHistory.size();
1258 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1259 for (int i=0; i<N; i++) {
1260 items.add(mSyncHistory.get(i));
1261 }
1262 return items;
1263 }
1264 }
Costin Manolache360e4542009-09-04 13:36:04 -07001265
Dianne Hackborn231cc602009-04-27 17:10:36 -07001266 /**
1267 * Return an array of the current per-day statistics. Note
1268 * that the objects inside the array are the real, live status objects,
1269 * so be careful what you do with them.
1270 */
1271 public DayStats[] getDayStatistics() {
1272 synchronized (mAuthorities) {
1273 DayStats[] ds = new DayStats[mDayStats.length];
1274 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1275 return ds;
1276 }
1277 }
Costin Manolache360e4542009-09-04 13:36:04 -07001278
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001279 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1280 AuthorityInfo authorityInfo) {
1281 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1282 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1283 }
1284
Dianne Hackborn55280a92009-05-07 15:53:46 -07001285 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001286 mCal.setTimeInMillis(System.currentTimeMillis());
1287 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1288 if (mYear != mCal.get(Calendar.YEAR)) {
1289 mYear = mCal.get(Calendar.YEAR);
1290 mCal.clear();
1291 mCal.set(Calendar.YEAR, mYear);
1292 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1293 }
1294 return dayOfYear + mYearInDays;
1295 }
Costin Manolache360e4542009-09-04 13:36:04 -07001296
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001298 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001299 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001300 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001302 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001304 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001305 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1306 AccountInfo accountInfo = mAccounts.get(au);
1307 if (accountInfo == null) {
1308 if (tag != null) {
1309 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1310 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001311 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001312 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001313 return null;
1314 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001315 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1316 if (authority == null) {
1317 if (tag != null) {
1318 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1319 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1320 }
1321 }
1322 return null;
1323 }
1324 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001325 }
Costin Manolache360e4542009-09-04 13:36:04 -07001326
Matthew Williamsfa774182013-06-18 15:44:11 -07001327 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001328 * @param info info identifying target.
1329 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001330 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001331 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001332 * exists.
1333 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001334 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1335 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001336 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1337 AccountInfo account = mAccounts.get(au);
1338 if (account == null) {
1339 account = new AccountInfo(au);
1340 mAccounts.put(au, account);
1341 }
1342 authority = account.authorities.get(info.provider);
1343 if (authority == null) {
1344 authority = createAuthorityLocked(info, ident, doWrite);
1345 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001346 }
1347 return authority;
1348 }
1349
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001350 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1351 AuthorityInfo authority;
1352 if (ident < 0) {
1353 ident = mNextAuthorityId;
1354 mNextAuthorityId++;
1355 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001356 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001357 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001358 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001359 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001360 authority = new AuthorityInfo(info, ident);
1361 mAuthorities.put(ident, authority);
1362 if (doWrite) {
1363 writeAccountInfoLocked();
1364 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001365 return authority;
1366 }
Costin Manolache360e4542009-09-04 13:36:04 -07001367
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001368 public void removeAuthority(EndPoint info) {
1369 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001370 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001371 }
1372 }
1373
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001374
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001375 /**
1376 * Remove an authority associated with a provider. Needs to be a standalone function for
1377 * backward compatibility.
1378 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001379 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001380 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001382 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001383 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1384 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001385 if (mAuthorityRemovedListener != null) {
1386 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1387 }
Fred Quintanafb084402010-03-23 17:57:03 -07001388 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001389 if (doWrite) {
1390 writeAccountInfoLocked();
1391 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001392 }
1393 }
1394 }
1395
Dianne Hackborn231cc602009-04-27 17:10:36 -07001396 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1397 SyncStatusInfo status = mSyncStatus.get(authorityId);
1398 if (status == null) {
1399 status = new SyncStatusInfo(authorityId);
1400 mSyncStatus.put(authorityId, status);
1401 }
1402 return status;
1403 }
Costin Manolache360e4542009-09-04 13:36:04 -07001404
Dianne Hackborn55280a92009-05-07 15:53:46 -07001405 public void writeAllState() {
1406 synchronized (mAuthorities) {
1407 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001408 writeStatusLocked();
1409 writeStatisticsLocked();
1410 }
1411 }
Costin Manolache360e4542009-09-04 13:36:04 -07001412
Dianne Hackborn231cc602009-04-27 17:10:36 -07001413 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001414 * public for testing
1415 */
1416 public void clearAndReadState() {
1417 synchronized (mAuthorities) {
1418 mAuthorities.clear();
1419 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001420 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001421 mSyncStatus.clear();
1422 mSyncHistory.clear();
1423
1424 readAccountInfoLocked();
1425 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001426 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001427 readAndDeleteLegacyAccountInfoLocked();
1428 writeAccountInfoLocked();
1429 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001430 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001431 }
1432 }
1433
1434 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001435 * Read all account information back in to the initial engine state.
1436 */
1437 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001438 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001439 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001442 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001443 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001444 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001445 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001446 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001448 while (eventType != XmlPullParser.START_TAG &&
1449 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001450 eventType = parser.next();
1451 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001452 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001453 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001454 return;
1455 }
1456
Dianne Hackborn231cc602009-04-27 17:10:36 -07001457 String tagName = parser.getName();
1458 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001459 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001460 String versionString = parser.getAttributeValue(null, "version");
1461 int version;
1462 try {
1463 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1464 } catch (NumberFormatException e) {
1465 version = 0;
1466 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001467 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001468 try {
1469 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1470 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1471 } catch (NumberFormatException e) {
1472 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001473 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001474 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1475 try {
1476 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1477 } catch (NumberFormatException e) {
1478 mSyncRandomOffset = 0;
1479 }
1480 if (mSyncRandomOffset == 0) {
1481 Random random = new Random(System.currentTimeMillis());
1482 mSyncRandomOffset = random.nextInt(86400);
1483 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001484 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001485 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001486 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001487 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001488 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001489 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001490 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001491 if (parser.getDepth() == 2) {
1492 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001493 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001494 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001495 if (authority != null) {
1496 if (authority.ident > highestAuthorityId) {
1497 highestAuthorityId = authority.ident;
1498 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001499 } else {
1500 EventLog.writeEvent(0x534e4554, "26513719", -1,
1501 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001502 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001503 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1504 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001505 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001506 } else if (parser.getDepth() == 3) {
1507 if ("periodicSync".equals(tagName) && authority != null) {
1508 periodicSync = parsePeriodicSync(parser, authority);
1509 }
1510 } else if (parser.getDepth() == 4 && periodicSync != null) {
1511 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001512 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001513 }
1514 }
1515 }
1516 eventType = parser.next();
1517 } while (eventType != XmlPullParser.END_DOCUMENT);
1518 }
1519 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001520 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001521 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001523 if (fis == null) Slog.i(TAG, "No initial accounts");
1524 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001525 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001527 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001528 if (fis != null) {
1529 try {
1530 fis.close();
1531 } catch (java.io.IOException e1) {
1532 }
1533 }
1534 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001535
Fred Quintana77c560f2010-03-29 22:20:26 -07001536 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001537 }
Costin Manolache360e4542009-09-04 13:36:04 -07001538
Fred Quintanafb084402010-03-23 17:57:03 -07001539 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001540 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1541 * pending.xml was used starting in KLP.
1542 * @param syncDir directory where the sync files are located.
1543 */
1544 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1545 File file = new File(syncDir, "pending.bin");
1546 if (!file.exists()) {
1547 return;
1548 } else {
1549 file.delete();
1550 }
1551 }
1552
1553 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001554 * some authority names have changed. copy over their settings and delete the old ones
1555 * @return true if a change was made
1556 */
1557 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1558 boolean writeNeeded = false;
1559
1560 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1561 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001562 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001563 AuthorityInfo authority = mAuthorities.valueAt(i);
1564 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001565 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001566 if (newAuthorityName == null) {
1567 continue;
1568 }
1569
1570 // remember this authority so we can remove it later. we can't remove it
1571 // now without messing up this loop iteration
1572 authoritiesToRemove.add(authority);
1573
1574 // this authority isn't enabled, no need to copy it to the new authority name since
1575 // the default is "disabled"
1576 if (!authority.enabled) {
1577 continue;
1578 }
1579
1580 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001581 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001582 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001583 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001584 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001585 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001586 continue;
1587 }
1588
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001589 AuthorityInfo newAuthority =
1590 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001591 newAuthority.enabled = true;
1592 writeNeeded = true;
1593 }
1594
1595 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001596 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001597 authorityInfo.target.account,
1598 authorityInfo.target.userId,
1599 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001600 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001601 writeNeeded = true;
1602 }
1603
1604 return writeNeeded;
1605 }
1606
Amith Yamasani04e0d262012-02-14 11:50:53 -08001607 private void parseListenForTickles(XmlPullParser parser) {
1608 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1609 int userId = 0;
1610 try {
1611 userId = Integer.parseInt(user);
1612 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001613 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001614 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001615 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001616 }
1617 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1618 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1619 mMasterSyncAutomatically.put(userId, listen);
1620 }
1621
Fred Quintanac2e46912010-03-15 16:10:44 -07001622 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001623 AuthorityInfo authority = null;
1624 int id = -1;
1625 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001626 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001627 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001628 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001629 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001630 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001631 }
1632 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001633 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001634 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001635 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001636 String accountName = parser.getAttributeValue(null, "account");
1637 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001639 String packageName = parser.getAttributeValue(null, "package");
1640 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001641 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001642 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001643 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001644 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001645 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001646 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001647 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001648 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001649 + " account=" + accountName
1650 + " accountType=" + accountType
1651 + " auth=" + authorityName
1652 + " package=" + packageName
1653 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001654 + " user=" + userId
1655 + " enabled=" + enabled
1656 + " syncable=" + syncable);
1657 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001658 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001659 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001660 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001661 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001662 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001663 if (accountName != null && authorityName != null) {
1664 info = new EndPoint(
1665 new Account(accountName, accountType),
1666 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001667 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001668 if (info != null) {
1669 authority = getOrCreateAuthorityLocked(info, id, false);
1670 // If the version is 0 then we are upgrading from a file format that did not
1671 // know about periodic syncs. In that case don't clear the list since we
1672 // want the default, which is a daily periodic sync.
1673 // Otherwise clear out this default list since we will populate it later with
1674 // the periodic sync descriptions that are read from the configuration file.
1675 if (version > 0) {
1676 authority.periodicSyncs.clear();
1677 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001678 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001679 }
1680 if (authority != null) {
1681 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001682 try {
1683 authority.syncable = (syncable == null) ?
1684 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1685 } catch (NumberFormatException e) {
1686 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1687 // format.
1688 if ("unknown".equals(syncable)) {
1689 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1690 } else {
1691 authority.syncable = Boolean.parseBoolean(syncable) ?
1692 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1693 }
1694
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001695 }
1696 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001697 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001698 + accountName + " auth=" + authorityName
1699 + " enabled=" + enabled
1700 + " syncable=" + syncable);
1701 }
1702 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001703 return authority;
1704 }
1705
Matthew Williamsfa774182013-06-18 15:44:11 -07001706 /**
1707 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1708 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001709 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001710 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001711 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001712 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001713 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001714 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 try {
1716 period = Long.parseLong(periodValue);
1717 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001718 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001719 return null;
1720 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001721 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001722 return null;
1723 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001724 try {
1725 flextime = Long.parseLong(flexValue);
1726 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001727 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001728 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001729 + ", using default: "
1730 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001731 } catch (NullPointerException expected) {
1732 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001733 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1734 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001735 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001736 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001737 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001738 new PeriodicSync(authorityInfo.target.account,
1739 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001740 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001741 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001742 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001743 return periodicSync;
1744 }
1745
Matthew Williamsfa774182013-06-18 15:44:11 -07001746 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001747 String name = parser.getAttributeValue(null, "name");
1748 String type = parser.getAttributeValue(null, "type");
1749 String value1 = parser.getAttributeValue(null, "value1");
1750 String value2 = parser.getAttributeValue(null, "value2");
1751
1752 try {
1753 if ("long".equals(type)) {
1754 extras.putLong(name, Long.parseLong(value1));
1755 } else if ("integer".equals(type)) {
1756 extras.putInt(name, Integer.parseInt(value1));
1757 } else if ("double".equals(type)) {
1758 extras.putDouble(name, Double.parseDouble(value1));
1759 } else if ("float".equals(type)) {
1760 extras.putFloat(name, Float.parseFloat(value1));
1761 } else if ("boolean".equals(type)) {
1762 extras.putBoolean(name, Boolean.parseBoolean(value1));
1763 } else if ("string".equals(type)) {
1764 extras.putString(name, value1);
1765 } else if ("account".equals(type)) {
1766 extras.putParcelable(name, new Account(value1, value2));
1767 }
1768 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001769 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001770 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001771 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001772 }
1773 }
1774
Dianne Hackborn231cc602009-04-27 17:10:36 -07001775 /**
1776 * Write all account information to the account file.
1777 */
1778 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001779 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001780 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001781 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001782 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001783
Dianne Hackborn231cc602009-04-27 17:10:36 -07001784 try {
1785 fos = mAccountInfoFile.startWrite();
1786 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001787 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001788 out.startDocument(null, true);
1789 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001790
Dianne Hackborn231cc602009-04-27 17:10:36 -07001791 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001792 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001793 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001794 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001795
1796 // Write the Sync Automatically flags for each user
1797 final int M = mMasterSyncAutomatically.size();
1798 for (int m = 0; m < M; m++) {
1799 int userId = mMasterSyncAutomatically.keyAt(m);
1800 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1801 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1802 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1803 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1804 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001805 }
Costin Manolache360e4542009-09-04 13:36:04 -07001806
Dianne Hackborn231cc602009-04-27 17:10:36 -07001807 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001808 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001809 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001810 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 out.startTag(null, "authority");
1812 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001813 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001814 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001815 out.attribute(null, "account", info.account.name);
1816 out.attribute(null, "type", info.account.type);
1817 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001818 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001819 out.endTag(null, "authority");
1820 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001821 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001823 mAccountInfoFile.finishWrite(fos);
1824 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001825 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 if (fos != null) {
1827 mAccountInfoFile.failWrite(fos);
1828 }
1829 }
1830 }
Costin Manolache360e4542009-09-04 13:36:04 -07001831
Dianne Hackborn231cc602009-04-27 17:10:36 -07001832 static int getIntColumn(Cursor c, String name) {
1833 return c.getInt(c.getColumnIndex(name));
1834 }
Costin Manolache360e4542009-09-04 13:36:04 -07001835
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 static long getLongColumn(Cursor c, String name) {
1837 return c.getLong(c.getColumnIndex(name));
1838 }
Costin Manolache360e4542009-09-04 13:36:04 -07001839
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 /**
1841 * Load sync engine state from the old syncmanager database, and then
1842 * erase it. Note that we don't deal with pending operations, active
1843 * sync, or history.
1844 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001845 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001846 // Look for old database to initialize from.
1847 File file = mContext.getDatabasePath("syncmanager.db");
1848 if (!file.exists()) {
1849 return;
1850 }
1851 String path = file.getPath();
1852 SQLiteDatabase db = null;
1853 try {
1854 db = SQLiteDatabase.openDatabase(path, null,
1855 SQLiteDatabase.OPEN_READONLY);
1856 } catch (SQLiteException e) {
1857 }
Costin Manolache360e4542009-09-04 13:36:04 -07001858
Dianne Hackborn231cc602009-04-27 17:10:36 -07001859 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001860 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001861
Dianne Hackborn231cc602009-04-27 17:10:36 -07001862 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001863 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001864 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001865 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001866 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1867 qb.setTables("stats, status");
1868 HashMap<String,String> map = new HashMap<String,String>();
1869 map.put("_id", "status._id as _id");
1870 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001871 if (hasType) {
1872 map.put("account_type", "stats.account_type as account_type");
1873 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001874 map.put("authority", "stats.authority as authority");
1875 map.put("totalElapsedTime", "totalElapsedTime");
1876 map.put("numSyncs", "numSyncs");
1877 map.put("numSourceLocal", "numSourceLocal");
1878 map.put("numSourcePoll", "numSourcePoll");
1879 map.put("numSourceServer", "numSourceServer");
1880 map.put("numSourceUser", "numSourceUser");
1881 map.put("lastSuccessSource", "lastSuccessSource");
1882 map.put("lastSuccessTime", "lastSuccessTime");
1883 map.put("lastFailureSource", "lastFailureSource");
1884 map.put("lastFailureTime", "lastFailureTime");
1885 map.put("lastFailureMesg", "lastFailureMesg");
1886 map.put("pending", "pending");
1887 qb.setProjectionMap(map);
1888 qb.appendWhere("stats._id = status.stats_id");
1889 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001891 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001892 String accountType = hasType
1893 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001894 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001895 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001897 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001898 AuthorityInfo authority =
1899 this.getOrCreateAuthorityLocked(
1900 new EndPoint(new Account(accountName, accountType),
1901 authorityName,
1902 0 /* legacy is single-user */)
1903 , -1,
1904 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001905 if (authority != null) {
1906 int i = mSyncStatus.size();
1907 boolean found = false;
1908 SyncStatusInfo st = null;
1909 while (i > 0) {
1910 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001911 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001912 if (st.authorityId == authority.ident) {
1913 found = true;
1914 break;
1915 }
1916 }
1917 if (!found) {
1918 st = new SyncStatusInfo(authority.ident);
1919 mSyncStatus.put(authority.ident, st);
1920 }
1921 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1922 st.numSyncs = getIntColumn(c, "numSyncs");
1923 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1924 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1925 st.numSourceServer = getIntColumn(c, "numSourceServer");
1926 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001927 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001928 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1929 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1930 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1931 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1932 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1933 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Costin Manolache360e4542009-09-04 13:36:04 -07001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001938
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 // Retrieve the settings.
1940 qb = new SQLiteQueryBuilder();
1941 qb.setTables("settings");
1942 c = qb.query(db, null, null, null, null, null, null);
1943 while (c.moveToNext()) {
1944 String name = c.getString(c.getColumnIndex("name"));
1945 String value = c.getString(c.getColumnIndex("value"));
1946 if (name == null) continue;
1947 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001948 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001949 } else if (name.startsWith("sync_provider_")) {
1950 String provider = name.substring("sync_provider_".length(),
1951 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001952 int i = mAuthorities.size();
1953 while (i > 0) {
1954 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001955 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001956 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001957 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001958 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001959 }
1960 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
Costin Manolache360e4542009-09-04 13:36:04 -07001963
Dianne Hackborn231cc602009-04-27 17:10:36 -07001964 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001965
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001967
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 (new File(path)).delete();
1969 }
1970 }
Costin Manolache360e4542009-09-04 13:36:04 -07001971
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 public static final int STATUS_FILE_END = 0;
1973 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001974
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 /**
1976 * Read all sync status back in to the initial engine state.
1977 */
1978 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001979 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001980 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001981 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001982 try {
1983 byte[] data = mStatusFile.readFully();
1984 Parcel in = Parcel.obtain();
1985 in.unmarshall(data, 0, data.length);
1986 in.setDataPosition(0);
1987 int token;
1988 while ((token=in.readInt()) != STATUS_FILE_END) {
1989 if (token == STATUS_FILE_ITEM) {
1990 SyncStatusInfo status = new SyncStatusInfo(in);
1991 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1992 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07001993 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001994 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07001995 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001996 mSyncStatus.put(status.authorityId, status);
1997 }
1998 } else {
1999 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002000 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002001 break;
2002 }
2003 }
2004 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002005 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002006 }
2007 }
Costin Manolache360e4542009-09-04 13:36:04 -07002008
Dianne Hackborn231cc602009-04-27 17:10:36 -07002009 /**
2010 * Write all sync status to the sync status file.
2011 */
2012 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002013 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002014 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002015 }
Costin Manolache360e4542009-09-04 13:36:04 -07002016
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 // The file is being written, so we don't need to have a scheduled
2018 // write until the next change.
2019 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002020
Dianne Hackborn231cc602009-04-27 17:10:36 -07002021 FileOutputStream fos = null;
2022 try {
2023 fos = mStatusFile.startWrite();
2024 Parcel out = Parcel.obtain();
2025 final int N = mSyncStatus.size();
2026 for (int i=0; i<N; i++) {
2027 SyncStatusInfo status = mSyncStatus.valueAt(i);
2028 out.writeInt(STATUS_FILE_ITEM);
2029 status.writeToParcel(out, 0);
2030 }
2031 out.writeInt(STATUS_FILE_END);
2032 fos.write(out.marshall());
2033 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002034
Dianne Hackborn231cc602009-04-27 17:10:36 -07002035 mStatusFile.finishWrite(fos);
2036 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002037 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002038 if (fos != null) {
2039 mStatusFile.failWrite(fos);
2040 }
2041 }
2042 }
Costin Manolache360e4542009-09-04 13:36:04 -07002043
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002044 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2045 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2046 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002047 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002048 } else {
2049 SyncRequest.Builder req =
2050 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002051 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002052 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002053 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002054 ContentResolver.requestSync(req.build());
2055 }
2056 }
2057
Alon Albert57286f92012-10-09 14:21:38 -07002058 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002059 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002060 // If this is happening in the system process, then call the syncrequest listener
2061 // to make a request back to the SyncManager directly.
2062 // If this is probably a test instance, then call back through the ContentResolver
2063 // which will know which userId to apply based on the Binder id.
2064 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2065 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002066 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002067 new EndPoint(account, authority, userId),
2068 reason,
2069 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002070 } else {
2071 ContentResolver.requestSync(account, authority, extras);
2072 }
2073 }
2074
Dianne Hackborn231cc602009-04-27 17:10:36 -07002075 public static final int STATISTICS_FILE_END = 0;
2076 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2077 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002078
Dianne Hackborn231cc602009-04-27 17:10:36 -07002079 /**
2080 * Read all sync statistics back in to the initial engine state.
2081 */
2082 private void readStatisticsLocked() {
2083 try {
2084 byte[] data = mStatisticsFile.readFully();
2085 Parcel in = Parcel.obtain();
2086 in.unmarshall(data, 0, data.length);
2087 in.setDataPosition(0);
2088 int token;
2089 int index = 0;
2090 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2091 if (token == STATISTICS_FILE_ITEM
2092 || token == STATISTICS_FILE_ITEM_OLD) {
2093 int day = in.readInt();
2094 if (token == STATISTICS_FILE_ITEM_OLD) {
2095 day = day - 2009 + 14245; // Magic!
2096 }
2097 DayStats ds = new DayStats(day);
2098 ds.successCount = in.readInt();
2099 ds.successTime = in.readLong();
2100 ds.failureCount = in.readInt();
2101 ds.failureTime = in.readLong();
2102 if (index < mDayStats.length) {
2103 mDayStats[index] = ds;
2104 index++;
2105 }
2106 } else {
2107 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002108 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002109 break;
2110 }
2111 }
2112 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002113 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002114 }
2115 }
Costin Manolache360e4542009-09-04 13:36:04 -07002116
Dianne Hackborn231cc602009-04-27 17:10:36 -07002117 /**
2118 * Write all sync statistics to the sync status file.
2119 */
2120 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002121 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002122 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002123 }
Costin Manolache360e4542009-09-04 13:36:04 -07002124
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 // The file is being written, so we don't need to have a scheduled
2126 // write until the next change.
2127 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002128
Dianne Hackborn231cc602009-04-27 17:10:36 -07002129 FileOutputStream fos = null;
2130 try {
2131 fos = mStatisticsFile.startWrite();
2132 Parcel out = Parcel.obtain();
2133 final int N = mDayStats.length;
2134 for (int i=0; i<N; i++) {
2135 DayStats ds = mDayStats[i];
2136 if (ds == null) {
2137 break;
2138 }
2139 out.writeInt(STATISTICS_FILE_ITEM);
2140 out.writeInt(ds.day);
2141 out.writeInt(ds.successCount);
2142 out.writeLong(ds.successTime);
2143 out.writeInt(ds.failureCount);
2144 out.writeLong(ds.failureTime);
2145 }
2146 out.writeInt(STATISTICS_FILE_END);
2147 fos.write(out.marshall());
2148 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002149
Dianne Hackborn231cc602009-04-27 17:10:36 -07002150 mStatisticsFile.finishWrite(fos);
2151 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002152 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002153 if (fos != null) {
2154 mStatisticsFile.failWrite(fos);
2155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002158
2159 /**
Marvin Paula6533252014-11-24 12:57:48 -08002160 * Let the BackupManager know that account sync settings have changed. This will trigger
2161 * {@link com.android.server.backup.SystemBackupAgent} to run.
2162 */
2163 public void queueBackup() {
2164 BackupManager.dataChanged("android");
2165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166}