blob: 05aabf1f17b3060aa9f5f87dbdc0fe98f67ab5c0 [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 Basarge6275d492016-02-12 20:27:49 +000083 static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080084
Shreyas Basarge8c834c02016-01-07 13:53:16 +000085 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070086 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
87
88 /** Lower bound on sync time from which we assign a default flex time. */
89 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
90
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080091 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 /** Enum value for a sync start event. */
95 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a sync stop event. */
98 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a server-initiated sync. */
101 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a local-initiated sync. */
104 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700105 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a user-initiated sync. */
109 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800111 /** Enum value for a periodic sync. */
112 public static final int SOURCE_PERIODIC = 4;
113
Fred Quintana307da1a2010-01-21 14:24:20 -0800114 public static final long NOT_IN_BACKOFF_MODE = -1;
115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 // TODO: i18n -- grab these out of resources.
117 /** String names for the sync source types. */
118 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000119 "LOCAL",
120 "POLL",
121 "USER",
122 "PERIODIC",
123 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // The MESG column will contain one of these or one of the Error types.
126 public static final String MESG_SUCCESS = "success";
127 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700129 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 private static final int MSG_WRITE_STATUS = 1;
132 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATISTICS = 2;
135 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700136
137 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Fred Quintanac2e46912010-03-15 16:10:44 -0700139 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700140 private static final int ACCOUNTS_VERSION = 2;
141
142 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000143 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700144
145 static {
146 sAuthorityRenames = new HashMap<String, String>();
147 sAuthorityRenames.put("contacts", "com.android.contacts");
148 sAuthorityRenames.put("calendar", "com.android.calendar");
149 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700150
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800152 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 final HashMap<String, AuthorityInfo> authorities =
154 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 AccountInfo(AccountAndUser accountAndUser) {
157 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 }
159 }
Costin Manolache360e4542009-09-04 13:36:04 -0700160
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700161 /** Bare bones representation of a sync target. */
162 public static class EndPoint {
163 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
164 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700165 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800166 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700167 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168
169 public EndPoint(Account account, String provider, int userId) {
170 this.account = account;
171 this.provider = provider;
172 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 }
174
175 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700176 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
177 *
178 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000179 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700181 public boolean matchesSpec(EndPoint spec) {
182 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700184 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700185 return false;
186 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000187 boolean accountsMatch;
188 if (spec.account == null) {
189 accountsMatch = true;
190 } else {
191 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000193 boolean providersMatch;
194 if (spec.provider == null) {
195 providersMatch = true;
196 } else {
197 providersMatch = provider.equals(spec.provider);
198 }
199 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 }
201
202 public String toString() {
203 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000204 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 .append("/")
206 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700207 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 return sb.toString();
209 }
210 }
211
212 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700213 // Legal values of getIsSyncable
214 /**
215 * Default state for a newly installed adapter. An uninitialized adapter will receive an
216 * initialization sync which are governed by a different set of rules to that of regular
217 * syncs.
218 */
219 public static final int NOT_INITIALIZED = -1;
220 /**
221 * The adapter will not receive any syncs. This is behaviourally equivalent to
222 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
223 * while this is generally meant to be controlled by the developer.
224 */
225 public static final int NOT_SYNCABLE = 0;
226 /**
227 * The adapter is initialized and functioning. This is the normal state for an adapter.
228 */
229 public static final int SYNCABLE = 1;
230 /**
231 * The adapter is syncable but still requires an initialization sync. For example an adapter
232 * than has been restored from a previous device will be in this state. Not meant for
233 * external use.
234 */
235 public static final int SYNCABLE_NOT_INITIALIZED = 2;
236
Matthew Williams8ef22042013-07-26 12:56:39 -0700237 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700238 final int ident;
239 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700240 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700241 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800242 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700243 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800244 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700245 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800246 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700247
Matthew Williamsfa774182013-06-18 15:44:11 -0700248 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700249
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700250 /**
251 * Copy constructor for making deep-ish copies. Only the bundles stored
252 * in periodic syncs can make unexpected changes.
253 *
254 * @param toCopy AuthorityInfo to be copied.
255 */
256 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700257 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700258 ident = toCopy.ident;
259 enabled = toCopy.enabled;
260 syncable = toCopy.syncable;
261 backoffTime = toCopy.backoffTime;
262 backoffDelay = toCopy.backoffDelay;
263 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700264 periodicSyncs = new ArrayList<PeriodicSync>();
265 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700266 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700267 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700268 }
269 }
270
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700272 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700273 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000274 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275 periodicSyncs = new ArrayList<PeriodicSync>();
276 defaultInitialisation();
277 }
278
279 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700280 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800281 backoffTime = -1; // if < 0 then we aren't in backoff mode
282 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000283
284 if (mPeriodicSyncAddedListener != null) {
285 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
286 DEFAULT_POLL_FREQUENCY_SECONDS,
287 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700288 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700289 }
Matthew Williams06485a72013-07-26 12:56:39 -0700290
291 @Override
292 public String toString() {
293 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
294 + backoffTime + ", delay=" + delayUntil;
295 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 }
Costin Manolache360e4542009-09-04 13:36:04 -0700297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 public static class SyncHistoryItem {
299 int authorityId;
300 int historyId;
301 long eventTime;
302 long elapsedTime;
303 int source;
304 int event;
305 long upstreamActivity;
306 long downstreamActivity;
307 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700308 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700309 Bundle extras;
310 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 }
Costin Manolache360e4542009-09-04 13:36:04 -0700312
Dianne Hackborn231cc602009-04-27 17:10:36 -0700313 public static class DayStats {
314 public final int day;
315 public int successCount;
316 public long successTime;
317 public int failureCount;
318 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700319
Dianne Hackborn231cc602009-04-27 17:10:36 -0700320 public DayStats(int day) {
321 this.day = day;
322 }
323 }
Costin Manolache360e4542009-09-04 13:36:04 -0700324
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700326
327 /** Called when a sync is needed on an account(s) due to some change in state. */
328 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800329 }
330
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000331 interface PeriodicSyncAddedListener {
332 /** Called when a periodic sync is added. */
333 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
334 }
335
336 interface OnAuthorityRemovedListener {
337 /** Called when an authority is removed. */
338 void onAuthorityRemoved(EndPoint removedAuthority);
339 }
340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 // Primary list of all syncable authorities. Also our global lock.
342 private final SparseArray<AuthorityInfo> mAuthorities =
343 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700344
Amith Yamasani04e0d262012-02-14 11:50:53 -0800345 private final HashMap<AccountAndUser, AccountInfo> mAccounts
346 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
Amith Yamasani04e0d262012-02-14 11:50:53 -0800348 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
349 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 private final SparseArray<SyncStatusInfo> mSyncStatus =
352 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 private final ArrayList<SyncHistoryItem> mSyncHistory =
355 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
358 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Matthew Williams8ef22042013-07-26 12:56:39 -0700360 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700361 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
362 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700363
Fred Quintana77c560f2010-03-29 22:20:26 -0700364 private int mNextAuthorityId = 0;
365
Dianne Hackborn231cc602009-04-27 17:10:36 -0700366 // We keep 4 weeks of stats.
367 private final DayStats[] mDayStats = new DayStats[7*4];
368 private final Calendar mCal;
369 private int mYear;
370 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800373
Dianne Hackborn231cc602009-04-27 17:10:36 -0700374 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700375
Ashish Sharma69d95de2012-04-11 17:27:24 -0700376 private int mSyncRandomOffset;
377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 /**
379 * This file contains the core engine state: all accounts and the
380 * settings for them. It must never be lost, and should be changed
381 * infrequently, so it is stored as an XML file.
382 */
383 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700384
Dianne Hackborn231cc602009-04-27 17:10:36 -0700385 /**
386 * This file contains the current sync status. We would like to retain
387 * it across boots, but its loss is not the end of the world, so we store
388 * this information as binary data.
389 */
390 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700391
Dianne Hackborn231cc602009-04-27 17:10:36 -0700392 /**
393 * This file contains sync statistics. This is purely debugging information
394 * so is written infrequently and can be thrown away at any time.
395 */
396 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800400 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800401
402 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000403 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700404
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800405 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700408
Dianne Hackborn231cc602009-04-27 17:10:36 -0700409 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800411 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000412 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 File systemDir = new File(dataDir, "system");
415 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800416 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700417
418 maybeDeleteLegacyPendingInfoLocked(syncDir);
419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
421 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 readAccountInfoLocked();
425 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700427 readAndDeleteLegacyAccountInfoLocked();
428 writeAccountInfoLocked();
429 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700430 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 }
432
433 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800434 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436
437 public static void init(Context context) {
438 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800439 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
Jeff Sharkey8212ae02016-02-10 14:46:43 -0700441 File dataDir = Environment.getDataDirectory();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800442 sSyncStorageEngine = new SyncStorageEngine(context, dataDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 }
444
445 public static SyncStorageEngine getSingleton() {
446 if (sSyncStorageEngine == null) {
447 throw new IllegalStateException("not initialized");
448 }
449 return sSyncStorageEngine;
450 }
451
Amith Yamasani04e0d262012-02-14 11:50:53 -0800452 protected void setOnSyncRequestListener(OnSyncRequestListener listener) {
453 if (mSyncRequestListener == null) {
454 mSyncRequestListener = listener;
455 }
456 }
457
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000458 protected void setOnAuthorityRemovedListener(OnAuthorityRemovedListener listener) {
459 if (mAuthorityRemovedListener == null) {
460 mAuthorityRemovedListener = listener;
461 }
462 }
463
464 protected void setPeriodicSyncAddedListener(PeriodicSyncAddedListener listener) {
465 if (mPeriodicSyncAddedListener == null) {
466 mPeriodicSyncAddedListener = listener;
467 }
468 }
469
Dianne Hackborn231cc602009-04-27 17:10:36 -0700470 @Override public void handleMessage(Message msg) {
471 if (msg.what == MSG_WRITE_STATUS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700472 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700473 writeStatusLocked();
Fred Quintanad9d2f112009-04-23 13:36:27 -0700474 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700475 } else if (msg.what == MSG_WRITE_STATISTICS) {
Dianne Hackborn4e808202010-04-06 22:00:59 -0700476 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700477 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800478 }
479 }
480 }
Costin Manolache360e4542009-09-04 13:36:04 -0700481
Ashish Sharma69d95de2012-04-11 17:27:24 -0700482 public int getSyncRandomOffset() {
483 return mSyncRandomOffset;
484 }
485
Dianne Hackborn231cc602009-04-27 17:10:36 -0700486 public void addStatusChangeListener(int mask, ISyncStatusObserver callback) {
487 synchronized (mAuthorities) {
488 mChangeListeners.register(callback, mask);
489 }
490 }
Costin Manolache360e4542009-09-04 13:36:04 -0700491
Dianne Hackborn231cc602009-04-27 17:10:36 -0700492 public void removeStatusChangeListener(ISyncStatusObserver callback) {
493 synchronized (mAuthorities) {
494 mChangeListeners.unregister(callback);
495 }
496 }
Costin Manolache360e4542009-09-04 13:36:04 -0700497
Matthew Williamsfa774182013-06-18 15:44:11 -0700498 /**
499 * Figure out a reasonable flex time for cases where none is provided (old api calls).
500 * @param syncTimeSeconds requested sync time from now.
501 * @return amount of seconds before syncTimeSeconds that the sync can occur.
502 * I.e.
503 * earliest_sync_time = syncTimeSeconds - calculateDefaultFlexTime(syncTimeSeconds)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700504 * The flex time is capped at a percentage of the {@link #DEFAULT_POLL_FREQUENCY_SECONDS}.
Matthew Williamsfa774182013-06-18 15:44:11 -0700505 */
506 public static long calculateDefaultFlexTime(long syncTimeSeconds) {
507 if (syncTimeSeconds < DEFAULT_MIN_FLEX_ALLOWED_SECS) {
508 // Small enough sync request time that we don't add flex time - developer probably
509 // wants to wait for an operation to occur before syncing so we honour the
510 // request time.
511 return 0L;
512 } else if (syncTimeSeconds < DEFAULT_POLL_FREQUENCY_SECONDS) {
513 return (long) (syncTimeSeconds * DEFAULT_FLEX_PERCENT_SYNC);
514 } else {
515 // Large enough sync request time that we cap the flex time.
516 return (long) (DEFAULT_POLL_FREQUENCY_SECONDS * DEFAULT_FLEX_PERCENT_SYNC);
517 }
518 }
519
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000520 void reportChange(int which) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700521 ArrayList<ISyncStatusObserver> reports = null;
522 synchronized (mAuthorities) {
523 int i = mChangeListeners.beginBroadcast();
524 while (i > 0) {
525 i--;
526 Integer mask = (Integer)mChangeListeners.getBroadcastCookie(i);
527 if ((which & mask.intValue()) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 continue;
529 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700530 if (reports == null) {
531 reports = new ArrayList<ISyncStatusObserver>(i);
532 }
533 reports.add(mChangeListeners.getBroadcastItem(i));
534 }
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700535 mChangeListeners.finishBroadcast();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700536 }
Costin Manolache360e4542009-09-04 13:36:04 -0700537
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700538 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000539 Slog.v(TAG, "reportChange " + which + " to: " + reports);
Fred Quintana77c560f2010-03-29 22:20:26 -0700540 }
Costin Manolache360e4542009-09-04 13:36:04 -0700541
Dianne Hackborn231cc602009-04-27 17:10:36 -0700542 if (reports != null) {
543 int i = reports.size();
544 while (i > 0) {
545 i--;
546 try {
547 reports.get(i).onStatusChanged(which);
548 } catch (RemoteException e) {
549 // The remote callback list will take care of this for us.
550 }
551 }
552 }
553 }
Amith Yamasani70c874b2009-07-06 14:53:25 -0700554
Amith Yamasani04e0d262012-02-14 11:50:53 -0800555 public boolean getSyncAutomatically(Account account, int userId, String providerName) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700556 synchronized (mAuthorities) {
557 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700558 AuthorityInfo authority = getAuthorityLocked(
559 new EndPoint(account, providerName, userId),
Fred Quintanaac9385e2009-06-22 18:00:59 -0700560 "getSyncAutomatically");
561 return authority != null && authority.enabled;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700562 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700563
Dianne Hackborn231cc602009-04-27 17:10:36 -0700564 int i = mAuthorities.size();
565 while (i > 0) {
566 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700567 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700568 if (authorityInfo.target.matchesSpec(new EndPoint(account, providerName, userId))
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700569 && authorityInfo.enabled) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700570 return true;
571 }
572 }
573 return false;
574 }
575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576
Amith Yamasani04e0d262012-02-14 11:50:53 -0800577 public void setSyncAutomatically(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000578 boolean sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700579 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000580 Slog.d(TAG, "setSyncAutomatically: " + /* account + */" provider " + providerName
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800581 + ", user " + userId + " -> " + sync);
582 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700583 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700584 AuthorityInfo authority =
585 getOrCreateAuthorityLocked(
586 new EndPoint(account, providerName, userId),
587 -1 /* ident */,
588 false);
Fred Quintana77c560f2010-03-29 22:20:26 -0700589 if (authority.enabled == sync) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700590 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000591 Slog.d(TAG, "setSyncAutomatically: already set to " + sync + ", doing nothing");
Dianne Hackborn40e9f292012-11-27 19:12:23 -0800592 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700593 return;
594 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700595 // If the adapter was syncable but missing its initialization sync, set it to
596 // uninitialized now. This is to give it a chance to run any one-time initialization
597 // logic.
598 if (sync && authority.syncable == AuthorityInfo.SYNCABLE_NOT_INITIALIZED) {
599 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
600 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700601 authority.enabled = sync;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700602 writeAccountInfoLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
Joe Onorato8294fad2009-07-15 16:08:44 -0700604
Fred Quintana77c560f2010-03-29 22:20:26 -0700605 if (sync) {
Alon Albert57286f92012-10-09 14:21:38 -0700606 requestSync(account, userId, SyncOperation.REASON_SYNC_AUTO, providerName,
607 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700608 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700609 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Marvin Paula6533252014-11-24 12:57:48 -0800610 queueBackup();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 }
612
Amith Yamasani04e0d262012-02-14 11:50:53 -0800613 public int getIsSyncable(Account account, int userId, String providerName) {
Fred Quintana5e787c42009-08-16 23:13:53 -0700614 synchronized (mAuthorities) {
615 if (account != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700616 AuthorityInfo authority = getAuthorityLocked(
617 new EndPoint(account, providerName, userId),
618 "get authority syncable");
Fred Quintana5e787c42009-08-16 23:13:53 -0700619 if (authority == null) {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700620 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700621 }
622 return authority.syncable;
623 }
624
625 int i = mAuthorities.size();
626 while (i > 0) {
627 i--;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700628 AuthorityInfo authorityInfo = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -0700629 if (authorityInfo.target != null
630 && authorityInfo.target.provider.equals(providerName)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700631 return authorityInfo.syncable;
Fred Quintana5e787c42009-08-16 23:13:53 -0700632 }
633 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700634 return AuthorityInfo.NOT_INITIALIZED;
Fred Quintana5e787c42009-08-16 23:13:53 -0700635 }
636 }
637
Amith Yamasani04e0d262012-02-14 11:50:53 -0800638 public void setIsSyncable(Account account, int userId, String providerName, int syncable) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700639 setSyncableStateForEndPoint(new EndPoint(account, providerName, userId), syncable);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700640 }
641
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700642 /**
643 * An enabled sync service and a syncable provider's adapter both get resolved to the same
644 * persisted variable - namely the "syncable" attribute for an AuthorityInfo in accounts.xml.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700645 * @param target target to set value for.
646 * @param syncable 0 indicates unsyncable, <0 unknown, >0 is active/syncable.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700647 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700648 private void setSyncableStateForEndPoint(EndPoint target, int syncable) {
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700649 AuthorityInfo aInfo;
650 synchronized (mAuthorities) {
651 aInfo = getOrCreateAuthorityLocked(target, -1, false);
Matthew Williams53abfdb2015-06-10 20:06:37 -0700652 if (syncable < AuthorityInfo.NOT_INITIALIZED) {
653 syncable = AuthorityInfo.NOT_INITIALIZED;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700654 }
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700655 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000656 Slog.d(TAG, "setIsSyncable: " + aInfo.toString() + " -> " + syncable);
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700657 }
658 if (aInfo.syncable == syncable) {
659 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000660 Slog.d(TAG, "setIsSyncable: already set to " + syncable + ", doing nothing");
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700661 }
662 return;
663 }
664 aInfo.syncable = syncable;
665 writeAccountInfoLocked();
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700666 }
Matthew Williams53abfdb2015-06-10 20:06:37 -0700667 if (syncable == AuthorityInfo.SYNCABLE) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700668 requestSync(aInfo, SyncOperation.REASON_IS_SYNCABLE, new Bundle());
Fred Quintana5e787c42009-08-16 23:13:53 -0700669 }
670 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
671 }
672
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700673 public Pair<Long, Long> getBackoff(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800674 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700675 AuthorityInfo authority = getAuthorityLocked(info, "getBackoff");
676 if (authority != null) {
677 return Pair.create(authority.backoffTime, authority.backoffDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800678 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700679 return null;
Fred Quintana307da1a2010-01-21 14:24:20 -0800680 }
681 }
682
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700683 /**
684 * Update the backoff for the given endpoint. The endpoint may be for a provider/account and
685 * the account or provider info be null, which signifies all accounts or providers.
686 */
687 public void setBackoff(EndPoint info, long nextSyncTime, long nextDelay) {
688 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000689 Slog.v(TAG, "setBackoff: " + info
Fred Quintana307da1a2010-01-21 14:24:20 -0800690 + " -> nextSyncTime " + nextSyncTime + ", nextDelay " + nextDelay);
691 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700692 boolean changed;
Fred Quintana307da1a2010-01-21 14:24:20 -0800693 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000694 if (info.account == null || info.provider == null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700695 // Do more work for a provider sync if the provided info has specified all
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000696 // accounts/providers.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700697 changed = setBackoffLocked(
698 info.account /* may be null */,
699 info.userId,
700 info.provider /* may be null */,
701 nextSyncTime, nextDelay);
Fred Quintana307da1a2010-01-21 14:24:20 -0800702 } else {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700703 AuthorityInfo authorityInfo =
704 getOrCreateAuthorityLocked(info, -1 /* ident */, true);
705 if (authorityInfo.backoffTime == nextSyncTime
706 && authorityInfo.backoffDelay == nextDelay) {
707 changed = false;
708 } else {
709 authorityInfo.backoffTime = nextSyncTime;
710 authorityInfo.backoffDelay = nextDelay;
711 changed = true;
Fred Quintana307da1a2010-01-21 14:24:20 -0800712 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800713 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800714 }
Fred Quintana307da1a2010-01-21 14:24:20 -0800715 if (changed) {
716 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
717 }
718 }
719
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700720 /**
721 * Either set backoff for a specific authority, or set backoff for all the
722 * accounts on a specific adapter/all adapters.
723 *
724 * @param account account for which to set backoff. Null to specify all accounts.
725 * @param userId id of the user making this request.
726 * @param providerName provider for which to set backoff. Null to specify all providers.
Matthew Williams7a2ab3a2013-09-11 14:25:51 -0700727 * @return true if a change occured.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700728 */
729 private boolean setBackoffLocked(Account account, int userId, String providerName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000730 long nextSyncTime, long nextDelay) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700731 boolean changed = false;
732 for (AccountInfo accountInfo : mAccounts.values()) {
733 if (account != null && !account.equals(accountInfo.accountAndUser.account)
734 && userId != accountInfo.accountAndUser.userId) {
735 continue;
736 }
737 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
738 if (providerName != null
Matthew Williams8ef22042013-07-26 12:56:39 -0700739 && !providerName.equals(authorityInfo.target.provider)) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700740 continue;
741 }
742 if (authorityInfo.backoffTime != nextSyncTime
743 || authorityInfo.backoffDelay != nextDelay) {
744 authorityInfo.backoffTime = nextSyncTime;
745 authorityInfo.backoffDelay = nextDelay;
746 changed = true;
747 }
748 }
749 }
750 return changed;
751 }
752
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000753 public void clearAllBackoffsLocked() {
Alon Albert744e310f2010-12-14 11:37:20 -0800754 boolean changed = false;
755 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000756 // Clear backoff for all sync adapters.
757 for (AccountInfo accountInfo : mAccounts.values()) {
758 for (AuthorityInfo authorityInfo : accountInfo.authorities.values()) {
759 if (authorityInfo.backoffTime != NOT_IN_BACKOFF_MODE
760 || authorityInfo.backoffDelay != NOT_IN_BACKOFF_MODE) {
761 if (Log.isLoggable(TAG, Log.VERBOSE)) {
762 Slog.v(TAG, "clearAllBackoffsLocked:"
763 + " authority:" + authorityInfo.target
764 + " account:" + accountInfo.accountAndUser.account.name
765 + " user:" + accountInfo.accountAndUser.userId
766 + " backoffTime was: " + authorityInfo.backoffTime
767 + " backoffDelay was: " + authorityInfo.backoffDelay);
Alon Albert744e310f2010-12-14 11:37:20 -0800768 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000769 authorityInfo.backoffTime = NOT_IN_BACKOFF_MODE;
770 authorityInfo.backoffDelay = NOT_IN_BACKOFF_MODE;
771 changed = true;
Alon Albert744e310f2010-12-14 11:37:20 -0800772 }
773 }
774 }
775 }
776
777 if (changed) {
778 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
779 }
780 }
781
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700782 public long getDelayUntilTime(EndPoint info) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800783 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700784 AuthorityInfo authority = getAuthorityLocked(info, "getDelayUntil");
Fred Quintana307da1a2010-01-21 14:24:20 -0800785 if (authority == null) {
786 return 0;
787 }
788 return authority.delayUntil;
789 }
790 }
791
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700792 public void setDelayUntilTime(EndPoint info, long delayUntil) {
793 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000794 Slog.v(TAG, "setDelayUntil: " + info
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700795 + " -> delayUntil " + delayUntil);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800796 }
797 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700798 AuthorityInfo authority = getOrCreateAuthorityLocked(info, -1, true);
799 if (authority.delayUntil == delayUntil) {
800 return;
Matthew Williamsfa774182013-06-18 15:44:11 -0700801 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700802 authority.delayUntil = delayUntil;
803 }
804 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
805 }
806
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700807 /**
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000808 * Restore all periodic syncs read from persisted files. Used to restore periodic syncs
809 * after an OS update.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700810 */
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000811 boolean restoreAllPeriodicSyncs() {
812 if (mPeriodicSyncAddedListener == null) {
813 return false;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800814 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000815 synchronized (mAuthorities) {
816 for (int i=0; i<mAuthorities.size(); i++) {
817 AuthorityInfo authority = mAuthorities.valueAt(i);
818 for (PeriodicSync periodicSync: authority.periodicSyncs) {
819 mPeriodicSyncAddedListener.onPeriodicSyncAdded(authority.target,
820 periodicSync.extras, periodicSync.period, periodicSync.flexTime);
821 }
822 authority.periodicSyncs.clear();
823 }
824 writeAccountInfoLocked();
825 }
826 return true;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800827 }
828
Amith Yamasani04e0d262012-02-14 11:50:53 -0800829 public void setMasterSyncAutomatically(boolean flag, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700830 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800831 Boolean auto = mMasterSyncAutomatically.get(userId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700832 if (auto != null && auto.equals(flag)) {
Fred Quintana77c560f2010-03-29 22:20:26 -0700833 return;
834 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800835 mMasterSyncAutomatically.put(userId, flag);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700836 writeAccountInfoLocked();
837 }
Fred Quintana77c560f2010-03-29 22:20:26 -0700838 if (flag) {
Alon Albert57286f92012-10-09 14:21:38 -0700839 requestSync(null, userId, SyncOperation.REASON_MASTER_SYNC_AUTO, null,
840 new Bundle());
Joe Onorato8294fad2009-07-15 16:08:44 -0700841 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700842 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS);
Jeff Sharkey7a96c392012-11-15 14:01:46 -0800843 mContext.sendBroadcast(ContentResolver.ACTION_SYNC_CONN_STATUS_CHANGED);
Marvin Paula6533252014-11-24 12:57:48 -0800844 queueBackup();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846
Amith Yamasani04e0d262012-02-14 11:50:53 -0800847 public boolean getMasterSyncAutomatically(int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700848 synchronized (mAuthorities) {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800849 Boolean auto = mMasterSyncAutomatically.get(userId);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800850 return auto == null ? mDefaultMasterSyncAutomatically : auto;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700851 }
852 }
Costin Manolache360e4542009-09-04 13:36:04 -0700853
Dianne Hackborn231cc602009-04-27 17:10:36 -0700854 public AuthorityInfo getAuthority(int authorityId) {
855 synchronized (mAuthorities) {
856 return mAuthorities.get(authorityId);
857 }
858 }
Costin Manolache360e4542009-09-04 13:36:04 -0700859
Shreyas Basarge6275d492016-02-12 20:27:49 +0000860 List<AuthorityInfo> getAllAuthorities() {
861 List<AuthorityInfo> authorities = new ArrayList<AuthorityInfo>();
862 synchronized (mAuthorities) {
863 for (int i = 0; i < mAuthorities.size(); i++) {
864 authorities.add(mAuthorities.valueAt(i));
865 }
866 }
867 return authorities;
868 }
869
Dianne Hackborn231cc602009-04-27 17:10:36 -0700870 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700871 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700872 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700873 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700874 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700875 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700876 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700877 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700878 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700879 return true;
880 }
881 }
882 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 return false;
884 }
Costin Manolache360e4542009-09-04 13:36:04 -0700885
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000886 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700887 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000888 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
889 -1 /* desired identifier */,
890 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700891 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000892 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700893 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700894 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000895 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700896 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700897 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700898 }
Costin Manolache360e4542009-09-04 13:36:04 -0700899
Dianne Hackborn231cc602009-04-27 17:10:36 -0700900 /**
901 * Called when the set of account has changed, given the new array of
902 * active accounts.
903 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800904 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700906 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000907 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700908 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700909 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
910 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
911 while (accIt.hasNext()) {
912 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800913 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
914 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700915 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700916 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000917 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700918 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700919 for (AuthorityInfo auth : acc.authorities.values()) {
920 removing.put(auth.ident, auth);
921 }
922 accIt.remove();
923 }
924 }
Costin Manolache360e4542009-09-04 13:36:04 -0700925
Dianne Hackborn231cc602009-04-27 17:10:36 -0700926 // Clean out all data structures.
927 int i = removing.size();
928 if (i > 0) {
929 while (i > 0) {
930 i--;
931 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000932 AuthorityInfo auth = removing.valueAt(i);
933 if (mAuthorityRemovedListener != null) {
934 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
935 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700936 mAuthorities.remove(ident);
937 int j = mSyncStatus.size();
938 while (j > 0) {
939 j--;
940 if (mSyncStatus.keyAt(j) == ident) {
941 mSyncStatus.remove(mSyncStatus.keyAt(j));
942 }
943 }
944 j = mSyncHistory.size();
945 while (j > 0) {
946 j--;
947 if (mSyncHistory.get(j).authorityId == ident) {
948 mSyncHistory.remove(j);
949 }
950 }
951 }
952 writeAccountInfoLocked();
953 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700954 writeStatisticsLocked();
955 }
956 }
957 }
958
959 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700960 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
961 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700962 */
Fred Quintana918339a2010-10-05 14:00:39 -0700963 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
964 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700965 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700966 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000967 Slog.v(TAG, "setActiveSync: account="
968 + " auth=" + activeSyncContext.mSyncOperation.target
969 + " src=" + activeSyncContext.mSyncOperation.syncSource
970 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700971 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700972 final EndPoint info = activeSyncContext.mSyncOperation.target;
973 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
974 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700975 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700976 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700977 syncInfo = new SyncInfo(
978 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700979 authorityInfo.target.account,
980 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700981 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700982 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700983 }
Fred Quintana918339a2010-10-05 14:00:39 -0700984 reportActiveChange();
985 return syncInfo;
986 }
987
988 /**
989 * Called to indicate that a previously active sync is no longer active.
990 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800991 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700992 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700993 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000994 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800995 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -0700996 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -0700997 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800998 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -0700999 }
1000
1001 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001002 }
1003
1004 /**
1005 * To allow others to send active change reports, to poke clients.
1006 */
1007 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001008 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001009 }
Costin Manolache360e4542009-09-04 13:36:04 -07001010
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001012 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001013 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001014 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001015 long id;
1016 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001017 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001018 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001019 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001020 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001021 if (authority == null) {
1022 return -1;
1023 }
1024 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001025 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001026 item.authorityId = authority.ident;
1027 item.historyId = mNextHistoryId++;
1028 if (mNextHistoryId < 0) mNextHistoryId = 0;
1029 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001030 item.source = op.syncSource;
1031 item.reason = op.reason;
1032 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 item.event = EVENT_START;
1034 mSyncHistory.add(0, item);
1035 while (mSyncHistory.size() > MAX_HISTORY) {
1036 mSyncHistory.remove(mSyncHistory.size()-1);
1037 }
1038 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001039 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001040 }
Costin Manolache360e4542009-09-04 13:36:04 -07001041
Fred Quintanaac9385e2009-06-22 18:00:59 -07001042 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001043 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 }
1045
Fred Quintana77c560f2010-03-29 22:20:26 -07001046 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001047 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001048 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001049 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001050 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001051 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001052 SyncHistoryItem item = null;
1053 int i = mSyncHistory.size();
1054 while (i > 0) {
1055 i--;
1056 item = mSyncHistory.get(i);
1057 if (item.historyId == historyId) {
1058 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001060 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
Costin Manolache360e4542009-09-04 13:36:04 -07001062
Dianne Hackborn231cc602009-04-27 17:10:36 -07001063 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001064 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001065 return;
1066 }
Costin Manolache360e4542009-09-04 13:36:04 -07001067
Dianne Hackborn231cc602009-04-27 17:10:36 -07001068 item.elapsedTime = elapsedTime;
1069 item.event = EVENT_STOP;
1070 item.mesg = resultMessage;
1071 item.downstreamActivity = downstreamActivity;
1072 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001073
Dianne Hackborn231cc602009-04-27 17:10:36 -07001074 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001075
Dianne Hackborn231cc602009-04-27 17:10:36 -07001076 status.numSyncs++;
1077 status.totalElapsedTime += elapsedTime;
1078 switch (item.source) {
1079 case SOURCE_LOCAL:
1080 status.numSourceLocal++;
1081 break;
1082 case SOURCE_POLL:
1083 status.numSourcePoll++;
1084 break;
1085 case SOURCE_USER:
1086 status.numSourceUser++;
1087 break;
1088 case SOURCE_SERVER:
1089 status.numSourceServer++;
1090 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001091 case SOURCE_PERIODIC:
1092 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001093 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001094 }
Costin Manolache360e4542009-09-04 13:36:04 -07001095
Dianne Hackborn231cc602009-04-27 17:10:36 -07001096 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001097 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 if (mDayStats[0] == null) {
1099 mDayStats[0] = new DayStats(day);
1100 } else if (day != mDayStats[0].day) {
1101 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1102 mDayStats[0] = new DayStats(day);
1103 writeStatisticsNow = true;
1104 } else if (mDayStats[0] == null) {
1105 }
1106 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001107
Dianne Hackborn231cc602009-04-27 17:10:36 -07001108 final long lastSyncTime = (item.eventTime + elapsedTime);
1109 boolean writeStatusNow = false;
1110 if (MESG_SUCCESS.equals(resultMessage)) {
1111 // - if successful, update the successful columns
1112 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1113 writeStatusNow = true;
1114 }
1115 status.lastSuccessTime = lastSyncTime;
1116 status.lastSuccessSource = item.source;
1117 status.lastFailureTime = 0;
1118 status.lastFailureSource = -1;
1119 status.lastFailureMesg = null;
1120 status.initialFailureTime = 0;
1121 ds.successCount++;
1122 ds.successTime += elapsedTime;
1123 } else if (!MESG_CANCELED.equals(resultMessage)) {
1124 if (status.lastFailureTime == 0) {
1125 writeStatusNow = true;
1126 }
1127 status.lastFailureTime = lastSyncTime;
1128 status.lastFailureSource = item.source;
1129 status.lastFailureMesg = resultMessage;
1130 if (status.initialFailureTime == 0) {
1131 status.initialFailureTime = lastSyncTime;
1132 }
1133 ds.failureCount++;
1134 ds.failureTime += elapsedTime;
1135 }
Costin Manolache360e4542009-09-04 13:36:04 -07001136
Dianne Hackborn231cc602009-04-27 17:10:36 -07001137 if (writeStatusNow) {
1138 writeStatusLocked();
1139 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1140 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1141 WRITE_STATUS_DELAY);
1142 }
1143 if (writeStatisticsNow) {
1144 writeStatisticsLocked();
1145 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1146 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1147 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001148 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001149 }
Costin Manolache360e4542009-09-04 13:36:04 -07001150
Fred Quintanaac9385e2009-06-22 18:00:59 -07001151 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 }
1153
1154 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001155 * Return a list of the currently active syncs. Note that the returned
1156 * items are the real, live active sync objects, so be careful what you do
1157 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001158 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001159 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001160 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001161 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001162 }
1163 }
Costin Manolache360e4542009-09-04 13:36:04 -07001164
Dianne Hackborn231cc602009-04-27 17:10:36 -07001165 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001166 * @param userId Id of user to return current sync info.
1167 * @param canAccessAccounts Determines whether to redact Account information from the result.
1168 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001169 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001170 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001171 synchronized (mAuthorities) {
1172 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1173 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1174 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001175 SyncInfo copy;
1176 if (!canAccessAccounts) {
1177 copy = SyncInfo.createAccountRedacted(
1178 sync.authorityId, sync.authority, sync.startTime);
1179 } else {
1180 copy = new SyncInfo(sync);
1181 }
1182 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001183 }
1184 return syncsCopy;
1185 }
1186 }
1187
1188 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1189 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1190 if (syncs == null) {
1191 syncs = new ArrayList<SyncInfo>();
1192 mCurrentSyncs.put(userId, syncs);
1193 }
1194 return syncs;
1195 }
1196
1197 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001198 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001199 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001200 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001201 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001202 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001203 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001204 true /* write to storage if this results in a change */);
1205 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1206 }
1207 }
1208
1209 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001210 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001211 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001212 * @param info the endpoint target we are querying status info for.
1213 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001214 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001215 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001216 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001217 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001218 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001219 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001220 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001221 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001222 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001223 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001224 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001225 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001226 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001227 }
1228 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001229 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001230 }
1231 }
Costin Manolache360e4542009-09-04 13:36:04 -07001232
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001233 /** Return true if the pending status is true of any matching authorities. */
1234 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001235 synchronized (mAuthorities) {
1236 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001237 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001238 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001239 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1240 if (ainfo == null) {
1241 continue;
1242 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001243 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001244 continue;
1245 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001246 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001247 return true;
1248 }
1249 }
1250 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 }
1252 }
1253
1254 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001255 * Return an array of the current sync status for all authorities. Note
1256 * that the objects inside the array are the real, live status objects,
1257 * so be careful what you do with them.
1258 */
1259 public ArrayList<SyncHistoryItem> getSyncHistory() {
1260 synchronized (mAuthorities) {
1261 final int N = mSyncHistory.size();
1262 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1263 for (int i=0; i<N; i++) {
1264 items.add(mSyncHistory.get(i));
1265 }
1266 return items;
1267 }
1268 }
Costin Manolache360e4542009-09-04 13:36:04 -07001269
Dianne Hackborn231cc602009-04-27 17:10:36 -07001270 /**
1271 * Return an array of the current per-day statistics. Note
1272 * that the objects inside the array are the real, live status objects,
1273 * so be careful what you do with them.
1274 */
1275 public DayStats[] getDayStatistics() {
1276 synchronized (mAuthorities) {
1277 DayStats[] ds = new DayStats[mDayStats.length];
1278 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1279 return ds;
1280 }
1281 }
Costin Manolache360e4542009-09-04 13:36:04 -07001282
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001283 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1284 AuthorityInfo authorityInfo) {
1285 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1286 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1287 }
1288
Dianne Hackborn55280a92009-05-07 15:53:46 -07001289 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001290 mCal.setTimeInMillis(System.currentTimeMillis());
1291 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1292 if (mYear != mCal.get(Calendar.YEAR)) {
1293 mYear = mCal.get(Calendar.YEAR);
1294 mCal.clear();
1295 mCal.set(Calendar.YEAR, mYear);
1296 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1297 }
1298 return dayOfYear + mYearInDays;
1299 }
Costin Manolache360e4542009-09-04 13:36:04 -07001300
Dianne Hackborn231cc602009-04-27 17:10:36 -07001301 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001302 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001303 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001304 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001305 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001306 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001308 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001309 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1310 AccountInfo accountInfo = mAccounts.get(au);
1311 if (accountInfo == null) {
1312 if (tag != null) {
1313 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1314 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001315 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001316 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001317 return null;
1318 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001319 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1320 if (authority == null) {
1321 if (tag != null) {
1322 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1323 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1324 }
1325 }
1326 return null;
1327 }
1328 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001329 }
Costin Manolache360e4542009-09-04 13:36:04 -07001330
Matthew Williamsfa774182013-06-18 15:44:11 -07001331 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001332 * @param info info identifying target.
1333 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001334 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001335 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001336 * exists.
1337 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001338 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1339 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001340 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1341 AccountInfo account = mAccounts.get(au);
1342 if (account == null) {
1343 account = new AccountInfo(au);
1344 mAccounts.put(au, account);
1345 }
1346 authority = account.authorities.get(info.provider);
1347 if (authority == null) {
1348 authority = createAuthorityLocked(info, ident, doWrite);
1349 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001350 }
1351 return authority;
1352 }
1353
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001354 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1355 AuthorityInfo authority;
1356 if (ident < 0) {
1357 ident = mNextAuthorityId;
1358 mNextAuthorityId++;
1359 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001360 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001361 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001362 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001363 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001364 authority = new AuthorityInfo(info, ident);
1365 mAuthorities.put(ident, authority);
1366 if (doWrite) {
1367 writeAccountInfoLocked();
1368 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001369 return authority;
1370 }
Costin Manolache360e4542009-09-04 13:36:04 -07001371
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001372 public void removeAuthority(EndPoint info) {
1373 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001374 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001375 }
1376 }
1377
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001378
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001379 /**
1380 * Remove an authority associated with a provider. Needs to be a standalone function for
1381 * backward compatibility.
1382 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001383 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001384 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001385 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001386 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001387 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1388 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001389 if (mAuthorityRemovedListener != null) {
1390 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1391 }
Fred Quintanafb084402010-03-23 17:57:03 -07001392 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001393 if (doWrite) {
1394 writeAccountInfoLocked();
1395 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001396 }
1397 }
1398 }
1399
Dianne Hackborn231cc602009-04-27 17:10:36 -07001400 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1401 SyncStatusInfo status = mSyncStatus.get(authorityId);
1402 if (status == null) {
1403 status = new SyncStatusInfo(authorityId);
1404 mSyncStatus.put(authorityId, status);
1405 }
1406 return status;
1407 }
Costin Manolache360e4542009-09-04 13:36:04 -07001408
Dianne Hackborn55280a92009-05-07 15:53:46 -07001409 public void writeAllState() {
1410 synchronized (mAuthorities) {
1411 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001412 writeStatusLocked();
1413 writeStatisticsLocked();
1414 }
1415 }
Costin Manolache360e4542009-09-04 13:36:04 -07001416
Dianne Hackborn231cc602009-04-27 17:10:36 -07001417 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001418 * public for testing
1419 */
1420 public void clearAndReadState() {
1421 synchronized (mAuthorities) {
1422 mAuthorities.clear();
1423 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001424 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001425 mSyncStatus.clear();
1426 mSyncHistory.clear();
1427
1428 readAccountInfoLocked();
1429 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001430 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001431 readAndDeleteLegacyAccountInfoLocked();
1432 writeAccountInfoLocked();
1433 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001434 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001435 }
1436 }
1437
1438 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001439 * Read all account information back in to the initial engine state.
1440 */
1441 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001442 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001443 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001445 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001446 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001447 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001448 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001449 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001450 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001451 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001452 while (eventType != XmlPullParser.START_TAG &&
1453 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001454 eventType = parser.next();
1455 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001456 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001457 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001458 return;
1459 }
1460
Dianne Hackborn231cc602009-04-27 17:10:36 -07001461 String tagName = parser.getName();
1462 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001463 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001464 String versionString = parser.getAttributeValue(null, "version");
1465 int version;
1466 try {
1467 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1468 } catch (NumberFormatException e) {
1469 version = 0;
1470 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001471 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001472 try {
1473 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1474 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1475 } catch (NumberFormatException e) {
1476 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001477 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001478 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1479 try {
1480 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1481 } catch (NumberFormatException e) {
1482 mSyncRandomOffset = 0;
1483 }
1484 if (mSyncRandomOffset == 0) {
1485 Random random = new Random(System.currentTimeMillis());
1486 mSyncRandomOffset = random.nextInt(86400);
1487 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001488 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001489 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001490 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001491 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001492 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001493 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001494 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001495 if (parser.getDepth() == 2) {
1496 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001497 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001498 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001499 if (authority != null) {
1500 if (authority.ident > highestAuthorityId) {
1501 highestAuthorityId = authority.ident;
1502 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001503 } else {
1504 EventLog.writeEvent(0x534e4554, "26513719", -1,
1505 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001506 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001507 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1508 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001509 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001510 } else if (parser.getDepth() == 3) {
1511 if ("periodicSync".equals(tagName) && authority != null) {
1512 periodicSync = parsePeriodicSync(parser, authority);
1513 }
1514 } else if (parser.getDepth() == 4 && periodicSync != null) {
1515 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001516 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001517 }
1518 }
1519 }
1520 eventType = parser.next();
1521 } while (eventType != XmlPullParser.END_DOCUMENT);
1522 }
1523 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001524 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001525 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001526 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001527 if (fis == null) Slog.i(TAG, "No initial accounts");
1528 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001529 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001530 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001531 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001532 if (fis != null) {
1533 try {
1534 fis.close();
1535 } catch (java.io.IOException e1) {
1536 }
1537 }
1538 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001539
Fred Quintana77c560f2010-03-29 22:20:26 -07001540 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001541 }
Costin Manolache360e4542009-09-04 13:36:04 -07001542
Fred Quintanafb084402010-03-23 17:57:03 -07001543 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001544 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1545 * pending.xml was used starting in KLP.
1546 * @param syncDir directory where the sync files are located.
1547 */
1548 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1549 File file = new File(syncDir, "pending.bin");
1550 if (!file.exists()) {
1551 return;
1552 } else {
1553 file.delete();
1554 }
1555 }
1556
1557 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001558 * some authority names have changed. copy over their settings and delete the old ones
1559 * @return true if a change was made
1560 */
1561 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1562 boolean writeNeeded = false;
1563
1564 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1565 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001566 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001567 AuthorityInfo authority = mAuthorities.valueAt(i);
1568 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001569 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001570 if (newAuthorityName == null) {
1571 continue;
1572 }
1573
1574 // remember this authority so we can remove it later. we can't remove it
1575 // now without messing up this loop iteration
1576 authoritiesToRemove.add(authority);
1577
1578 // this authority isn't enabled, no need to copy it to the new authority name since
1579 // the default is "disabled"
1580 if (!authority.enabled) {
1581 continue;
1582 }
1583
1584 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001585 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001586 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001587 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001588 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001589 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001590 continue;
1591 }
1592
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001593 AuthorityInfo newAuthority =
1594 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001595 newAuthority.enabled = true;
1596 writeNeeded = true;
1597 }
1598
1599 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001600 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001601 authorityInfo.target.account,
1602 authorityInfo.target.userId,
1603 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001604 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001605 writeNeeded = true;
1606 }
1607
1608 return writeNeeded;
1609 }
1610
Amith Yamasani04e0d262012-02-14 11:50:53 -08001611 private void parseListenForTickles(XmlPullParser parser) {
1612 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1613 int userId = 0;
1614 try {
1615 userId = Integer.parseInt(user);
1616 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001617 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001618 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001619 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001620 }
1621 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1622 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1623 mMasterSyncAutomatically.put(userId, listen);
1624 }
1625
Fred Quintanac2e46912010-03-15 16:10:44 -07001626 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001627 AuthorityInfo authority = null;
1628 int id = -1;
1629 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001630 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001631 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001632 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001633 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001634 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001635 }
1636 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001637 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001638 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001639 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 String accountName = parser.getAttributeValue(null, "account");
1641 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001642 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001643 String packageName = parser.getAttributeValue(null, "package");
1644 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001645 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001646 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001647 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001648 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001649 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001650 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001651 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001652 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001653 + " account=" + accountName
1654 + " accountType=" + accountType
1655 + " auth=" + authorityName
1656 + " package=" + packageName
1657 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001658 + " user=" + userId
1659 + " enabled=" + enabled
1660 + " syncable=" + syncable);
1661 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001662 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001663 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001664 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001665 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001666 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001667 if (accountName != null && authorityName != null) {
1668 info = new EndPoint(
1669 new Account(accountName, accountType),
1670 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001671 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001672 if (info != null) {
1673 authority = getOrCreateAuthorityLocked(info, id, false);
1674 // If the version is 0 then we are upgrading from a file format that did not
1675 // know about periodic syncs. In that case don't clear the list since we
1676 // want the default, which is a daily periodic sync.
1677 // Otherwise clear out this default list since we will populate it later with
1678 // the periodic sync descriptions that are read from the configuration file.
1679 if (version > 0) {
1680 authority.periodicSyncs.clear();
1681 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001682 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001683 }
1684 if (authority != null) {
1685 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001686 try {
1687 authority.syncable = (syncable == null) ?
1688 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1689 } catch (NumberFormatException e) {
1690 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1691 // format.
1692 if ("unknown".equals(syncable)) {
1693 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1694 } else {
1695 authority.syncable = Boolean.parseBoolean(syncable) ?
1696 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1697 }
1698
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001699 }
1700 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001701 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001702 + accountName + " auth=" + authorityName
1703 + " enabled=" + enabled
1704 + " syncable=" + syncable);
1705 }
1706 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001707 return authority;
1708 }
1709
Matthew Williamsfa774182013-06-18 15:44:11 -07001710 /**
1711 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1712 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001713 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001714 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001715 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001716 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001717 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001718 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001719 try {
1720 period = Long.parseLong(periodValue);
1721 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001722 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001723 return null;
1724 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001725 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001726 return null;
1727 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001728 try {
1729 flextime = Long.parseLong(flexValue);
1730 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001731 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001732 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001733 + ", using default: "
1734 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001735 } catch (NullPointerException expected) {
1736 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001737 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1738 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001739 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001740 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001741 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001742 new PeriodicSync(authorityInfo.target.account,
1743 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001744 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001745 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001746 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001747 return periodicSync;
1748 }
1749
Matthew Williamsfa774182013-06-18 15:44:11 -07001750 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001751 String name = parser.getAttributeValue(null, "name");
1752 String type = parser.getAttributeValue(null, "type");
1753 String value1 = parser.getAttributeValue(null, "value1");
1754 String value2 = parser.getAttributeValue(null, "value2");
1755
1756 try {
1757 if ("long".equals(type)) {
1758 extras.putLong(name, Long.parseLong(value1));
1759 } else if ("integer".equals(type)) {
1760 extras.putInt(name, Integer.parseInt(value1));
1761 } else if ("double".equals(type)) {
1762 extras.putDouble(name, Double.parseDouble(value1));
1763 } else if ("float".equals(type)) {
1764 extras.putFloat(name, Float.parseFloat(value1));
1765 } else if ("boolean".equals(type)) {
1766 extras.putBoolean(name, Boolean.parseBoolean(value1));
1767 } else if ("string".equals(type)) {
1768 extras.putString(name, value1);
1769 } else if ("account".equals(type)) {
1770 extras.putParcelable(name, new Account(value1, value2));
1771 }
1772 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001773 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001774 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001775 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001776 }
1777 }
1778
Dianne Hackborn231cc602009-04-27 17:10:36 -07001779 /**
1780 * Write all account information to the account file.
1781 */
1782 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001783 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001784 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001785 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001786 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001787
Dianne Hackborn231cc602009-04-27 17:10:36 -07001788 try {
1789 fos = mAccountInfoFile.startWrite();
1790 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001791 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001792 out.startDocument(null, true);
1793 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001794
Dianne Hackborn231cc602009-04-27 17:10:36 -07001795 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001796 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001797 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001798 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001799
1800 // Write the Sync Automatically flags for each user
1801 final int M = mMasterSyncAutomatically.size();
1802 for (int m = 0; m < M; m++) {
1803 int userId = mMasterSyncAutomatically.keyAt(m);
1804 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1805 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1806 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1807 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1808 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001809 }
Costin Manolache360e4542009-09-04 13:36:04 -07001810
Dianne Hackborn231cc602009-04-27 17:10:36 -07001811 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001812 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001813 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001814 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 out.startTag(null, "authority");
1816 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001817 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001818 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001819 out.attribute(null, "account", info.account.name);
1820 out.attribute(null, "type", info.account.type);
1821 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001822 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001823 out.endTag(null, "authority");
1824 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001825 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001827 mAccountInfoFile.finishWrite(fos);
1828 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001829 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001830 if (fos != null) {
1831 mAccountInfoFile.failWrite(fos);
1832 }
1833 }
1834 }
Costin Manolache360e4542009-09-04 13:36:04 -07001835
Dianne Hackborn231cc602009-04-27 17:10:36 -07001836 static int getIntColumn(Cursor c, String name) {
1837 return c.getInt(c.getColumnIndex(name));
1838 }
Costin Manolache360e4542009-09-04 13:36:04 -07001839
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 static long getLongColumn(Cursor c, String name) {
1841 return c.getLong(c.getColumnIndex(name));
1842 }
Costin Manolache360e4542009-09-04 13:36:04 -07001843
Dianne Hackborn231cc602009-04-27 17:10:36 -07001844 /**
1845 * Load sync engine state from the old syncmanager database, and then
1846 * erase it. Note that we don't deal with pending operations, active
1847 * sync, or history.
1848 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001849 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001850 // Look for old database to initialize from.
1851 File file = mContext.getDatabasePath("syncmanager.db");
1852 if (!file.exists()) {
1853 return;
1854 }
1855 String path = file.getPath();
1856 SQLiteDatabase db = null;
1857 try {
1858 db = SQLiteDatabase.openDatabase(path, null,
1859 SQLiteDatabase.OPEN_READONLY);
1860 } catch (SQLiteException e) {
1861 }
Costin Manolache360e4542009-09-04 13:36:04 -07001862
Dianne Hackborn231cc602009-04-27 17:10:36 -07001863 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001864 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001865
Dianne Hackborn231cc602009-04-27 17:10:36 -07001866 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001867 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001868 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001869 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001870 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1871 qb.setTables("stats, status");
1872 HashMap<String,String> map = new HashMap<String,String>();
1873 map.put("_id", "status._id as _id");
1874 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001875 if (hasType) {
1876 map.put("account_type", "stats.account_type as account_type");
1877 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001878 map.put("authority", "stats.authority as authority");
1879 map.put("totalElapsedTime", "totalElapsedTime");
1880 map.put("numSyncs", "numSyncs");
1881 map.put("numSourceLocal", "numSourceLocal");
1882 map.put("numSourcePoll", "numSourcePoll");
1883 map.put("numSourceServer", "numSourceServer");
1884 map.put("numSourceUser", "numSourceUser");
1885 map.put("lastSuccessSource", "lastSuccessSource");
1886 map.put("lastSuccessTime", "lastSuccessTime");
1887 map.put("lastFailureSource", "lastFailureSource");
1888 map.put("lastFailureTime", "lastFailureTime");
1889 map.put("lastFailureMesg", "lastFailureMesg");
1890 map.put("pending", "pending");
1891 qb.setProjectionMap(map);
1892 qb.appendWhere("stats._id = status.stats_id");
1893 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001895 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001896 String accountType = hasType
1897 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001898 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001899 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001901 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001902 AuthorityInfo authority =
1903 this.getOrCreateAuthorityLocked(
1904 new EndPoint(new Account(accountName, accountType),
1905 authorityName,
1906 0 /* legacy is single-user */)
1907 , -1,
1908 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001909 if (authority != null) {
1910 int i = mSyncStatus.size();
1911 boolean found = false;
1912 SyncStatusInfo st = null;
1913 while (i > 0) {
1914 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001915 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001916 if (st.authorityId == authority.ident) {
1917 found = true;
1918 break;
1919 }
1920 }
1921 if (!found) {
1922 st = new SyncStatusInfo(authority.ident);
1923 mSyncStatus.put(authority.ident, st);
1924 }
1925 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1926 st.numSyncs = getIntColumn(c, "numSyncs");
1927 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1928 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1929 st.numSourceServer = getIntColumn(c, "numSourceServer");
1930 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001931 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001932 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1933 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1934 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1935 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1936 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1937 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 }
Costin Manolache360e4542009-09-04 13:36:04 -07001940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001942
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 // Retrieve the settings.
1944 qb = new SQLiteQueryBuilder();
1945 qb.setTables("settings");
1946 c = qb.query(db, null, null, null, null, null, null);
1947 while (c.moveToNext()) {
1948 String name = c.getString(c.getColumnIndex("name"));
1949 String value = c.getString(c.getColumnIndex("value"));
1950 if (name == null) continue;
1951 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001952 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001953 } else if (name.startsWith("sync_provider_")) {
1954 String provider = name.substring("sync_provider_".length(),
1955 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001956 int i = mAuthorities.size();
1957 while (i > 0) {
1958 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001959 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001960 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001961 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001962 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001963 }
1964 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001966 }
Costin Manolache360e4542009-09-04 13:36:04 -07001967
Dianne Hackborn231cc602009-04-27 17:10:36 -07001968 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001969
Dianne Hackborn231cc602009-04-27 17:10:36 -07001970 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001971
Dianne Hackborn231cc602009-04-27 17:10:36 -07001972 (new File(path)).delete();
1973 }
1974 }
Costin Manolache360e4542009-09-04 13:36:04 -07001975
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 public static final int STATUS_FILE_END = 0;
1977 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001978
Dianne Hackborn231cc602009-04-27 17:10:36 -07001979 /**
1980 * Read all sync status back in to the initial engine state.
1981 */
1982 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001983 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001984 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001985 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001986 try {
1987 byte[] data = mStatusFile.readFully();
1988 Parcel in = Parcel.obtain();
1989 in.unmarshall(data, 0, data.length);
1990 in.setDataPosition(0);
1991 int token;
1992 while ((token=in.readInt()) != STATUS_FILE_END) {
1993 if (token == STATUS_FILE_ITEM) {
1994 SyncStatusInfo status = new SyncStatusInfo(in);
1995 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1996 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07001997 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001998 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07001999 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 mSyncStatus.put(status.authorityId, status);
2001 }
2002 } else {
2003 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002004 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002005 break;
2006 }
2007 }
2008 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002009 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002010 }
2011 }
Costin Manolache360e4542009-09-04 13:36:04 -07002012
Dianne Hackborn231cc602009-04-27 17:10:36 -07002013 /**
2014 * Write all sync status to the sync status file.
2015 */
2016 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002017 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002018 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002019 }
Costin Manolache360e4542009-09-04 13:36:04 -07002020
Dianne Hackborn231cc602009-04-27 17:10:36 -07002021 // The file is being written, so we don't need to have a scheduled
2022 // write until the next change.
2023 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002024
Dianne Hackborn231cc602009-04-27 17:10:36 -07002025 FileOutputStream fos = null;
2026 try {
2027 fos = mStatusFile.startWrite();
2028 Parcel out = Parcel.obtain();
2029 final int N = mSyncStatus.size();
2030 for (int i=0; i<N; i++) {
2031 SyncStatusInfo status = mSyncStatus.valueAt(i);
2032 out.writeInt(STATUS_FILE_ITEM);
2033 status.writeToParcel(out, 0);
2034 }
2035 out.writeInt(STATUS_FILE_END);
2036 fos.write(out.marshall());
2037 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002038
Dianne Hackborn231cc602009-04-27 17:10:36 -07002039 mStatusFile.finishWrite(fos);
2040 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002041 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002042 if (fos != null) {
2043 mStatusFile.failWrite(fos);
2044 }
2045 }
2046 }
Costin Manolache360e4542009-09-04 13:36:04 -07002047
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002048 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2049 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2050 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002051 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002052 } else {
2053 SyncRequest.Builder req =
2054 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002055 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002056 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002057 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002058 ContentResolver.requestSync(req.build());
2059 }
2060 }
2061
Alon Albert57286f92012-10-09 14:21:38 -07002062 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002063 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002064 // If this is happening in the system process, then call the syncrequest listener
2065 // to make a request back to the SyncManager directly.
2066 // If this is probably a test instance, then call back through the ContentResolver
2067 // which will know which userId to apply based on the Binder id.
2068 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2069 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002070 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002071 new EndPoint(account, authority, userId),
2072 reason,
2073 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002074 } else {
2075 ContentResolver.requestSync(account, authority, extras);
2076 }
2077 }
2078
Dianne Hackborn231cc602009-04-27 17:10:36 -07002079 public static final int STATISTICS_FILE_END = 0;
2080 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2081 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002082
Dianne Hackborn231cc602009-04-27 17:10:36 -07002083 /**
2084 * Read all sync statistics back in to the initial engine state.
2085 */
2086 private void readStatisticsLocked() {
2087 try {
2088 byte[] data = mStatisticsFile.readFully();
2089 Parcel in = Parcel.obtain();
2090 in.unmarshall(data, 0, data.length);
2091 in.setDataPosition(0);
2092 int token;
2093 int index = 0;
2094 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2095 if (token == STATISTICS_FILE_ITEM
2096 || token == STATISTICS_FILE_ITEM_OLD) {
2097 int day = in.readInt();
2098 if (token == STATISTICS_FILE_ITEM_OLD) {
2099 day = day - 2009 + 14245; // Magic!
2100 }
2101 DayStats ds = new DayStats(day);
2102 ds.successCount = in.readInt();
2103 ds.successTime = in.readLong();
2104 ds.failureCount = in.readInt();
2105 ds.failureTime = in.readLong();
2106 if (index < mDayStats.length) {
2107 mDayStats[index] = ds;
2108 index++;
2109 }
2110 } else {
2111 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002112 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002113 break;
2114 }
2115 }
2116 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002117 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002118 }
2119 }
Costin Manolache360e4542009-09-04 13:36:04 -07002120
Dianne Hackborn231cc602009-04-27 17:10:36 -07002121 /**
2122 * Write all sync statistics to the sync status file.
2123 */
2124 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002125 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002126 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002127 }
Costin Manolache360e4542009-09-04 13:36:04 -07002128
Dianne Hackborn231cc602009-04-27 17:10:36 -07002129 // The file is being written, so we don't need to have a scheduled
2130 // write until the next change.
2131 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002132
Dianne Hackborn231cc602009-04-27 17:10:36 -07002133 FileOutputStream fos = null;
2134 try {
2135 fos = mStatisticsFile.startWrite();
2136 Parcel out = Parcel.obtain();
2137 final int N = mDayStats.length;
2138 for (int i=0; i<N; i++) {
2139 DayStats ds = mDayStats[i];
2140 if (ds == null) {
2141 break;
2142 }
2143 out.writeInt(STATISTICS_FILE_ITEM);
2144 out.writeInt(ds.day);
2145 out.writeInt(ds.successCount);
2146 out.writeLong(ds.successTime);
2147 out.writeInt(ds.failureCount);
2148 out.writeLong(ds.failureTime);
2149 }
2150 out.writeInt(STATISTICS_FILE_END);
2151 fos.write(out.marshall());
2152 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002153
Dianne Hackborn231cc602009-04-27 17:10:36 -07002154 mStatisticsFile.finishWrite(fos);
2155 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002156 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002157 if (fos != null) {
2158 mStatisticsFile.failWrite(fos);
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002162
2163 /**
Marvin Paula6533252014-11-24 12:57:48 -08002164 * Let the BackupManager know that account sync settings have changed. This will trigger
2165 * {@link com.android.server.backup.SystemBackupAgent} to run.
2166 */
2167 public void queueBackup() {
2168 BackupManager.dataChanged("android");
2169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170}