blob: 8289bae8793bd82c89b28812c47a85340cbdc820 [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Shreyas Basarge8c834c02016-01-07 13:53:16 +000042import android.util.*;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastXmlSerializer;
47
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Dianne Hackborn231cc602009-04-27 17:10:36 -070052import java.io.File;
53import java.io.FileInputStream;
54import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010055import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080060import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070061import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060062import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * @hide
69 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070070public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070073 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070074
Amith Yamasani04e0d262012-02-14 11:50:53 -080075 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
76 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070077 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080078 private static final String XML_ATTR_ENABLED = "enabled";
79 private static final String XML_ATTR_USER = "user";
80 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
81
Matthew Williamsfa774182013-06-18 15:44:11 -070082 /** Default time for a periodic sync. */
Shreyas Basargecf939c12016-02-19 15:45:29 +000083 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080084
Shreyas Basarge8c834c02016-01-07 13:53:16 +000085 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070086 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
87
88 /** Lower bound on sync time from which we assign a default flex time. */
89 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
90
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080091 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 /** Enum value for a sync start event. */
95 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a sync stop event. */
98 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a server-initiated sync. */
101 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a local-initiated sync. */
104 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700105 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a user-initiated sync. */
109 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800111 /** Enum value for a periodic sync. */
112 public static final int SOURCE_PERIODIC = 4;
113
Fred Quintana307da1a2010-01-21 14:24:20 -0800114 public static final long NOT_IN_BACKOFF_MODE = -1;
115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 // TODO: i18n -- grab these out of resources.
117 /** String names for the sync source types. */
118 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000119 "LOCAL",
120 "POLL",
121 "USER",
122 "PERIODIC",
123 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // The MESG column will contain one of these or one of the Error types.
126 public static final String MESG_SUCCESS = "success";
127 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700129 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 private static final int MSG_WRITE_STATUS = 1;
132 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATISTICS = 2;
135 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700136
137 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Fred Quintanac2e46912010-03-15 16:10:44 -0700139 // the version of the accounts xml file format
Svet Ganov65712b02016-09-01 10:24:11 -0700140 private static final int ACCOUNTS_VERSION = 3;
Fred Quintanafb084402010-03-23 17:57:03 -0700141
142 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000143 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700144
145 static {
146 sAuthorityRenames = new HashMap<String, String>();
147 sAuthorityRenames.put("contacts", "com.android.contacts");
148 sAuthorityRenames.put("calendar", "com.android.calendar");
149 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700150
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800152 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 final HashMap<String, AuthorityInfo> authorities =
154 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 AccountInfo(AccountAndUser accountAndUser) {
157 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 }
159 }
Costin Manolache360e4542009-09-04 13:36:04 -0700160
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700161 /** Bare bones representation of a sync target. */
162 public static class EndPoint {
163 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
164 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700165 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800166 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700167 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168
169 public EndPoint(Account account, String provider, int userId) {
170 this.account = account;
171 this.provider = provider;
172 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 }
174
175 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700176 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
177 *
178 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000179 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700181 public boolean matchesSpec(EndPoint spec) {
182 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700184 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700185 return false;
186 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000187 boolean accountsMatch;
188 if (spec.account == null) {
189 accountsMatch = true;
190 } else {
191 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000193 boolean providersMatch;
194 if (spec.provider == null) {
195 providersMatch = true;
196 } else {
197 providersMatch = provider.equals(spec.provider);
198 }
199 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 }
201
202 public String toString() {
203 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000204 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 .append("/")
206 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700207 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 return sb.toString();
209 }
210 }
211
212 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700213 // Legal values of getIsSyncable
214 /**
215 * Default state for a newly installed adapter. An uninitialized adapter will receive an
216 * initialization sync which are governed by a different set of rules to that of regular
217 * syncs.
218 */
219 public static final int NOT_INITIALIZED = -1;
220 /**
221 * The adapter will not receive any syncs. This is behaviourally equivalent to
222 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
223 * while this is generally meant to be controlled by the developer.
224 */
225 public static final int NOT_SYNCABLE = 0;
226 /**
227 * The adapter is initialized and functioning. This is the normal state for an adapter.
228 */
229 public static final int SYNCABLE = 1;
230 /**
231 * The adapter is syncable but still requires an initialization sync. For example an adapter
232 * than has been restored from a previous device will be in this state. Not meant for
233 * external use.
234 */
235 public static final int SYNCABLE_NOT_INITIALIZED = 2;
236
Svetoslav Ganov5cb29732016-07-11 19:32:30 -0700237 /**
238 * The adapter is syncable but does not have access to the synced account and needs a
239 * user access approval.
240 */
241 public static final int SYNCABLE_NO_ACCOUNT_ACCESS = 3;
242
Matthew Williams8ef22042013-07-26 12:56:39 -0700243 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700244 final int ident;
245 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700246 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700247 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800248 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700249 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800250 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700251 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800252 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700253
Matthew Williamsfa774182013-06-18 15:44:11 -0700254 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700255
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700256 /**
257 * Copy constructor for making deep-ish copies. Only the bundles stored
258 * in periodic syncs can make unexpected changes.
259 *
260 * @param toCopy AuthorityInfo to be copied.
261 */
262 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700263 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700264 ident = toCopy.ident;
265 enabled = toCopy.enabled;
266 syncable = toCopy.syncable;
267 backoffTime = toCopy.backoffTime;
268 backoffDelay = toCopy.backoffDelay;
269 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700270 periodicSyncs = new ArrayList<PeriodicSync>();
271 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700272 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700273 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700274 }
275 }
276
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700277 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700278 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700279 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000280 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700281 periodicSyncs = new ArrayList<PeriodicSync>();
282 defaultInitialisation();
283 }
284
285 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700286 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800287 backoffTime = -1; // if < 0 then we aren't in backoff mode
288 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000289
290 if (mPeriodicSyncAddedListener != null) {
291 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
292 DEFAULT_POLL_FREQUENCY_SECONDS,
293 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700294 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700295 }
Matthew Williams06485a72013-07-26 12:56:39 -0700296
297 @Override
298 public String toString() {
299 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
300 + backoffTime + ", delay=" + delayUntil;
301 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700302 }
Costin Manolache360e4542009-09-04 13:36:04 -0700303
Dianne Hackborn231cc602009-04-27 17:10:36 -0700304 public static class SyncHistoryItem {
305 int authorityId;
306 int historyId;
307 long eventTime;
308 long elapsedTime;
309 int source;
310 int event;
311 long upstreamActivity;
312 long downstreamActivity;
313 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700314 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700315 Bundle extras;
316 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700317 }
Costin Manolache360e4542009-09-04 13:36:04 -0700318
Dianne Hackborn231cc602009-04-27 17:10:36 -0700319 public static class DayStats {
320 public final int day;
321 public int successCount;
322 public long successTime;
323 public int failureCount;
324 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700325
Dianne Hackborn231cc602009-04-27 17:10:36 -0700326 public DayStats(int day) {
327 this.day = day;
328 }
329 }
Costin Manolache360e4542009-09-04 13:36:04 -0700330
Amith Yamasani04e0d262012-02-14 11:50:53 -0800331 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700332
333 /** Called when a sync is needed on an account(s) due to some change in state. */
334 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800335 }
336
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000337 interface PeriodicSyncAddedListener {
338 /** Called when a periodic sync is added. */
339 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
340 }
341
342 interface OnAuthorityRemovedListener {
343 /** Called when an authority is removed. */
344 void onAuthorityRemoved(EndPoint removedAuthority);
345 }
346
Dianne Hackborn231cc602009-04-27 17:10:36 -0700347 // Primary list of all syncable authorities. Also our global lock.
348 private final SparseArray<AuthorityInfo> mAuthorities =
349 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Amith Yamasani04e0d262012-02-14 11:50:53 -0800351 private final HashMap<AccountAndUser, AccountInfo> mAccounts
352 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353
Amith Yamasani04e0d262012-02-14 11:50:53 -0800354 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
355 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private final SparseArray<SyncStatusInfo> mSyncStatus =
358 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Dianne Hackborn231cc602009-04-27 17:10:36 -0700360 private final ArrayList<SyncHistoryItem> mSyncHistory =
361 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700362
Dianne Hackborn231cc602009-04-27 17:10:36 -0700363 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
364 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700365
Matthew Williams8ef22042013-07-26 12:56:39 -0700366 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700367 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
368 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700369
Fred Quintana77c560f2010-03-29 22:20:26 -0700370 private int mNextAuthorityId = 0;
371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 // We keep 4 weeks of stats.
373 private final DayStats[] mDayStats = new DayStats[7*4];
374 private final Calendar mCal;
375 private int mYear;
376 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800379
Dianne Hackborn231cc602009-04-27 17:10:36 -0700380 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700381
Ashish Sharma69d95de2012-04-11 17:27:24 -0700382 private int mSyncRandomOffset;
383
Dianne Hackborn231cc602009-04-27 17:10:36 -0700384 /**
385 * This file contains the core engine state: all accounts and the
386 * settings for them. It must never be lost, and should be changed
387 * infrequently, so it is stored as an XML file.
388 */
389 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700390
Dianne Hackborn231cc602009-04-27 17:10:36 -0700391 /**
392 * This file contains the current sync status. We would like to retain
393 * it across boots, but its loss is not the end of the world, so we store
394 * this information as binary data.
395 */
396 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 /**
399 * This file contains sync statistics. This is purely debugging information
400 * so is written infrequently and can be thrown away at any time.
401 */
402 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700403
Dianne Hackborn231cc602009-04-27 17:10:36 -0700404 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800405 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800406 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800407
408 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000409 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Svet Ganov65712b02016-09-01 10:24:11 -0700411 private boolean mGrantSyncAdaptersAccountAccess;
412
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800413 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800414 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700416
Dianne Hackborn231cc602009-04-27 17:10:36 -0700417 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700418
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800419 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000420 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800421
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 File systemDir = new File(dataDir, "system");
423 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800424 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700425
426 maybeDeleteLegacyPendingInfoLocked(syncDir);
427
Dianne Hackborn231cc602009-04-27 17:10:36 -0700428 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
429 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700430 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700431
Dianne Hackborn231cc602009-04-27 17:10:36 -0700432 readAccountInfoLocked();
433 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700434 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700435 readAndDeleteLegacyAccountInfoLocked();
436 writeAccountInfoLocked();
437 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700438 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439 }
440
441 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800442 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 }
444
445 public static void init(Context context) {
446 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800447 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700449 File dataDir = Environment.getDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800450 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
453 public static SyncStorageEngine getSingleton() {
454 if (sSyncStorageEngine == null) {
455 throw new IllegalStateException("not initialized");
456 }
457 return sSyncStorageEngine;
458 }
459
Amith Yamasani04e0d262012-02-14 11:50:53 -0800460 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
461 if (mSyncRequestListener == null) {
462 mSyncRequestListener = listener;
463 }
464 }
465
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000466 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
467 if (mAuthorityRemovedListener == null) {
468 mAuthorityRemovedListener = listener;
469 }
470 }
471
472 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
473 if (mPeriodicSyncAddedListener == null) {
474 mPeriodicSyncAddedListener = listener;
475 }
476 }
477
Dianne Hackborn231cc602009-04-27 17:10:36 -0700478 @Override public void handleMessage(Message msg) {
479 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700480 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700481 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700482 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700483 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700484 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700485 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
487 }
488 }
Costin Manolache360e4542009-09-04 13:36:04 -0700489
Ashish Sharma69d95de2012-04-11 17:27:24 -0700490 public int getSyncRandomOffset() {
491 return mSyncRandomOffset;
492 }
493
Dianne Hackborn231cc602009-04-27 17:10:36 -0700494 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
495 synchronized (mAuthorities) {
496 mChangeListeners.register(callback, mask);
497 }
498 }
Costin Manolache360e4542009-09-04 13:36:04 -0700499
Dianne Hackborn231cc602009-04-27 17:10:36 -0700500 public void removeStatusChangeListener(ISyncStatusObserver callback) {
501 synchronized (mAuthorities) {
502 mChangeListeners.unregister(callback);
503 }
504 }
Costin Manolache360e4542009-09-04 13:36:04 -0700505
Matthew Williamsfa774182013-06-18 15:44:11 -0700506 /**
507 * Figure out a reasonable flex time for cases where none is provided (old api calls).
508 * @param syncTimeSeconds requested sync time from now.
509 * @return amount of seconds before syncTimeSeconds that the sync can occur.
510 * I.e.
511 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700512 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700513 */
514 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
515 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
516 // Small enough sync request time that we don't add flex time - developer probably
517 // wants to wait for an operation to occur before syncing so we honour the
518 // request time.
519 return 0L;
520 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
521 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
522 } else {
523 // Large enough sync request time that we cap the flex time.
524 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
525 }
526 }
527
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000528 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700529 ArrayList<ISyncStatusObserver> reports = null;
530 synchronized (mAuthorities) {
531 int i = mChangeListeners.beginBroadcast();
532 while (i > 0) {
533 i--;
534 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
535 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536 continue;
537 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700538 if (reports == null) {
539 reports = new ArrayList<ISyncStatusObserver>(i);
540 }
541 reports.add(mChangeListeners.getBroadcastItem(i));
542 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700543 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700544 }
Costin Manolache360e4542009-09-04 13:36:04 -0700545
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700546 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000547 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700548 }
Costin Manolache360e4542009-09-04 13:36:04 -0700549
Dianne Hackborn231cc602009-04-27 17:10:36 -0700550 if (reports != null) {
551 int i = reports.size();
552 while (i > 0) {
553 i--;
554 try {
555 reports.get(i).onStatusChanged(which);
556 } catch (RemoteException e) {
557 // The remote callback list will take care of this for us.
558 }
559 }
560 }
561 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700562
Amith Yamasani04e0d262012-02-14 11:50:53 -0800563 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700564 synchronized (mAuthorities) {
565 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700566 AuthorityInfo authority = getAuthorityLocked(
567 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700568 "getSyncAutomatically");
569 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700570 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700571
Dianne Hackborn231cc602009-04-27 17:10:36 -0700572 int i = mAuthorities.size();
573 while (i > 0) {
574 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700575 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700576 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700577 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700578 return true;
579 }
580 }
581 return false;
582 }
583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584
Amith Yamasani04e0d262012-02-14 11:50:53 -0800585 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000586 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700587 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000588 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800589 + ", user " + userId + " -> " + sync);
590 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700591 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700592 AuthorityInfo authority =
593 getOrCreateAuthorityLocked(
594 new EndPoint(account, providerName, userId),
595 -1 /* ident */,
596 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700597 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700598 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000599 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800600 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700601 return;
602 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700603 // If the adapter was syncable but missing its initialization sync, set it to
604 // uninitialized now. This is to give it a chance to run any one-time initialization
605 // logic.
606 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
607 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
608 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700609 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700610 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700612
Fred Quintana77c560f2010-03-29 22:20:26 -0700613 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700614 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
615 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700616 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700617 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800618 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 }
620
Amith Yamasani04e0d262012-02-14 11:50:53 -0800621 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700622 synchronized (mAuthorities) {
623 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700624 AuthorityInfo authority = getAuthorityLocked(
625 new EndPoint(account, providerName, userId),
626 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700627 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700628 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700629 }
630 return authority.syncable;
631 }
632
633 int i = mAuthorities.size();
634 while (i > 0) {
635 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700636 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700637 if (authorityInfo.target != null
638 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700639 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700640 }
641 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700642 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700643 }
644 }
645
Amith Yamasani04e0d262012-02-14 11:50:53 -0800646 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700647 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700648 }
649
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700650 /**
651 * An enabled sync service and a syncable provider's adapter both get resolved to the same
652 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700653 * @param target target to set value for.
654 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700655 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700656 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700657 AuthorityInfo aInfo;
658 synchronized (mAuthorities) {
659 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700660 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
661 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700662 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700663 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000664 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700665 }
666 if (aInfo.syncable == syncable) {
667 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000668 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700669 }
670 return;
671 }
672 aInfo.syncable = syncable;
673 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700674 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700675 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700676 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700677 }
678 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
679 }
680
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700681 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800682 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700683 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
684 if (authority != null) {
685 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800686 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700687 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800688 }
689 }
690
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700691 /**
692 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
693 * the account or provider info be null, which signifies all accounts or providers.
694 */
695 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
696 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000697 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800698 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
699 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700700 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800701 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000702 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700703 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000704 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700705 changed = setBackoffLocked(
706 info.account /* may be null */,
707 info.userId,
708 info.provider /* may be null */,
709 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800710 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700711 AuthorityInfo authorityInfo =
712 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
713 if (authorityInfo.backoffTime == nextSyncTime
714 && authorityInfo.backoffDelay == nextDelay) {
715 changed = false;
716 } else {
717 authorityInfo.backoffTime = nextSyncTime;
718 authorityInfo.backoffDelay = nextDelay;
719 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800720 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800721 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800722 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800723 if (changed) {
724 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
725 }
726 }
727
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 /**
729 * Either set backoff for a specific authority, or set backoff for all the
730 * accounts on a specific adapter/all adapters.
731 *
732 * @param account account for which to set backoff. Null to specify all accounts.
733 * @param userId id of the user making this request.
734 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700735 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700736 */
737 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000738 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700739 boolean changed = false;
740 for (AccountInfo accountInfo : mAccounts.values()) {
741 if (account != null && !account.equals(accountInfo.accountAndUser.account)
742 && userId != accountInfo.accountAndUser.userId) {
743 continue;
744 }
745 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
746 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700747 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700748 continue;
749 }
750 if (authorityInfo.backoffTime != nextSyncTime
751 || authorityInfo.backoffDelay != nextDelay) {
752 authorityInfo.backoffTime = nextSyncTime;
753 authorityInfo.backoffDelay = nextDelay;
754 changed = true;
755 }
756 }
757 }
758 return changed;
759 }
760
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000761 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800762 boolean changed = false;
763 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000764 // Clear backoff for all sync adapters.
765 for (AccountInfo accountInfo : mAccounts.values()) {
766 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
767 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
768 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
769 if (Log.isLoggable(TAG, Log.VERBOSE)) {
770 Slog.v(TAG, "clearAllBackoffsLocked:"
771 + " authority:" + authorityInfo.target
772 + " account:" + accountInfo.accountAndUser.account.name
773 + " user:" + accountInfo.accountAndUser.userId
774 + " backoffTime was: " + authorityInfo.backoffTime
775 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800776 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000777 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
778 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
779 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800780 }
781 }
782 }
783 }
784
785 if (changed) {
786 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
787 }
788 }
789
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700790 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800791 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700792 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800793 if (authority == null) {
794 return 0;
795 }
796 return authority.delayUntil;
797 }
798 }
799
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700800 public void setDelayUntilTime(EndPoint info, long delayUntil) {
801 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000802 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700803 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800804 }
805 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700806 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
807 if (authority.delayUntil == delayUntil) {
808 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700809 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700810 authority.delayUntil = delayUntil;
811 }
812 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
813 }
814
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700815 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000816 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
817 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700818 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000819 boolean restoreAllPeriodicSyncs() {
820 if (mPeriodicSyncAddedListener == null) {
821 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800822 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000823 synchronized (mAuthorities) {
824 for (int i=0; i<mAuthorities.size(); i++) {
825 AuthorityInfo authority = mAuthorities.valueAt(i);
826 for (PeriodicSync periodicSync: authority.periodicSyncs) {
827 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
828 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
829 }
830 authority.periodicSyncs.clear();
831 }
832 writeAccountInfoLocked();
833 }
834 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800835 }
836
Amith Yamasani04e0d262012-02-14 11:50:53 -0800837 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700838 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800839 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700840 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700841 return;
842 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800843 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700844 writeAccountInfoLocked();
845 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700846 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700847 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
848 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700849 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700850 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800851 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800852 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
Amith Yamasani04e0d262012-02-14 11:50:53 -0800855 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700856 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800857 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800858 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700859 }
860 }
Costin Manolache360e4542009-09-04 13:36:04 -0700861
Dianne Hackborn231cc602009-04-27 17:10:36 -0700862 public AuthorityInfo getAuthority(int authorityId) {
863 synchronized (mAuthorities) {
864 return mAuthorities.get(authorityId);
865 }
866 }
Costin Manolache360e4542009-09-04 13:36:04 -0700867
Dianne Hackborn231cc602009-04-27 17:10:36 -0700868 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700869 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700870 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700871 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700872 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700873 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700874 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700875 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700876 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700877 return true;
878 }
879 }
880 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 return false;
882 }
Costin Manolache360e4542009-09-04 13:36:04 -0700883
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000884 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700885 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000886 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
887 -1 /* desired identifier */,
888 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700889 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000890 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700891 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700892 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000893 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700895 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700896 }
Costin Manolache360e4542009-09-04 13:36:04 -0700897
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 /**
899 * Called when the set of account has changed, given the new array of
900 * active accounts.
901 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800902 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700903 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700904 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000905 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700906 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700907 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
908 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
909 while (accIt.hasNext()) {
910 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800911 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
912 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700913 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700914 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000915 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700916 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700917 for (AuthorityInfo auth : acc.authorities.values()) {
918 removing.put(auth.ident, auth);
919 }
920 accIt.remove();
921 }
922 }
Costin Manolache360e4542009-09-04 13:36:04 -0700923
Dianne Hackborn231cc602009-04-27 17:10:36 -0700924 // Clean out all data structures.
925 int i = removing.size();
926 if (i > 0) {
927 while (i > 0) {
928 i--;
929 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000930 AuthorityInfo auth = removing.valueAt(i);
931 if (mAuthorityRemovedListener != null) {
932 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
933 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700934 mAuthorities.remove(ident);
935 int j = mSyncStatus.size();
936 while (j > 0) {
937 j--;
938 if (mSyncStatus.keyAt(j) == ident) {
939 mSyncStatus.remove(mSyncStatus.keyAt(j));
940 }
941 }
942 j = mSyncHistory.size();
943 while (j > 0) {
944 j--;
945 if (mSyncHistory.get(j).authorityId == ident) {
946 mSyncHistory.remove(j);
947 }
948 }
949 }
950 writeAccountInfoLocked();
951 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 writeStatisticsLocked();
953 }
954 }
955 }
956
957 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700958 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
959 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700960 */
Fred Quintana918339a2010-10-05 14:00:39 -0700961 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
962 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700963 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700964 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000965 Slog.v(TAG, "setActiveSync: account="
966 + " auth=" + activeSyncContext.mSyncOperation.target
967 + " src=" + activeSyncContext.mSyncOperation.syncSource
968 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700969 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700970 final EndPoint info = activeSyncContext.mSyncOperation.target;
971 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
972 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700973 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700974 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700975 syncInfo = new SyncInfo(
976 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700977 authorityInfo.target.account,
978 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700979 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700980 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700981 }
Fred Quintana918339a2010-10-05 14:00:39 -0700982 reportActiveChange();
983 return syncInfo;
984 }
985
986 /**
987 * Called to indicate that a previously active sync is no longer active.
988 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800989 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700990 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700991 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000992 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800993 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -0700994 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -0700995 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800996 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -0700997 }
998
999 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001000 }
1001
1002 /**
1003 * To allow others to send active change reports, to poke clients.
1004 */
1005 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001006 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001007 }
Costin Manolache360e4542009-09-04 13:36:04 -07001008
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001010 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001012 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 long id;
1014 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001015 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001016 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001017 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001018 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001019 if (authority == null) {
1020 return -1;
1021 }
1022 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001023 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001024 item.authorityId = authority.ident;
1025 item.historyId = mNextHistoryId++;
1026 if (mNextHistoryId < 0) mNextHistoryId = 0;
1027 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001028 item.source = op.syncSource;
1029 item.reason = op.reason;
1030 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001031 item.event = EVENT_START;
1032 mSyncHistory.add(0, item);
1033 while (mSyncHistory.size() > MAX_HISTORY) {
1034 mSyncHistory.remove(mSyncHistory.size()-1);
1035 }
1036 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001037 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 }
Costin Manolache360e4542009-09-04 13:36:04 -07001039
Fred Quintanaac9385e2009-06-22 18:00:59 -07001040 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001041 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001042 }
1043
Fred Quintana77c560f2010-03-29 22:20:26 -07001044 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001045 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001046 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001047 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001048 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001049 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 SyncHistoryItem item = null;
1051 int i = mSyncHistory.size();
1052 while (i > 0) {
1053 i--;
1054 item = mSyncHistory.get(i);
1055 if (item.historyId == historyId) {
1056 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Costin Manolache360e4542009-09-04 13:36:04 -07001060
Dianne Hackborn231cc602009-04-27 17:10:36 -07001061 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001062 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001063 return;
1064 }
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 item.elapsedTime = elapsedTime;
1067 item.event = EVENT_STOP;
1068 item.mesg = resultMessage;
1069 item.downstreamActivity = downstreamActivity;
1070 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001071
Dianne Hackborn231cc602009-04-27 17:10:36 -07001072 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001073
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 status.numSyncs++;
1075 status.totalElapsedTime += elapsedTime;
1076 switch (item.source) {
1077 case SOURCE_LOCAL:
1078 status.numSourceLocal++;
1079 break;
1080 case SOURCE_POLL:
1081 status.numSourcePoll++;
1082 break;
1083 case SOURCE_USER:
1084 status.numSourceUser++;
1085 break;
1086 case SOURCE_SERVER:
1087 status.numSourceServer++;
1088 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001089 case SOURCE_PERIODIC:
1090 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001091 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001092 }
Costin Manolache360e4542009-09-04 13:36:04 -07001093
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001095 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 if (mDayStats[0] == null) {
1097 mDayStats[0] = new DayStats(day);
1098 } else if (day != mDayStats[0].day) {
1099 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1100 mDayStats[0] = new DayStats(day);
1101 writeStatisticsNow = true;
1102 } else if (mDayStats[0] == null) {
1103 }
1104 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001105
Dianne Hackborn231cc602009-04-27 17:10:36 -07001106 final long lastSyncTime = (item.eventTime + elapsedTime);
1107 boolean writeStatusNow = false;
1108 if (MESG_SUCCESS.equals(resultMessage)) {
1109 // - if successful, update the successful columns
1110 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1111 writeStatusNow = true;
1112 }
1113 status.lastSuccessTime = lastSyncTime;
1114 status.lastSuccessSource = item.source;
1115 status.lastFailureTime = 0;
1116 status.lastFailureSource = -1;
1117 status.lastFailureMesg = null;
1118 status.initialFailureTime = 0;
1119 ds.successCount++;
1120 ds.successTime += elapsedTime;
1121 } else if (!MESG_CANCELED.equals(resultMessage)) {
1122 if (status.lastFailureTime == 0) {
1123 writeStatusNow = true;
1124 }
1125 status.lastFailureTime = lastSyncTime;
1126 status.lastFailureSource = item.source;
1127 status.lastFailureMesg = resultMessage;
1128 if (status.initialFailureTime == 0) {
1129 status.initialFailureTime = lastSyncTime;
1130 }
1131 ds.failureCount++;
1132 ds.failureTime += elapsedTime;
1133 }
Costin Manolache360e4542009-09-04 13:36:04 -07001134
Dianne Hackborn231cc602009-04-27 17:10:36 -07001135 if (writeStatusNow) {
1136 writeStatusLocked();
1137 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1138 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1139 WRITE_STATUS_DELAY);
1140 }
1141 if (writeStatisticsNow) {
1142 writeStatisticsLocked();
1143 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1144 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1145 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001146 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001147 }
Costin Manolache360e4542009-09-04 13:36:04 -07001148
Fred Quintanaac9385e2009-06-22 18:00:59 -07001149 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001150 }
1151
1152 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001153 * Return a list of the currently active syncs. Note that the returned
1154 * items are the real, live active sync objects, so be careful what you do
1155 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001156 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001157 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001158 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001159 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001160 }
1161 }
Costin Manolache360e4542009-09-04 13:36:04 -07001162
Dianne Hackborn231cc602009-04-27 17:10:36 -07001163 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001164 * @param userId Id of user to return current sync info.
1165 * @param canAccessAccounts Determines whether to redact Account information from the result.
1166 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001167 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001168 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001169 synchronized (mAuthorities) {
1170 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1171 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1172 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001173 SyncInfo copy;
1174 if (!canAccessAccounts) {
1175 copy = SyncInfo.createAccountRedacted(
1176 sync.authorityId, sync.authority, sync.startTime);
1177 } else {
1178 copy = new SyncInfo(sync);
1179 }
1180 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001181 }
1182 return syncsCopy;
1183 }
1184 }
1185
1186 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1187 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1188 if (syncs == null) {
1189 syncs = new ArrayList<SyncInfo>();
1190 mCurrentSyncs.put(userId, syncs);
1191 }
1192 return syncs;
1193 }
1194
1195 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001196 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001197 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001198 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001199 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001200 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001201 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001202 true /* write to storage if this results in a change */);
1203 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1204 }
1205 }
1206
1207 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001208 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001209 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001210 * @param info the endpoint target we are querying status info for.
1211 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001212 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001213 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001214 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001215 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001216 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001218 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001219 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001220 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001221 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001222 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001223 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001224 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001225 }
1226 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001227 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001228 }
1229 }
Costin Manolache360e4542009-09-04 13:36:04 -07001230
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001231 /** Return true if the pending status is true of any matching authorities. */
1232 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001233 synchronized (mAuthorities) {
1234 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001235 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001236 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1238 if (ainfo == null) {
1239 continue;
1240 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001241 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001242 continue;
1243 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001244 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 return true;
1246 }
1247 }
1248 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 }
1250 }
1251
1252 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001253 * Return an array of the current sync status for all authorities. Note
1254 * that the objects inside the array are the real, live status objects,
1255 * so be careful what you do with them.
1256 */
1257 public ArrayList<SyncHistoryItem> getSyncHistory() {
1258 synchronized (mAuthorities) {
1259 final int N = mSyncHistory.size();
1260 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1261 for (int i=0; i<N; i++) {
1262 items.add(mSyncHistory.get(i));
1263 }
1264 return items;
1265 }
1266 }
Costin Manolache360e4542009-09-04 13:36:04 -07001267
Dianne Hackborn231cc602009-04-27 17:10:36 -07001268 /**
1269 * Return an array of the current per-day statistics. Note
1270 * that the objects inside the array are the real, live status objects,
1271 * so be careful what you do with them.
1272 */
1273 public DayStats[] getDayStatistics() {
1274 synchronized (mAuthorities) {
1275 DayStats[] ds = new DayStats[mDayStats.length];
1276 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1277 return ds;
1278 }
1279 }
Costin Manolache360e4542009-09-04 13:36:04 -07001280
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001281 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1282 AuthorityInfo authorityInfo) {
1283 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1284 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1285 }
1286
Dianne Hackborn55280a92009-05-07 15:53:46 -07001287 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001288 mCal.setTimeInMillis(System.currentTimeMillis());
1289 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1290 if (mYear != mCal.get(Calendar.YEAR)) {
1291 mYear = mCal.get(Calendar.YEAR);
1292 mCal.clear();
1293 mCal.set(Calendar.YEAR, mYear);
1294 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1295 }
1296 return dayOfYear + mYearInDays;
1297 }
Costin Manolache360e4542009-09-04 13:36:04 -07001298
Dianne Hackborn231cc602009-04-27 17:10:36 -07001299 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001300 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001301 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001302 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001303 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001304 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001306 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001307 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1308 AccountInfo accountInfo = mAccounts.get(au);
1309 if (accountInfo == null) {
1310 if (tag != null) {
1311 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1312 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001313 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001314 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001315 return null;
1316 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001317 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1318 if (authority == null) {
1319 if (tag != null) {
1320 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1321 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1322 }
1323 }
1324 return null;
1325 }
1326 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001327 }
Costin Manolache360e4542009-09-04 13:36:04 -07001328
Matthew Williamsfa774182013-06-18 15:44:11 -07001329 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001330 * @param info info identifying target.
1331 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001332 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001333 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001334 * exists.
1335 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001336 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1337 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001338 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1339 AccountInfo account = mAccounts.get(au);
1340 if (account == null) {
1341 account = new AccountInfo(au);
1342 mAccounts.put(au, account);
1343 }
1344 authority = account.authorities.get(info.provider);
1345 if (authority == null) {
1346 authority = createAuthorityLocked(info, ident, doWrite);
1347 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001348 }
1349 return authority;
1350 }
1351
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001352 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1353 AuthorityInfo authority;
1354 if (ident < 0) {
1355 ident = mNextAuthorityId;
1356 mNextAuthorityId++;
1357 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001358 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001359 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001360 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001361 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001362 authority = new AuthorityInfo(info, ident);
1363 mAuthorities.put(ident, authority);
1364 if (doWrite) {
1365 writeAccountInfoLocked();
1366 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001367 return authority;
1368 }
Costin Manolache360e4542009-09-04 13:36:04 -07001369
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001370 public void removeAuthority(EndPoint info) {
1371 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001372 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001373 }
1374 }
1375
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001376
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001377 /**
1378 * Remove an authority associated with a provider. Needs to be a standalone function for
1379 * backward compatibility.
1380 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001381 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001382 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001383 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001384 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001385 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1386 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001387 if (mAuthorityRemovedListener != null) {
1388 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1389 }
Fred Quintanafb084402010-03-23 17:57:03 -07001390 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001391 if (doWrite) {
1392 writeAccountInfoLocked();
1393 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001394 }
1395 }
1396 }
1397
Dianne Hackborn231cc602009-04-27 17:10:36 -07001398 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1399 SyncStatusInfo status = mSyncStatus.get(authorityId);
1400 if (status == null) {
1401 status = new SyncStatusInfo(authorityId);
1402 mSyncStatus.put(authorityId, status);
1403 }
1404 return status;
1405 }
Costin Manolache360e4542009-09-04 13:36:04 -07001406
Dianne Hackborn55280a92009-05-07 15:53:46 -07001407 public void writeAllState() {
1408 synchronized (mAuthorities) {
1409 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001410 writeStatusLocked();
1411 writeStatisticsLocked();
1412 }
1413 }
Costin Manolache360e4542009-09-04 13:36:04 -07001414
Svet Ganov65712b02016-09-01 10:24:11 -07001415 public boolean shouldGrantSyncAdaptersAccountAccess() {
1416 return mGrantSyncAdaptersAccountAccess;
1417 }
1418
Dianne Hackborn231cc602009-04-27 17:10:36 -07001419 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001420 * public for testing
1421 */
1422 public void clearAndReadState() {
1423 synchronized (mAuthorities) {
1424 mAuthorities.clear();
1425 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001426 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001427 mSyncStatus.clear();
1428 mSyncHistory.clear();
1429
1430 readAccountInfoLocked();
1431 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001432 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001433 readAndDeleteLegacyAccountInfoLocked();
1434 writeAccountInfoLocked();
1435 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001436 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001437 }
1438 }
1439
1440 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 * Read all account information back in to the initial engine state.
1442 */
1443 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001444 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001445 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001447 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001448 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001449 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001450 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001451 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001452 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001453 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001454 while (eventType != XmlPullParser.START_TAG &&
1455 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001456 eventType = parser.next();
1457 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001458 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001459 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001460 return;
1461 }
1462
Dianne Hackborn231cc602009-04-27 17:10:36 -07001463 String tagName = parser.getName();
1464 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001465 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001466 String versionString = parser.getAttributeValue(null, "version");
1467 int version;
1468 try {
1469 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1470 } catch (NumberFormatException e) {
1471 version = 0;
1472 }
Svet Ganov65712b02016-09-01 10:24:11 -07001473
1474 if (version < 3) {
1475 mGrantSyncAdaptersAccountAccess = true;
1476 }
1477
Amith Yamasani04e0d262012-02-14 11:50:53 -08001478 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001479 try {
1480 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1481 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1482 } catch (NumberFormatException e) {
1483 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001484 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001485 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1486 try {
1487 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1488 } catch (NumberFormatException e) {
1489 mSyncRandomOffset = 0;
1490 }
1491 if (mSyncRandomOffset == 0) {
1492 Random random = new Random(System.currentTimeMillis());
1493 mSyncRandomOffset = random.nextInt(86400);
1494 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001495 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001496 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001497 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001498 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001499 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001500 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001501 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001502 if (parser.getDepth() == 2) {
1503 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001504 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001505 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001506 if (authority != null) {
1507 if (authority.ident > highestAuthorityId) {
1508 highestAuthorityId = authority.ident;
1509 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001510 } else {
1511 EventLog.writeEvent(0x534e4554, "26513719", -1,
1512 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001513 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001514 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1515 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001516 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001517 } else if (parser.getDepth() == 3) {
1518 if ("periodicSync".equals(tagName) && authority != null) {
1519 periodicSync = parsePeriodicSync(parser, authority);
1520 }
1521 } else if (parser.getDepth() == 4 && periodicSync != null) {
1522 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001523 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001524 }
1525 }
1526 }
1527 eventType = parser.next();
1528 } while (eventType != XmlPullParser.END_DOCUMENT);
1529 }
1530 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001531 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001532 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001533 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001534 if (fis == null) Slog.i(TAG, "No initial accounts");
1535 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001536 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001537 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001538 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001539 if (fis != null) {
1540 try {
1541 fis.close();
1542 } catch (java.io.IOException e1) {
1543 }
1544 }
1545 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001546
Fred Quintana77c560f2010-03-29 22:20:26 -07001547 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001548 }
Costin Manolache360e4542009-09-04 13:36:04 -07001549
Fred Quintanafb084402010-03-23 17:57:03 -07001550 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001551 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1552 * pending.xml was used starting in KLP.
1553 * @param syncDir directory where the sync files are located.
1554 */
1555 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1556 File file = new File(syncDir, "pending.bin");
1557 if (!file.exists()) {
1558 return;
1559 } else {
1560 file.delete();
1561 }
1562 }
1563
1564 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001565 * some authority names have changed. copy over their settings and delete the old ones
1566 * @return true if a change was made
1567 */
1568 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1569 boolean writeNeeded = false;
1570
1571 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1572 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001573 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001574 AuthorityInfo authority = mAuthorities.valueAt(i);
1575 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001576 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001577 if (newAuthorityName == null) {
1578 continue;
1579 }
1580
1581 // remember this authority so we can remove it later. we can't remove it
1582 // now without messing up this loop iteration
1583 authoritiesToRemove.add(authority);
1584
1585 // this authority isn't enabled, no need to copy it to the new authority name since
1586 // the default is "disabled"
1587 if (!authority.enabled) {
1588 continue;
1589 }
1590
1591 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001592 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001593 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001594 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001595 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001596 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001597 continue;
1598 }
1599
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001600 AuthorityInfo newAuthority =
1601 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001602 newAuthority.enabled = true;
1603 writeNeeded = true;
1604 }
1605
1606 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001607 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001608 authorityInfo.target.account,
1609 authorityInfo.target.userId,
1610 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001611 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001612 writeNeeded = true;
1613 }
1614
1615 return writeNeeded;
1616 }
1617
Amith Yamasani04e0d262012-02-14 11:50:53 -08001618 private void parseListenForTickles(XmlPullParser parser) {
1619 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1620 int userId = 0;
1621 try {
1622 userId = Integer.parseInt(user);
1623 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001624 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001625 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001626 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001627 }
1628 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1629 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1630 mMasterSyncAutomatically.put(userId, listen);
1631 }
1632
Fred Quintanac2e46912010-03-15 16:10:44 -07001633 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001634 AuthorityInfo authority = null;
1635 int id = -1;
1636 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001637 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001638 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001639 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001641 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001642 }
1643 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001644 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001646 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 String accountName = parser.getAttributeValue(null, "account");
1648 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001649 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001650 String packageName = parser.getAttributeValue(null, "package");
1651 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001652 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001653 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001654 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001655 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001656 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001657 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001658 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001659 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001660 + " account=" + accountName
1661 + " accountType=" + accountType
1662 + " auth=" + authorityName
1663 + " package=" + packageName
1664 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001665 + " user=" + userId
1666 + " enabled=" + enabled
1667 + " syncable=" + syncable);
1668 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001669 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001670 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001671 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001672 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001673 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001674 if (accountName != null && authorityName != null) {
1675 info = new EndPoint(
1676 new Account(accountName, accountType),
1677 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001678 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001679 if (info != null) {
1680 authority = getOrCreateAuthorityLocked(info, id, false);
1681 // If the version is 0 then we are upgrading from a file format that did not
1682 // know about periodic syncs. In that case don't clear the list since we
1683 // want the default, which is a daily periodic sync.
1684 // Otherwise clear out this default list since we will populate it later with
1685 // the periodic sync descriptions that are read from the configuration file.
1686 if (version > 0) {
1687 authority.periodicSyncs.clear();
1688 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001689 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001690 }
1691 if (authority != null) {
1692 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001693 try {
1694 authority.syncable = (syncable == null) ?
1695 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1696 } catch (NumberFormatException e) {
1697 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1698 // format.
1699 if ("unknown".equals(syncable)) {
1700 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1701 } else {
1702 authority.syncable = Boolean.parseBoolean(syncable) ?
1703 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1704 }
1705
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001706 }
1707 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001708 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001709 + accountName + " auth=" + authorityName
1710 + " enabled=" + enabled
1711 + " syncable=" + syncable);
1712 }
1713 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001714 return authority;
1715 }
1716
Matthew Williamsfa774182013-06-18 15:44:11 -07001717 /**
1718 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1719 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001720 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001721 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001722 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001723 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001724 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001725 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001726 try {
1727 period = Long.parseLong(periodValue);
1728 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001729 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001730 return null;
1731 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001732 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001733 return null;
1734 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001735 try {
1736 flextime = Long.parseLong(flexValue);
1737 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001738 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001739 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001740 + ", using default: "
1741 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001742 } catch (NullPointerException expected) {
1743 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001744 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1745 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001746 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001747 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001748 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001749 new PeriodicSync(authorityInfo.target.account,
1750 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001751 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001752 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001753 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001754 return periodicSync;
1755 }
1756
Matthew Williamsfa774182013-06-18 15:44:11 -07001757 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001758 String name = parser.getAttributeValue(null, "name");
1759 String type = parser.getAttributeValue(null, "type");
1760 String value1 = parser.getAttributeValue(null, "value1");
1761 String value2 = parser.getAttributeValue(null, "value2");
1762
1763 try {
1764 if ("long".equals(type)) {
1765 extras.putLong(name, Long.parseLong(value1));
1766 } else if ("integer".equals(type)) {
1767 extras.putInt(name, Integer.parseInt(value1));
1768 } else if ("double".equals(type)) {
1769 extras.putDouble(name, Double.parseDouble(value1));
1770 } else if ("float".equals(type)) {
1771 extras.putFloat(name, Float.parseFloat(value1));
1772 } else if ("boolean".equals(type)) {
1773 extras.putBoolean(name, Boolean.parseBoolean(value1));
1774 } else if ("string".equals(type)) {
1775 extras.putString(name, value1);
1776 } else if ("account".equals(type)) {
1777 extras.putParcelable(name, new Account(value1, value2));
1778 }
1779 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001780 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001781 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001782 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001783 }
1784 }
1785
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 /**
1787 * Write all account information to the account file.
1788 */
1789 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001790 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001791 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001792 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001793 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001794
Dianne Hackborn231cc602009-04-27 17:10:36 -07001795 try {
1796 fos = mAccountInfoFile.startWrite();
1797 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001798 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001799 out.startDocument(null, true);
1800 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001801
Dianne Hackborn231cc602009-04-27 17:10:36 -07001802 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001803 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001804 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001805 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001806
1807 // Write the Sync Automatically flags for each user
1808 final int M = mMasterSyncAutomatically.size();
1809 for (int m = 0; m < M; m++) {
1810 int userId = mMasterSyncAutomatically.keyAt(m);
1811 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1812 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1813 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1814 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1815 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 }
Costin Manolache360e4542009-09-04 13:36:04 -07001817
Dianne Hackborn231cc602009-04-27 17:10:36 -07001818 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001819 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001820 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001821 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001822 out.startTag(null, "authority");
1823 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001824 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001825 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001826 out.attribute(null, "account", info.account.name);
1827 out.attribute(null, "type", info.account.type);
1828 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001829 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001830 out.endTag(null, "authority");
1831 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001832 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001833 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001834 mAccountInfoFile.finishWrite(fos);
1835 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001836 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001837 if (fos != null) {
1838 mAccountInfoFile.failWrite(fos);
1839 }
1840 }
1841 }
Costin Manolache360e4542009-09-04 13:36:04 -07001842
Dianne Hackborn231cc602009-04-27 17:10:36 -07001843 static int getIntColumn(Cursor c, String name) {
1844 return c.getInt(c.getColumnIndex(name));
1845 }
Costin Manolache360e4542009-09-04 13:36:04 -07001846
Dianne Hackborn231cc602009-04-27 17:10:36 -07001847 static long getLongColumn(Cursor c, String name) {
1848 return c.getLong(c.getColumnIndex(name));
1849 }
Costin Manolache360e4542009-09-04 13:36:04 -07001850
Dianne Hackborn231cc602009-04-27 17:10:36 -07001851 /**
1852 * Load sync engine state from the old syncmanager database, and then
1853 * erase it. Note that we don't deal with pending operations, active
1854 * sync, or history.
1855 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001856 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001857 // Look for old database to initialize from.
1858 File file = mContext.getDatabasePath("syncmanager.db");
1859 if (!file.exists()) {
1860 return;
1861 }
1862 String path = file.getPath();
1863 SQLiteDatabase db = null;
1864 try {
1865 db = SQLiteDatabase.openDatabase(path, null,
1866 SQLiteDatabase.OPEN_READONLY);
1867 } catch (SQLiteException e) {
1868 }
Costin Manolache360e4542009-09-04 13:36:04 -07001869
Dianne Hackborn231cc602009-04-27 17:10:36 -07001870 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001871 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001872
Dianne Hackborn231cc602009-04-27 17:10:36 -07001873 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001874 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001875 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001876 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001877 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1878 qb.setTables("stats, status");
1879 HashMap<String,String> map = new HashMap<String,String>();
1880 map.put("_id", "status._id as _id");
1881 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001882 if (hasType) {
1883 map.put("account_type", "stats.account_type as account_type");
1884 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 map.put("authority", "stats.authority as authority");
1886 map.put("totalElapsedTime", "totalElapsedTime");
1887 map.put("numSyncs", "numSyncs");
1888 map.put("numSourceLocal", "numSourceLocal");
1889 map.put("numSourcePoll", "numSourcePoll");
1890 map.put("numSourceServer", "numSourceServer");
1891 map.put("numSourceUser", "numSourceUser");
1892 map.put("lastSuccessSource", "lastSuccessSource");
1893 map.put("lastSuccessTime", "lastSuccessTime");
1894 map.put("lastFailureSource", "lastFailureSource");
1895 map.put("lastFailureTime", "lastFailureTime");
1896 map.put("lastFailureMesg", "lastFailureMesg");
1897 map.put("pending", "pending");
1898 qb.setProjectionMap(map);
1899 qb.appendWhere("stats._id = status.stats_id");
1900 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001902 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001903 String accountType = hasType
1904 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001905 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001906 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001908 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001909 AuthorityInfo authority =
1910 this.getOrCreateAuthorityLocked(
1911 new EndPoint(new Account(accountName, accountType),
1912 authorityName,
1913 0 /* legacy is single-user */)
1914 , -1,
1915 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001916 if (authority != null) {
1917 int i = mSyncStatus.size();
1918 boolean found = false;
1919 SyncStatusInfo st = null;
1920 while (i > 0) {
1921 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001922 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001923 if (st.authorityId == authority.ident) {
1924 found = true;
1925 break;
1926 }
1927 }
1928 if (!found) {
1929 st = new SyncStatusInfo(authority.ident);
1930 mSyncStatus.put(authority.ident, st);
1931 }
1932 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1933 st.numSyncs = getIntColumn(c, "numSyncs");
1934 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1935 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1936 st.numSourceServer = getIntColumn(c, "numSourceServer");
1937 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001938 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001939 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1940 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1941 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1942 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1943 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1944 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
Costin Manolache360e4542009-09-04 13:36:04 -07001947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001949
Dianne Hackborn231cc602009-04-27 17:10:36 -07001950 // Retrieve the settings.
1951 qb = new SQLiteQueryBuilder();
1952 qb.setTables("settings");
1953 c = qb.query(db, null, null, null, null, null, null);
1954 while (c.moveToNext()) {
1955 String name = c.getString(c.getColumnIndex("name"));
1956 String value = c.getString(c.getColumnIndex("value"));
1957 if (name == null) continue;
1958 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001959 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 } else if (name.startsWith("sync_provider_")) {
1961 String provider = name.substring("sync_provider_".length(),
1962 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001963 int i = mAuthorities.size();
1964 while (i > 0) {
1965 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001966 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001967 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001968 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001969 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001970 }
1971 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 }
Costin Manolache360e4542009-09-04 13:36:04 -07001974
Dianne Hackborn231cc602009-04-27 17:10:36 -07001975 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001976
Dianne Hackborn231cc602009-04-27 17:10:36 -07001977 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001978
Dianne Hackborn231cc602009-04-27 17:10:36 -07001979 (new File(path)).delete();
1980 }
1981 }
Costin Manolache360e4542009-09-04 13:36:04 -07001982
Dianne Hackborn231cc602009-04-27 17:10:36 -07001983 public static final int STATUS_FILE_END = 0;
1984 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001985
Dianne Hackborn231cc602009-04-27 17:10:36 -07001986 /**
1987 * Read all sync status back in to the initial engine state.
1988 */
1989 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001990 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001991 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001992 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001993 try {
1994 byte[] data = mStatusFile.readFully();
1995 Parcel in = Parcel.obtain();
1996 in.unmarshall(data, 0, data.length);
1997 in.setDataPosition(0);
1998 int token;
1999 while ((token=in.readInt()) != STATUS_FILE_END) {
2000 if (token == STATUS_FILE_ITEM) {
2001 SyncStatusInfo status = new SyncStatusInfo(in);
2002 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
2003 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07002004 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002005 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07002006 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002007 mSyncStatus.put(status.authorityId, status);
2008 }
2009 } else {
2010 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002011 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002012 break;
2013 }
2014 }
2015 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002016 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002017 }
2018 }
Costin Manolache360e4542009-09-04 13:36:04 -07002019
Dianne Hackborn231cc602009-04-27 17:10:36 -07002020 /**
2021 * Write all sync status to the sync status file.
2022 */
2023 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002024 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002025 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002026 }
Costin Manolache360e4542009-09-04 13:36:04 -07002027
Dianne Hackborn231cc602009-04-27 17:10:36 -07002028 // The file is being written, so we don't need to have a scheduled
2029 // write until the next change.
2030 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002031
Dianne Hackborn231cc602009-04-27 17:10:36 -07002032 FileOutputStream fos = null;
2033 try {
2034 fos = mStatusFile.startWrite();
2035 Parcel out = Parcel.obtain();
2036 final int N = mSyncStatus.size();
2037 for (int i=0; i<N; i++) {
2038 SyncStatusInfo status = mSyncStatus.valueAt(i);
2039 out.writeInt(STATUS_FILE_ITEM);
2040 status.writeToParcel(out, 0);
2041 }
2042 out.writeInt(STATUS_FILE_END);
2043 fos.write(out.marshall());
2044 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002045
Dianne Hackborn231cc602009-04-27 17:10:36 -07002046 mStatusFile.finishWrite(fos);
2047 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002048 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002049 if (fos != null) {
2050 mStatusFile.failWrite(fos);
2051 }
2052 }
2053 }
Costin Manolache360e4542009-09-04 13:36:04 -07002054
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002055 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2056 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2057 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002058 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002059 } else {
2060 SyncRequest.Builder req =
2061 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002062 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002063 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002064 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002065 ContentResolver.requestSync(req.build());
2066 }
2067 }
2068
Alon Albert57286f92012-10-09 14:21:38 -07002069 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002070 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002071 // If this is happening in the system process, then call the syncrequest listener
2072 // to make a request back to the SyncManager directly.
2073 // If this is probably a test instance, then call back through the ContentResolver
2074 // which will know which userId to apply based on the Binder id.
2075 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2076 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002077 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002078 new EndPoint(account, authority, userId),
2079 reason,
2080 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002081 } else {
2082 ContentResolver.requestSync(account, authority, extras);
2083 }
2084 }
2085
Dianne Hackborn231cc602009-04-27 17:10:36 -07002086 public static final int STATISTICS_FILE_END = 0;
2087 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2088 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002089
Dianne Hackborn231cc602009-04-27 17:10:36 -07002090 /**
2091 * Read all sync statistics back in to the initial engine state.
2092 */
2093 private void readStatisticsLocked() {
2094 try {
2095 byte[] data = mStatisticsFile.readFully();
2096 Parcel in = Parcel.obtain();
2097 in.unmarshall(data, 0, data.length);
2098 in.setDataPosition(0);
2099 int token;
2100 int index = 0;
2101 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2102 if (token == STATISTICS_FILE_ITEM
2103 || token == STATISTICS_FILE_ITEM_OLD) {
2104 int day = in.readInt();
2105 if (token == STATISTICS_FILE_ITEM_OLD) {
2106 day = day - 2009 + 14245; // Magic!
2107 }
2108 DayStats ds = new DayStats(day);
2109 ds.successCount = in.readInt();
2110 ds.successTime = in.readLong();
2111 ds.failureCount = in.readInt();
2112 ds.failureTime = in.readLong();
2113 if (index < mDayStats.length) {
2114 mDayStats[index] = ds;
2115 index++;
2116 }
2117 } else {
2118 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002119 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002120 break;
2121 }
2122 }
2123 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002124 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002125 }
2126 }
Costin Manolache360e4542009-09-04 13:36:04 -07002127
Dianne Hackborn231cc602009-04-27 17:10:36 -07002128 /**
2129 * Write all sync statistics to the sync status file.
2130 */
2131 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002132 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002133 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002134 }
Costin Manolache360e4542009-09-04 13:36:04 -07002135
Dianne Hackborn231cc602009-04-27 17:10:36 -07002136 // The file is being written, so we don't need to have a scheduled
2137 // write until the next change.
2138 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002139
Dianne Hackborn231cc602009-04-27 17:10:36 -07002140 FileOutputStream fos = null;
2141 try {
2142 fos = mStatisticsFile.startWrite();
2143 Parcel out = Parcel.obtain();
2144 final int N = mDayStats.length;
2145 for (int i=0; i<N; i++) {
2146 DayStats ds = mDayStats[i];
2147 if (ds == null) {
2148 break;
2149 }
2150 out.writeInt(STATISTICS_FILE_ITEM);
2151 out.writeInt(ds.day);
2152 out.writeInt(ds.successCount);
2153 out.writeLong(ds.successTime);
2154 out.writeInt(ds.failureCount);
2155 out.writeLong(ds.failureTime);
2156 }
2157 out.writeInt(STATISTICS_FILE_END);
2158 fos.write(out.marshall());
2159 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002160
Dianne Hackborn231cc602009-04-27 17:10:36 -07002161 mStatisticsFile.finishWrite(fos);
2162 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002163 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002164 if (fos != null) {
2165 mStatisticsFile.failWrite(fos);
2166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002167 }
2168 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002169
2170 /**
Marvin Paula6533252014-11-24 12:57:48 -08002171 * Let the BackupManager know that account sync settings have changed. This will trigger
2172 * {@link com.android.server.backup.SystemBackupAgent} to run.
2173 */
2174 public void queueBackup() {
2175 BackupManager.dataChanged("android");
2176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177}