blob: f8e3e48f80264f34df274e041fa7faa9a110fcf1 [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. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080083 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
84
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
Matthew Williams8ef22042013-07-26 12:56:39 -0700237 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700238 final int ident;
239 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700240 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700241 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800242 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700243 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800244 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700245 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800246 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700247
Matthew Williamsfa774182013-06-18 15:44:11 -0700248 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700249
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700250 /**
251 * Copy constructor for making deep-ish copies. Only the bundles stored
252 * in periodic syncs can make unexpected changes.
253 *
254 * @param toCopy AuthorityInfo to be copied.
255 */
256 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700257 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700258 ident = toCopy.ident;
259 enabled = toCopy.enabled;
260 syncable = toCopy.syncable;
261 backoffTime = toCopy.backoffTime;
262 backoffDelay = toCopy.backoffDelay;
263 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700264 periodicSyncs = new ArrayList<PeriodicSync>();
265 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700266 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700267 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700268 }
269 }
270
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700272 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700273 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000274 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275 periodicSyncs = new ArrayList<PeriodicSync>();
276 defaultInitialisation();
277 }
278
279 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700280 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800281 backoffTime = -1; // if < 0 then we aren't in backoff mode
282 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000283
284 if (mPeriodicSyncAddedListener != null) {
285 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
286 DEFAULT_POLL_FREQUENCY_SECONDS,
287 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700288 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700289 }
Matthew Williams06485a72013-07-26 12:56:39 -0700290
291 @Override
292 public String toString() {
293 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
294 + backoffTime + ", delay=" + delayUntil;
295 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 }
Costin Manolache360e4542009-09-04 13:36:04 -0700297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 public static class SyncHistoryItem {
299 int authorityId;
300 int historyId;
301 long eventTime;
302 long elapsedTime;
303 int source;
304 int event;
305 long upstreamActivity;
306 long downstreamActivity;
307 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700308 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700309 Bundle extras;
310 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 }
Costin Manolache360e4542009-09-04 13:36:04 -0700312
Dianne Hackborn231cc602009-04-27 17:10:36 -0700313 public static class DayStats {
314 public final int day;
315 public int successCount;
316 public long successTime;
317 public int failureCount;
318 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700319
Dianne Hackborn231cc602009-04-27 17:10:36 -0700320 public DayStats(int day) {
321 this.day = day;
322 }
323 }
Costin Manolache360e4542009-09-04 13:36:04 -0700324
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700326
327 /** Called when a sync is needed on an account(s) due to some change in state. */
328 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800329 }
330
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000331 interface PeriodicSyncAddedListener {
332 /** Called when a periodic sync is added. */
333 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
334 }
335
336 interface OnAuthorityRemovedListener {
337 /** Called when an authority is removed. */
338 void onAuthorityRemoved(EndPoint removedAuthority);
339 }
340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 // Primary list of all syncable authorities. Also our global lock.
342 private final SparseArray<AuthorityInfo> mAuthorities =
343 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700344
Amith Yamasani04e0d262012-02-14 11:50:53 -0800345 private final HashMap<AccountAndUser, AccountInfo> mAccounts
346 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
Amith Yamasani04e0d262012-02-14 11:50:53 -0800348 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
349 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 private final SparseArray<SyncStatusInfo> mSyncStatus =
352 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 private final ArrayList<SyncHistoryItem> mSyncHistory =
355 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
358 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Matthew Williams8ef22042013-07-26 12:56:39 -0700360 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700361 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
362 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700363
Fred Quintana77c560f2010-03-29 22:20:26 -0700364 private int mNextAuthorityId = 0;
365
Dianne Hackborn231cc602009-04-27 17:10:36 -0700366 // We keep 4 weeks of stats.
367 private final DayStats[] mDayStats = new DayStats[7*4];
368 private final Calendar mCal;
369 private int mYear;
370 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800373
Dianne Hackborn231cc602009-04-27 17:10:36 -0700374 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700375
Ashish Sharma69d95de2012-04-11 17:27:24 -0700376 private int mSyncRandomOffset;
377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 /**
379 * This file contains the core engine state: all accounts and the
380 * settings for them. It must never be lost, and should be changed
381 * infrequently, so it is stored as an XML file.
382 */
383 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700384
Dianne Hackborn231cc602009-04-27 17:10:36 -0700385 /**
386 * This file contains the current sync status. We would like to retain
387 * it across boots, but its loss is not the end of the world, so we store
388 * this information as binary data.
389 */
390 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700391
Dianne Hackborn231cc602009-04-27 17:10:36 -0700392 /**
393 * This file contains sync statistics. This is purely debugging information
394 * so is written infrequently and can be thrown away at any time.
395 */
396 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800400 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800401
402 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000403 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700404
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800405 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700408
Dianne Hackborn231cc602009-04-27 17:10:36 -0700409 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800411 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000412 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 File systemDir = new File(dataDir, "system");
415 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800416 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700417
418 maybeDeleteLegacyPendingInfoLocked(syncDir);
419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
421 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 readAccountInfoLocked();
425 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700427 readAndDeleteLegacyAccountInfoLocked();
428 writeAccountInfoLocked();
429 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700430 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 }
432
433 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800434 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436
437 public static void init(Context context) {
438 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800439 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800441 // This call will return the correct directory whether Encrypted File Systems is
442 // enabled or not.
Jason parksa3cdaa52011-01-13 14:15:43 -0600443 File dataDir = Environment.getSecureDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800444 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 }
446
447 public static SyncStorageEngine getSingleton() {
448 if (sSyncStorageEngine == null) {
449 throw new IllegalStateException("not initialized");
450 }
451 return sSyncStorageEngine;
452 }
453
Amith Yamasani04e0d262012-02-14 11:50:53 -0800454 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
455 if (mSyncRequestListener == null) {
456 mSyncRequestListener = listener;
457 }
458 }
459
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000460 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
461 if (mAuthorityRemovedListener == null) {
462 mAuthorityRemovedListener = listener;
463 }
464 }
465
466 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
467 if (mPeriodicSyncAddedListener == null) {
468 mPeriodicSyncAddedListener = listener;
469 }
470 }
471
Dianne Hackborn231cc602009-04-27 17:10:36 -0700472 @Override public void handleMessage(Message msg) {
473 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700474 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700476 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700478 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700479 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800480 }
481 }
482 }
Costin Manolache360e4542009-09-04 13:36:04 -0700483
Ashish Sharma69d95de2012-04-11 17:27:24 -0700484 public int getSyncRandomOffset() {
485 return mSyncRandomOffset;
486 }
487
Dianne Hackborn231cc602009-04-27 17:10:36 -0700488 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
489 synchronized (mAuthorities) {
490 mChangeListeners.register(callback, mask);
491 }
492 }
Costin Manolache360e4542009-09-04 13:36:04 -0700493
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 public void removeStatusChangeListener(ISyncStatusObserver callback) {
495 synchronized (mAuthorities) {
496 mChangeListeners.unregister(callback);
497 }
498 }
Costin Manolache360e4542009-09-04 13:36:04 -0700499
Matthew Williamsfa774182013-06-18 15:44:11 -0700500 /**
501 * Figure out a reasonable flex time for cases where none is provided (old api calls).
502 * @param syncTimeSeconds requested sync time from now.
503 * @return amount of seconds before syncTimeSeconds that the sync can occur.
504 * I.e.
505 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700506 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700507 */
508 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
509 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
510 // Small enough sync request time that we don't add flex time - developer probably
511 // wants to wait for an operation to occur before syncing so we honour the
512 // request time.
513 return 0L;
514 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
515 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
516 } else {
517 // Large enough sync request time that we cap the flex time.
518 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
519 }
520 }
521
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000522 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700523 ArrayList<ISyncStatusObserver> reports = null;
524 synchronized (mAuthorities) {
525 int i = mChangeListeners.beginBroadcast();
526 while (i > 0) {
527 i--;
528 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
529 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 continue;
531 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700532 if (reports == null) {
533 reports = new ArrayList<ISyncStatusObserver>(i);
534 }
535 reports.add(mChangeListeners.getBroadcastItem(i));
536 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700537 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700538 }
Costin Manolache360e4542009-09-04 13:36:04 -0700539
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700540 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000541 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700542 }
Costin Manolache360e4542009-09-04 13:36:04 -0700543
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 if (reports != null) {
545 int i = reports.size();
546 while (i > 0) {
547 i--;
548 try {
549 reports.get(i).onStatusChanged(which);
550 } catch (RemoteException e) {
551 // The remote callback list will take care of this for us.
552 }
553 }
554 }
555 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700556
Amith Yamasani04e0d262012-02-14 11:50:53 -0800557 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700558 synchronized (mAuthorities) {
559 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700560 AuthorityInfo authority = getAuthorityLocked(
561 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700562 "getSyncAutomatically");
563 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700564 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700565
Dianne Hackborn231cc602009-04-27 17:10:36 -0700566 int i = mAuthorities.size();
567 while (i > 0) {
568 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700569 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700570 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700571 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700572 return true;
573 }
574 }
575 return false;
576 }
577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578
Amith Yamasani04e0d262012-02-14 11:50:53 -0800579 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000580 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700581 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000582 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800583 + ", user " + userId + " -> " + sync);
584 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700585 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700586 AuthorityInfo authority =
587 getOrCreateAuthorityLocked(
588 new EndPoint(account, providerName, userId),
589 -1 /* ident */,
590 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700591 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700592 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000593 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800594 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700595 return;
596 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700597 // If the adapter was syncable but missing its initialization sync, set it to
598 // uninitialized now. This is to give it a chance to run any one-time initialization
599 // logic.
600 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
601 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
602 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700603 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700604 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700606
Fred Quintana77c560f2010-03-29 22:20:26 -0700607 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700608 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
609 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700610 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700611 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800612 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 }
614
Amith Yamasani04e0d262012-02-14 11:50:53 -0800615 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700616 synchronized (mAuthorities) {
617 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700618 AuthorityInfo authority = getAuthorityLocked(
619 new EndPoint(account, providerName, userId),
620 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700621 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700622 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700623 }
624 return authority.syncable;
625 }
626
627 int i = mAuthorities.size();
628 while (i > 0) {
629 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700630 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700631 if (authorityInfo.target != null
632 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700633 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700634 }
635 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700636 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700637 }
638 }
639
Amith Yamasani04e0d262012-02-14 11:50:53 -0800640 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700641 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700642 }
643
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700644 /**
645 * An enabled sync service and a syncable provider's adapter both get resolved to the same
646 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700647 * @param target target to set value for.
648 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700649 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700650 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700651 AuthorityInfo aInfo;
652 synchronized (mAuthorities) {
653 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700654 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
655 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700656 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700657 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000658 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700659 }
660 if (aInfo.syncable == syncable) {
661 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000662 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700663 }
664 return;
665 }
666 aInfo.syncable = syncable;
667 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700668 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700669 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700670 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700671 }
672 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
673 }
674
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700675 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800676 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700677 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
678 if (authority != null) {
679 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800680 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700681 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800682 }
683 }
684
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700685 /**
686 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
687 * the account or provider info be null, which signifies all accounts or providers.
688 */
689 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
690 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000691 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800692 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
693 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700694 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800695 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000696 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700697 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000698 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700699 changed = setBackoffLocked(
700 info.account /* may be null */,
701 info.userId,
702 info.provider /* may be null */,
703 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800704 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700705 AuthorityInfo authorityInfo =
706 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
707 if (authorityInfo.backoffTime == nextSyncTime
708 && authorityInfo.backoffDelay == nextDelay) {
709 changed = false;
710 } else {
711 authorityInfo.backoffTime = nextSyncTime;
712 authorityInfo.backoffDelay = nextDelay;
713 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800714 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800715 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800716 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800717 if (changed) {
718 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
719 }
720 }
721
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700722 /**
723 * Either set backoff for a specific authority, or set backoff for all the
724 * accounts on a specific adapter/all adapters.
725 *
726 * @param account account for which to set backoff. Null to specify all accounts.
727 * @param userId id of the user making this request.
728 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700729 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700730 */
731 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000732 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700733 boolean changed = false;
734 for (AccountInfo accountInfo : mAccounts.values()) {
735 if (account != null && !account.equals(accountInfo.accountAndUser.account)
736 && userId != accountInfo.accountAndUser.userId) {
737 continue;
738 }
739 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
740 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700741 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700742 continue;
743 }
744 if (authorityInfo.backoffTime != nextSyncTime
745 || authorityInfo.backoffDelay != nextDelay) {
746 authorityInfo.backoffTime = nextSyncTime;
747 authorityInfo.backoffDelay = nextDelay;
748 changed = true;
749 }
750 }
751 }
752 return changed;
753 }
754
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000755 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800756 boolean changed = false;
757 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000758 // Clear backoff for all sync adapters.
759 for (AccountInfo accountInfo : mAccounts.values()) {
760 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
761 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
762 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
763 if (Log.isLoggable(TAG, Log.VERBOSE)) {
764 Slog.v(TAG, "clearAllBackoffsLocked:"
765 + " authority:" + authorityInfo.target
766 + " account:" + accountInfo.accountAndUser.account.name
767 + " user:" + accountInfo.accountAndUser.userId
768 + " backoffTime was: " + authorityInfo.backoffTime
769 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800770 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000771 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
772 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
773 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800774 }
775 }
776 }
777 }
778
779 if (changed) {
780 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
781 }
782 }
783
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700784 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800785 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700786 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800787 if (authority == null) {
788 return 0;
789 }
790 return authority.delayUntil;
791 }
792 }
793
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700794 public void setDelayUntilTime(EndPoint info, long delayUntil) {
795 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000796 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700797 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800798 }
799 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700800 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
801 if (authority.delayUntil == delayUntil) {
802 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700803 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700804 authority.delayUntil = delayUntil;
805 }
806 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
807 }
808
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700809 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000810 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
811 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700812 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000813 boolean restoreAllPeriodicSyncs() {
814 if (mPeriodicSyncAddedListener == null) {
815 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800816 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000817 synchronized (mAuthorities) {
818 for (int i=0; i<mAuthorities.size(); i++) {
819 AuthorityInfo authority = mAuthorities.valueAt(i);
820 for (PeriodicSync periodicSync: authority.periodicSyncs) {
821 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
822 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
823 }
824 authority.periodicSyncs.clear();
825 }
826 writeAccountInfoLocked();
827 }
828 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800829 }
830
Amith Yamasani04e0d262012-02-14 11:50:53 -0800831 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700832 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800833 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700834 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700835 return;
836 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700838 writeAccountInfoLocked();
839 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700840 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700841 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
842 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700843 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700844 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800845 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800846 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848
Amith Yamasani04e0d262012-02-14 11:50:53 -0800849 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700850 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800851 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800852 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700853 }
854 }
Costin Manolache360e4542009-09-04 13:36:04 -0700855
Dianne Hackborn231cc602009-04-27 17:10:36 -0700856 public AuthorityInfo getAuthority(int authorityId) {
857 synchronized (mAuthorities) {
858 return mAuthorities.get(authorityId);
859 }
860 }
Costin Manolache360e4542009-09-04 13:36:04 -0700861
Dianne Hackborn231cc602009-04-27 17:10:36 -0700862 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700863 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700864 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700865 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700867 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700868 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700869 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700870 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700871 return true;
872 }
873 }
874 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 return false;
876 }
Costin Manolache360e4542009-09-04 13:36:04 -0700877
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000878 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700879 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000880 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
881 -1 /* desired identifier */,
882 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000884 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700885 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700886 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000887 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700889 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700890 }
Costin Manolache360e4542009-09-04 13:36:04 -0700891
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 /**
893 * Called when the set of account has changed, given the new array of
894 * active accounts.
895 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800896 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700897 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700898 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000899 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700900 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700901 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
902 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
903 while (accIt.hasNext()) {
904 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800905 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
906 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700908 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000909 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700910 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700911 for (AuthorityInfo auth : acc.authorities.values()) {
912 removing.put(auth.ident, auth);
913 }
914 accIt.remove();
915 }
916 }
Costin Manolache360e4542009-09-04 13:36:04 -0700917
Dianne Hackborn231cc602009-04-27 17:10:36 -0700918 // Clean out all data structures.
919 int i = removing.size();
920 if (i > 0) {
921 while (i > 0) {
922 i--;
923 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000924 AuthorityInfo auth = removing.valueAt(i);
925 if (mAuthorityRemovedListener != null) {
926 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
927 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700928 mAuthorities.remove(ident);
929 int j = mSyncStatus.size();
930 while (j > 0) {
931 j--;
932 if (mSyncStatus.keyAt(j) == ident) {
933 mSyncStatus.remove(mSyncStatus.keyAt(j));
934 }
935 }
936 j = mSyncHistory.size();
937 while (j > 0) {
938 j--;
939 if (mSyncHistory.get(j).authorityId == ident) {
940 mSyncHistory.remove(j);
941 }
942 }
943 }
944 writeAccountInfoLocked();
945 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700946 writeStatisticsLocked();
947 }
948 }
949 }
950
951 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700952 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
953 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 */
Fred Quintana918339a2010-10-05 14:00:39 -0700955 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
956 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700957 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700958 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000959 Slog.v(TAG, "setActiveSync: account="
960 + " auth=" + activeSyncContext.mSyncOperation.target
961 + " src=" + activeSyncContext.mSyncOperation.syncSource
962 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700964 final EndPoint info = activeSyncContext.mSyncOperation.target;
965 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
966 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700967 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700968 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700969 syncInfo = new SyncInfo(
970 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700971 authorityInfo.target.account,
972 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700973 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700974 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700975 }
Fred Quintana918339a2010-10-05 14:00:39 -0700976 reportActiveChange();
977 return syncInfo;
978 }
979
980 /**
981 * Called to indicate that a previously active sync is no longer active.
982 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800983 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700984 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700985 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000986 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800987 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -0700988 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -0700989 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800990 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -0700991 }
992
993 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700994 }
995
996 /**
997 * To allow others to send active change reports, to poke clients.
998 */
999 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001000 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 }
Costin Manolache360e4542009-09-04 13:36:04 -07001002
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001004 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001006 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001007 long id;
1008 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001009 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001010 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001011 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001012 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 if (authority == null) {
1014 return -1;
1015 }
1016 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001017 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001018 item.authorityId = authority.ident;
1019 item.historyId = mNextHistoryId++;
1020 if (mNextHistoryId < 0) mNextHistoryId = 0;
1021 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001022 item.source = op.syncSource;
1023 item.reason = op.reason;
1024 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001025 item.event = EVENT_START;
1026 mSyncHistory.add(0, item);
1027 while (mSyncHistory.size() > MAX_HISTORY) {
1028 mSyncHistory.remove(mSyncHistory.size()-1);
1029 }
1030 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001031 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001032 }
Costin Manolache360e4542009-09-04 13:36:04 -07001033
Fred Quintanaac9385e2009-06-22 18:00:59 -07001034 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001035 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037
Fred Quintana77c560f2010-03-29 22:20:26 -07001038 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001039 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001041 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001042 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001043 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001044 SyncHistoryItem item = null;
1045 int i = mSyncHistory.size();
1046 while (i > 0) {
1047 i--;
1048 item = mSyncHistory.get(i);
1049 if (item.historyId == historyId) {
1050 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
Costin Manolache360e4542009-09-04 13:36:04 -07001054
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001056 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001057 return;
1058 }
Costin Manolache360e4542009-09-04 13:36:04 -07001059
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 item.elapsedTime = elapsedTime;
1061 item.event = EVENT_STOP;
1062 item.mesg = resultMessage;
1063 item.downstreamActivity = downstreamActivity;
1064 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001067
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 status.numSyncs++;
1069 status.totalElapsedTime += elapsedTime;
1070 switch (item.source) {
1071 case SOURCE_LOCAL:
1072 status.numSourceLocal++;
1073 break;
1074 case SOURCE_POLL:
1075 status.numSourcePoll++;
1076 break;
1077 case SOURCE_USER:
1078 status.numSourceUser++;
1079 break;
1080 case SOURCE_SERVER:
1081 status.numSourceServer++;
1082 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001083 case SOURCE_PERIODIC:
1084 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001085 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001086 }
Costin Manolache360e4542009-09-04 13:36:04 -07001087
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001089 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001090 if (mDayStats[0] == null) {
1091 mDayStats[0] = new DayStats(day);
1092 } else if (day != mDayStats[0].day) {
1093 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1094 mDayStats[0] = new DayStats(day);
1095 writeStatisticsNow = true;
1096 } else if (mDayStats[0] == null) {
1097 }
1098 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001099
Dianne Hackborn231cc602009-04-27 17:10:36 -07001100 final long lastSyncTime = (item.eventTime + elapsedTime);
1101 boolean writeStatusNow = false;
1102 if (MESG_SUCCESS.equals(resultMessage)) {
1103 // - if successful, update the successful columns
1104 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1105 writeStatusNow = true;
1106 }
1107 status.lastSuccessTime = lastSyncTime;
1108 status.lastSuccessSource = item.source;
1109 status.lastFailureTime = 0;
1110 status.lastFailureSource = -1;
1111 status.lastFailureMesg = null;
1112 status.initialFailureTime = 0;
1113 ds.successCount++;
1114 ds.successTime += elapsedTime;
1115 } else if (!MESG_CANCELED.equals(resultMessage)) {
1116 if (status.lastFailureTime == 0) {
1117 writeStatusNow = true;
1118 }
1119 status.lastFailureTime = lastSyncTime;
1120 status.lastFailureSource = item.source;
1121 status.lastFailureMesg = resultMessage;
1122 if (status.initialFailureTime == 0) {
1123 status.initialFailureTime = lastSyncTime;
1124 }
1125 ds.failureCount++;
1126 ds.failureTime += elapsedTime;
1127 }
Costin Manolache360e4542009-09-04 13:36:04 -07001128
Dianne Hackborn231cc602009-04-27 17:10:36 -07001129 if (writeStatusNow) {
1130 writeStatusLocked();
1131 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1132 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1133 WRITE_STATUS_DELAY);
1134 }
1135 if (writeStatisticsNow) {
1136 writeStatisticsLocked();
1137 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1138 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1139 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001140 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001141 }
Costin Manolache360e4542009-09-04 13:36:04 -07001142
Fred Quintanaac9385e2009-06-22 18:00:59 -07001143 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001144 }
1145
1146 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001147 * Return a list of the currently active syncs. Note that the returned
1148 * items are the real, live active sync objects, so be careful what you do
1149 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001150 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001151 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001152 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001153 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001154 }
1155 }
Costin Manolache360e4542009-09-04 13:36:04 -07001156
Dianne Hackborn231cc602009-04-27 17:10:36 -07001157 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001158 * @param userId Id of user to return current sync info.
1159 * @param canAccessAccounts Determines whether to redact Account information from the result.
1160 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001161 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001162 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001163 synchronized (mAuthorities) {
1164 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1165 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1166 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001167 SyncInfo copy;
1168 if (!canAccessAccounts) {
1169 copy = SyncInfo.createAccountRedacted(
1170 sync.authorityId, sync.authority, sync.startTime);
1171 } else {
1172 copy = new SyncInfo(sync);
1173 }
1174 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001175 }
1176 return syncsCopy;
1177 }
1178 }
1179
1180 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1181 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1182 if (syncs == null) {
1183 syncs = new ArrayList<SyncInfo>();
1184 mCurrentSyncs.put(userId, syncs);
1185 }
1186 return syncs;
1187 }
1188
1189 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001190 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001191 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001192 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001193 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001194 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001195 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001196 true /* write to storage if this results in a change */);
1197 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1198 }
1199 }
1200
1201 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001202 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001203 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001204 * @param info the endpoint target we are querying status info for.
1205 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001206 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001207 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001208 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001209 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001210 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001211 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001212 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001213 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001214 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001215 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001216 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001217 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001218 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 }
1220 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001221 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001222 }
1223 }
Costin Manolache360e4542009-09-04 13:36:04 -07001224
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001225 /** Return true if the pending status is true of any matching authorities. */
1226 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 synchronized (mAuthorities) {
1228 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001229 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001230 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001231 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1232 if (ainfo == null) {
1233 continue;
1234 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001235 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001236 continue;
1237 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001238 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 return true;
1240 }
1241 }
1242 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244 }
1245
1246 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001247 * Return an array of the current sync status for all authorities. Note
1248 * that the objects inside the array are the real, live status objects,
1249 * so be careful what you do with them.
1250 */
1251 public ArrayList<SyncHistoryItem> getSyncHistory() {
1252 synchronized (mAuthorities) {
1253 final int N = mSyncHistory.size();
1254 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1255 for (int i=0; i<N; i++) {
1256 items.add(mSyncHistory.get(i));
1257 }
1258 return items;
1259 }
1260 }
Costin Manolache360e4542009-09-04 13:36:04 -07001261
Dianne Hackborn231cc602009-04-27 17:10:36 -07001262 /**
1263 * Return an array of the current per-day statistics. Note
1264 * that the objects inside the array are the real, live status objects,
1265 * so be careful what you do with them.
1266 */
1267 public DayStats[] getDayStatistics() {
1268 synchronized (mAuthorities) {
1269 DayStats[] ds = new DayStats[mDayStats.length];
1270 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1271 return ds;
1272 }
1273 }
Costin Manolache360e4542009-09-04 13:36:04 -07001274
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001275 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1276 AuthorityInfo authorityInfo) {
1277 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1278 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1279 }
1280
Dianne Hackborn55280a92009-05-07 15:53:46 -07001281 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001282 mCal.setTimeInMillis(System.currentTimeMillis());
1283 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1284 if (mYear != mCal.get(Calendar.YEAR)) {
1285 mYear = mCal.get(Calendar.YEAR);
1286 mCal.clear();
1287 mCal.set(Calendar.YEAR, mYear);
1288 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1289 }
1290 return dayOfYear + mYearInDays;
1291 }
Costin Manolache360e4542009-09-04 13:36:04 -07001292
Dianne Hackborn231cc602009-04-27 17:10:36 -07001293 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001294 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001295 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001296 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001298 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001299 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001300 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001301 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1302 AccountInfo accountInfo = mAccounts.get(au);
1303 if (accountInfo == null) {
1304 if (tag != null) {
1305 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1306 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001307 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001308 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001309 return null;
1310 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001311 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1312 if (authority == null) {
1313 if (tag != null) {
1314 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1315 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1316 }
1317 }
1318 return null;
1319 }
1320 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001321 }
Costin Manolache360e4542009-09-04 13:36:04 -07001322
Matthew Williamsfa774182013-06-18 15:44:11 -07001323 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001324 * @param info info identifying target.
1325 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001326 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001327 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001328 * exists.
1329 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001330 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1331 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001332 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1333 AccountInfo account = mAccounts.get(au);
1334 if (account == null) {
1335 account = new AccountInfo(au);
1336 mAccounts.put(au, account);
1337 }
1338 authority = account.authorities.get(info.provider);
1339 if (authority == null) {
1340 authority = createAuthorityLocked(info, ident, doWrite);
1341 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001342 }
1343 return authority;
1344 }
1345
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001346 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1347 AuthorityInfo authority;
1348 if (ident < 0) {
1349 ident = mNextAuthorityId;
1350 mNextAuthorityId++;
1351 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001352 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001353 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001354 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001355 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001356 authority = new AuthorityInfo(info, ident);
1357 mAuthorities.put(ident, authority);
1358 if (doWrite) {
1359 writeAccountInfoLocked();
1360 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 return authority;
1362 }
Costin Manolache360e4542009-09-04 13:36:04 -07001363
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001364 public void removeAuthority(EndPoint info) {
1365 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001366 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001367 }
1368 }
1369
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001370
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001371 /**
1372 * Remove an authority associated with a provider. Needs to be a standalone function for
1373 * backward compatibility.
1374 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001375 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001376 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001377 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001378 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001379 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1380 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001381 if (mAuthorityRemovedListener != null) {
1382 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1383 }
Fred Quintanafb084402010-03-23 17:57:03 -07001384 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001385 if (doWrite) {
1386 writeAccountInfoLocked();
1387 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001388 }
1389 }
1390 }
1391
Dianne Hackborn231cc602009-04-27 17:10:36 -07001392 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1393 SyncStatusInfo status = mSyncStatus.get(authorityId);
1394 if (status == null) {
1395 status = new SyncStatusInfo(authorityId);
1396 mSyncStatus.put(authorityId, status);
1397 }
1398 return status;
1399 }
Costin Manolache360e4542009-09-04 13:36:04 -07001400
Dianne Hackborn55280a92009-05-07 15:53:46 -07001401 public void writeAllState() {
1402 synchronized (mAuthorities) {
1403 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001404 writeStatusLocked();
1405 writeStatisticsLocked();
1406 }
1407 }
Costin Manolache360e4542009-09-04 13:36:04 -07001408
Dianne Hackborn231cc602009-04-27 17:10:36 -07001409 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001410 * public for testing
1411 */
1412 public void clearAndReadState() {
1413 synchronized (mAuthorities) {
1414 mAuthorities.clear();
1415 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001416 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001417 mSyncStatus.clear();
1418 mSyncHistory.clear();
1419
1420 readAccountInfoLocked();
1421 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001422 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001423 readAndDeleteLegacyAccountInfoLocked();
1424 writeAccountInfoLocked();
1425 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001426 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001427 }
1428 }
1429
1430 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001431 * Read all account information back in to the initial engine state.
1432 */
1433 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001434 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001435 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001436 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001437 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001438 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001439 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001440 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001442 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001443 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001444 while (eventType != XmlPullParser.START_TAG &&
1445 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001446 eventType = parser.next();
1447 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001448 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001449 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001450 return;
1451 }
1452
Dianne Hackborn231cc602009-04-27 17:10:36 -07001453 String tagName = parser.getName();
1454 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001455 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001456 String versionString = parser.getAttributeValue(null, "version");
1457 int version;
1458 try {
1459 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1460 } catch (NumberFormatException e) {
1461 version = 0;
1462 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001463 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001464 try {
1465 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1466 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1467 } catch (NumberFormatException e) {
1468 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001469 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001470 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1471 try {
1472 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1473 } catch (NumberFormatException e) {
1474 mSyncRandomOffset = 0;
1475 }
1476 if (mSyncRandomOffset == 0) {
1477 Random random = new Random(System.currentTimeMillis());
1478 mSyncRandomOffset = random.nextInt(86400);
1479 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001480 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001481 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001482 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001483 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001484 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001485 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001486 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001487 if (parser.getDepth() == 2) {
1488 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001489 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001490 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001491 if (authority != null) {
1492 if (authority.ident > highestAuthorityId) {
1493 highestAuthorityId = authority.ident;
1494 }
Fred Quintana77c560f2010-03-29 22:20:26 -07001495 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001496 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1497 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001498 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001499 } else if (parser.getDepth() == 3) {
1500 if ("periodicSync".equals(tagName) && authority != null) {
1501 periodicSync = parsePeriodicSync(parser, authority);
1502 }
1503 } else if (parser.getDepth() == 4 && periodicSync != null) {
1504 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001505 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001506 }
1507 }
1508 }
1509 eventType = parser.next();
1510 } while (eventType != XmlPullParser.END_DOCUMENT);
1511 }
1512 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001513 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001514 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001515 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001516 if (fis == null) Slog.i(TAG, "No initial accounts");
1517 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001518 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001519 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001520 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001521 if (fis != null) {
1522 try {
1523 fis.close();
1524 } catch (java.io.IOException e1) {
1525 }
1526 }
1527 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001528
Fred Quintana77c560f2010-03-29 22:20:26 -07001529 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 }
Costin Manolache360e4542009-09-04 13:36:04 -07001531
Fred Quintanafb084402010-03-23 17:57:03 -07001532 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001533 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1534 * pending.xml was used starting in KLP.
1535 * @param syncDir directory where the sync files are located.
1536 */
1537 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1538 File file = new File(syncDir, "pending.bin");
1539 if (!file.exists()) {
1540 return;
1541 } else {
1542 file.delete();
1543 }
1544 }
1545
1546 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001547 * some authority names have changed. copy over their settings and delete the old ones
1548 * @return true if a change was made
1549 */
1550 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1551 boolean writeNeeded = false;
1552
1553 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1554 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001555 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001556 AuthorityInfo authority = mAuthorities.valueAt(i);
1557 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001558 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001559 if (newAuthorityName == null) {
1560 continue;
1561 }
1562
1563 // remember this authority so we can remove it later. we can't remove it
1564 // now without messing up this loop iteration
1565 authoritiesToRemove.add(authority);
1566
1567 // this authority isn't enabled, no need to copy it to the new authority name since
1568 // the default is "disabled"
1569 if (!authority.enabled) {
1570 continue;
1571 }
1572
1573 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001574 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001575 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001576 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001577 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001578 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001579 continue;
1580 }
1581
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001582 AuthorityInfo newAuthority =
1583 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001584 newAuthority.enabled = true;
1585 writeNeeded = true;
1586 }
1587
1588 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001589 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001590 authorityInfo.target.account,
1591 authorityInfo.target.userId,
1592 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001593 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001594 writeNeeded = true;
1595 }
1596
1597 return writeNeeded;
1598 }
1599
Amith Yamasani04e0d262012-02-14 11:50:53 -08001600 private void parseListenForTickles(XmlPullParser parser) {
1601 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1602 int userId = 0;
1603 try {
1604 userId = Integer.parseInt(user);
1605 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001606 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001607 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001608 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001609 }
1610 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1611 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1612 mMasterSyncAutomatically.put(userId, listen);
1613 }
1614
Fred Quintanac2e46912010-03-15 16:10:44 -07001615 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001616 AuthorityInfo authority = null;
1617 int id = -1;
1618 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001619 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001620 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001621 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001622 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001623 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001624 }
1625 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001626 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001627 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001628 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001629 String accountName = parser.getAttributeValue(null, "account");
1630 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001631 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001632 String packageName = parser.getAttributeValue(null, "package");
1633 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001634 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001635 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001636 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001637 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001638 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001639 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001640 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001641 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001642 + " account=" + accountName
1643 + " accountType=" + accountType
1644 + " auth=" + authorityName
1645 + " package=" + packageName
1646 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001647 + " user=" + userId
1648 + " enabled=" + enabled
1649 + " syncable=" + syncable);
1650 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001651 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001652 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001653 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001654 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001655 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001656 if (accountName != null && authorityName != null) {
1657 info = new EndPoint(
1658 new Account(accountName, accountType),
1659 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001660 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001661 if (info != null) {
1662 authority = getOrCreateAuthorityLocked(info, id, false);
1663 // If the version is 0 then we are upgrading from a file format that did not
1664 // know about periodic syncs. In that case don't clear the list since we
1665 // want the default, which is a daily periodic sync.
1666 // Otherwise clear out this default list since we will populate it later with
1667 // the periodic sync descriptions that are read from the configuration file.
1668 if (version > 0) {
1669 authority.periodicSyncs.clear();
1670 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001671 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001672 }
1673 if (authority != null) {
1674 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001675 try {
1676 authority.syncable = (syncable == null) ?
1677 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1678 } catch (NumberFormatException e) {
1679 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1680 // format.
1681 if ("unknown".equals(syncable)) {
1682 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1683 } else {
1684 authority.syncable = Boolean.parseBoolean(syncable) ?
1685 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1686 }
1687
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001688 }
1689 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001690 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001691 + accountName + " auth=" + authorityName
1692 + " enabled=" + enabled
1693 + " syncable=" + syncable);
1694 }
1695 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001696 return authority;
1697 }
1698
Matthew Williamsfa774182013-06-18 15:44:11 -07001699 /**
1700 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1701 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001702 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001703 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001704 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001705 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001706 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001707 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001708 try {
1709 period = Long.parseLong(periodValue);
1710 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001711 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001712 return null;
1713 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001714 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 return null;
1716 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001717 try {
1718 flextime = Long.parseLong(flexValue);
1719 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001720 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001721 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001722 + ", using default: "
1723 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001724 } catch (NullPointerException expected) {
1725 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001726 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1727 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001728 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001729 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001730 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001731 new PeriodicSync(authorityInfo.target.account,
1732 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001733 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001734 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001735 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001736 return periodicSync;
1737 }
1738
Matthew Williamsfa774182013-06-18 15:44:11 -07001739 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001740 String name = parser.getAttributeValue(null, "name");
1741 String type = parser.getAttributeValue(null, "type");
1742 String value1 = parser.getAttributeValue(null, "value1");
1743 String value2 = parser.getAttributeValue(null, "value2");
1744
1745 try {
1746 if ("long".equals(type)) {
1747 extras.putLong(name, Long.parseLong(value1));
1748 } else if ("integer".equals(type)) {
1749 extras.putInt(name, Integer.parseInt(value1));
1750 } else if ("double".equals(type)) {
1751 extras.putDouble(name, Double.parseDouble(value1));
1752 } else if ("float".equals(type)) {
1753 extras.putFloat(name, Float.parseFloat(value1));
1754 } else if ("boolean".equals(type)) {
1755 extras.putBoolean(name, Boolean.parseBoolean(value1));
1756 } else if ("string".equals(type)) {
1757 extras.putString(name, value1);
1758 } else if ("account".equals(type)) {
1759 extras.putParcelable(name, new Account(value1, value2));
1760 }
1761 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001762 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001763 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001764 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001765 }
1766 }
1767
Dianne Hackborn231cc602009-04-27 17:10:36 -07001768 /**
1769 * Write all account information to the account file.
1770 */
1771 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001772 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001773 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001774 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001775 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001776
Dianne Hackborn231cc602009-04-27 17:10:36 -07001777 try {
1778 fos = mAccountInfoFile.startWrite();
1779 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001780 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001781 out.startDocument(null, true);
1782 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001783
Dianne Hackborn231cc602009-04-27 17:10:36 -07001784 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001785 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001786 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001787 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001788
1789 // Write the Sync Automatically flags for each user
1790 final int M = mMasterSyncAutomatically.size();
1791 for (int m = 0; m < M; m++) {
1792 int userId = mMasterSyncAutomatically.keyAt(m);
1793 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1794 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1795 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1796 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1797 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001798 }
Costin Manolache360e4542009-09-04 13:36:04 -07001799
Dianne Hackborn231cc602009-04-27 17:10:36 -07001800 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001801 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001802 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001803 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001804 out.startTag(null, "authority");
1805 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001806 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001807 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001808 out.attribute(null, "account", info.account.name);
1809 out.attribute(null, "type", info.account.type);
1810 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001811 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001812 out.endTag(null, "authority");
1813 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001814 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 mAccountInfoFile.finishWrite(fos);
1817 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001818 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001819 if (fos != null) {
1820 mAccountInfoFile.failWrite(fos);
1821 }
1822 }
1823 }
Costin Manolache360e4542009-09-04 13:36:04 -07001824
Dianne Hackborn231cc602009-04-27 17:10:36 -07001825 static int getIntColumn(Cursor c, String name) {
1826 return c.getInt(c.getColumnIndex(name));
1827 }
Costin Manolache360e4542009-09-04 13:36:04 -07001828
Dianne Hackborn231cc602009-04-27 17:10:36 -07001829 static long getLongColumn(Cursor c, String name) {
1830 return c.getLong(c.getColumnIndex(name));
1831 }
Costin Manolache360e4542009-09-04 13:36:04 -07001832
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 /**
1834 * Load sync engine state from the old syncmanager database, and then
1835 * erase it. Note that we don't deal with pending operations, active
1836 * sync, or history.
1837 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001838 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001839 // Look for old database to initialize from.
1840 File file = mContext.getDatabasePath("syncmanager.db");
1841 if (!file.exists()) {
1842 return;
1843 }
1844 String path = file.getPath();
1845 SQLiteDatabase db = null;
1846 try {
1847 db = SQLiteDatabase.openDatabase(path, null,
1848 SQLiteDatabase.OPEN_READONLY);
1849 } catch (SQLiteException e) {
1850 }
Costin Manolache360e4542009-09-04 13:36:04 -07001851
Dianne Hackborn231cc602009-04-27 17:10:36 -07001852 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001853 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001854
Dianne Hackborn231cc602009-04-27 17:10:36 -07001855 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001856 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001857 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001858 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001859 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1860 qb.setTables("stats, status");
1861 HashMap<String,String> map = new HashMap<String,String>();
1862 map.put("_id", "status._id as _id");
1863 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001864 if (hasType) {
1865 map.put("account_type", "stats.account_type as account_type");
1866 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001867 map.put("authority", "stats.authority as authority");
1868 map.put("totalElapsedTime", "totalElapsedTime");
1869 map.put("numSyncs", "numSyncs");
1870 map.put("numSourceLocal", "numSourceLocal");
1871 map.put("numSourcePoll", "numSourcePoll");
1872 map.put("numSourceServer", "numSourceServer");
1873 map.put("numSourceUser", "numSourceUser");
1874 map.put("lastSuccessSource", "lastSuccessSource");
1875 map.put("lastSuccessTime", "lastSuccessTime");
1876 map.put("lastFailureSource", "lastFailureSource");
1877 map.put("lastFailureTime", "lastFailureTime");
1878 map.put("lastFailureMesg", "lastFailureMesg");
1879 map.put("pending", "pending");
1880 qb.setProjectionMap(map);
1881 qb.appendWhere("stats._id = status.stats_id");
1882 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001884 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001885 String accountType = hasType
1886 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001887 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001888 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001890 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001891 AuthorityInfo authority =
1892 this.getOrCreateAuthorityLocked(
1893 new EndPoint(new Account(accountName, accountType),
1894 authorityName,
1895 0 /* legacy is single-user */)
1896 , -1,
1897 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001898 if (authority != null) {
1899 int i = mSyncStatus.size();
1900 boolean found = false;
1901 SyncStatusInfo st = null;
1902 while (i > 0) {
1903 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001904 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001905 if (st.authorityId == authority.ident) {
1906 found = true;
1907 break;
1908 }
1909 }
1910 if (!found) {
1911 st = new SyncStatusInfo(authority.ident);
1912 mSyncStatus.put(authority.ident, st);
1913 }
1914 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1915 st.numSyncs = getIntColumn(c, "numSyncs");
1916 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1917 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1918 st.numSourceServer = getIntColumn(c, "numSourceServer");
1919 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001920 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001921 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1922 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1923 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1924 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1925 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1926 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
Costin Manolache360e4542009-09-04 13:36:04 -07001929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001931
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 // Retrieve the settings.
1933 qb = new SQLiteQueryBuilder();
1934 qb.setTables("settings");
1935 c = qb.query(db, null, null, null, null, null, null);
1936 while (c.moveToNext()) {
1937 String name = c.getString(c.getColumnIndex("name"));
1938 String value = c.getString(c.getColumnIndex("value"));
1939 if (name == null) continue;
1940 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001941 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001942 } else if (name.startsWith("sync_provider_")) {
1943 String provider = name.substring("sync_provider_".length(),
1944 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001945 int i = mAuthorities.size();
1946 while (i > 0) {
1947 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001948 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001949 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001950 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001951 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001952 }
1953 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
Costin Manolache360e4542009-09-04 13:36:04 -07001956
Dianne Hackborn231cc602009-04-27 17:10:36 -07001957 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001958
Dianne Hackborn231cc602009-04-27 17:10:36 -07001959 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001960
Dianne Hackborn231cc602009-04-27 17:10:36 -07001961 (new File(path)).delete();
1962 }
1963 }
Costin Manolache360e4542009-09-04 13:36:04 -07001964
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 public static final int STATUS_FILE_END = 0;
1966 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001967
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 /**
1969 * Read all sync status back in to the initial engine state.
1970 */
1971 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001972 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001973 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001974 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 try {
1976 byte[] data = mStatusFile.readFully();
1977 Parcel in = Parcel.obtain();
1978 in.unmarshall(data, 0, data.length);
1979 in.setDataPosition(0);
1980 int token;
1981 while ((token=in.readInt()) != STATUS_FILE_END) {
1982 if (token == STATUS_FILE_ITEM) {
1983 SyncStatusInfo status = new SyncStatusInfo(in);
1984 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1985 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07001986 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001987 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07001988 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001989 mSyncStatus.put(status.authorityId, status);
1990 }
1991 } else {
1992 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001993 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001994 break;
1995 }
1996 }
1997 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001998 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001999 }
2000 }
Costin Manolache360e4542009-09-04 13:36:04 -07002001
Dianne Hackborn231cc602009-04-27 17:10:36 -07002002 /**
2003 * Write all sync status to the sync status file.
2004 */
2005 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002006 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002007 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002008 }
Costin Manolache360e4542009-09-04 13:36:04 -07002009
Dianne Hackborn231cc602009-04-27 17:10:36 -07002010 // The file is being written, so we don't need to have a scheduled
2011 // write until the next change.
2012 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002013
Dianne Hackborn231cc602009-04-27 17:10:36 -07002014 FileOutputStream fos = null;
2015 try {
2016 fos = mStatusFile.startWrite();
2017 Parcel out = Parcel.obtain();
2018 final int N = mSyncStatus.size();
2019 for (int i=0; i<N; i++) {
2020 SyncStatusInfo status = mSyncStatus.valueAt(i);
2021 out.writeInt(STATUS_FILE_ITEM);
2022 status.writeToParcel(out, 0);
2023 }
2024 out.writeInt(STATUS_FILE_END);
2025 fos.write(out.marshall());
2026 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002027
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 mStatusFile.finishWrite(fos);
2029 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002030 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002031 if (fos != null) {
2032 mStatusFile.failWrite(fos);
2033 }
2034 }
2035 }
Costin Manolache360e4542009-09-04 13:36:04 -07002036
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002037 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2038 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2039 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002040 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002041 } else {
2042 SyncRequest.Builder req =
2043 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002044 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002045 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002046 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002047 ContentResolver.requestSync(req.build());
2048 }
2049 }
2050
Alon Albert57286f92012-10-09 14:21:38 -07002051 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002052 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002053 // If this is happening in the system process, then call the syncrequest listener
2054 // to make a request back to the SyncManager directly.
2055 // If this is probably a test instance, then call back through the ContentResolver
2056 // which will know which userId to apply based on the Binder id.
2057 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2058 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002059 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002060 new EndPoint(account, authority, userId),
2061 reason,
2062 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002063 } else {
2064 ContentResolver.requestSync(account, authority, extras);
2065 }
2066 }
2067
Dianne Hackborn231cc602009-04-27 17:10:36 -07002068 public static final int STATISTICS_FILE_END = 0;
2069 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2070 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002071
Dianne Hackborn231cc602009-04-27 17:10:36 -07002072 /**
2073 * Read all sync statistics back in to the initial engine state.
2074 */
2075 private void readStatisticsLocked() {
2076 try {
2077 byte[] data = mStatisticsFile.readFully();
2078 Parcel in = Parcel.obtain();
2079 in.unmarshall(data, 0, data.length);
2080 in.setDataPosition(0);
2081 int token;
2082 int index = 0;
2083 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2084 if (token == STATISTICS_FILE_ITEM
2085 || token == STATISTICS_FILE_ITEM_OLD) {
2086 int day = in.readInt();
2087 if (token == STATISTICS_FILE_ITEM_OLD) {
2088 day = day - 2009 + 14245; // Magic!
2089 }
2090 DayStats ds = new DayStats(day);
2091 ds.successCount = in.readInt();
2092 ds.successTime = in.readLong();
2093 ds.failureCount = in.readInt();
2094 ds.failureTime = in.readLong();
2095 if (index < mDayStats.length) {
2096 mDayStats[index] = ds;
2097 index++;
2098 }
2099 } else {
2100 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002101 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002102 break;
2103 }
2104 }
2105 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002106 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002107 }
2108 }
Costin Manolache360e4542009-09-04 13:36:04 -07002109
Dianne Hackborn231cc602009-04-27 17:10:36 -07002110 /**
2111 * Write all sync statistics to the sync status file.
2112 */
2113 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002114 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002115 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002116 }
Costin Manolache360e4542009-09-04 13:36:04 -07002117
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 // The file is being written, so we don't need to have a scheduled
2119 // write until the next change.
2120 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002121
Dianne Hackborn231cc602009-04-27 17:10:36 -07002122 FileOutputStream fos = null;
2123 try {
2124 fos = mStatisticsFile.startWrite();
2125 Parcel out = Parcel.obtain();
2126 final int N = mDayStats.length;
2127 for (int i=0; i<N; i++) {
2128 DayStats ds = mDayStats[i];
2129 if (ds == null) {
2130 break;
2131 }
2132 out.writeInt(STATISTICS_FILE_ITEM);
2133 out.writeInt(ds.day);
2134 out.writeInt(ds.successCount);
2135 out.writeLong(ds.successTime);
2136 out.writeInt(ds.failureCount);
2137 out.writeLong(ds.failureTime);
2138 }
2139 out.writeInt(STATISTICS_FILE_END);
2140 fos.write(out.marshall());
2141 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002142
Dianne Hackborn231cc602009-04-27 17:10:36 -07002143 mStatisticsFile.finishWrite(fos);
2144 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002145 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002146 if (fos != null) {
2147 mStatisticsFile.failWrite(fos);
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002151
2152 /**
Marvin Paula6533252014-11-24 12:57:48 -08002153 * Let the BackupManager know that account sync settings have changed. This will trigger
2154 * {@link com.android.server.backup.SystemBackupAgent} to run.
2155 */
2156 public void queueBackup() {
2157 BackupManager.dataChanged("android");
2158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002159}