blob: bc3fc6a47aef72f84c8e3fd4343b23585e8d143e [file] [log] [blame]
Dianne Hackborn231cc602009-04-27 17:10:36 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Sharkey7a96c392012-11-15 14:01:46 -080017package com.android.server.content;
Jason parksa3cdaa52011-01-13 14:15:43 -060018
Fred Quintanad9d2f112009-04-23 13:36:27 -070019import android.accounts.Account;
Amith Yamasanif29f2362012-04-05 18:29:52 -070020import android.accounts.AccountAndUser;
Marvin Paula6533252014-11-24 12:57:48 -080021import android.app.backup.BackupManager;
Matthew Williamsfa774182013-06-18 15:44:11 -070022import android.content.ComponentName;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080023import android.content.ContentResolver;
24import android.content.Context;
25import android.content.ISyncStatusObserver;
26import android.content.PeriodicSync;
27import android.content.SyncInfo;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070028import android.content.SyncRequest;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080029import android.content.SyncStatusInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.database.Cursor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.database.sqlite.SQLiteDatabase;
Dianne Hackborn231cc602009-04-27 17:10:36 -070032import android.database.sqlite.SQLiteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.database.sqlite.SQLiteQueryBuilder;
Dianne Hackborn231cc602009-04-27 17:10:36 -070034import android.os.Bundle;
35import android.os.Environment;
36import android.os.Handler;
37import android.os.Message;
38import android.os.Parcel;
39import android.os.RemoteCallbackList;
40import android.os.RemoteException;
Matthew Williams56dbf8f2013-07-26 12:56:39 -070041import android.os.UserHandle;
Shreyas Basarge8c834c02016-01-07 13:53:16 +000042import android.util.*;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080043
44import com.android.internal.annotations.VisibleForTesting;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastXmlSerializer;
47
48import org.xmlpull.v1.XmlPullParser;
49import org.xmlpull.v1.XmlPullParserException;
50import org.xmlpull.v1.XmlSerializer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051
Dianne Hackborn231cc602009-04-27 17:10:36 -070052import java.io.File;
53import java.io.FileInputStream;
54import java.io.FileOutputStream;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +010055import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Dianne Hackborn231cc602009-04-27 17:10:36 -070057import java.util.Calendar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import java.util.HashMap;
Dianne Hackborn231cc602009-04-27 17:10:36 -070059import java.util.Iterator;
Jeff Sharkey7a96c392012-11-15 14:01:46 -080060import java.util.List;
Ashish Sharma69d95de2012-04-11 17:27:24 -070061import java.util.Random;
Jason parks1125d782011-01-12 09:47:26 -060062import java.util.TimeZone;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
64/**
Dianne Hackborn231cc602009-04-27 17:10:36 -070065 * Singleton that tracks the sync data and overall sync
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066 * history on the device.
Costin Manolache360e4542009-09-04 13:36:04 -070067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 * @hide
69 */
Dianne Hackborn231cc602009-04-27 17:10:36 -070070public class SyncStorageEngine extends Handler {
Amith Yamasani04e0d262012-02-14 11:50:53 -080071
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072 private static final String TAG = "SyncManager";
Matthew Williamsba352712013-08-13 15:53:31 -070073 private static final String TAG_FILE = "SyncManagerFile";
Costin Manolache360e4542009-09-04 13:36:04 -070074
Amith Yamasani04e0d262012-02-14 11:50:53 -080075 private static final String XML_ATTR_NEXT_AUTHORITY_ID = "nextAuthorityId";
76 private static final String XML_ATTR_LISTEN_FOR_TICKLES = "listen-for-tickles";
Ashish Sharma69d95de2012-04-11 17:27:24 -070077 private static final String XML_ATTR_SYNC_RANDOM_OFFSET = "offsetInSeconds";
Amith Yamasani04e0d262012-02-14 11:50:53 -080078 private static final String XML_ATTR_ENABLED = "enabled";
79 private static final String XML_ATTR_USER = "user";
80 private static final String XML_TAG_LISTEN_FOR_TICKLES = "listenForTickles";
81
Matthew Williamsfa774182013-06-18 15:44:11 -070082 /** Default time for a periodic sync. */
Fred Quintanac5d1c6d2010-01-27 12:17:49 -080083 private static final long DEFAULT_POLL_FREQUENCY_SECONDS = 60 * 60 * 24; // One day
84
Shreyas Basarge8c834c02016-01-07 13:53:16 +000085 /** Percentage of period that is flex by default, if no flexMillis is set. */
Matthew Williamsfa774182013-06-18 15:44:11 -070086 private static final double DEFAULT_FLEX_PERCENT_SYNC = 0.04;
87
88 /** Lower bound on sync time from which we assign a default flex time. */
89 private static final long DEFAULT_MIN_FLEX_ALLOWED_SECS = 5;
90
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -080091 @VisibleForTesting
Dianne Hackborn231cc602009-04-27 17:10:36 -070092 static final long MILLIS_IN_4WEEKS = 1000L * 60 * 60 * 24 * 7 * 4;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093
Dianne Hackborn231cc602009-04-27 17:10:36 -070094 /** Enum value for a sync start event. */
95 public static final int EVENT_START = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Dianne Hackborn231cc602009-04-27 17:10:36 -070097 /** Enum value for a sync stop event. */
98 public static final int EVENT_STOP = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Dianne Hackborn231cc602009-04-27 17:10:36 -0700100 /** Enum value for a server-initiated sync. */
101 public static final int SOURCE_SERVER = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Dianne Hackborn231cc602009-04-27 17:10:36 -0700103 /** Enum value for a local-initiated sync. */
104 public static final int SOURCE_LOCAL = 1;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700105 /** Enum value for a poll-based sync (e.g., upon connection to network) */
Dianne Hackborn231cc602009-04-27 17:10:36 -0700106 public static final int SOURCE_POLL = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Dianne Hackborn231cc602009-04-27 17:10:36 -0700108 /** Enum value for a user-initiated sync. */
109 public static final int SOURCE_USER = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800111 /** Enum value for a periodic sync. */
112 public static final int SOURCE_PERIODIC = 4;
113
Fred Quintana307da1a2010-01-21 14:24:20 -0800114 public static final long NOT_IN_BACKOFF_MODE = -1;
115
Dianne Hackborn231cc602009-04-27 17:10:36 -0700116 // TODO: i18n -- grab these out of resources.
117 /** String names for the sync source types. */
118 public static final String[] SOURCES = { "SERVER",
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000119 "LOCAL",
120 "POLL",
121 "USER",
122 "PERIODIC",
123 "SERVICE"};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124
Dianne Hackborn231cc602009-04-27 17:10:36 -0700125 // The MESG column will contain one of these or one of the Error types.
126 public static final String MESG_SUCCESS = "success";
127 public static final String MESG_CANCELED = "canceled";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700129 public static final int MAX_HISTORY = 100;
Costin Manolache360e4542009-09-04 13:36:04 -0700130
Dianne Hackborn231cc602009-04-27 17:10:36 -0700131 private static final int MSG_WRITE_STATUS = 1;
132 private static final long WRITE_STATUS_DELAY = 1000*60*10; // 10 minutes
Costin Manolache360e4542009-09-04 13:36:04 -0700133
Dianne Hackborn231cc602009-04-27 17:10:36 -0700134 private static final int MSG_WRITE_STATISTICS = 2;
135 private static final long WRITE_STATISTICS_DELAY = 1000*60*30; // 1/2 hour
Joe Onorato8294fad2009-07-15 16:08:44 -0700136
137 private static final boolean SYNC_ENABLED_DEFAULT = false;
Costin Manolache360e4542009-09-04 13:36:04 -0700138
Fred Quintanac2e46912010-03-15 16:10:44 -0700139 // the version of the accounts xml file format
Fred Quintanafb084402010-03-23 17:57:03 -0700140 private static final int ACCOUNTS_VERSION = 2;
141
142 private static HashMap<String, String> sAuthorityRenames;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000143 private static PeriodicSyncAddedListener mPeriodicSyncAddedListener;
Fred Quintanafb084402010-03-23 17:57:03 -0700144
145 static {
146 sAuthorityRenames = new HashMap<String, String>();
147 sAuthorityRenames.put("contacts", "com.android.contacts");
148 sAuthorityRenames.put("calendar", "com.android.calendar");
149 }
Fred Quintanac2e46912010-03-15 16:10:44 -0700150
Dianne Hackborn231cc602009-04-27 17:10:36 -0700151 static class AccountInfo {
Amith Yamasani04e0d262012-02-14 11:50:53 -0800152 final AccountAndUser accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700153 final HashMap<String, AuthorityInfo> authorities =
154 new HashMap<String, AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700155
Amith Yamasani04e0d262012-02-14 11:50:53 -0800156 AccountInfo(AccountAndUser accountAndUser) {
157 this.accountAndUser = accountAndUser;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700158 }
159 }
Costin Manolache360e4542009-09-04 13:36:04 -0700160
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700161 /** Bare bones representation of a sync target. */
162 public static class EndPoint {
163 public final static EndPoint USER_ALL_PROVIDER_ALL_ACCOUNTS_ALL =
164 new EndPoint(null, null, UserHandle.USER_ALL);
Dianne Hackborn7a135592009-05-06 00:28:37 -0700165 final Account account;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800166 final int userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700167 final String provider;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700168
169 public EndPoint(Account account, String provider, int userId) {
170 this.account = account;
171 this.provider = provider;
172 this.userId = userId;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700173 }
174
175 /**
Matthew Williams8ef22042013-07-26 12:56:39 -0700176 * An Endpoint for a sync matches if it targets the same sync adapter for the same user.
177 *
178 * @param spec the Endpoint to match. If the spec has null fields, they indicate a wildcard
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000179 * and match any.
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700180 */
Matthew Williams8ef22042013-07-26 12:56:39 -0700181 public boolean matchesSpec(EndPoint spec) {
182 if (userId != spec.userId
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700183 && userId != UserHandle.USER_ALL
Matthew Williams8ef22042013-07-26 12:56:39 -0700184 && spec.userId != UserHandle.USER_ALL) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700185 return false;
186 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000187 boolean accountsMatch;
188 if (spec.account == null) {
189 accountsMatch = true;
190 } else {
191 accountsMatch = account.equals(spec.account);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700192 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000193 boolean providersMatch;
194 if (spec.provider == null) {
195 providersMatch = true;
196 } else {
197 providersMatch = provider.equals(spec.provider);
198 }
199 return accountsMatch && providersMatch;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700200 }
201
202 public String toString() {
203 StringBuilder sb = new StringBuilder();
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000204 sb.append(account == null ? "ALL ACCS" : account.name)
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700205 .append("/")
206 .append(provider == null ? "ALL PDRS" : provider);
Matthew Williams8ef22042013-07-26 12:56:39 -0700207 sb.append(":u" + userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700208 return sb.toString();
209 }
210 }
211
212 public static class AuthorityInfo {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700213 // Legal values of getIsSyncable
214 /**
215 * Default state for a newly installed adapter. An uninitialized adapter will receive an
216 * initialization sync which are governed by a different set of rules to that of regular
217 * syncs.
218 */
219 public static final int NOT_INITIALIZED = -1;
220 /**
221 * The adapter will not receive any syncs. This is behaviourally equivalent to
222 * setSyncAutomatically -> false. However setSyncAutomatically is surfaced to the user
223 * while this is generally meant to be controlled by the developer.
224 */
225 public static final int NOT_SYNCABLE = 0;
226 /**
227 * The adapter is initialized and functioning. This is the normal state for an adapter.
228 */
229 public static final int SYNCABLE = 1;
230 /**
231 * The adapter is syncable but still requires an initialization sync. For example an adapter
232 * than has been restored from a previous device will be in this state. Not meant for
233 * external use.
234 */
235 public static final int SYNCABLE_NOT_INITIALIZED = 2;
236
Matthew Williams8ef22042013-07-26 12:56:39 -0700237 final EndPoint target;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700238 final int ident;
239 boolean enabled;
Fred Quintana5e787c42009-08-16 23:13:53 -0700240 int syncable;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700241 /** Time at which this sync will run, taking into account backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800242 long backoffTime;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700243 /** Amount of delay due to backoff. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800244 long backoffDelay;
Matthew Williams8ef22042013-07-26 12:56:39 -0700245 /** Time offset to add to any requests coming to this target. */
Fred Quintana307da1a2010-01-21 14:24:20 -0800246 long delayUntil;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700247
Matthew Williamsfa774182013-06-18 15:44:11 -0700248 final ArrayList<PeriodicSync> periodicSyncs;
Fred Quintanaac9385e2009-06-22 18:00:59 -0700249
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700250 /**
251 * Copy constructor for making deep-ish copies. Only the bundles stored
252 * in periodic syncs can make unexpected changes.
253 *
254 * @param toCopy AuthorityInfo to be copied.
255 */
256 AuthorityInfo(AuthorityInfo toCopy) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700257 target = toCopy.target;
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700258 ident = toCopy.ident;
259 enabled = toCopy.enabled;
260 syncable = toCopy.syncable;
261 backoffTime = toCopy.backoffTime;
262 backoffDelay = toCopy.backoffDelay;
263 delayUntil = toCopy.delayUntil;
Matthew Williamsfa774182013-06-18 15:44:11 -0700264 periodicSyncs = new ArrayList<PeriodicSync>();
265 for (PeriodicSync sync : toCopy.periodicSyncs) {
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700266 // Still not a perfect copy, because we are just copying the mappings.
Matthew Williamsfa774182013-06-18 15:44:11 -0700267 periodicSyncs.add(new PeriodicSync(sync));
Carlos Valdivia3aca7d72012-05-07 19:03:51 -0700268 }
269 }
270
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700271 AuthorityInfo(EndPoint info, int id) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700272 target = info;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700273 ident = id;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000274 enabled = SYNC_ENABLED_DEFAULT;
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700275 periodicSyncs = new ArrayList<PeriodicSync>();
276 defaultInitialisation();
277 }
278
279 private void defaultInitialisation() {
Matthew Williams53abfdb2015-06-10 20:06:37 -0700280 syncable = NOT_INITIALIZED; // default to "unknown"
Fred Quintana307da1a2010-01-21 14:24:20 -0800281 backoffTime = -1; // if < 0 then we aren't in backoff mode
282 backoffDelay = -1; // if < 0 then we aren't in backoff mode
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000283
284 if (mPeriodicSyncAddedListener != null) {
285 mPeriodicSyncAddedListener.onPeriodicSyncAdded(target, new Bundle(),
286 DEFAULT_POLL_FREQUENCY_SECONDS,
287 calculateDefaultFlexTime(DEFAULT_POLL_FREQUENCY_SECONDS));
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700288 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700289 }
Matthew Williams06485a72013-07-26 12:56:39 -0700290
291 @Override
292 public String toString() {
293 return target + ", enabled=" + enabled + ", syncable=" + syncable + ", backoff="
294 + backoffTime + ", delay=" + delayUntil;
295 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700296 }
Costin Manolache360e4542009-09-04 13:36:04 -0700297
Dianne Hackborn231cc602009-04-27 17:10:36 -0700298 public static class SyncHistoryItem {
299 int authorityId;
300 int historyId;
301 long eventTime;
302 long elapsedTime;
303 int source;
304 int event;
305 long upstreamActivity;
306 long downstreamActivity;
307 String mesg;
Fred Quintanadc475562012-05-04 15:51:54 -0700308 boolean initialization;
Alon Albert57286f92012-10-09 14:21:38 -0700309 Bundle extras;
310 int reason;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700311 }
Costin Manolache360e4542009-09-04 13:36:04 -0700312
Dianne Hackborn231cc602009-04-27 17:10:36 -0700313 public static class DayStats {
314 public final int day;
315 public int successCount;
316 public long successTime;
317 public int failureCount;
318 public long failureTime;
Costin Manolache360e4542009-09-04 13:36:04 -0700319
Dianne Hackborn231cc602009-04-27 17:10:36 -0700320 public DayStats(int day) {
321 this.day = day;
322 }
323 }
Costin Manolache360e4542009-09-04 13:36:04 -0700324
Amith Yamasani04e0d262012-02-14 11:50:53 -0800325 interface OnSyncRequestListener {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700326
327 /** Called when a sync is needed on an account(s) due to some change in state. */
328 public void onSyncRequest(EndPoint info, int reason, Bundle extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -0800329 }
330
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000331 interface PeriodicSyncAddedListener {
332 /** Called when a periodic sync is added. */
333 void onPeriodicSyncAdded(EndPoint target, Bundle extras, long pollFrequency, long flex);
334 }
335
336 interface OnAuthorityRemovedListener {
337 /** Called when an authority is removed. */
338 void onAuthorityRemoved(EndPoint removedAuthority);
339 }
340
Dianne Hackborn231cc602009-04-27 17:10:36 -0700341 // Primary list of all syncable authorities. Also our global lock.
342 private final SparseArray<AuthorityInfo> mAuthorities =
343 new SparseArray<AuthorityInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700344
Amith Yamasani04e0d262012-02-14 11:50:53 -0800345 private final HashMap<AccountAndUser, AccountInfo> mAccounts
346 = new HashMap<AccountAndUser, AccountInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347
Amith Yamasani04e0d262012-02-14 11:50:53 -0800348 private final SparseArray<ArrayList<SyncInfo>> mCurrentSyncs
349 = new SparseArray<ArrayList<SyncInfo>>();
Costin Manolache360e4542009-09-04 13:36:04 -0700350
Dianne Hackborn231cc602009-04-27 17:10:36 -0700351 private final SparseArray<SyncStatusInfo> mSyncStatus =
352 new SparseArray<SyncStatusInfo>();
Costin Manolache360e4542009-09-04 13:36:04 -0700353
Dianne Hackborn231cc602009-04-27 17:10:36 -0700354 private final ArrayList<SyncHistoryItem> mSyncHistory =
355 new ArrayList<SyncHistoryItem>();
Costin Manolache360e4542009-09-04 13:36:04 -0700356
Dianne Hackborn231cc602009-04-27 17:10:36 -0700357 private final RemoteCallbackList<ISyncStatusObserver> mChangeListeners
358 = new RemoteCallbackList<ISyncStatusObserver>();
Costin Manolache360e4542009-09-04 13:36:04 -0700359
Matthew Williams8ef22042013-07-26 12:56:39 -0700360 /** Reverse mapping for component name -> <userid -> target id>. */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700361 private final ArrayMap<ComponentName, SparseArray<AuthorityInfo>> mServices =
362 new ArrayMap<ComponentName, SparseArray<AuthorityInfo>>();
Matthew Williamsfa774182013-06-18 15:44:11 -0700363
Fred Quintana77c560f2010-03-29 22:20:26 -0700364 private int mNextAuthorityId = 0;
365
Dianne Hackborn231cc602009-04-27 17:10:36 -0700366 // We keep 4 weeks of stats.
367 private final DayStats[] mDayStats = new DayStats[7*4];
368 private final Calendar mCal;
369 private int mYear;
370 private int mYearInDays;
Costin Manolache360e4542009-09-04 13:36:04 -0700371
Dianne Hackborn231cc602009-04-27 17:10:36 -0700372 private final Context mContext;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800373
Dianne Hackborn231cc602009-04-27 17:10:36 -0700374 private static volatile SyncStorageEngine sSyncStorageEngine = null;
Costin Manolache360e4542009-09-04 13:36:04 -0700375
Ashish Sharma69d95de2012-04-11 17:27:24 -0700376 private int mSyncRandomOffset;
377
Dianne Hackborn231cc602009-04-27 17:10:36 -0700378 /**
379 * This file contains the core engine state: all accounts and the
380 * settings for them. It must never be lost, and should be changed
381 * infrequently, so it is stored as an XML file.
382 */
383 private final AtomicFile mAccountInfoFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700384
Dianne Hackborn231cc602009-04-27 17:10:36 -0700385 /**
386 * This file contains the current sync status. We would like to retain
387 * it across boots, but its loss is not the end of the world, so we store
388 * this information as binary data.
389 */
390 private final AtomicFile mStatusFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700391
Dianne Hackborn231cc602009-04-27 17:10:36 -0700392 /**
393 * This file contains sync statistics. This is purely debugging information
394 * so is written infrequently and can be thrown away at any time.
395 */
396 private final AtomicFile mStatisticsFile;
Costin Manolache360e4542009-09-04 13:36:04 -0700397
Dianne Hackborn231cc602009-04-27 17:10:36 -0700398 private int mNextHistoryId = 0;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800399 private SparseArray<Boolean> mMasterSyncAutomatically = new SparseArray<Boolean>();
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800400 private boolean mDefaultMasterSyncAutomatically;
Amith Yamasani04e0d262012-02-14 11:50:53 -0800401
402 private OnSyncRequestListener mSyncRequestListener;
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000403 private OnAuthorityRemovedListener mAuthorityRemovedListener;
Costin Manolache360e4542009-09-04 13:36:04 -0700404
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800405 private SyncStorageEngine(Context context, File dataDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 mContext = context;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407 sSyncStorageEngine = this;
Costin Manolache360e4542009-09-04 13:36:04 -0700408
Dianne Hackborn231cc602009-04-27 17:10:36 -0700409 mCal = Calendar.getInstance(TimeZone.getTimeZone("GMT+0"));
Costin Manolache360e4542009-09-04 13:36:04 -0700410
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800411 mDefaultMasterSyncAutomatically = mContext.getResources().getBoolean(
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000412 com.android.internal.R.bool.config_syncstorageengine_masterSyncAutomatically);
Yameng Huang2b5d0ea2011-01-11 14:00:19 +0800413
Dianne Hackborn231cc602009-04-27 17:10:36 -0700414 File systemDir = new File(dataDir, "system");
415 File syncDir = new File(systemDir, "sync");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800416 syncDir.mkdirs();
Matthew Williamsba352712013-08-13 15:53:31 -0700417
418 maybeDeleteLegacyPendingInfoLocked(syncDir);
419
Dianne Hackborn231cc602009-04-27 17:10:36 -0700420 mAccountInfoFile = new AtomicFile(new File(syncDir, "accounts.xml"));
421 mStatusFile = new AtomicFile(new File(syncDir, "status.bin"));
Dianne Hackborn231cc602009-04-27 17:10:36 -0700422 mStatisticsFile = new AtomicFile(new File(syncDir, "stats.bin"));
Costin Manolache360e4542009-09-04 13:36:04 -0700423
Dianne Hackborn231cc602009-04-27 17:10:36 -0700424 readAccountInfoLocked();
425 readStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700426 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700427 readAndDeleteLegacyAccountInfoLocked();
428 writeAccountInfoLocked();
429 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -0700430 writeStatisticsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 }
432
433 public static SyncStorageEngine newTestInstance(Context context) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -0800434 return new SyncStorageEngine(context, context.getFilesDir());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 }
436
437 public static void init(Context context) {
438 if (sSyncStorageEngine != null) {
Fred Quintana307da1a2010-01-21 14:24:20 -0800439 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 }
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
Dianne Hackborn231cc602009-04-27 17:10:36 -0700860 /**
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700861 * Returns true if there is currently a sync operation being actively processed for the given
Matthew Williams8ef22042013-07-26 12:56:39 -0700862 * target.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700863 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700864 public boolean isSyncActive(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700865 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700866 for (SyncInfo syncInfo : getCurrentSyncs(info.userId)) {
Fred Quintana918339a2010-10-05 14:00:39 -0700867 AuthorityInfo ainfo = getAuthority(syncInfo.authorityId);
Matthew Williams8ef22042013-07-26 12:56:39 -0700868 if (ainfo != null && ainfo.target.matchesSpec(info)) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700869 return true;
870 }
871 }
872 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700873 return false;
874 }
Costin Manolache360e4542009-09-04 13:36:04 -0700875
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000876 public void markPending(EndPoint info, boolean pendingValue) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700877 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000878 AuthorityInfo authority = getOrCreateAuthorityLocked(info,
879 -1 /* desired identifier */,
880 true /* write accounts to storage */);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700881 if (authority == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000882 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700883 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700884 SyncStatusInfo status = getOrCreateSyncStatusLocked(authority.ident);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000885 status.pending = pendingValue;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700886 }
Fred Quintanaac9385e2009-06-22 18:00:59 -0700887 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_PENDING);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700888 }
Costin Manolache360e4542009-09-04 13:36:04 -0700889
Dianne Hackborn231cc602009-04-27 17:10:36 -0700890 /**
891 * Called when the set of account has changed, given the new array of
892 * active accounts.
893 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800894 public void doDatabaseCleanup(Account[] accounts, int userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700895 synchronized (mAuthorities) {
Matthew Williams8ef22042013-07-26 12:56:39 -0700896 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000897 Slog.v(TAG, "Updating for new accounts...");
Matthew Williams8ef22042013-07-26 12:56:39 -0700898 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700899 SparseArray<AuthorityInfo> removing = new SparseArray<AuthorityInfo>();
900 Iterator<AccountInfo> accIt = mAccounts.values().iterator();
901 while (accIt.hasNext()) {
902 AccountInfo acc = accIt.next();
Amith Yamasani04e0d262012-02-14 11:50:53 -0800903 if (!ArrayUtils.contains(accounts, acc.accountAndUser.account)
904 && acc.accountAndUser.userId == userId) {
Dianne Hackborn231cc602009-04-27 17:10:36 -0700905 // This account no longer exists...
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700906 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000907 Slog.v(TAG, "Account removed: " + acc.accountAndUser);
Fred Quintana77c560f2010-03-29 22:20:26 -0700908 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700909 for (AuthorityInfo auth : acc.authorities.values()) {
910 removing.put(auth.ident, auth);
911 }
912 accIt.remove();
913 }
914 }
Costin Manolache360e4542009-09-04 13:36:04 -0700915
Dianne Hackborn231cc602009-04-27 17:10:36 -0700916 // Clean out all data structures.
917 int i = removing.size();
918 if (i > 0) {
919 while (i > 0) {
920 i--;
921 int ident = removing.keyAt(i);
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000922 AuthorityInfo auth = removing.valueAt(i);
923 if (mAuthorityRemovedListener != null) {
924 mAuthorityRemovedListener.onAuthorityRemoved(auth.target);
925 }
Dianne Hackborn231cc602009-04-27 17:10:36 -0700926 mAuthorities.remove(ident);
927 int j = mSyncStatus.size();
928 while (j > 0) {
929 j--;
930 if (mSyncStatus.keyAt(j) == ident) {
931 mSyncStatus.remove(mSyncStatus.keyAt(j));
932 }
933 }
934 j = mSyncHistory.size();
935 while (j > 0) {
936 j--;
937 if (mSyncHistory.get(j).authorityId == ident) {
938 mSyncHistory.remove(j);
939 }
940 }
941 }
942 writeAccountInfoLocked();
943 writeStatusLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700944 writeStatisticsLocked();
945 }
946 }
947 }
948
949 /**
Fred Quintana918339a2010-10-05 14:00:39 -0700950 * Called when a sync is starting. Supply a valid ActiveSyncContext with information
951 * about the sync.
Dianne Hackborn231cc602009-04-27 17:10:36 -0700952 */
Fred Quintana918339a2010-10-05 14:00:39 -0700953 public SyncInfo addActiveSync(SyncManager.ActiveSyncContext activeSyncContext) {
954 final SyncInfo syncInfo;
Dianne Hackborn231cc602009-04-27 17:10:36 -0700955 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700956 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000957 Slog.v(TAG, "setActiveSync: account="
958 + " auth=" + activeSyncContext.mSyncOperation.target
959 + " src=" + activeSyncContext.mSyncOperation.syncSource
960 + " extras=" + activeSyncContext.mSyncOperation.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700961 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700962 final EndPoint info = activeSyncContext.mSyncOperation.target;
963 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(
964 info,
Matthew Williams8ef22042013-07-26 12:56:39 -0700965 -1 /* assign a new identifier if creating a new target */,
Fred Quintana918339a2010-10-05 14:00:39 -0700966 true /* write to storage if this results in a change */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700967 syncInfo = new SyncInfo(
968 authorityInfo.ident,
Matthew Williams8ef22042013-07-26 12:56:39 -0700969 authorityInfo.target.account,
970 authorityInfo.target.provider,
Fred Quintana918339a2010-10-05 14:00:39 -0700971 activeSyncContext.mStartTime);
Matthew Williams8ef22042013-07-26 12:56:39 -0700972 getCurrentSyncs(authorityInfo.target.userId).add(syncInfo);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700973 }
Fred Quintana918339a2010-10-05 14:00:39 -0700974 reportActiveChange();
975 return syncInfo;
976 }
977
978 /**
979 * Called to indicate that a previously active sync is no longer active.
980 */
Amith Yamasani04e0d262012-02-14 11:50:53 -0800981 public void removeActiveSync(SyncInfo syncInfo, int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -0700982 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -0700983 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +0000984 Slog.v(TAG, "removeActiveSync: account=" + syncInfo.account
Amith Yamasani04e0d262012-02-14 11:50:53 -0800985 + " user=" + userId
Matthew Williams5a9decd2014-06-04 09:25:11 -0700986 + " auth=" + syncInfo.authority);
Fred Quintana918339a2010-10-05 14:00:39 -0700987 }
Amith Yamasani04e0d262012-02-14 11:50:53 -0800988 getCurrentSyncs(userId).remove(syncInfo);
Fred Quintana918339a2010-10-05 14:00:39 -0700989 }
990
991 reportActiveChange();
Dianne Hackborn231cc602009-04-27 17:10:36 -0700992 }
993
994 /**
995 * To allow others to send active change reports, to poke clients.
996 */
997 public void reportActiveChange() {
Fred Quintanaac9385e2009-06-22 18:00:59 -0700998 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE);
Dianne Hackborn231cc602009-04-27 17:10:36 -0700999 }
Costin Manolache360e4542009-09-04 13:36:04 -07001000
Dianne Hackborn231cc602009-04-27 17:10:36 -07001001 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001002 * Note that sync has started for the given operation.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001003 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001004 public long insertStartSyncEvent(SyncOperation op, long now) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001005 long id;
1006 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001007 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001008 Slog.v(TAG, "insertStartSyncEvent: " + op);
Fred Quintana77c560f2010-03-29 22:20:26 -07001009 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001010 AuthorityInfo authority = getAuthorityLocked(op.target, "insertStartSyncEvent");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001011 if (authority == null) {
1012 return -1;
1013 }
1014 SyncHistoryItem item = new SyncHistoryItem();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001015 item.initialization = op.isInitialization();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001016 item.authorityId = authority.ident;
1017 item.historyId = mNextHistoryId++;
1018 if (mNextHistoryId < 0) mNextHistoryId = 0;
1019 item.eventTime = now;
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001020 item.source = op.syncSource;
1021 item.reason = op.reason;
1022 item.extras = op.extras;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001023 item.event = EVENT_START;
1024 mSyncHistory.add(0, item);
1025 while (mSyncHistory.size() > MAX_HISTORY) {
1026 mSyncHistory.remove(mSyncHistory.size()-1);
1027 }
1028 id = item.historyId;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001029 if (Log.isLoggable(TAG, Log.VERBOSE)) Slog.v(TAG, "returning historyId " + id);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001030 }
Costin Manolache360e4542009-09-04 13:36:04 -07001031
Fred Quintanaac9385e2009-06-22 18:00:59 -07001032 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001033 return id;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 }
1035
Fred Quintana77c560f2010-03-29 22:20:26 -07001036 public void stopSyncEvent(long historyId, long elapsedTime, String resultMessage,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001037 long downstreamActivity, long upstreamActivity) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001038 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001039 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001040 Slog.v(TAG, "stopSyncEvent: historyId=" + historyId);
Fred Quintana77c560f2010-03-29 22:20:26 -07001041 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001042 SyncHistoryItem item = null;
1043 int i = mSyncHistory.size();
1044 while (i > 0) {
1045 i--;
1046 item = mSyncHistory.get(i);
1047 if (item.historyId == historyId) {
1048 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001050 item = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
Costin Manolache360e4542009-09-04 13:36:04 -07001052
Dianne Hackborn231cc602009-04-27 17:10:36 -07001053 if (item == null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001054 Slog.w(TAG, "stopSyncEvent: no history for id " + historyId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001055 return;
1056 }
Costin Manolache360e4542009-09-04 13:36:04 -07001057
Dianne Hackborn231cc602009-04-27 17:10:36 -07001058 item.elapsedTime = elapsedTime;
1059 item.event = EVENT_STOP;
1060 item.mesg = resultMessage;
1061 item.downstreamActivity = downstreamActivity;
1062 item.upstreamActivity = upstreamActivity;
Costin Manolache360e4542009-09-04 13:36:04 -07001063
Dianne Hackborn231cc602009-04-27 17:10:36 -07001064 SyncStatusInfo status = getOrCreateSyncStatusLocked(item.authorityId);
Costin Manolache360e4542009-09-04 13:36:04 -07001065
Dianne Hackborn231cc602009-04-27 17:10:36 -07001066 status.numSyncs++;
1067 status.totalElapsedTime += elapsedTime;
1068 switch (item.source) {
1069 case SOURCE_LOCAL:
1070 status.numSourceLocal++;
1071 break;
1072 case SOURCE_POLL:
1073 status.numSourcePoll++;
1074 break;
1075 case SOURCE_USER:
1076 status.numSourceUser++;
1077 break;
1078 case SOURCE_SERVER:
1079 status.numSourceServer++;
1080 break;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001081 case SOURCE_PERIODIC:
1082 status.numSourcePeriodic++;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001083 break;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001084 }
Costin Manolache360e4542009-09-04 13:36:04 -07001085
Dianne Hackborn231cc602009-04-27 17:10:36 -07001086 boolean writeStatisticsNow = false;
Dianne Hackborn55280a92009-05-07 15:53:46 -07001087 int day = getCurrentDayLocked();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001088 if (mDayStats[0] == null) {
1089 mDayStats[0] = new DayStats(day);
1090 } else if (day != mDayStats[0].day) {
1091 System.arraycopy(mDayStats, 0, mDayStats, 1, mDayStats.length-1);
1092 mDayStats[0] = new DayStats(day);
1093 writeStatisticsNow = true;
1094 } else if (mDayStats[0] == null) {
1095 }
1096 final DayStats ds = mDayStats[0];
Costin Manolache360e4542009-09-04 13:36:04 -07001097
Dianne Hackborn231cc602009-04-27 17:10:36 -07001098 final long lastSyncTime = (item.eventTime + elapsedTime);
1099 boolean writeStatusNow = false;
1100 if (MESG_SUCCESS.equals(resultMessage)) {
1101 // - if successful, update the successful columns
1102 if (status.lastSuccessTime == 0 || status.lastFailureTime != 0) {
1103 writeStatusNow = true;
1104 }
1105 status.lastSuccessTime = lastSyncTime;
1106 status.lastSuccessSource = item.source;
1107 status.lastFailureTime = 0;
1108 status.lastFailureSource = -1;
1109 status.lastFailureMesg = null;
1110 status.initialFailureTime = 0;
1111 ds.successCount++;
1112 ds.successTime += elapsedTime;
1113 } else if (!MESG_CANCELED.equals(resultMessage)) {
1114 if (status.lastFailureTime == 0) {
1115 writeStatusNow = true;
1116 }
1117 status.lastFailureTime = lastSyncTime;
1118 status.lastFailureSource = item.source;
1119 status.lastFailureMesg = resultMessage;
1120 if (status.initialFailureTime == 0) {
1121 status.initialFailureTime = lastSyncTime;
1122 }
1123 ds.failureCount++;
1124 ds.failureTime += elapsedTime;
1125 }
Costin Manolache360e4542009-09-04 13:36:04 -07001126
Dianne Hackborn231cc602009-04-27 17:10:36 -07001127 if (writeStatusNow) {
1128 writeStatusLocked();
1129 } else if (!hasMessages(MSG_WRITE_STATUS)) {
1130 sendMessageDelayed(obtainMessage(MSG_WRITE_STATUS),
1131 WRITE_STATUS_DELAY);
1132 }
1133 if (writeStatisticsNow) {
1134 writeStatisticsLocked();
1135 } else if (!hasMessages(MSG_WRITE_STATISTICS)) {
1136 sendMessageDelayed(obtainMessage(MSG_WRITE_STATISTICS),
1137 WRITE_STATISTICS_DELAY);
Costin Manolache360e4542009-09-04 13:36:04 -07001138 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001139 }
Costin Manolache360e4542009-09-04 13:36:04 -07001140
Fred Quintanaac9385e2009-06-22 18:00:59 -07001141 reportChange(ContentResolver.SYNC_OBSERVER_TYPE_STATUS);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001142 }
1143
1144 /**
Matthew Williamsa7456e42013-11-12 14:41:02 -08001145 * Return a list of the currently active syncs. Note that the returned
1146 * items are the real, live active sync objects, so be careful what you do
1147 * with it.
Fred Quintana918339a2010-10-05 14:00:39 -07001148 */
Matthew Williamsa7456e42013-11-12 14:41:02 -08001149 private List<SyncInfo> getCurrentSyncs(int userId) {
Fred Quintana918339a2010-10-05 14:00:39 -07001150 synchronized (mAuthorities) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001151 return getCurrentSyncsLocked(userId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001152 }
1153 }
Costin Manolache360e4542009-09-04 13:36:04 -07001154
Dianne Hackborn231cc602009-04-27 17:10:36 -07001155 /**
Matthew Williamsf39549e2016-01-19 23:04:04 +00001156 * @param userId Id of user to return current sync info.
1157 * @param canAccessAccounts Determines whether to redact Account information from the result.
1158 * @return a copy of the current syncs data structure. Will not return null.
Matthew Williamsa7456e42013-11-12 14:41:02 -08001159 */
Matthew Williamsf39549e2016-01-19 23:04:04 +00001160 public List<SyncInfo> getCurrentSyncsCopy(int userId, boolean canAccessAccounts) {
Matthew Williamsa7456e42013-11-12 14:41:02 -08001161 synchronized (mAuthorities) {
1162 final List<SyncInfo> syncs = getCurrentSyncsLocked(userId);
1163 final List<SyncInfo> syncsCopy = new ArrayList<SyncInfo>();
1164 for (SyncInfo sync : syncs) {
Matthew Williamsf39549e2016-01-19 23:04:04 +00001165 SyncInfo copy;
1166 if (!canAccessAccounts) {
1167 copy = SyncInfo.createAccountRedacted(
1168 sync.authorityId, sync.authority, sync.startTime);
1169 } else {
1170 copy = new SyncInfo(sync);
1171 }
1172 syncsCopy.add(copy);
Matthew Williamsa7456e42013-11-12 14:41:02 -08001173 }
1174 return syncsCopy;
1175 }
1176 }
1177
1178 private List<SyncInfo> getCurrentSyncsLocked(int userId) {
1179 ArrayList<SyncInfo> syncs = mCurrentSyncs.get(userId);
1180 if (syncs == null) {
1181 syncs = new ArrayList<SyncInfo>();
1182 mCurrentSyncs.put(userId, syncs);
1183 }
1184 return syncs;
1185 }
1186
1187 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001188 * Return a copy of the specified target with the corresponding sync status
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001189 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001190 public Pair<AuthorityInfo, SyncStatusInfo> getCopyOfAuthorityWithSyncStatus(EndPoint info) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001191 synchronized (mAuthorities) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001192 AuthorityInfo authorityInfo = getOrCreateAuthorityLocked(info,
Matthew Williams8ef22042013-07-26 12:56:39 -07001193 -1 /* assign a new identifier if creating a new target */,
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001194 true /* write to storage if this results in a change */);
1195 return createCopyPairOfAuthorityWithSyncStatusLocked(authorityInfo);
1196 }
1197 }
1198
1199 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001200 * Returns the status that matches the target.
Costin Manolacheb7520982009-09-02 18:03:05 -07001201 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001202 * @param info the endpoint target we are querying status info for.
1203 * @return the SyncStatusInfo for the endpoint.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001204 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001205 public SyncStatusInfo getStatusByAuthority(EndPoint info) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001206 if (info.account == null || info.provider == null) {
Matthew Williamsd08d6682013-10-14 10:39:41 -07001207 return null;
Costin Manolacheb7520982009-09-02 18:03:05 -07001208 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001209 synchronized (mAuthorities) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001210 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001211 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001212 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001213 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001214 if (ainfo != null
Matthew Williams8ef22042013-07-26 12:56:39 -07001215 && ainfo.target.matchesSpec(info)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001216 return cur;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001217 }
1218 }
Costin Manolacheb7520982009-09-02 18:03:05 -07001219 return null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001220 }
1221 }
Costin Manolache360e4542009-09-04 13:36:04 -07001222
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001223 /** Return true if the pending status is true of any matching authorities. */
1224 public boolean isSyncPending(EndPoint info) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001225 synchronized (mAuthorities) {
1226 final int N = mSyncStatus.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001227 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001228 SyncStatusInfo cur = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001229 AuthorityInfo ainfo = mAuthorities.get(cur.authorityId);
1230 if (ainfo == null) {
1231 continue;
1232 }
Matthew Williams8ef22042013-07-26 12:56:39 -07001233 if (!ainfo.target.matchesSpec(info)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001234 continue;
1235 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001236 if (cur.pending) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001237 return true;
1238 }
1239 }
1240 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
1242 }
1243
1244 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001245 * Return an array of the current sync status for all authorities. Note
1246 * that the objects inside the array are the real, live status objects,
1247 * so be careful what you do with them.
1248 */
1249 public ArrayList<SyncHistoryItem> getSyncHistory() {
1250 synchronized (mAuthorities) {
1251 final int N = mSyncHistory.size();
1252 ArrayList<SyncHistoryItem> items = new ArrayList<SyncHistoryItem>(N);
1253 for (int i=0; i<N; i++) {
1254 items.add(mSyncHistory.get(i));
1255 }
1256 return items;
1257 }
1258 }
Costin Manolache360e4542009-09-04 13:36:04 -07001259
Dianne Hackborn231cc602009-04-27 17:10:36 -07001260 /**
1261 * Return an array of the current per-day statistics. Note
1262 * that the objects inside the array are the real, live status objects,
1263 * so be careful what you do with them.
1264 */
1265 public DayStats[] getDayStatistics() {
1266 synchronized (mAuthorities) {
1267 DayStats[] ds = new DayStats[mDayStats.length];
1268 System.arraycopy(mDayStats, 0, ds, 0, ds.length);
1269 return ds;
1270 }
1271 }
Costin Manolache360e4542009-09-04 13:36:04 -07001272
Georgi Nikolovdbe846b2013-06-25 14:09:56 -07001273 private Pair<AuthorityInfo, SyncStatusInfo> createCopyPairOfAuthorityWithSyncStatusLocked(
1274 AuthorityInfo authorityInfo) {
1275 SyncStatusInfo syncStatusInfo = getOrCreateSyncStatusLocked(authorityInfo.ident);
1276 return Pair.create(new AuthorityInfo(authorityInfo), new SyncStatusInfo(syncStatusInfo));
1277 }
1278
Dianne Hackborn55280a92009-05-07 15:53:46 -07001279 private int getCurrentDayLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001280 mCal.setTimeInMillis(System.currentTimeMillis());
1281 final int dayOfYear = mCal.get(Calendar.DAY_OF_YEAR);
1282 if (mYear != mCal.get(Calendar.YEAR)) {
1283 mYear = mCal.get(Calendar.YEAR);
1284 mCal.clear();
1285 mCal.set(Calendar.YEAR, mYear);
1286 mYearInDays = (int)(mCal.getTimeInMillis()/86400000);
1287 }
1288 return dayOfYear + mYearInDays;
1289 }
Costin Manolache360e4542009-09-04 13:36:04 -07001290
Dianne Hackborn231cc602009-04-27 17:10:36 -07001291 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001292 * Retrieve a target's full info, returning null if one does not exist.
Costin Manolache360e4542009-09-04 13:36:04 -07001293 *
Matthew Williams8ef22042013-07-26 12:56:39 -07001294 * @param info info of the target to look up.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001295 * @param tag If non-null, this will be used in a log message if the
Matthew Williams8ef22042013-07-26 12:56:39 -07001296 * requested target does not exist.
Dianne Hackborn231cc602009-04-27 17:10:36 -07001297 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001298 private AuthorityInfo getAuthorityLocked(EndPoint info, String tag) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001299 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1300 AccountInfo accountInfo = mAccounts.get(au);
1301 if (accountInfo == null) {
1302 if (tag != null) {
1303 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1304 Slog.v(TAG, tag + ": unknown account " + au);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001305 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001306 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001307 return null;
1308 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001309 AuthorityInfo authority = accountInfo.authorities.get(info.provider);
1310 if (authority == null) {
1311 if (tag != null) {
1312 if (Log.isLoggable(TAG, Log.VERBOSE)) {
1313 Slog.v(TAG, tag + ": unknown provider " + info.provider);
1314 }
1315 }
1316 return null;
1317 }
1318 return authority;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001319 }
Costin Manolache360e4542009-09-04 13:36:04 -07001320
Matthew Williamsfa774182013-06-18 15:44:11 -07001321 /**
Matthew Williams8ef22042013-07-26 12:56:39 -07001322 * @param info info identifying target.
1323 * @param ident unique identifier for target. -1 for none.
Matthew Williamsfa774182013-06-18 15:44:11 -07001324 * @param doWrite if true, update the accounts.xml file on the disk.
Matthew Williams8ef22042013-07-26 12:56:39 -07001325 * @return the authority that corresponds to the provided sync target, creating it if none
Matthew Williamsfa774182013-06-18 15:44:11 -07001326 * exists.
1327 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001328 private AuthorityInfo getOrCreateAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1329 AuthorityInfo authority = null;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001330 AccountAndUser au = new AccountAndUser(info.account, info.userId);
1331 AccountInfo account = mAccounts.get(au);
1332 if (account == null) {
1333 account = new AccountInfo(au);
1334 mAccounts.put(au, account);
1335 }
1336 authority = account.authorities.get(info.provider);
1337 if (authority == null) {
1338 authority = createAuthorityLocked(info, ident, doWrite);
1339 account.authorities.put(info.provider, authority);
Matthew Williamsfa774182013-06-18 15:44:11 -07001340 }
1341 return authority;
1342 }
1343
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001344 private AuthorityInfo createAuthorityLocked(EndPoint info, int ident, boolean doWrite) {
1345 AuthorityInfo authority;
1346 if (ident < 0) {
1347 ident = mNextAuthorityId;
1348 mNextAuthorityId++;
1349 doWrite = true;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001350 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001351 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001352 Slog.v(TAG, "created a new AuthorityInfo for " + info);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001353 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001354 authority = new AuthorityInfo(info, ident);
1355 mAuthorities.put(ident, authority);
1356 if (doWrite) {
1357 writeAccountInfoLocked();
1358 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001359 return authority;
1360 }
Costin Manolache360e4542009-09-04 13:36:04 -07001361
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001362 public void removeAuthority(EndPoint info) {
1363 synchronized (mAuthorities) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001364 removeAuthorityLocked(info.account, info.userId, info.provider, true /* doWrite */);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001365 }
1366 }
1367
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001368
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001369 /**
1370 * Remove an authority associated with a provider. Needs to be a standalone function for
1371 * backward compatibility.
1372 */
Amith Yamasani04e0d262012-02-14 11:50:53 -08001373 private void removeAuthorityLocked(Account account, int userId, String authorityName,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001374 boolean doWrite) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001375 AccountInfo accountInfo = mAccounts.get(new AccountAndUser(account, userId));
Fred Quintana7620f1a2010-03-16 15:58:44 -07001376 if (accountInfo != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001377 final AuthorityInfo authorityInfo = accountInfo.authorities.remove(authorityName);
1378 if (authorityInfo != null) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001379 if (mAuthorityRemovedListener != null) {
1380 mAuthorityRemovedListener.onAuthorityRemoved(authorityInfo.target);
1381 }
Fred Quintanafb084402010-03-23 17:57:03 -07001382 mAuthorities.remove(authorityInfo.ident);
Fred Quintana77c560f2010-03-29 22:20:26 -07001383 if (doWrite) {
1384 writeAccountInfoLocked();
1385 }
Fred Quintana7620f1a2010-03-16 15:58:44 -07001386 }
1387 }
1388 }
1389
Dianne Hackborn231cc602009-04-27 17:10:36 -07001390 private SyncStatusInfo getOrCreateSyncStatusLocked(int authorityId) {
1391 SyncStatusInfo status = mSyncStatus.get(authorityId);
1392 if (status == null) {
1393 status = new SyncStatusInfo(authorityId);
1394 mSyncStatus.put(authorityId, status);
1395 }
1396 return status;
1397 }
Costin Manolache360e4542009-09-04 13:36:04 -07001398
Dianne Hackborn55280a92009-05-07 15:53:46 -07001399 public void writeAllState() {
1400 synchronized (mAuthorities) {
1401 // Account info is always written so no need to do it here.
Dianne Hackborn55280a92009-05-07 15:53:46 -07001402 writeStatusLocked();
1403 writeStatisticsLocked();
1404 }
1405 }
Costin Manolache360e4542009-09-04 13:36:04 -07001406
Dianne Hackborn231cc602009-04-27 17:10:36 -07001407 /**
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001408 * public for testing
1409 */
1410 public void clearAndReadState() {
1411 synchronized (mAuthorities) {
1412 mAuthorities.clear();
1413 mAccounts.clear();
Matthew Williamsfa774182013-06-18 15:44:11 -07001414 mServices.clear();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001415 mSyncStatus.clear();
1416 mSyncHistory.clear();
1417
1418 readAccountInfoLocked();
1419 readStatusLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001420 readStatisticsLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001421 readAndDeleteLegacyAccountInfoLocked();
1422 writeAccountInfoLocked();
1423 writeStatusLocked();
Fred Quintana77c560f2010-03-29 22:20:26 -07001424 writeStatisticsLocked();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001425 }
1426 }
1427
1428 /**
Dianne Hackborn231cc602009-04-27 17:10:36 -07001429 * Read all account information back in to the initial engine state.
1430 */
1431 private void readAccountInfoLocked() {
Fred Quintana77c560f2010-03-29 22:20:26 -07001432 int highestAuthorityId = -1;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001433 FileInputStream fis = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 try {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001435 fis = mAccountInfoFile.openRead();
Matthew Williamsba352712013-08-13 15:53:31 -07001436 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001437 Slog.v(TAG_FILE, "Reading " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001438 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001439 XmlPullParser parser = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001440 parser.setInput(fis, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001441 int eventType = parser.getEventType();
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001442 while (eventType != XmlPullParser.START_TAG &&
1443 eventType != XmlPullParser.END_DOCUMENT) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001444 eventType = parser.next();
1445 }
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001446 if (eventType == XmlPullParser.END_DOCUMENT) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001447 Slog.i(TAG, "No initial accounts");
Narayan Kamath2ac3cb72014-01-06 11:31:35 +00001448 return;
1449 }
1450
Dianne Hackborn231cc602009-04-27 17:10:36 -07001451 String tagName = parser.getName();
1452 if ("accounts".equals(tagName)) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001453 String listen = parser.getAttributeValue(null, XML_ATTR_LISTEN_FOR_TICKLES);
Fred Quintanac2e46912010-03-15 16:10:44 -07001454 String versionString = parser.getAttributeValue(null, "version");
1455 int version;
1456 try {
1457 version = (versionString == null) ? 0 : Integer.parseInt(versionString);
1458 } catch (NumberFormatException e) {
1459 version = 0;
1460 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001461 String nextIdString = parser.getAttributeValue(null, XML_ATTR_NEXT_AUTHORITY_ID);
Fred Quintana77c560f2010-03-29 22:20:26 -07001462 try {
1463 int id = (nextIdString == null) ? 0 : Integer.parseInt(nextIdString);
1464 mNextAuthorityId = Math.max(mNextAuthorityId, id);
1465 } catch (NumberFormatException e) {
1466 // don't care
Fred Quintanac2e46912010-03-15 16:10:44 -07001467 }
Ashish Sharma69d95de2012-04-11 17:27:24 -07001468 String offsetString = parser.getAttributeValue(null, XML_ATTR_SYNC_RANDOM_OFFSET);
1469 try {
1470 mSyncRandomOffset = (offsetString == null) ? 0 : Integer.parseInt(offsetString);
1471 } catch (NumberFormatException e) {
1472 mSyncRandomOffset = 0;
1473 }
1474 if (mSyncRandomOffset == 0) {
1475 Random random = new Random(System.currentTimeMillis());
1476 mSyncRandomOffset = random.nextInt(86400);
1477 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001478 mMasterSyncAutomatically.put(0, listen == null || Boolean.parseBoolean(listen));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001479 eventType = parser.next();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001480 AuthorityInfo authority = null;
Matthew Williamsfa774182013-06-18 15:44:11 -07001481 PeriodicSync periodicSync = null;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001482 do {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001483 if (eventType == XmlPullParser.START_TAG) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001484 tagName = parser.getName();
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001485 if (parser.getDepth() == 2) {
1486 if ("authority".equals(tagName)) {
Fred Quintanac2e46912010-03-15 16:10:44 -07001487 authority = parseAuthority(parser, version);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001488 periodicSync = null;
Shreyas Basarge11cb4e22016-01-13 14:27:16 +00001489 if (authority != null) {
1490 if (authority.ident > highestAuthorityId) {
1491 highestAuthorityId = authority.ident;
1492 }
Shreyas Basargebae9ded2016-02-17 13:54:44 +00001493 } else {
1494 EventLog.writeEvent(0x534e4554, "26513719", -1,
1495 "Malformed authority");
Fred Quintana77c560f2010-03-29 22:20:26 -07001496 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001497 } else if (XML_TAG_LISTEN_FOR_TICKLES.equals(tagName)) {
1498 parseListenForTickles(parser);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001499 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001500 } else if (parser.getDepth() == 3) {
1501 if ("periodicSync".equals(tagName) && authority != null) {
1502 periodicSync = parsePeriodicSync(parser, authority);
1503 }
1504 } else if (parser.getDepth() == 4 && periodicSync != null) {
1505 if ("extra".equals(tagName)) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001506 parseExtra(parser, periodicSync.extras);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001507 }
1508 }
1509 }
1510 eventType = parser.next();
1511 } while (eventType != XmlPullParser.END_DOCUMENT);
1512 }
1513 } catch (XmlPullParserException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001514 Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001515 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001516 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001517 if (fis == null) Slog.i(TAG, "No initial accounts");
1518 else Slog.w(TAG, "Error reading accounts", e);
Fred Quintanac2e46912010-03-15 16:10:44 -07001519 return;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001520 } finally {
Fred Quintana77c560f2010-03-29 22:20:26 -07001521 mNextAuthorityId = Math.max(highestAuthorityId + 1, mNextAuthorityId);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001522 if (fis != null) {
1523 try {
1524 fis.close();
1525 } catch (java.io.IOException e1) {
1526 }
1527 }
1528 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001529
Fred Quintana77c560f2010-03-29 22:20:26 -07001530 maybeMigrateSettingsForRenamedAuthorities();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001531 }
Costin Manolache360e4542009-09-04 13:36:04 -07001532
Fred Quintanafb084402010-03-23 17:57:03 -07001533 /**
Matthew Williamsba352712013-08-13 15:53:31 -07001534 * Ensure the old pending.bin is deleted, as it has been changed to pending.xml.
1535 * pending.xml was used starting in KLP.
1536 * @param syncDir directory where the sync files are located.
1537 */
1538 private void maybeDeleteLegacyPendingInfoLocked(File syncDir) {
1539 File file = new File(syncDir, "pending.bin");
1540 if (!file.exists()) {
1541 return;
1542 } else {
1543 file.delete();
1544 }
1545 }
1546
1547 /**
Fred Quintanafb084402010-03-23 17:57:03 -07001548 * some authority names have changed. copy over their settings and delete the old ones
1549 * @return true if a change was made
1550 */
1551 private boolean maybeMigrateSettingsForRenamedAuthorities() {
1552 boolean writeNeeded = false;
1553
1554 ArrayList<AuthorityInfo> authoritiesToRemove = new ArrayList<AuthorityInfo>();
1555 final int N = mAuthorities.size();
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001556 for (int i = 0; i < N; i++) {
Fred Quintanafb084402010-03-23 17:57:03 -07001557 AuthorityInfo authority = mAuthorities.valueAt(i);
1558 // skip this authority if it isn't one of the renamed ones
Matthew Williams8ef22042013-07-26 12:56:39 -07001559 final String newAuthorityName = sAuthorityRenames.get(authority.target.provider);
Fred Quintanafb084402010-03-23 17:57:03 -07001560 if (newAuthorityName == null) {
1561 continue;
1562 }
1563
1564 // remember this authority so we can remove it later. we can't remove it
1565 // now without messing up this loop iteration
1566 authoritiesToRemove.add(authority);
1567
1568 // this authority isn't enabled, no need to copy it to the new authority name since
1569 // the default is "disabled"
1570 if (!authority.enabled) {
1571 continue;
1572 }
1573
1574 // if we already have a record of this new authority then don't copy over the settings
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001575 EndPoint newInfo =
Matthew Williams8ef22042013-07-26 12:56:39 -07001576 new EndPoint(authority.target.account,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001577 newAuthorityName,
Matthew Williams8ef22042013-07-26 12:56:39 -07001578 authority.target.userId);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001579 if (getAuthorityLocked(newInfo, "cleanup") != null) {
Fred Quintanafb084402010-03-23 17:57:03 -07001580 continue;
1581 }
1582
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001583 AuthorityInfo newAuthority =
1584 getOrCreateAuthorityLocked(newInfo, -1 /* ident */, false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001585 newAuthority.enabled = true;
1586 writeNeeded = true;
1587 }
1588
1589 for (AuthorityInfo authorityInfo : authoritiesToRemove) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001590 removeAuthorityLocked(
Matthew Williams8ef22042013-07-26 12:56:39 -07001591 authorityInfo.target.account,
1592 authorityInfo.target.userId,
1593 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001594 false /* doWrite */);
Fred Quintanafb084402010-03-23 17:57:03 -07001595 writeNeeded = true;
1596 }
1597
1598 return writeNeeded;
1599 }
1600
Amith Yamasani04e0d262012-02-14 11:50:53 -08001601 private void parseListenForTickles(XmlPullParser parser) {
1602 String user = parser.getAttributeValue(null, XML_ATTR_USER);
1603 int userId = 0;
1604 try {
1605 userId = Integer.parseInt(user);
1606 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001607 Slog.e(TAG, "error parsing the user for listen-for-tickles", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001608 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001609 Slog.e(TAG, "the user in listen-for-tickles is null", e);
Amith Yamasani04e0d262012-02-14 11:50:53 -08001610 }
1611 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
1612 boolean listen = enabled == null || Boolean.parseBoolean(enabled);
1613 mMasterSyncAutomatically.put(userId, listen);
1614 }
1615
Fred Quintanac2e46912010-03-15 16:10:44 -07001616 private AuthorityInfo parseAuthority(XmlPullParser parser, int version) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001617 AuthorityInfo authority = null;
1618 int id = -1;
1619 try {
Matthew Williamsfa774182013-06-18 15:44:11 -07001620 id = Integer.parseInt(parser.getAttributeValue(null, "id"));
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001621 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001622 Slog.e(TAG, "error parsing the id of the authority", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001623 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001624 Slog.e(TAG, "the id of the authority is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001625 }
1626 if (id >= 0) {
Fred Quintanafb084402010-03-23 17:57:03 -07001627 String authorityName = parser.getAttributeValue(null, "authority");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001628 String enabled = parser.getAttributeValue(null, XML_ATTR_ENABLED);
Fred Quintanafb084402010-03-23 17:57:03 -07001629 String syncable = parser.getAttributeValue(null, "syncable");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001630 String accountName = parser.getAttributeValue(null, "account");
1631 String accountType = parser.getAttributeValue(null, "type");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001632 String user = parser.getAttributeValue(null, XML_ATTR_USER);
Matthew Williamsfa774182013-06-18 15:44:11 -07001633 String packageName = parser.getAttributeValue(null, "package");
1634 String className = parser.getAttributeValue(null, "class");
Amith Yamasani04e0d262012-02-14 11:50:53 -08001635 int userId = user == null ? 0 : Integer.parseInt(user);
Matthew Williams8ef22042013-07-26 12:56:39 -07001636 if (accountType == null && packageName == null) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001637 accountType = "com.google";
Matthew Williams53abfdb2015-06-10 20:06:37 -07001638 syncable = String.valueOf(AuthorityInfo.NOT_INITIALIZED);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001639 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001640 authority = mAuthorities.get(id);
Matthew Williamsba352712013-08-13 15:53:31 -07001641 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001642 Slog.v(TAG_FILE, "Adding authority:"
Matthew Williams8ef22042013-07-26 12:56:39 -07001643 + " account=" + accountName
1644 + " accountType=" + accountType
1645 + " auth=" + authorityName
1646 + " package=" + packageName
1647 + " class=" + className
Matthew Williamsba352712013-08-13 15:53:31 -07001648 + " user=" + userId
1649 + " enabled=" + enabled
1650 + " syncable=" + syncable);
1651 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001652 if (authority == null) {
Matthew Williamsba352712013-08-13 15:53:31 -07001653 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001654 Slog.v(TAG_FILE, "Creating authority entry");
Matthew Williamsfa774182013-06-18 15:44:11 -07001655 }
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001656 EndPoint info = null;
Matthew Williams8ef22042013-07-26 12:56:39 -07001657 if (accountName != null && authorityName != null) {
1658 info = new EndPoint(
1659 new Account(accountName, accountType),
1660 authorityName, userId);
Matthew Williamsfa774182013-06-18 15:44:11 -07001661 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001662 if (info != null) {
1663 authority = getOrCreateAuthorityLocked(info, id, false);
1664 // If the version is 0 then we are upgrading from a file format that did not
1665 // know about periodic syncs. In that case don't clear the list since we
1666 // want the default, which is a daily periodic sync.
1667 // Otherwise clear out this default list since we will populate it later with
1668 // the periodic sync descriptions that are read from the configuration file.
1669 if (version > 0) {
1670 authority.periodicSyncs.clear();
1671 }
Fred Quintanac2e46912010-03-15 16:10:44 -07001672 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001673 }
1674 if (authority != null) {
1675 authority.enabled = enabled == null || Boolean.parseBoolean(enabled);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001676 try {
1677 authority.syncable = (syncable == null) ?
1678 AuthorityInfo.NOT_INITIALIZED : Integer.parseInt(syncable);
1679 } catch (NumberFormatException e) {
1680 // On L we stored this as {"unknown", "true", "false"} so fall back to this
1681 // format.
1682 if ("unknown".equals(syncable)) {
1683 authority.syncable = AuthorityInfo.NOT_INITIALIZED;
1684 } else {
1685 authority.syncable = Boolean.parseBoolean(syncable) ?
1686 AuthorityInfo.SYNCABLE : AuthorityInfo.NOT_SYNCABLE;
1687 }
1688
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001689 }
1690 } else {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001691 Slog.w(TAG, "Failure adding authority: account="
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001692 + accountName + " auth=" + authorityName
1693 + " enabled=" + enabled
1694 + " syncable=" + syncable);
1695 }
1696 }
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001697 return authority;
1698 }
1699
Matthew Williamsfa774182013-06-18 15:44:11 -07001700 /**
1701 * Parse a periodic sync from accounts.xml. Sets the bundle to be empty.
1702 */
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001703 private PeriodicSync parsePeriodicSync(XmlPullParser parser, AuthorityInfo authorityInfo) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001704 Bundle extras = new Bundle(); // Gets filled in later.
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001705 String periodValue = parser.getAttributeValue(null, "period");
Matthew Williamsfa774182013-06-18 15:44:11 -07001706 String flexValue = parser.getAttributeValue(null, "flex");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001707 final long period;
Matthew Williamsfa774182013-06-18 15:44:11 -07001708 long flextime;
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001709 try {
1710 period = Long.parseLong(periodValue);
1711 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001712 Slog.e(TAG, "error parsing the period of a periodic sync", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001713 return null;
1714 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001715 Slog.e(TAG, "the period of a periodic sync is null", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001716 return null;
1717 }
Matthew Williamsfa774182013-06-18 15:44:11 -07001718 try {
1719 flextime = Long.parseLong(flexValue);
1720 } catch (NumberFormatException e) {
Matthew Williamsfa774182013-06-18 15:44:11 -07001721 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001722 Slog.e(TAG, "Error formatting value parsed for periodic sync flex: " + flexValue
Matthew Williams8ef22042013-07-26 12:56:39 -07001723 + ", using default: "
1724 + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001725 } catch (NullPointerException expected) {
1726 flextime = calculateDefaultFlexTime(period);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001727 Slog.d(TAG, "No flex time specified for this sync, using a default. period: "
1728 + period + " flex: " + flextime);
Matthew Williamsfa774182013-06-18 15:44:11 -07001729 }
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001730 PeriodicSync periodicSync;
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001731 periodicSync =
Matthew Williams8ef22042013-07-26 12:56:39 -07001732 new PeriodicSync(authorityInfo.target.account,
1733 authorityInfo.target.provider,
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001734 extras,
Matthew Williamsfa774182013-06-18 15:44:11 -07001735 period, flextime);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001736 authorityInfo.periodicSyncs.add(periodicSync);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001737 return periodicSync;
1738 }
1739
Matthew Williamsfa774182013-06-18 15:44:11 -07001740 private void parseExtra(XmlPullParser parser, Bundle extras) {
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001741 String name = parser.getAttributeValue(null, "name");
1742 String type = parser.getAttributeValue(null, "type");
1743 String value1 = parser.getAttributeValue(null, "value1");
1744 String value2 = parser.getAttributeValue(null, "value2");
1745
1746 try {
1747 if ("long".equals(type)) {
1748 extras.putLong(name, Long.parseLong(value1));
1749 } else if ("integer".equals(type)) {
1750 extras.putInt(name, Integer.parseInt(value1));
1751 } else if ("double".equals(type)) {
1752 extras.putDouble(name, Double.parseDouble(value1));
1753 } else if ("float".equals(type)) {
1754 extras.putFloat(name, Float.parseFloat(value1));
1755 } else if ("boolean".equals(type)) {
1756 extras.putBoolean(name, Boolean.parseBoolean(value1));
1757 } else if ("string".equals(type)) {
1758 extras.putString(name, value1);
1759 } else if ("account".equals(type)) {
1760 extras.putParcelable(name, new Account(value1, value2));
1761 }
1762 } catch (NumberFormatException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001763 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001764 } catch (NullPointerException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001765 Slog.e(TAG, "error parsing bundle value", e);
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001766 }
1767 }
1768
Dianne Hackborn231cc602009-04-27 17:10:36 -07001769 /**
1770 * Write all account information to the account file.
1771 */
1772 private void writeAccountInfoLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001773 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001774 Slog.v(TAG_FILE, "Writing new " + mAccountInfoFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001775 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001776 FileOutputStream fos = null;
Costin Manolache360e4542009-09-04 13:36:04 -07001777
Dianne Hackborn231cc602009-04-27 17:10:36 -07001778 try {
1779 fos = mAccountInfoFile.startWrite();
1780 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001781 out.setOutput(fos, StandardCharsets.UTF_8.name());
Dianne Hackborn231cc602009-04-27 17:10:36 -07001782 out.startDocument(null, true);
1783 out.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
Costin Manolache360e4542009-09-04 13:36:04 -07001784
Dianne Hackborn231cc602009-04-27 17:10:36 -07001785 out.startTag(null, "accounts");
Fred Quintanac2e46912010-03-15 16:10:44 -07001786 out.attribute(null, "version", Integer.toString(ACCOUNTS_VERSION));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001787 out.attribute(null, XML_ATTR_NEXT_AUTHORITY_ID, Integer.toString(mNextAuthorityId));
Ashish Sharma69d95de2012-04-11 17:27:24 -07001788 out.attribute(null, XML_ATTR_SYNC_RANDOM_OFFSET, Integer.toString(mSyncRandomOffset));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001789
1790 // Write the Sync Automatically flags for each user
1791 final int M = mMasterSyncAutomatically.size();
1792 for (int m = 0; m < M; m++) {
1793 int userId = mMasterSyncAutomatically.keyAt(m);
1794 Boolean listen = mMasterSyncAutomatically.valueAt(m);
1795 out.startTag(null, XML_TAG_LISTEN_FOR_TICKLES);
1796 out.attribute(null, XML_ATTR_USER, Integer.toString(userId));
1797 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(listen));
1798 out.endTag(null, XML_TAG_LISTEN_FOR_TICKLES);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001799 }
Costin Manolache360e4542009-09-04 13:36:04 -07001800
Dianne Hackborn231cc602009-04-27 17:10:36 -07001801 final int N = mAuthorities.size();
Matthew Williamsfa774182013-06-18 15:44:11 -07001802 for (int i = 0; i < N; i++) {
Costin Manolache360e4542009-09-04 13:36:04 -07001803 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001804 EndPoint info = authority.target;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001805 out.startTag(null, "authority");
1806 out.attribute(null, "id", Integer.toString(authority.ident));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001807 out.attribute(null, XML_ATTR_USER, Integer.toString(info.userId));
Amith Yamasani04e0d262012-02-14 11:50:53 -08001808 out.attribute(null, XML_ATTR_ENABLED, Boolean.toString(authority.enabled));
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001809 out.attribute(null, "account", info.account.name);
1810 out.attribute(null, "type", info.account.type);
1811 out.attribute(null, "authority", info.provider);
Matthew Williams53abfdb2015-06-10 20:06:37 -07001812 out.attribute(null, "syncable", Integer.toString(authority.syncable));
Dianne Hackborn231cc602009-04-27 17:10:36 -07001813 out.endTag(null, "authority");
1814 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001815 out.endTag(null, "accounts");
Dianne Hackborn231cc602009-04-27 17:10:36 -07001816 out.endDocument();
Dianne Hackborn231cc602009-04-27 17:10:36 -07001817 mAccountInfoFile.finishWrite(fos);
1818 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001819 Slog.w(TAG, "Error writing accounts", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001820 if (fos != null) {
1821 mAccountInfoFile.failWrite(fos);
1822 }
1823 }
1824 }
Costin Manolache360e4542009-09-04 13:36:04 -07001825
Dianne Hackborn231cc602009-04-27 17:10:36 -07001826 static int getIntColumn(Cursor c, String name) {
1827 return c.getInt(c.getColumnIndex(name));
1828 }
Costin Manolache360e4542009-09-04 13:36:04 -07001829
Dianne Hackborn231cc602009-04-27 17:10:36 -07001830 static long getLongColumn(Cursor c, String name) {
1831 return c.getLong(c.getColumnIndex(name));
1832 }
Costin Manolache360e4542009-09-04 13:36:04 -07001833
Dianne Hackborn231cc602009-04-27 17:10:36 -07001834 /**
1835 * Load sync engine state from the old syncmanager database, and then
1836 * erase it. Note that we don't deal with pending operations, active
1837 * sync, or history.
1838 */
Fred Quintana77c560f2010-03-29 22:20:26 -07001839 private void readAndDeleteLegacyAccountInfoLocked() {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001840 // Look for old database to initialize from.
1841 File file = mContext.getDatabasePath("syncmanager.db");
1842 if (!file.exists()) {
1843 return;
1844 }
1845 String path = file.getPath();
1846 SQLiteDatabase db = null;
1847 try {
1848 db = SQLiteDatabase.openDatabase(path, null,
1849 SQLiteDatabase.OPEN_READONLY);
1850 } catch (SQLiteException e) {
1851 }
Costin Manolache360e4542009-09-04 13:36:04 -07001852
Dianne Hackborn231cc602009-04-27 17:10:36 -07001853 if (db != null) {
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001854 final boolean hasType = db.getVersion() >= 11;
Costin Manolache360e4542009-09-04 13:36:04 -07001855
Dianne Hackborn231cc602009-04-27 17:10:36 -07001856 // Copy in all of the status information, as well as accounts.
Matthew Williamsba352712013-08-13 15:53:31 -07001857 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001858 Slog.v(TAG_FILE, "Reading legacy sync accounts db");
Matthew Williamsba352712013-08-13 15:53:31 -07001859 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001860 SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1861 qb.setTables("stats, status");
1862 HashMap<String,String> map = new HashMap<String,String>();
1863 map.put("_id", "status._id as _id");
1864 map.put("account", "stats.account as account");
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001865 if (hasType) {
1866 map.put("account_type", "stats.account_type as account_type");
1867 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001868 map.put("authority", "stats.authority as authority");
1869 map.put("totalElapsedTime", "totalElapsedTime");
1870 map.put("numSyncs", "numSyncs");
1871 map.put("numSourceLocal", "numSourceLocal");
1872 map.put("numSourcePoll", "numSourcePoll");
1873 map.put("numSourceServer", "numSourceServer");
1874 map.put("numSourceUser", "numSourceUser");
1875 map.put("lastSuccessSource", "lastSuccessSource");
1876 map.put("lastSuccessTime", "lastSuccessTime");
1877 map.put("lastFailureSource", "lastFailureSource");
1878 map.put("lastFailureTime", "lastFailureTime");
1879 map.put("lastFailureMesg", "lastFailureMesg");
1880 map.put("pending", "pending");
1881 qb.setProjectionMap(map);
1882 qb.appendWhere("stats._id = status.stats_id");
1883 Cursor c = qb.query(db, null, null, null, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 while (c.moveToNext()) {
Dianne Hackborn231cc602009-04-27 17:10:36 -07001885 String accountName = c.getString(c.getColumnIndex("account"));
Dianne Hackborn2d5ed1f2009-05-06 15:22:38 -07001886 String accountType = hasType
1887 ? c.getString(c.getColumnIndex("account_type")) : null;
Dianne Hackborn7a135592009-05-06 00:28:37 -07001888 if (accountType == null) {
Costin Manolache3348f142009-09-29 18:58:36 -07001889 accountType = "com.google";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001891 String authorityName = c.getString(c.getColumnIndex("authority"));
Matthew Williams56dbf8f2013-07-26 12:56:39 -07001892 AuthorityInfo authority =
1893 this.getOrCreateAuthorityLocked(
1894 new EndPoint(new Account(accountName, accountType),
1895 authorityName,
1896 0 /* legacy is single-user */)
1897 , -1,
1898 false);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001899 if (authority != null) {
1900 int i = mSyncStatus.size();
1901 boolean found = false;
1902 SyncStatusInfo st = null;
1903 while (i > 0) {
1904 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001905 st = mSyncStatus.valueAt(i);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001906 if (st.authorityId == authority.ident) {
1907 found = true;
1908 break;
1909 }
1910 }
1911 if (!found) {
1912 st = new SyncStatusInfo(authority.ident);
1913 mSyncStatus.put(authority.ident, st);
1914 }
1915 st.totalElapsedTime = getLongColumn(c, "totalElapsedTime");
1916 st.numSyncs = getIntColumn(c, "numSyncs");
1917 st.numSourceLocal = getIntColumn(c, "numSourceLocal");
1918 st.numSourcePoll = getIntColumn(c, "numSourcePoll");
1919 st.numSourceServer = getIntColumn(c, "numSourceServer");
1920 st.numSourceUser = getIntColumn(c, "numSourceUser");
Fred Quintanac5d1c6d2010-01-27 12:17:49 -08001921 st.numSourcePeriodic = 0;
Dianne Hackborn231cc602009-04-27 17:10:36 -07001922 st.lastSuccessSource = getIntColumn(c, "lastSuccessSource");
1923 st.lastSuccessTime = getLongColumn(c, "lastSuccessTime");
1924 st.lastFailureSource = getIntColumn(c, "lastFailureSource");
1925 st.lastFailureTime = getLongColumn(c, "lastFailureTime");
1926 st.lastFailureMesg = c.getString(c.getColumnIndex("lastFailureMesg"));
1927 st.pending = getIntColumn(c, "pending") != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 }
Costin Manolache360e4542009-09-04 13:36:04 -07001930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001932
Dianne Hackborn231cc602009-04-27 17:10:36 -07001933 // Retrieve the settings.
1934 qb = new SQLiteQueryBuilder();
1935 qb.setTables("settings");
1936 c = qb.query(db, null, null, null, null, null, null);
1937 while (c.moveToNext()) {
1938 String name = c.getString(c.getColumnIndex("name"));
1939 String value = c.getString(c.getColumnIndex("value"));
1940 if (name == null) continue;
1941 if (name.equals("listen_for_tickles")) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08001942 setMasterSyncAutomatically(value == null || Boolean.parseBoolean(value), 0);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001943 } else if (name.startsWith("sync_provider_")) {
1944 String provider = name.substring("sync_provider_".length(),
1945 name.length());
Fred Quintanaac9385e2009-06-22 18:00:59 -07001946 int i = mAuthorities.size();
1947 while (i > 0) {
1948 i--;
Costin Manolache360e4542009-09-04 13:36:04 -07001949 AuthorityInfo authority = mAuthorities.valueAt(i);
Matthew Williams8ef22042013-07-26 12:56:39 -07001950 if (authority.target.provider.equals(provider)) {
Fred Quintanaac9385e2009-06-22 18:00:59 -07001951 authority.enabled = value == null || Boolean.parseBoolean(value);
Fred Quintana5e787c42009-08-16 23:13:53 -07001952 authority.syncable = 1;
Fred Quintanaac9385e2009-06-22 18:00:59 -07001953 }
1954 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 }
Costin Manolache360e4542009-09-04 13:36:04 -07001957
Dianne Hackborn231cc602009-04-27 17:10:36 -07001958 c.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001959
Dianne Hackborn231cc602009-04-27 17:10:36 -07001960 db.close();
Costin Manolache360e4542009-09-04 13:36:04 -07001961
Dianne Hackborn231cc602009-04-27 17:10:36 -07001962 (new File(path)).delete();
1963 }
1964 }
Costin Manolache360e4542009-09-04 13:36:04 -07001965
Dianne Hackborn231cc602009-04-27 17:10:36 -07001966 public static final int STATUS_FILE_END = 0;
1967 public static final int STATUS_FILE_ITEM = 100;
Costin Manolache360e4542009-09-04 13:36:04 -07001968
Dianne Hackborn231cc602009-04-27 17:10:36 -07001969 /**
1970 * Read all sync status back in to the initial engine state.
1971 */
1972 private void readStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07001973 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001974 Slog.v(TAG_FILE, "Reading " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07001975 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001976 try {
1977 byte[] data = mStatusFile.readFully();
1978 Parcel in = Parcel.obtain();
1979 in.unmarshall(data, 0, data.length);
1980 in.setDataPosition(0);
1981 int token;
1982 while ((token=in.readInt()) != STATUS_FILE_END) {
1983 if (token == STATUS_FILE_ITEM) {
1984 SyncStatusInfo status = new SyncStatusInfo(in);
1985 if (mAuthorities.indexOfKey(status.authorityId) >= 0) {
1986 status.pending = false;
Matthew Williamsba352712013-08-13 15:53:31 -07001987 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001988 Slog.v(TAG_FILE, "Adding status for id " + status.authorityId);
Matthew Williamsba352712013-08-13 15:53:31 -07001989 }
Dianne Hackborn231cc602009-04-27 17:10:36 -07001990 mSyncStatus.put(status.authorityId, status);
1991 }
1992 } else {
1993 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001994 Slog.w(TAG, "Unknown status token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07001995 break;
1996 }
1997 }
1998 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00001999 Slog.i(TAG, "No initial status");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002000 }
2001 }
Costin Manolache360e4542009-09-04 13:36:04 -07002002
Dianne Hackborn231cc602009-04-27 17:10:36 -07002003 /**
2004 * Write all sync status to the sync status file.
2005 */
2006 private void writeStatusLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002007 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002008 Slog.v(TAG_FILE, "Writing new " + mStatusFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002009 }
Costin Manolache360e4542009-09-04 13:36:04 -07002010
Dianne Hackborn231cc602009-04-27 17:10:36 -07002011 // The file is being written, so we don't need to have a scheduled
2012 // write until the next change.
2013 removeMessages(MSG_WRITE_STATUS);
Costin Manolache360e4542009-09-04 13:36:04 -07002014
Dianne Hackborn231cc602009-04-27 17:10:36 -07002015 FileOutputStream fos = null;
2016 try {
2017 fos = mStatusFile.startWrite();
2018 Parcel out = Parcel.obtain();
2019 final int N = mSyncStatus.size();
2020 for (int i=0; i<N; i++) {
2021 SyncStatusInfo status = mSyncStatus.valueAt(i);
2022 out.writeInt(STATUS_FILE_ITEM);
2023 status.writeToParcel(out, 0);
2024 }
2025 out.writeInt(STATUS_FILE_END);
2026 fos.write(out.marshall());
2027 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002028
Dianne Hackborn231cc602009-04-27 17:10:36 -07002029 mStatusFile.finishWrite(fos);
2030 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002031 Slog.w(TAG, "Error writing status", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002032 if (fos != null) {
2033 mStatusFile.failWrite(fos);
2034 }
2035 }
2036 }
Costin Manolache360e4542009-09-04 13:36:04 -07002037
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002038 private void requestSync(AuthorityInfo authorityInfo, int reason, Bundle extras) {
2039 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2040 && mSyncRequestListener != null) {
Matthew Williams8ef22042013-07-26 12:56:39 -07002041 mSyncRequestListener.onSyncRequest(authorityInfo.target, reason, extras);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002042 } else {
2043 SyncRequest.Builder req =
2044 new SyncRequest.Builder()
Nick Kralevich69002ae2013-10-19 08:43:08 -07002045 .syncOnce()
Matthew Williams8ef22042013-07-26 12:56:39 -07002046 .setExtras(extras);
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002047 req.setSyncAdapter(authorityInfo.target.account, authorityInfo.target.provider);
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002048 ContentResolver.requestSync(req.build());
2049 }
2050 }
2051
Alon Albert57286f92012-10-09 14:21:38 -07002052 private void requestSync(Account account, int userId, int reason, String authority,
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002053 Bundle extras) {
Amith Yamasani04e0d262012-02-14 11:50:53 -08002054 // If this is happening in the system process, then call the syncrequest listener
2055 // to make a request back to the SyncManager directly.
2056 // If this is probably a test instance, then call back through the ContentResolver
2057 // which will know which userId to apply based on the Binder id.
2058 if (android.os.Process.myUid() == android.os.Process.SYSTEM_UID
2059 && mSyncRequestListener != null) {
Matthew Williams56dbf8f2013-07-26 12:56:39 -07002060 mSyncRequestListener.onSyncRequest(
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002061 new EndPoint(account, authority, userId),
2062 reason,
2063 extras);
Amith Yamasani04e0d262012-02-14 11:50:53 -08002064 } else {
2065 ContentResolver.requestSync(account, authority, extras);
2066 }
2067 }
2068
Dianne Hackborn231cc602009-04-27 17:10:36 -07002069 public static final int STATISTICS_FILE_END = 0;
2070 public static final int STATISTICS_FILE_ITEM_OLD = 100;
2071 public static final int STATISTICS_FILE_ITEM = 101;
Costin Manolache360e4542009-09-04 13:36:04 -07002072
Dianne Hackborn231cc602009-04-27 17:10:36 -07002073 /**
2074 * Read all sync statistics back in to the initial engine state.
2075 */
2076 private void readStatisticsLocked() {
2077 try {
2078 byte[] data = mStatisticsFile.readFully();
2079 Parcel in = Parcel.obtain();
2080 in.unmarshall(data, 0, data.length);
2081 in.setDataPosition(0);
2082 int token;
2083 int index = 0;
2084 while ((token=in.readInt()) != STATISTICS_FILE_END) {
2085 if (token == STATISTICS_FILE_ITEM
2086 || token == STATISTICS_FILE_ITEM_OLD) {
2087 int day = in.readInt();
2088 if (token == STATISTICS_FILE_ITEM_OLD) {
2089 day = day - 2009 + 14245; // Magic!
2090 }
2091 DayStats ds = new DayStats(day);
2092 ds.successCount = in.readInt();
2093 ds.successTime = in.readLong();
2094 ds.failureCount = in.readInt();
2095 ds.failureTime = in.readLong();
2096 if (index < mDayStats.length) {
2097 mDayStats[index] = ds;
2098 index++;
2099 }
2100 } else {
2101 // Ooops.
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002102 Slog.w(TAG, "Unknown stats token: " + token);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002103 break;
2104 }
2105 }
2106 } catch (java.io.IOException e) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002107 Slog.i(TAG, "No initial statistics");
Dianne Hackborn231cc602009-04-27 17:10:36 -07002108 }
2109 }
Costin Manolache360e4542009-09-04 13:36:04 -07002110
Dianne Hackborn231cc602009-04-27 17:10:36 -07002111 /**
2112 * Write all sync statistics to the sync status file.
2113 */
2114 private void writeStatisticsLocked() {
Matthew Williamsba352712013-08-13 15:53:31 -07002115 if (Log.isLoggable(TAG_FILE, Log.VERBOSE)) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002116 Slog.v(TAG, "Writing new " + mStatisticsFile.getBaseFile());
Matthew Williamsba352712013-08-13 15:53:31 -07002117 }
Costin Manolache360e4542009-09-04 13:36:04 -07002118
Dianne Hackborn231cc602009-04-27 17:10:36 -07002119 // The file is being written, so we don't need to have a scheduled
2120 // write until the next change.
2121 removeMessages(MSG_WRITE_STATISTICS);
Costin Manolache360e4542009-09-04 13:36:04 -07002122
Dianne Hackborn231cc602009-04-27 17:10:36 -07002123 FileOutputStream fos = null;
2124 try {
2125 fos = mStatisticsFile.startWrite();
2126 Parcel out = Parcel.obtain();
2127 final int N = mDayStats.length;
2128 for (int i=0; i<N; i++) {
2129 DayStats ds = mDayStats[i];
2130 if (ds == null) {
2131 break;
2132 }
2133 out.writeInt(STATISTICS_FILE_ITEM);
2134 out.writeInt(ds.day);
2135 out.writeInt(ds.successCount);
2136 out.writeLong(ds.successTime);
2137 out.writeInt(ds.failureCount);
2138 out.writeLong(ds.failureTime);
2139 }
2140 out.writeInt(STATISTICS_FILE_END);
2141 fos.write(out.marshall());
2142 out.recycle();
Costin Manolache360e4542009-09-04 13:36:04 -07002143
Dianne Hackborn231cc602009-04-27 17:10:36 -07002144 mStatisticsFile.finishWrite(fos);
2145 } catch (java.io.IOException e1) {
Shreyas Basarge8c834c02016-01-07 13:53:16 +00002146 Slog.w(TAG, "Error writing stats", e1);
Dianne Hackborn231cc602009-04-27 17:10:36 -07002147 if (fos != null) {
2148 mStatisticsFile.failWrite(fos);
2149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
2151 }
Matthew Williamsfa774182013-06-18 15:44:11 -07002152
2153 /**
Marvin Paula6533252014-11-24 12:57:48 -08002154 * Let the BackupManager know that account sync settings have changed. This will trigger
2155 * {@link com.android.server.backup.SystemBackupAgent} to run.
2156 */
2157 public void queueBackup() {
2158 BackupManager.dataChanged("android");
2159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160}