blob: 91dfaf3d65b470900220155d66621fae415f322f [file] [log] [blame]
Christopher Tate487529a2009-04-29 14:03:25 -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
17package com.android.server;
18
Christopher Tate181fafa2009-05-14 11:12:14 -070019import android.app.ActivityManagerNative;
Christopher Tate1bb69062010-02-19 17:02:12 -080020import android.app.ActivityThread;
Christopher Tateb6787f22009-07-02 17:40:45 -070021import android.app.AlarmManager;
Christopher Tate181fafa2009-05-14 11:12:14 -070022import android.app.IActivityManager;
23import android.app.IApplicationThread;
24import android.app.IBackupAgent;
Christopher Tateb6787f22009-07-02 17:40:45 -070025import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080026import android.app.backup.RestoreSet;
27import android.app.backup.IBackupManager;
28import android.app.backup.IRestoreObserver;
29import android.app.backup.IRestoreSession;
Christopher Tate3799bc22009-05-06 16:13:56 -070030import android.content.BroadcastReceiver;
Dan Egnor87a02bc2009-06-17 02:30:10 -070031import android.content.ComponentName;
Christopher Tate487529a2009-04-29 14:03:25 -070032import android.content.Context;
33import android.content.Intent;
Christopher Tate3799bc22009-05-06 16:13:56 -070034import android.content.IntentFilter;
Dan Egnor87a02bc2009-06-17 02:30:10 -070035import android.content.ServiceConnection;
Christopher Tate181fafa2009-05-14 11:12:14 -070036import android.content.pm.ApplicationInfo;
Christopher Tatec7b31e32009-06-10 15:49:30 -070037import android.content.pm.IPackageDataObserver;
Christopher Tate1bb69062010-02-19 17:02:12 -080038import android.content.pm.IPackageManager;
Christopher Tate7b881282009-06-07 13:52:37 -070039import android.content.pm.PackageInfo;
Dan Egnor87a02bc2009-06-17 02:30:10 -070040import android.content.pm.PackageManager;
Christopher Tateabce4e82009-06-18 18:35:32 -070041import android.content.pm.Signature;
Oscar Montemayora8529f62009-11-18 10:14:20 -080042import android.content.pm.PackageManager.NameNotFoundException;
Christopher Tate3799bc22009-05-06 16:13:56 -070043import android.net.Uri;
Christopher Tate487529a2009-04-29 14:03:25 -070044import android.os.Binder;
Christopher Tate3799bc22009-05-06 16:13:56 -070045import android.os.Bundle;
Christopher Tate22b87872009-05-04 16:41:53 -070046import android.os.Environment;
Christopher Tate487529a2009-04-29 14:03:25 -070047import android.os.Handler;
Christopher Tate44a27902010-01-27 17:15:49 -080048import android.os.HandlerThread;
Christopher Tate487529a2009-04-29 14:03:25 -070049import android.os.IBinder;
Christopher Tate44a27902010-01-27 17:15:49 -080050import android.os.Looper;
Christopher Tate487529a2009-04-29 14:03:25 -070051import android.os.Message;
Christopher Tate22b87872009-05-04 16:41:53 -070052import android.os.ParcelFileDescriptor;
Christopher Tateb6787f22009-07-02 17:40:45 -070053import android.os.PowerManager;
Christopher Tate043dadc2009-06-02 16:11:00 -070054import android.os.Process;
Christopher Tate487529a2009-04-29 14:03:25 -070055import android.os.RemoteException;
Dan Egnorbb9001c2009-07-27 12:20:13 -070056import android.os.SystemClock;
Oscar Montemayora8529f62009-11-18 10:14:20 -080057import android.provider.Settings;
Dan Egnorbb9001c2009-07-27 12:20:13 -070058import android.util.EventLog;
Joe Onorato8a9b2202010-02-26 18:56:32 -080059import android.util.Slog;
Christopher Tate487529a2009-04-29 14:03:25 -070060import android.util.SparseArray;
Christopher Tate44a27902010-01-27 17:15:49 -080061import android.util.SparseIntArray;
Christopher Tate487529a2009-04-29 14:03:25 -070062
Christopher Tated55e18a2009-09-21 10:12:59 -070063import com.android.internal.backup.BackupConstants;
Christopher Tate043dadc2009-06-02 16:11:00 -070064import com.android.internal.backup.IBackupTransport;
Oscar Montemayora8529f62009-11-18 10:14:20 -080065import com.android.internal.backup.LocalTransport;
Christopher Tate6aa41f42009-06-19 14:14:22 -070066import com.android.server.PackageManagerBackupAgent.Metadata;
Christopher Tate6785dd82009-06-18 15:58:25 -070067
Christopher Tatecde87f42009-06-12 12:55:53 -070068import java.io.EOFException;
Christopher Tate22b87872009-05-04 16:41:53 -070069import java.io.File;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070070import java.io.FileDescriptor;
Christopher Tate1168baa2010-02-17 13:03:40 -080071import java.io.FileNotFoundException;
Christopher Tate4cc86e12009-09-21 19:36:51 -070072import java.io.FileOutputStream;
Christopher Tatec7b31e32009-06-10 15:49:30 -070073import java.io.IOException;
Joe Onoratob1a7ffe2009-05-06 18:06:21 -070074import java.io.PrintWriter;
Christopher Tatecde87f42009-06-12 12:55:53 -070075import java.io.RandomAccessFile;
Joe Onorato8ad02812009-05-13 01:41:44 -040076import java.util.ArrayList;
77import java.util.HashMap;
Christopher Tate487529a2009-04-29 14:03:25 -070078import java.util.HashSet;
79import java.util.List;
Christopher Tate91717492009-06-26 21:07:13 -070080import java.util.Map;
Dan Egnorc1c49c02009-10-30 17:35:39 -070081import java.util.Random;
Christopher Tateb49ceb32010-02-08 16:22:24 -080082import java.util.Set;
Christopher Tate487529a2009-04-29 14:03:25 -070083
84class BackupManagerService extends IBackupManager.Stub {
85 private static final String TAG = "BackupManagerService";
Christopher Tate13f4a642009-09-30 20:06:45 -070086 private static final boolean DEBUG = false;
Christopher Tateaa088442009-06-16 18:25:46 -070087
Christopher Tate49401dd2009-07-01 12:34:29 -070088 // How often we perform a backup pass. Privileged external callers can
89 // trigger an immediate pass.
Christopher Tateb6787f22009-07-02 17:40:45 -070090 private static final long BACKUP_INTERVAL = AlarmManager.INTERVAL_HOUR;
Christopher Tate487529a2009-04-29 14:03:25 -070091
Dan Egnorc1c49c02009-10-30 17:35:39 -070092 // Random variation in backup scheduling time to avoid server load spikes
93 private static final int FUZZ_MILLIS = 5 * 60 * 1000;
94
Christopher Tate8031a3d2009-07-06 16:36:05 -070095 // The amount of time between the initial provisioning of the device and
96 // the first backup pass.
97 private static final long FIRST_BACKUP_INTERVAL = 12 * AlarmManager.INTERVAL_HOUR;
98
Christopher Tate45281862010-03-05 15:46:30 -080099 private static final String RUN_BACKUP_ACTION = "android.app.backup.intent.RUN";
100 private static final String RUN_INITIALIZE_ACTION = "android.app.backup.intent.INIT";
101 private static final String RUN_CLEAR_ACTION = "android.app.backup.intent.CLEAR";
Christopher Tate487529a2009-04-29 14:03:25 -0700102 private static final int MSG_RUN_BACKUP = 1;
Christopher Tate043dadc2009-06-02 16:11:00 -0700103 private static final int MSG_RUN_FULL_BACKUP = 2;
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700104 private static final int MSG_RUN_RESTORE = 3;
Christopher Tateee0e78a2009-07-02 11:17:03 -0700105 private static final int MSG_RUN_CLEAR = 4;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700106 private static final int MSG_RUN_INITIALIZE = 5;
Christopher Tate2d449afe2010-03-29 19:14:24 -0700107 private static final int MSG_RUN_GET_RESTORE_SETS = 6;
108 private static final int MSG_TIMEOUT = 7;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700109
110 // Timeout interval for deciding that a bind or clear-data has taken too long
111 static final long TIMEOUT_INTERVAL = 10 * 1000;
112
Christopher Tate44a27902010-01-27 17:15:49 -0800113 // Timeout intervals for agent backup & restore operations
114 static final long TIMEOUT_BACKUP_INTERVAL = 30 * 1000;
115 static final long TIMEOUT_RESTORE_INTERVAL = 60 * 1000;
116
Christopher Tate487529a2009-04-29 14:03:25 -0700117 private Context mContext;
118 private PackageManager mPackageManager;
Christopher Tate1bb69062010-02-19 17:02:12 -0800119 IPackageManager mPackageManagerBinder;
Christopher Tate6ef58a12009-06-29 14:56:28 -0700120 private IActivityManager mActivityManager;
Christopher Tateb6787f22009-07-02 17:40:45 -0700121 private PowerManager mPowerManager;
122 private AlarmManager mAlarmManager;
Christopher Tate44a27902010-01-27 17:15:49 -0800123 IBackupManager mBackupManagerBinder;
Christopher Tateb6787f22009-07-02 17:40:45 -0700124
Christopher Tate73e02522009-07-15 14:18:26 -0700125 boolean mEnabled; // access to this is synchronized on 'this'
126 boolean mProvisioned;
Christopher Tatecce9da52010-02-03 15:11:15 -0800127 boolean mAutoRestore;
Christopher Tate73e02522009-07-15 14:18:26 -0700128 PowerManager.WakeLock mWakelock;
Christopher Tate44a27902010-01-27 17:15:49 -0800129 HandlerThread mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
130 BackupHandler mBackupHandler;
Christopher Tate4cc86e12009-09-21 19:36:51 -0700131 PendingIntent mRunBackupIntent, mRunInitIntent;
132 BroadcastReceiver mRunBackupReceiver, mRunInitReceiver;
Christopher Tate487529a2009-04-29 14:03:25 -0700133 // map UIDs to the set of backup client services within that UID's app set
Christopher Tate73e02522009-07-15 14:18:26 -0700134 final SparseArray<HashSet<ApplicationInfo>> mBackupParticipants
Christopher Tate181fafa2009-05-14 11:12:14 -0700135 = new SparseArray<HashSet<ApplicationInfo>>();
Christopher Tate487529a2009-04-29 14:03:25 -0700136 // set of backup services that have pending changes
Christopher Tate73e02522009-07-15 14:18:26 -0700137 class BackupRequest {
Christopher Tate181fafa2009-05-14 11:12:14 -0700138 public ApplicationInfo appInfo;
Christopher Tate46758122009-05-06 11:22:00 -0700139 public boolean fullBackup;
Christopher Tateaa088442009-06-16 18:25:46 -0700140
Christopher Tate181fafa2009-05-14 11:12:14 -0700141 BackupRequest(ApplicationInfo app, boolean isFull) {
142 appInfo = app;
Christopher Tate46758122009-05-06 11:22:00 -0700143 fullBackup = isFull;
144 }
Christopher Tate181fafa2009-05-14 11:12:14 -0700145
146 public String toString() {
147 return "BackupRequest{app=" + appInfo + " full=" + fullBackup + "}";
148 }
Christopher Tate46758122009-05-06 11:22:00 -0700149 }
Joe Onorato8ad02812009-05-13 01:41:44 -0400150 // Backups that we haven't started yet.
Christopher Tate73e02522009-07-15 14:18:26 -0700151 HashMap<ApplicationInfo,BackupRequest> mPendingBackups
Christopher Tate181fafa2009-05-14 11:12:14 -0700152 = new HashMap<ApplicationInfo,BackupRequest>();
Christopher Tate5cb400b2009-06-25 16:03:14 -0700153
154 // Pseudoname that we use for the Package Manager metadata "package"
Christopher Tate73e02522009-07-15 14:18:26 -0700155 static final String PACKAGE_MANAGER_SENTINEL = "@pm@";
Christopher Tate6aa41f42009-06-19 14:14:22 -0700156
157 // locking around the pending-backup management
Christopher Tate73e02522009-07-15 14:18:26 -0700158 final Object mQueueLock = new Object();
Christopher Tate487529a2009-04-29 14:03:25 -0700159
Christopher Tate043dadc2009-06-02 16:11:00 -0700160 // The thread performing the sequence of queued backups binds to each app's agent
161 // in succession. Bind notifications are asynchronously delivered through the
162 // Activity Manager; use this lock object to signal when a requested binding has
163 // completed.
Christopher Tate73e02522009-07-15 14:18:26 -0700164 final Object mAgentConnectLock = new Object();
165 IBackupAgent mConnectedAgent;
166 volatile boolean mConnecting;
Christopher Tate55f931a2009-09-29 17:17:34 -0700167 volatile long mLastBackupPass;
168 volatile long mNextBackupPass;
Christopher Tate043dadc2009-06-02 16:11:00 -0700169
Christopher Tate55f931a2009-09-29 17:17:34 -0700170 // A similar synchronization mechanism around clearing apps' data for restore
Christopher Tate73e02522009-07-15 14:18:26 -0700171 final Object mClearDataLock = new Object();
172 volatile boolean mClearingData;
Christopher Tatec7b31e32009-06-10 15:49:30 -0700173
Christopher Tate91717492009-06-26 21:07:13 -0700174 // Transport bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700175 final HashMap<String,IBackupTransport> mTransports
Christopher Tate91717492009-06-26 21:07:13 -0700176 = new HashMap<String,IBackupTransport>();
Christopher Tate73e02522009-07-15 14:18:26 -0700177 String mCurrentTransport;
178 IBackupTransport mLocalTransport, mGoogleTransport;
Christopher Tate80202c82010-01-25 19:37:47 -0800179 ActiveRestoreSession mActiveRestoreSession;
Christopher Tate043dadc2009-06-02 16:11:00 -0700180
Christopher Tate2d449afe2010-03-29 19:14:24 -0700181 class RestoreGetSetsParams {
182 public IBackupTransport transport;
183 public ActiveRestoreSession session;
184 public IRestoreObserver observer;
185
186 RestoreGetSetsParams(IBackupTransport _transport, ActiveRestoreSession _session,
187 IRestoreObserver _observer) {
188 transport = _transport;
189 session = _session;
190 observer = _observer;
191 }
192 }
193
Christopher Tate73e02522009-07-15 14:18:26 -0700194 class RestoreParams {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700195 public IBackupTransport transport;
196 public IRestoreObserver observer;
Dan Egnor156411d2009-06-26 13:20:02 -0700197 public long token;
Christopher Tate84725812010-02-04 15:52:40 -0800198 public PackageInfo pkgInfo;
Christopher Tate1bb69062010-02-19 17:02:12 -0800199 public int pmToken; // in post-install restore, the PM's token for this transaction
Christopher Tate84725812010-02-04 15:52:40 -0800200
201 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs,
Christopher Tate1bb69062010-02-19 17:02:12 -0800202 long _token, PackageInfo _pkg, int _pmToken) {
Christopher Tate84725812010-02-04 15:52:40 -0800203 transport = _transport;
204 observer = _obs;
205 token = _token;
206 pkgInfo = _pkg;
Christopher Tate1bb69062010-02-19 17:02:12 -0800207 pmToken = _pmToken;
Christopher Tate84725812010-02-04 15:52:40 -0800208 }
Christopher Tate7d562ec2009-06-25 18:03:43 -0700209
Dan Egnor156411d2009-06-26 13:20:02 -0700210 RestoreParams(IBackupTransport _transport, IRestoreObserver _obs, long _token) {
Christopher Tate7d562ec2009-06-25 18:03:43 -0700211 transport = _transport;
212 observer = _obs;
Dan Egnor156411d2009-06-26 13:20:02 -0700213 token = _token;
Christopher Tate84725812010-02-04 15:52:40 -0800214 pkgInfo = null;
Christopher Tate1bb69062010-02-19 17:02:12 -0800215 pmToken = 0;
Christopher Tate7d562ec2009-06-25 18:03:43 -0700216 }
217 }
218
Christopher Tate73e02522009-07-15 14:18:26 -0700219 class ClearParams {
Christopher Tateee0e78a2009-07-02 11:17:03 -0700220 public IBackupTransport transport;
221 public PackageInfo packageInfo;
222
223 ClearParams(IBackupTransport _transport, PackageInfo _info) {
224 transport = _transport;
225 packageInfo = _info;
226 }
227 }
228
Christopher Tate44a27902010-01-27 17:15:49 -0800229 // Bookkeeping of in-flight operations for timeout etc. purposes. The operation
230 // token is the index of the entry in the pending-operations list.
231 static final int OP_PENDING = 0;
232 static final int OP_ACKNOWLEDGED = 1;
233 static final int OP_TIMEOUT = -1;
234
235 final SparseIntArray mCurrentOperations = new SparseIntArray();
236 final Object mCurrentOpLock = new Object();
237 final Random mTokenGenerator = new Random();
238
Christopher Tate5cb400b2009-06-25 16:03:14 -0700239 // Where we keep our journal files and other bookkeeping
Christopher Tate73e02522009-07-15 14:18:26 -0700240 File mBaseStateDir;
241 File mDataDir;
242 File mJournalDir;
243 File mJournal;
Christopher Tate73e02522009-07-15 14:18:26 -0700244
Christopher Tate84725812010-02-04 15:52:40 -0800245 // Keep a log of all the apps we've ever backed up, and what the
246 // dataset tokens are for both the current backup dataset and
247 // the ancestral dataset.
Christopher Tate73e02522009-07-15 14:18:26 -0700248 private File mEverStored;
Christopher Tate73e02522009-07-15 14:18:26 -0700249 HashSet<String> mEverStoredApps = new HashSet<String>();
250
Christopher Tateb49ceb32010-02-08 16:22:24 -0800251 static final int CURRENT_ANCESTRAL_RECORD_VERSION = 1; // increment when the schema changes
Christopher Tate84725812010-02-04 15:52:40 -0800252 File mTokenFile;
Christopher Tateb49ceb32010-02-08 16:22:24 -0800253 Set<String> mAncestralPackages = null;
Christopher Tate84725812010-02-04 15:52:40 -0800254 long mAncestralToken = 0;
255 long mCurrentToken = 0;
256
Christopher Tate4cc86e12009-09-21 19:36:51 -0700257 // Persistently track the need to do a full init
258 static final String INIT_SENTINEL_FILE_NAME = "_need_init_";
259 HashSet<String> mPendingInits = new HashSet<String>(); // transport names
Christopher Tateaa088442009-06-16 18:25:46 -0700260
Christopher Tate44a27902010-01-27 17:15:49 -0800261 // ----- Asynchronous backup/restore handler thread -----
262
263 private class BackupHandler extends Handler {
264 public BackupHandler(Looper looper) {
265 super(looper);
266 }
267
268 public void handleMessage(Message msg) {
269
270 switch (msg.what) {
271 case MSG_RUN_BACKUP:
272 {
273 mLastBackupPass = System.currentTimeMillis();
274 mNextBackupPass = mLastBackupPass + BACKUP_INTERVAL;
275
276 IBackupTransport transport = getTransport(mCurrentTransport);
277 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800278 Slog.v(TAG, "Backup requested but no transport available");
Christopher Tate44a27902010-01-27 17:15:49 -0800279 mWakelock.release();
280 break;
281 }
282
283 // snapshot the pending-backup set and work on that
284 ArrayList<BackupRequest> queue = new ArrayList<BackupRequest>();
Christopher Tatec61da312010-02-05 10:41:27 -0800285 File oldJournal = mJournal;
Christopher Tate44a27902010-01-27 17:15:49 -0800286 synchronized (mQueueLock) {
Christopher Tatec61da312010-02-05 10:41:27 -0800287 // Do we have any work to do? Construct the work queue
288 // then release the synchronization lock to actually run
289 // the backup.
Christopher Tate44a27902010-01-27 17:15:49 -0800290 if (mPendingBackups.size() > 0) {
291 for (BackupRequest b: mPendingBackups.values()) {
292 queue.add(b);
293 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800294 if (DEBUG) Slog.v(TAG, "clearing pending backups");
Christopher Tate44a27902010-01-27 17:15:49 -0800295 mPendingBackups.clear();
296
297 // Start a new backup-queue journal file too
Christopher Tate44a27902010-01-27 17:15:49 -0800298 mJournal = null;
299
Christopher Tate44a27902010-01-27 17:15:49 -0800300 }
301 }
Christopher Tatec61da312010-02-05 10:41:27 -0800302
303 if (queue.size() > 0) {
304 // At this point, we have started a new journal file, and the old
305 // file identity is being passed to the backup processing thread.
306 // When it completes successfully, that old journal file will be
307 // deleted. If we crash prior to that, the old journal is parsed
308 // at next boot and the journaled requests fulfilled.
309 (new PerformBackupTask(transport, queue, oldJournal)).run();
310 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800311 Slog.v(TAG, "Backup requested but nothing pending");
Christopher Tatec61da312010-02-05 10:41:27 -0800312 mWakelock.release();
313 }
Christopher Tate44a27902010-01-27 17:15:49 -0800314 break;
315 }
316
317 case MSG_RUN_FULL_BACKUP:
318 break;
319
320 case MSG_RUN_RESTORE:
321 {
322 RestoreParams params = (RestoreParams)msg.obj;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800323 Slog.d(TAG, "MSG_RUN_RESTORE observer=" + params.observer);
Christopher Tate44a27902010-01-27 17:15:49 -0800324 (new PerformRestoreTask(params.transport, params.observer,
Christopher Tate1bb69062010-02-19 17:02:12 -0800325 params.token, params.pkgInfo, params.pmToken)).run();
Christopher Tate44a27902010-01-27 17:15:49 -0800326 break;
327 }
328
329 case MSG_RUN_CLEAR:
330 {
331 ClearParams params = (ClearParams)msg.obj;
332 (new PerformClearTask(params.transport, params.packageInfo)).run();
333 break;
334 }
335
336 case MSG_RUN_INITIALIZE:
337 {
338 HashSet<String> queue;
339
340 // Snapshot the pending-init queue and work on that
341 synchronized (mQueueLock) {
342 queue = new HashSet<String>(mPendingInits);
343 mPendingInits.clear();
344 }
345
346 (new PerformInitializeTask(queue)).run();
347 break;
348 }
349
Christopher Tate2d449afe2010-03-29 19:14:24 -0700350 case MSG_RUN_GET_RESTORE_SETS:
351 {
352 // Like other async operations, this is entered with the wakelock held
353 RestoreSet[] sets = null;
354 RestoreGetSetsParams params = (RestoreGetSetsParams)msg.obj;
355 try {
356 sets = params.transport.getAvailableRestoreSets();
357 // cache the result in the active session
358 synchronized (params.session) {
359 params.session.mRestoreSets = sets;
360 }
361 if (sets == null) EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
362 } catch (Exception e) {
363 Slog.e(TAG, "Error from transport getting set list");
364 } finally {
365 if (params.observer != null) {
366 try {
367 params.observer.restoreSetsAvailable(sets);
368 } catch (RemoteException re) {
369 Slog.e(TAG, "Unable to report listing to observer");
370 } catch (Exception e) {
371 Slog.e(TAG, "Restore observer threw", e);
372 }
373 }
374
375 mWakelock.release();
376 }
377 break;
378 }
379
Christopher Tate44a27902010-01-27 17:15:49 -0800380 case MSG_TIMEOUT:
381 {
382 synchronized (mCurrentOpLock) {
383 final int token = msg.arg1;
384 int state = mCurrentOperations.get(token, OP_TIMEOUT);
385 if (state == OP_PENDING) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800386 if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);
Christopher Tate44a27902010-01-27 17:15:49 -0800387 mCurrentOperations.put(token, OP_TIMEOUT);
388 }
389 mCurrentOpLock.notifyAll();
390 }
391 break;
392 }
393 }
394 }
395 }
396
397 // ----- Main service implementation -----
398
Christopher Tate487529a2009-04-29 14:03:25 -0700399 public BackupManagerService(Context context) {
400 mContext = context;
401 mPackageManager = context.getPackageManager();
Christopher Tate1bb69062010-02-19 17:02:12 -0800402 mPackageManagerBinder = ActivityThread.getPackageManager();
Christopher Tate181fafa2009-05-14 11:12:14 -0700403 mActivityManager = ActivityManagerNative.getDefault();
Christopher Tate487529a2009-04-29 14:03:25 -0700404
Christopher Tateb6787f22009-07-02 17:40:45 -0700405 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
406 mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
407
Christopher Tate44a27902010-01-27 17:15:49 -0800408 mBackupManagerBinder = asInterface(asBinder());
409
410 // spin up the backup/restore handler thread
411 mHandlerThread = new HandlerThread("backup", Process.THREAD_PRIORITY_BACKGROUND);
412 mHandlerThread.start();
413 mBackupHandler = new BackupHandler(mHandlerThread.getLooper());
414
Christopher Tate22b87872009-05-04 16:41:53 -0700415 // Set up our bookkeeping
Christopher Tateb6787f22009-07-02 17:40:45 -0700416 boolean areEnabled = Settings.Secure.getInt(context.getContentResolver(),
Dianne Hackborncf098292009-07-01 19:55:20 -0700417 Settings.Secure.BACKUP_ENABLED, 0) != 0;
Christopher Tate8031a3d2009-07-06 16:36:05 -0700418 mProvisioned = Settings.Secure.getInt(context.getContentResolver(),
Joe Onoratoab9a2a52009-07-27 08:56:39 -0700419 Settings.Secure.BACKUP_PROVISIONED, 0) != 0;
Christopher Tatecce9da52010-02-03 15:11:15 -0800420 mAutoRestore = Settings.Secure.getInt(context.getContentResolver(),
Christopher Tate5035fda2010-02-25 18:01:14 -0800421 Settings.Secure.BACKUP_AUTO_RESTORE, 1) != 0;
Oscar Montemayora8529f62009-11-18 10:14:20 -0800422 // If Encrypted file systems is enabled or disabled, this call will return the
423 // correct directory.
Oscar Montemayor1f4df902010-03-26 18:44:14 -0700424 mBaseStateDir = new File(Environment.getDataDirectory(), "backup");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800425 mBaseStateDir.mkdirs();
Christopher Tatef4172472009-05-05 15:50:03 -0700426 mDataDir = Environment.getDownloadCacheDirectory();
Christopher Tate9bbc21a2009-06-10 20:23:25 -0700427
Christopher Tate4cc86e12009-09-21 19:36:51 -0700428 // Alarm receivers for scheduled backups & initialization operations
Christopher Tateb6787f22009-07-02 17:40:45 -0700429 mRunBackupReceiver = new RunBackupReceiver();
Christopher Tate4cc86e12009-09-21 19:36:51 -0700430 IntentFilter filter = new IntentFilter();
431 filter.addAction(RUN_BACKUP_ACTION);
432 context.registerReceiver(mRunBackupReceiver, filter,
433 android.Manifest.permission.BACKUP, null);
434
435 mRunInitReceiver = new RunInitializeReceiver();
436 filter = new IntentFilter();
437 filter.addAction(RUN_INITIALIZE_ACTION);
438 context.registerReceiver(mRunInitReceiver, filter,
439 android.Manifest.permission.BACKUP, null);
Christopher Tateb6787f22009-07-02 17:40:45 -0700440
441 Intent backupIntent = new Intent(RUN_BACKUP_ACTION);
Christopher Tateb6787f22009-07-02 17:40:45 -0700442 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
443 mRunBackupIntent = PendingIntent.getBroadcast(context, MSG_RUN_BACKUP, backupIntent, 0);
444
Christopher Tate4cc86e12009-09-21 19:36:51 -0700445 Intent initIntent = new Intent(RUN_INITIALIZE_ACTION);
446 backupIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
447 mRunInitIntent = PendingIntent.getBroadcast(context, MSG_RUN_INITIALIZE, initIntent, 0);
448
Christopher Tatecde87f42009-06-12 12:55:53 -0700449 // Set up the backup-request journaling
Christopher Tate5cb400b2009-06-25 16:03:14 -0700450 mJournalDir = new File(mBaseStateDir, "pending");
451 mJournalDir.mkdirs(); // creates mBaseStateDir along the way
Dan Egnor852f8e42009-09-30 11:20:45 -0700452 mJournal = null; // will be created on first use
Christopher Tatecde87f42009-06-12 12:55:53 -0700453
Christopher Tate73e02522009-07-15 14:18:26 -0700454 // Set up the various sorts of package tracking we do
455 initPackageTracking();
456
Christopher Tateabce4e82009-06-18 18:35:32 -0700457 // Build our mapping of uid to backup client services. This implicitly
458 // schedules a backup pass on the Package Manager metadata the first
459 // time anything needs to be backed up.
Christopher Tate3799bc22009-05-06 16:13:56 -0700460 synchronized (mBackupParticipants) {
461 addPackageParticipantsLocked(null);
Christopher Tate487529a2009-04-29 14:03:25 -0700462 }
463
Dan Egnor87a02bc2009-06-17 02:30:10 -0700464 // Set up our transport options and initialize the default transport
465 // TODO: Have transports register themselves somehow?
466 // TODO: Don't create transports that we don't need to?
Dan Egnor87a02bc2009-06-17 02:30:10 -0700467 mLocalTransport = new LocalTransport(context); // This is actually pretty cheap
Christopher Tate91717492009-06-26 21:07:13 -0700468 ComponentName localName = new ComponentName(context, LocalTransport.class);
469 registerTransport(localName.flattenToShortString(), mLocalTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700470
Christopher Tate91717492009-06-26 21:07:13 -0700471 mGoogleTransport = null;
Dianne Hackborncf098292009-07-01 19:55:20 -0700472 mCurrentTransport = Settings.Secure.getString(context.getContentResolver(),
473 Settings.Secure.BACKUP_TRANSPORT);
474 if ("".equals(mCurrentTransport)) {
475 mCurrentTransport = null;
Christopher Tatece0bf062009-07-01 11:43:53 -0700476 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800477 if (DEBUG) Slog.v(TAG, "Starting with transport " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -0700478
479 // Attach to the Google backup transport. When this comes up, it will set
480 // itself as the current transport because we explicitly reset mCurrentTransport
481 // to null.
Dan Egnor87a02bc2009-06-17 02:30:10 -0700482 Intent intent = new Intent().setComponent(new ComponentName(
483 "com.google.android.backup",
484 "com.google.android.backup.BackupTransportService"));
485 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
Christopher Tateaa088442009-06-16 18:25:46 -0700486
Christopher Tatecde87f42009-06-12 12:55:53 -0700487 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700488 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700489 parseLeftoverJournals();
490
Christopher Tateb6787f22009-07-02 17:40:45 -0700491 // Power management
492 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
493
494 // Start the backup passes going
495 setBackupEnabled(areEnabled);
496 }
497
498 private class RunBackupReceiver extends BroadcastReceiver {
499 public void onReceive(Context context, Intent intent) {
500 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700501 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700502 if (mPendingInits.size() > 0) {
503 // If there are pending init operations, we process those
504 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800505 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700506 try {
507 mAlarmManager.cancel(mRunInitIntent);
508 mRunInitIntent.send();
509 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800510 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700511 // can't really do more than bail here
512 }
513 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800514 // Don't run backups now if we're disabled or not yet
515 // fully set up.
516 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800517 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700518
519 // Acquire the wakelock and pass it to the backup thread. it will
520 // be released once backup concludes.
521 mWakelock.acquire();
522
523 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
524 mBackupHandler.sendMessage(msg);
525 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800526 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700527 }
528 }
529 }
530 }
531 }
532 }
533
534 private class RunInitializeReceiver extends BroadcastReceiver {
535 public void onReceive(Context context, Intent intent) {
536 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
537 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800538 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700539
540 // Acquire the wakelock and pass it to the init thread. it will
541 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700542 mWakelock.acquire();
543
Christopher Tate4cc86e12009-09-21 19:36:51 -0700544 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700545 mBackupHandler.sendMessage(msg);
546 }
547 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700548 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700549 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700550
Christopher Tate73e02522009-07-15 14:18:26 -0700551 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800552 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700553
Christopher Tate84725812010-02-04 15:52:40 -0800554 // Remember our ancestral dataset
555 mTokenFile = new File(mBaseStateDir, "ancestral");
556 try {
557 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800558 int version = tf.readInt();
559 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
560 mAncestralToken = tf.readLong();
561 mCurrentToken = tf.readLong();
562
563 int numPackages = tf.readInt();
564 if (numPackages >= 0) {
565 mAncestralPackages = new HashSet<String>();
566 for (int i = 0; i < numPackages; i++) {
567 String pkgName = tf.readUTF();
568 mAncestralPackages.add(pkgName);
569 }
570 }
571 }
Christopher Tate1168baa2010-02-17 13:03:40 -0800572 } catch (FileNotFoundException fnf) {
573 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800574 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800575 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800576 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800577 }
578
Christopher Tatee97e8072009-07-15 16:45:50 -0700579 // Keep a log of what apps we've ever backed up. Because we might have
580 // rebooted in the middle of an operation that was removing something from
581 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700582 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700583 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700584
Christopher Tatee97e8072009-07-15 16:45:50 -0700585 // If we were in the middle of removing something from the ever-backed-up
586 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700587 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700588 if (tempProcessedFile.exists()) {
589 tempProcessedFile.delete();
590 }
591
Dan Egnor852f8e42009-09-30 11:20:45 -0700592 // If there are previous contents, parse them out then start a new
593 // file to continue the recordkeeping.
594 if (mEverStored.exists()) {
595 RandomAccessFile temp = null;
596 RandomAccessFile in = null;
597
598 try {
599 temp = new RandomAccessFile(tempProcessedFile, "rws");
600 in = new RandomAccessFile(mEverStored, "r");
601
602 while (true) {
603 PackageInfo info;
604 String pkg = in.readUTF();
605 try {
606 info = mPackageManager.getPackageInfo(pkg, 0);
607 mEverStoredApps.add(pkg);
608 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800609 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700610 } catch (NameNotFoundException e) {
611 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800612 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700613 }
614 }
615 } catch (EOFException e) {
616 // Once we've rewritten the backup history log, atomically replace the
617 // old one with the new one then reopen the file for continuing use.
618 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800619 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700620 }
621 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800622 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700623 } finally {
624 try { if (temp != null) temp.close(); } catch (IOException e) {}
625 try { if (in != null) in.close(); } catch (IOException e) {}
626 }
627 }
628
Christopher Tate73e02522009-07-15 14:18:26 -0700629 // Register for broadcasts about package install, etc., so we can
630 // update the provider list.
631 IntentFilter filter = new IntentFilter();
632 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
633 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
634 filter.addDataScheme("package");
635 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800636 // Register for events related to sdcard installation.
637 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800638 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
639 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800640 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700641 }
642
Christopher Tatecde87f42009-06-12 12:55:53 -0700643 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700644 for (File f : mJournalDir.listFiles()) {
645 if (mJournal == null || f.compareTo(mJournal) != 0) {
646 // This isn't the current journal, so it must be a leftover. Read
647 // out the package names mentioned there and schedule them for
648 // backup.
649 RandomAccessFile in = null;
650 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800651 Slog.i(TAG, "Found stale backup journal, scheduling:");
Dan Egnor852f8e42009-09-30 11:20:45 -0700652 in = new RandomAccessFile(f, "r");
653 while (true) {
654 String packageName = in.readUTF();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800655 Slog.i(TAG, " + " + packageName);
Dan Egnor852f8e42009-09-30 11:20:45 -0700656 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700657 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700658 } catch (EOFException e) {
659 // no more data; we're done
660 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800661 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700662 } finally {
663 // close/delete the file
664 try { if (in != null) in.close(); } catch (IOException e) {}
665 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700666 }
667 }
668 }
669 }
670
Christopher Tate4cc86e12009-09-21 19:36:51 -0700671 // Maintain persistent state around whether need to do an initialize operation.
672 // Must be called with the queue lock held.
673 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800674 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700675 + " on transport " + transportName);
676 try {
677 IBackupTransport transport = getTransport(transportName);
678 String transportDirName = transport.transportDirName();
679 File stateDir = new File(mBaseStateDir, transportDirName);
680 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
681
682 if (isPending) {
683 // We need an init before we can proceed with sending backup data.
684 // Record that with an entry in our set of pending inits, as well as
685 // journaling it via creation of a sentinel file.
686 mPendingInits.add(transportName);
687 try {
688 (new FileOutputStream(initPendingFile)).close();
689 } catch (IOException ioe) {
690 // Something is badly wrong with our permissions; just try to move on
691 }
692 } else {
693 // No more initialization needed; wipe the journal and reset our state.
694 initPendingFile.delete();
695 mPendingInits.remove(transportName);
696 }
697 } catch (RemoteException e) {
698 // can't happen; the transport is local
699 }
700 }
701
Christopher Tated55e18a2009-09-21 10:12:59 -0700702 // Reset all of our bookkeeping, in response to having been told that
703 // the backend data has been wiped [due to idle expiry, for example],
704 // so we must re-upload all saved settings.
705 void resetBackupState(File stateFileDir) {
706 synchronized (mQueueLock) {
707 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700708 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700709 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700710
Christopher Tate84725812010-02-04 15:52:40 -0800711 mCurrentToken = 0;
712 writeRestoreTokens();
713
Christopher Tated55e18a2009-09-21 10:12:59 -0700714 // Remove all the state files
715 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700716 // ... but don't touch the needs-init sentinel
717 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
718 sf.delete();
719 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700720 }
721
722 // Enqueue a new backup of every participant
723 int N = mBackupParticipants.size();
724 for (int i=0; i<N; i++) {
725 int uid = mBackupParticipants.keyAt(i);
726 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
727 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700728 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700729 }
730 }
731 }
732 }
733
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800734 // Add a transport to our set of available backends. If 'transport' is null, this
735 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700736 private void registerTransport(String name, IBackupTransport transport) {
737 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800738 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800739 if (transport != null) {
740 mTransports.put(name, transport);
741 } else {
742 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800743 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800744 mCurrentTransport = null;
745 }
746 // Nothing further to do in the unregistration case
747 return;
748 }
Christopher Tate91717492009-06-26 21:07:13 -0700749 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700750
751 // If the init sentinel file exists, we need to be sure to perform the init
752 // as soon as practical. We also create the state directory at registration
753 // time to ensure it's present from the outset.
754 try {
755 String transportName = transport.transportDirName();
756 File stateDir = new File(mBaseStateDir, transportName);
757 stateDir.mkdirs();
758
759 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
760 if (initSentinel.exists()) {
761 synchronized (mQueueLock) {
762 mPendingInits.add(transportName);
763
764 // TODO: pick a better starting time than now + 1 minute
765 long delay = 1000 * 60; // one minute, in milliseconds
766 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
767 System.currentTimeMillis() + delay, mRunInitIntent);
768 }
769 }
770 } catch (RemoteException e) {
771 // can't happen, the transport is local
772 }
Christopher Tate91717492009-06-26 21:07:13 -0700773 }
774
Christopher Tate3799bc22009-05-06 16:13:56 -0700775 // ----- Track installation/removal of packages -----
776 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
777 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800778 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700779
Christopher Tate3799bc22009-05-06 16:13:56 -0700780 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800781 boolean replacing = false;
782 boolean added = false;
783 Bundle extras = intent.getExtras();
784 String pkgList[] = null;
785 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
786 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
787 Uri uri = intent.getData();
788 if (uri == null) {
789 return;
790 }
791 String pkgName = uri.getSchemeSpecificPart();
792 if (pkgName != null) {
793 pkgList = new String[] { pkgName };
794 }
795 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
796 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800797 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800798 added = true;
799 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800800 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800801 added = false;
802 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
803 }
804 if (pkgList == null || pkgList.length == 0) {
805 return;
806 }
807 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700808 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800809 for (String pkgName : pkgList) {
810 if (replacing) {
811 // The package was just upgraded
812 updatePackageParticipantsLocked(pkgName);
813 } else {
814 // The package was just added
815 addPackageParticipantsLocked(pkgName);
816 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700817 }
818 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800819 } else {
820 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700821 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
822 } else {
823 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800824 for (String pkgName : pkgList) {
825 removePackageParticipantsLocked(pkgName);
826 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700827 }
828 }
829 }
830 }
831 };
832
Dan Egnor87a02bc2009-06-17 02:30:10 -0700833 // ----- Track connection to GoogleBackupTransport service -----
834 ServiceConnection mGoogleConnection = new ServiceConnection() {
835 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800836 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700837 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700838 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700839 }
840
841 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800842 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700843 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700844 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700845 }
846 };
847
Christopher Tate181fafa2009-05-14 11:12:14 -0700848 // Add the backup agents in the given package to our set of known backup participants.
849 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700850 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700851 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800852 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700853 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700854 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700855 }
856
Christopher Tate181fafa2009-05-14 11:12:14 -0700857 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700858 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700859 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800860 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700861 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800862 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700863 + " uid=" + p.applicationInfo.uid
864 + " killAfterRestore="
865 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700866 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700867 }
868 }
869
Dan Egnorefe52642009-06-24 00:16:33 -0700870 for (PackageInfo pkg : targetPkgs) {
871 if (packageName == null || pkg.packageName.equals(packageName)) {
872 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700873 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700874 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700875 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700876 mBackupParticipants.put(uid, set);
877 }
Dan Egnorefe52642009-06-24 00:16:33 -0700878 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700879
880 // If we've never seen this app before, schedule a backup for it
881 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800882 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700883 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700884 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700885 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700886 }
Christopher Tate487529a2009-04-29 14:03:25 -0700887 }
888 }
889
Christopher Tate6785dd82009-06-18 15:58:25 -0700890 // Remove the given package's entry from our known active set. If
891 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700892 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800893 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700894 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700895 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700896 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700897 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700898 int flags = PackageManager.GET_SIGNATURES;
899 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700900 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700901 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700902 }
903 } else {
904 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700905 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700906 }
907 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700908 }
909
Joe Onorato8ad02812009-05-13 01:41:44 -0400910 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700911 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700912 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800913 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700914 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700915 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800916 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700917 }
918 }
Dan Egnorefe52642009-06-24 00:16:33 -0700919 for (PackageInfo pkg : agents) {
920 if (packageName == null || pkg.packageName.equals(packageName)) {
921 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700922 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700923 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700924 // Find the existing entry with the same package name, and remove it.
925 // We can't just remove(app) because the instances are different.
926 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700927 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700928 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700929 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700930 break;
931 }
932 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700933 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700934 mBackupParticipants.delete(uid);
935 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700936 }
937 }
938 }
939 }
940
Christopher Tate181fafa2009-05-14 11:12:14 -0700941 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700942 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700943 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700944 int flags = PackageManager.GET_SIGNATURES;
945 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
946 int N = packages.size();
947 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700948 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700949 try {
950 ApplicationInfo app = pkg.applicationInfo;
951 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800952 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700953 packages.remove(a);
954 }
955 else {
956 // we will need the shared library path, so look that up and store it here
957 app = mPackageManager.getApplicationInfo(pkg.packageName,
958 PackageManager.GET_SHARED_LIBRARY_FILES);
959 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
960 }
961 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700962 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700963 }
964 }
Dan Egnorefe52642009-06-24 00:16:33 -0700965 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700966 }
Christopher Tateaa088442009-06-16 18:25:46 -0700967
Christopher Tate3799bc22009-05-06 16:13:56 -0700968 // Reset the given package's known backup participants. Unlike add/remove, the update
969 // action cannot be passed a null package name.
970 void updatePackageParticipantsLocked(String packageName) {
971 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800972 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700973 return;
974 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800975 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700976
977 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700978 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700979 removePackageParticipantsLockedInner(packageName, allApps);
980 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700981 }
982
Christopher Tate84725812010-02-04 15:52:40 -0800983 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -0700984 // backed up at least once
985 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700986 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
987
988 synchronized (mEverStoredApps) {
989 if (!mEverStoredApps.add(packageName)) return;
990
991 RandomAccessFile out = null;
992 try {
993 out = new RandomAccessFile(mEverStored, "rws");
994 out.seek(out.length());
995 out.writeUTF(packageName);
996 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800997 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700998 } finally {
999 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001000 }
1001 }
1002 }
1003
Christopher Tatee97e8072009-07-15 16:45:50 -07001004 // Remove our awareness of having ever backed up the given package
1005 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001006 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001007
Dan Egnor852f8e42009-09-30 11:20:45 -07001008 synchronized (mEverStoredApps) {
1009 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1010 // we'll recognize on initialization time that the package no longer
1011 // exists and fix it up then.
1012 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1013 RandomAccessFile known = null;
1014 try {
1015 known = new RandomAccessFile(tempKnownFile, "rws");
1016 mEverStoredApps.remove(packageName);
1017 for (String s : mEverStoredApps) {
1018 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001019 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001020 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001021 known.close();
1022 known = null;
1023 if (!tempKnownFile.renameTo(mEverStored)) {
1024 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1025 }
1026 } catch (IOException e) {
1027 // Bad: we couldn't create the new copy. For safety's sake we
1028 // abandon the whole process and remove all what's-backed-up
1029 // state entirely, meaning we'll force a backup pass for every
1030 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001031 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001032 mEverStoredApps.clear();
1033 tempKnownFile.delete();
1034 mEverStored.delete();
1035 } finally {
1036 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001037 }
1038 }
1039 }
1040
Christopher Tateb49ceb32010-02-08 16:22:24 -08001041 // Persistently record the current and ancestral backup tokens as well
1042 // as the set of packages with data [supposedly] available in the
1043 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001044 void writeRestoreTokens() {
1045 try {
1046 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001047
1048 // First, the version number of this record, for futureproofing
1049 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1050
1051 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001052 af.writeLong(mAncestralToken);
1053 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001054
1055 // Now write the set of ancestral packages
1056 if (mAncestralPackages == null) {
1057 af.writeInt(-1);
1058 } else {
1059 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001060 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001061 for (String pkgName : mAncestralPackages) {
1062 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001063 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001064 }
1065 }
Christopher Tate84725812010-02-04 15:52:40 -08001066 af.close();
1067 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001068 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001069 }
1070 }
1071
Dan Egnor87a02bc2009-06-17 02:30:10 -07001072 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001073 private IBackupTransport getTransport(String transportName) {
1074 synchronized (mTransports) {
1075 IBackupTransport transport = mTransports.get(transportName);
1076 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001077 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001078 }
1079 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001080 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001081 }
1082
Christopher Tatedf01dea2009-06-09 20:45:02 -07001083 // fire off a backup agent, blocking until it attaches or times out
1084 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1085 IBackupAgent agent = null;
1086 synchronized(mAgentConnectLock) {
1087 mConnecting = true;
1088 mConnectedAgent = null;
1089 try {
1090 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001091 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001092
1093 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001094 // only wait 10 seconds for the clear data to happen
1095 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1096 while (mConnecting && mConnectedAgent == null
1097 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001098 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001099 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001100 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001101 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001102 return null;
1103 }
1104 }
1105
1106 // if we timed out with no connect, abort and move on
1107 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001108 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001109 return null;
1110 }
1111 agent = mConnectedAgent;
1112 }
1113 } catch (RemoteException e) {
1114 // can't happen
1115 }
1116 }
1117 return agent;
1118 }
1119
Christopher Tatec7b31e32009-06-10 15:49:30 -07001120 // clear an application's data, blocking until the operation completes or times out
1121 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001122 // Don't wipe packages marked allowClearUserData=false
1123 try {
1124 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1125 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001126 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001127 + packageName);
1128 return;
1129 }
1130 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001131 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001132 return;
1133 }
1134
Christopher Tatec7b31e32009-06-10 15:49:30 -07001135 ClearDataObserver observer = new ClearDataObserver();
1136
1137 synchronized(mClearDataLock) {
1138 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001139 try {
1140 mActivityManager.clearApplicationUserData(packageName, observer);
1141 } catch (RemoteException e) {
1142 // can't happen because the activity manager is in this process
1143 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001144
1145 // only wait 10 seconds for the clear data to happen
1146 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1147 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1148 try {
1149 mClearDataLock.wait(5000);
1150 } catch (InterruptedException e) {
1151 // won't happen, but still.
1152 mClearingData = false;
1153 }
1154 }
1155 }
1156 }
1157
1158 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001159 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001160 synchronized(mClearDataLock) {
1161 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001162 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001163 }
1164 }
1165 }
1166
Christopher Tate1bb69062010-02-19 17:02:12 -08001167 // Get the restore-set token for the best-available restore set for this package:
1168 // the active set if possible, else the ancestral one. Returns zero if none available.
1169 long getAvailableRestoreToken(String packageName) {
1170 long token = mAncestralToken;
1171 synchronized (mQueueLock) {
1172 if (mEverStoredApps.contains(packageName)) {
1173 token = mCurrentToken;
1174 }
1175 }
1176 return token;
1177 }
1178
Christopher Tate44a27902010-01-27 17:15:49 -08001179 // -----
1180 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1181 boolean waitUntilOperationComplete(int token) {
1182 int finalState = OP_PENDING;
1183 synchronized (mCurrentOpLock) {
1184 try {
1185 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1186 try {
1187 mCurrentOpLock.wait();
1188 } catch (InterruptedException e) {}
1189 }
1190 } catch (IndexOutOfBoundsException e) {
1191 // the operation has been mysteriously cleared from our
1192 // bookkeeping -- consider this a success and ignore it.
1193 }
1194 }
1195 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001196 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001197 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001198 return finalState == OP_ACKNOWLEDGED;
1199 }
1200
1201 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001202 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001203 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001204 mCurrentOperations.put(token, OP_PENDING);
1205 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1206 mBackupHandler.sendMessageDelayed(msg, interval);
1207 }
1208
Christopher Tate043dadc2009-06-02 16:11:00 -07001209 // ----- Back up a set of applications via a worker thread -----
1210
Christopher Tate44a27902010-01-27 17:15:49 -08001211 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001212 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001213 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001214 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001215 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001216 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001217
Christopher Tate44a27902010-01-27 17:15:49 -08001218 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001219 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001220 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001221 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001222 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001223
1224 try {
1225 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1226 } catch (RemoteException e) {
1227 // can't happen; the transport is local
1228 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001229 }
1230
Christopher Tate043dadc2009-06-02 16:11:00 -07001231 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001232 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001233 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001234 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001235
Christopher Tate79588342009-06-30 16:11:49 -07001236 // Backups run at background priority
1237 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1238
Christopher Tate043dadc2009-06-02 16:11:00 -07001239 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001240 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001241
Dan Egnor852f8e42009-09-30 11:20:45 -07001242 // If we haven't stored package manager metadata yet, we must init the transport.
1243 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1244 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001245 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001246 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001247 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001248 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001249 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001250 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001251 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001252 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001253 }
Dan Egnor01445162009-09-21 17:04:05 -07001254 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001255
1256 // The package manager doesn't have a proper <application> etc, but since
1257 // it's running here in the system process we can just set up its agent
1258 // directly and use a synthetic BackupRequest. We always run this pass
1259 // because it's cheap and this way we guarantee that we don't get out of
1260 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001261 if (status == BackupConstants.TRANSPORT_OK) {
1262 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1263 mPackageManager, allAgentPackages());
1264 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1265 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1266 status = processOneBackup(pmRequest,
1267 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1268 }
Christopher Tate90967f42009-09-20 15:28:33 -07001269
Dan Egnor01445162009-09-21 17:04:05 -07001270 if (status == BackupConstants.TRANSPORT_OK) {
1271 // Now run all the backups in our queue
1272 status = doQueuedBackups(mTransport);
1273 }
1274
1275 if (status == BackupConstants.TRANSPORT_OK) {
1276 // Tell the transport to finish everything it has buffered
1277 status = mTransport.finishBackup();
1278 if (status == BackupConstants.TRANSPORT_OK) {
1279 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001280 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001281 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001282 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001283 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001284 }
1285 }
1286
Dan Egnor01445162009-09-21 17:04:05 -07001287 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001288 // The backend reports that our dataset has been wiped. We need to
1289 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001290 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001291 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001292 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001293 }
1294 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001295 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001296 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001297 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001298 // If everything actually went through and this is the first time we've
1299 // done a backup, we can now record what the current backup dataset token
1300 // is.
1301 if ((mCurrentToken == 0) && (status != BackupConstants.TRANSPORT_OK)) {
1302 try {
1303 mCurrentToken = mTransport.getCurrentRestoreSet();
1304 } catch (RemoteException e) { /* cannot happen */ }
1305 writeRestoreTokens();
1306 }
1307
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001308 // If things went wrong, we need to re-stage the apps we had expected
1309 // to be backing up in this pass. This journals the package names in
1310 // the current active pending-backup file, not in the we are holding
1311 // here in mJournal.
1312 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001313 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001314 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001315 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001316 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001317
1318 // We also want to reset the backup schedule based on whatever
1319 // the transport suggests by way of retry/backoff time.
1320 try {
1321 startBackupAlarmsLocked(mTransport.requestBackupTime());
1322 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001323 }
1324
1325 // Either backup was successful, in which case we of course do not need
1326 // this pass's journal any more; or it failed, in which case we just
1327 // re-enqueued all of these packages in the current active journal.
1328 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001329 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001330 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001331 }
1332
Christopher Tatec2af5d32010-02-02 15:18:58 -08001333 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001334 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001335 backupNow();
1336 }
1337
Dan Egnorbb9001c2009-07-27 12:20:13 -07001338 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001339 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001340 }
1341
Dan Egnor01445162009-09-21 17:04:05 -07001342 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001343 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001344 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001345
1346 IBackupAgent agent = null;
1347 int mode = (request.fullBackup)
1348 ? IApplicationThread.BACKUP_MODE_FULL
1349 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1350 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001351 agent = bindToAgentSynchronous(request.appInfo, mode);
1352 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001353 int result = processOneBackup(request, agent, transport);
1354 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001355 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001356 } catch (SecurityException ex) {
1357 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001358 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001359 } finally {
1360 try { // unbind even on timeout, just in case
1361 mActivityManager.unbindBackupAgent(request.appInfo);
1362 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001363 }
1364 }
Dan Egnor01445162009-09-21 17:04:05 -07001365
1366 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001367 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001368
Dan Egnor01445162009-09-21 17:04:05 -07001369 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1370 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001371 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001372 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001373
Dan Egnorbb9001c2009-07-27 12:20:13 -07001374 File savedStateName = new File(mStateDir, packageName);
1375 File backupDataName = new File(mDataDir, packageName + ".data");
1376 File newStateName = new File(mStateDir, packageName + ".new");
1377
1378 ParcelFileDescriptor savedState = null;
1379 ParcelFileDescriptor backupData = null;
1380 ParcelFileDescriptor newState = null;
1381
1382 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001383 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001384 try {
1385 // Look up the package info & signatures. This is first so that if it
1386 // throws an exception, there's no file setup yet that would need to
1387 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001388 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1389 // The metadata 'package' is synthetic
1390 packInfo = new PackageInfo();
1391 packInfo.packageName = packageName;
1392 } else {
1393 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001394 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001395 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001396
Christopher Tatec7b31e32009-06-10 15:49:30 -07001397 // In a full backup, we pass a null ParcelFileDescriptor as
1398 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001399 if (!request.fullBackup) {
1400 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001401 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001402 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1403 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001404
Dan Egnorbb9001c2009-07-27 12:20:13 -07001405 backupData = ParcelFileDescriptor.open(backupDataName,
1406 ParcelFileDescriptor.MODE_READ_WRITE |
1407 ParcelFileDescriptor.MODE_CREATE |
1408 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001409
Dan Egnorbb9001c2009-07-27 12:20:13 -07001410 newState = ParcelFileDescriptor.open(newStateName,
1411 ParcelFileDescriptor.MODE_READ_WRITE |
1412 ParcelFileDescriptor.MODE_CREATE |
1413 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001414
Christopher Tate44a27902010-01-27 17:15:49 -08001415 // Initiate the target's backup pass
1416 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1417 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1418 boolean success = waitUntilOperationComplete(token);
1419
1420 if (!success) {
1421 // timeout -- bail out into the failed-transaction logic
1422 throw new RuntimeException("Backup timeout");
1423 }
1424
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001426 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001427 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001428 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001429 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001430 backupDataName.delete();
1431 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001432 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001433 } finally {
1434 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1435 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1436 try { if (newState != null) newState.close(); } catch (IOException e) {}
1437 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001438 synchronized (mCurrentOpLock) {
1439 mCurrentOperations.clear();
1440 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001441 }
1442
1443 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001444 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001445 try {
1446 int size = (int) backupDataName.length();
1447 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001448 if (result == BackupConstants.TRANSPORT_OK) {
1449 backupData = ParcelFileDescriptor.open(backupDataName,
1450 ParcelFileDescriptor.MODE_READ_ONLY);
1451 result = transport.performBackup(packInfo, backupData);
1452 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001453
Dan Egnor83861e72009-09-17 16:17:55 -07001454 // TODO - We call finishBackup() for each application backed up, because
1455 // we need to know now whether it succeeded or failed. Instead, we should
1456 // hold off on finishBackup() until the end, which implies holding off on
1457 // renaming *all* the output state files (see below) until that happens.
1458
Dan Egnor01445162009-09-21 17:04:05 -07001459 if (result == BackupConstants.TRANSPORT_OK) {
1460 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001461 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001462 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001463 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001464 }
1465
1466 // After successful transport, delete the now-stale data
1467 // and juggle the files so that next time we supply the agent
1468 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001469 if (result == BackupConstants.TRANSPORT_OK) {
1470 backupDataName.delete();
1471 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001473 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001474 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001475 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001476 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001478 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001479 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001480 } finally {
1481 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001482 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001483
Dan Egnor01445162009-09-21 17:04:05 -07001484 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001485 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001486 }
1487
Christopher Tatedf01dea2009-06-09 20:45:02 -07001488
1489 // ----- Restore handling -----
1490
Christopher Tate78dd4a72009-11-04 11:49:08 -08001491 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1492 // If the target resides on the system partition, we allow it to restore
1493 // data from the like-named package in a restore set even if the signatures
1494 // do not match. (Unlike general applications, those flashed to the system
1495 // partition will be signed with the device's platform certificate, so on
1496 // different phones the same system app will have different signatures.)
1497 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001498 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001499 return true;
1500 }
1501
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001502 // Allow unsigned apps, but not signed on one device and unsigned on the other
1503 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001504 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001506 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001507 if ((storedSigs == null || storedSigs.length == 0)
1508 && (deviceSigs == null || deviceSigs.length == 0)) {
1509 return true;
1510 }
1511 if (storedSigs == null || deviceSigs == null) {
1512 return false;
1513 }
1514
Christopher Tateabce4e82009-06-18 18:35:32 -07001515 // !!! TODO: this demands that every stored signature match one
1516 // that is present on device, and does not demand the converse.
1517 // Is this this right policy?
1518 int nStored = storedSigs.length;
1519 int nDevice = deviceSigs.length;
1520
1521 for (int i=0; i < nStored; i++) {
1522 boolean match = false;
1523 for (int j=0; j < nDevice; j++) {
1524 if (storedSigs[i].equals(deviceSigs[j])) {
1525 match = true;
1526 break;
1527 }
1528 }
1529 if (!match) {
1530 return false;
1531 }
1532 }
1533 return true;
1534 }
1535
Christopher Tate44a27902010-01-27 17:15:49 -08001536 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001537 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001538 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001539 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001540 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001541 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001542 private int mPmToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001543
Christopher Tate5cbbf562009-06-22 16:44:51 -07001544 class RestoreRequest {
1545 public PackageInfo app;
1546 public int storedAppVersion;
1547
1548 RestoreRequest(PackageInfo _app, int _version) {
1549 app = _app;
1550 storedAppVersion = _version;
1551 }
1552 }
1553
Christopher Tate44a27902010-01-27 17:15:49 -08001554 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate1bb69062010-02-19 17:02:12 -08001555 long restoreSetToken, PackageInfo targetPackage, int pmToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001556 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001557 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001558 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001559 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001560 mPmToken = pmToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001561
1562 try {
1563 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1564 } catch (RemoteException e) {
1565 // can't happen; the transport is local
1566 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001567 }
1568
Christopher Tatedf01dea2009-06-09 20:45:02 -07001569 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001570 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001572 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001573 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001574
Christopher Tateb49ceb32010-02-08 16:22:24 -08001575 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001576 int error = -1; // assume error
1577
Dan Egnorefe52642009-06-24 00:16:33 -07001578 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001579 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001580 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001581 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001582
Dan Egnorefe52642009-06-24 00:16:33 -07001583 // Get the list of all packages which have backup enabled.
1584 // (Include the Package Manager metadata pseudo-package first.)
1585 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1586 PackageInfo omPackage = new PackageInfo();
1587 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1588 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001589
Dan Egnorefe52642009-06-24 00:16:33 -07001590 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001591 if (mTargetPackage == null) {
1592 restorePackages.addAll(agentPackages);
1593 } else {
1594 // Just one package to attempt restore of
1595 restorePackages.add(mTargetPackage);
1596 }
Dan Egnorefe52642009-06-24 00:16:33 -07001597
Christopher Tate7d562ec2009-06-25 18:03:43 -07001598 // let the observer know that we're running
1599 if (mObserver != null) {
1600 try {
1601 // !!! TODO: get an actual count from the transport after
1602 // its startRestore() runs?
1603 mObserver.restoreStarting(restorePackages.size());
1604 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001606 mObserver = null;
1607 }
1608 }
1609
Dan Egnor01445162009-09-21 17:04:05 -07001610 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1611 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001612 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001613 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001614 return;
1615 }
1616
1617 String packageName = mTransport.nextRestorePackage();
1618 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001619 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001620 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001621 return;
1622 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001623 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001624 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001625 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001626 return;
1627 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001628 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001629 + "\", found only \"" + packageName + "\"");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001630 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001631 "Package manager data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001632 return;
1633 }
1634
1635 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001636 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001637 mPackageManager, agentPackages);
1638 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1639
Christopher Tate8c032472009-07-02 14:28:47 -07001640 // Verify that the backup set includes metadata. If not, we can't do
1641 // signature/version verification etc, so we simply do not proceed with
1642 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001643 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001644 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001645 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001646 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001647 return;
1648 }
1649
Christopher Tate7d562ec2009-06-25 18:03:43 -07001650 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001651 for (;;) {
1652 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001653
Dan Egnorefe52642009-06-24 00:16:33 -07001654 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001655 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001656 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001657 return;
1658 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001659 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001660 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001661 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001662
Christopher Tate7d562ec2009-06-25 18:03:43 -07001663 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001664 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001665 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001666 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001667 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001668 mObserver = null;
1669 }
1670 }
1671
Dan Egnorefe52642009-06-24 00:16:33 -07001672 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1673 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001675 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001676 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001677 continue;
1678 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001679
Dan Egnorbb9001c2009-07-27 12:20:13 -07001680 PackageInfo packageInfo;
1681 try {
1682 int flags = PackageManager.GET_SIGNATURES;
1683 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1684 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001685 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001686 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001687 "Package missing on device");
1688 continue;
1689 }
1690
Dan Egnorefe52642009-06-24 00:16:33 -07001691 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001692 // Data is from a "newer" version of the app than we have currently
1693 // installed. If the app has not declared that it is prepared to
1694 // handle this case, we do not attempt the restore.
1695 if ((packageInfo.applicationInfo.flags
1696 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1697 String message = "Version " + metaInfo.versionCode
1698 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001699 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001700 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1701 packageName, message);
1702 continue;
1703 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001704 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001705 + " > installed " + packageInfo.versionCode
1706 + " but restoreAnyVersion");
1707 }
Dan Egnorefe52642009-06-24 00:16:33 -07001708 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001709
Christopher Tate78dd4a72009-11-04 11:49:08 -08001710 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001711 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001712 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001713 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001714 continue;
1715 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001716
Joe Onorato8a9b2202010-02-26 18:56:32 -08001717 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001718 + " restore version [" + metaInfo.versionCode
1719 + "] is compatible with installed version ["
1720 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001721
Christopher Tate3de55bc2010-03-12 17:28:08 -08001722 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001723 IBackupAgent agent = bindToAgentSynchronous(
1724 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001725 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001726 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001727 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001728 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001729 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001730 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001731 }
1732
Christopher Tate5e1ab332009-09-01 20:32:49 -07001733 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001734 try {
1735 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001736 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001737 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001738 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001739 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001740
1741 // The agent was probably running with a stub Application object,
1742 // which isn't a valid run mode for the main app logic. Shut
1743 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001744 // usual full initialization. Note that this is only done for
1745 // full-system restores: when a single app has requested a restore,
1746 // it is explicitly not killed following that operation.
1747 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001748 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001749 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001750 + packageInfo.applicationInfo.processName);
1751 mActivityManager.killApplicationProcess(
1752 packageInfo.applicationInfo.processName,
1753 packageInfo.applicationInfo.uid);
1754 }
Dan Egnorefe52642009-06-24 00:16:33 -07001755 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001756 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001757
1758 // if we get this far, report success to the observer
1759 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001760 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001761 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001762 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001763 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001764 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001765 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001766
Dan Egnorefe52642009-06-24 00:16:33 -07001767 try {
1768 mTransport.finishRestore();
1769 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001770 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001771 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001772
1773 if (mObserver != null) {
1774 try {
1775 mObserver.restoreFinished(error);
1776 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001777 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001778 }
1779 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001780
Christopher Tate84725812010-02-04 15:52:40 -08001781 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001782 // ancestral dataset, as well as the set of apps that are possibly
1783 // restoreable from the dataset
1784 if (mTargetPackage == null && pmAgent != null) {
1785 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001786 mAncestralToken = mToken;
1787 writeRestoreTokens();
1788 }
1789
Christopher Tate1bb69062010-02-19 17:02:12 -08001790 // We must under all circumstances tell the Package Manager to
1791 // proceed with install notifications if it's waiting for us.
1792 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001794 try {
1795 mPackageManagerBinder.finishPackageInstall(mPmToken);
1796 } catch (RemoteException e) { /* can't happen */ }
1797 }
1798
Christopher Tateb6787f22009-07-02 17:40:45 -07001799 // done; we can finally release the wakelock
1800 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001801 }
1802 }
1803
Dan Egnorefe52642009-06-24 00:16:33 -07001804 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1805 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001806 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001807 final String packageName = app.packageName;
1808
Joe Onorato8a9b2202010-02-26 18:56:32 -08001809 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001810
Christopher Tatec7b31e32009-06-10 15:49:30 -07001811 // !!! TODO: get the dirs from the transport
1812 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001813 File newStateName = new File(mStateDir, packageName + ".new");
1814 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001815
Dan Egnorbb9001c2009-07-27 12:20:13 -07001816 ParcelFileDescriptor backupData = null;
1817 ParcelFileDescriptor newState = null;
1818
Christopher Tate44a27902010-01-27 17:15:49 -08001819 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001820 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001821 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001822 backupData = ParcelFileDescriptor.open(backupDataName,
1823 ParcelFileDescriptor.MODE_READ_WRITE |
1824 ParcelFileDescriptor.MODE_CREATE |
1825 ParcelFileDescriptor.MODE_TRUNCATE);
1826
Dan Egnor01445162009-09-21 17:04:05 -07001827 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001828 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001829 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001830 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001831 }
1832
1833 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001834 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001835 backupData = ParcelFileDescriptor.open(backupDataName,
1836 ParcelFileDescriptor.MODE_READ_ONLY);
1837
Dan Egnorbb9001c2009-07-27 12:20:13 -07001838 newState = ParcelFileDescriptor.open(newStateName,
1839 ParcelFileDescriptor.MODE_READ_WRITE |
1840 ParcelFileDescriptor.MODE_CREATE |
1841 ParcelFileDescriptor.MODE_TRUNCATE);
1842
Christopher Tate44a27902010-01-27 17:15:49 -08001843 // Kick off the restore, checking for hung agents
1844 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1845 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1846 boolean success = waitUntilOperationComplete(token);
1847
1848 if (!success) {
1849 throw new RuntimeException("restore timeout");
1850 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001851
1852 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001853 //
1854 // !!! TODO: the restored data should be migrated on the server
1855 // side into the current dataset. In that case the new state file
1856 // we just created would reflect the data already extant in the
1857 // backend, so there'd be nothing more to do. Until that happens,
1858 // however, we need to make sure that we record the data to the
1859 // current backend dataset. (Yes, this means shipping the data over
1860 // the wire in both directions. That's bad, but consistency comes
1861 // first, then efficiency.) Once we introduce server-side data
1862 // migration to the newly-restored device's dataset, we will change
1863 // the following from a discard of the newly-written state to the
1864 // "correct" operation of renaming into the canonical state blob.
1865 newStateName.delete(); // TODO: remove; see above comment
1866 //newStateName.renameTo(savedStateName); // TODO: replace with this
1867
Dan Egnorbb9001c2009-07-27 12:20:13 -07001868 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001869 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001870 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001871 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001872 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001873
Christopher Tate96733042009-07-20 14:49:13 -07001874 // If the agent fails restore, it might have put the app's data
1875 // into an incoherent state. For consistency we wipe its data
1876 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001877 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001878 } finally {
1879 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001880 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1881 try { if (newState != null) newState.close(); } catch (IOException e) {}
1882 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001883 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001884 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001885 }
1886 }
1887
Christopher Tate44a27902010-01-27 17:15:49 -08001888 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001889 IBackupTransport mTransport;
1890 PackageInfo mPackage;
1891
Christopher Tate44a27902010-01-27 17:15:49 -08001892 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001893 mTransport = transport;
1894 mPackage = packageInfo;
1895 }
1896
Christopher Tateee0e78a2009-07-02 11:17:03 -07001897 public void run() {
1898 try {
1899 // Clear the on-device backup state to ensure a full backup next time
1900 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1901 File stateFile = new File(stateDir, mPackage.packageName);
1902 stateFile.delete();
1903
1904 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001905 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001906 mTransport.clearBackupData(mPackage);
1907 } catch (RemoteException e) {
1908 // can't happen; the transport is local
1909 } finally {
1910 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001911 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001912 mTransport.finishBackup();
1913 } catch (RemoteException e) {
1914 // can't happen; the transport is local
1915 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001916
1917 // Last but not least, release the cpu
1918 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001919 }
1920 }
1921 }
1922
Christopher Tate44a27902010-01-27 17:15:49 -08001923 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001924 HashSet<String> mQueue;
1925
Christopher Tate44a27902010-01-27 17:15:49 -08001926 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001927 mQueue = transportNames;
1928 }
1929
Christopher Tate4cc86e12009-09-21 19:36:51 -07001930 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001931 try {
1932 for (String transportName : mQueue) {
1933 IBackupTransport transport = getTransport(transportName);
1934 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001935 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001936 continue;
1937 }
1938
Joe Onorato8a9b2202010-02-26 18:56:32 -08001939 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001940 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001941 long startRealtime = SystemClock.elapsedRealtime();
1942 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001943
Christopher Tate4cc86e12009-09-21 19:36:51 -07001944 if (status == BackupConstants.TRANSPORT_OK) {
1945 status = transport.finishBackup();
1946 }
1947
1948 // Okay, the wipe really happened. Clean up our local bookkeeping.
1949 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001950 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001951 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001952 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001953 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001954 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001955 synchronized (mQueueLock) {
1956 recordInitPendingLocked(false, transportName);
1957 }
Dan Egnor726247c2009-09-29 19:12:31 -07001958 } else {
1959 // If this didn't work, requeue this one and try again
1960 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08001961 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001962 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001963 synchronized (mQueueLock) {
1964 recordInitPendingLocked(true, transportName);
1965 }
1966 // do this via another alarm to make sure of the wakelock states
1967 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001968 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07001969 + transportName + " resched in " + delay);
1970 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1971 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001972 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001973 }
1974 } catch (RemoteException e) {
1975 // can't happen; the transports are local
1976 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001977 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001978 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001979 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001980 mWakelock.release();
1981 }
1982 }
1983 }
1984
Christopher Tatedf01dea2009-06-09 20:45:02 -07001985
Christopher Tate487529a2009-04-29 14:03:25 -07001986 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07001987
Dan Egnor852f8e42009-09-30 11:20:45 -07001988 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07001989 // Record that we need a backup pass for the caller. Since multiple callers
1990 // may share a uid, we need to note all candidates within that uid and schedule
1991 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001992 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07001993
Christopher Tate63d27002009-06-16 17:16:42 -07001994 // If the caller does not hold the BACKUP permission, it can only request a
1995 // backup of its own data.
1996 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07001997 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07001998 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
1999 targets = mBackupParticipants.get(Binder.getCallingUid());
2000 } else {
2001 // a caller with full permission can ask to back up any participating app
2002 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07002003 targets = new HashSet<ApplicationInfo>();
2004 int N = mBackupParticipants.size();
2005 for (int i = 0; i < N; i++) {
2006 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2007 if (s != null) {
2008 targets.addAll(s);
2009 }
2010 }
2011 }
Christopher Tate487529a2009-04-29 14:03:25 -07002012 if (targets != null) {
2013 synchronized (mQueueLock) {
2014 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07002015 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07002016 // validate the caller-supplied package name against the known set of
2017 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07002018 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04002019 // Add the caller to the set of pending backups. If there is
2020 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07002021 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07002022 if (mPendingBackups.put(app, req) == null) {
2023 // Journal this request in case of crash. The put()
2024 // operation returned null when this package was not already
2025 // in the set; we want to avoid touching the disk redundantly.
2026 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07002027
Christopher Tate22b60d82009-07-07 16:36:02 -07002028 if (DEBUG) {
2029 int numKeys = mPendingBackups.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002030 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate22b60d82009-07-07 16:36:02 -07002031 for (BackupRequest b : mPendingBackups.values()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002032 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
Christopher Tate22b60d82009-07-07 16:36:02 -07002033 }
2034 }
2035 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002036 }
2037 }
Christopher Tate487529a2009-04-29 14:03:25 -07002038 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002039 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002040 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
Christopher Tate73e02522009-07-15 14:18:26 -07002041 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07002042 }
2043 }
Christopher Tate46758122009-05-06 11:22:00 -07002044
Christopher Tatecde87f42009-06-12 12:55:53 -07002045 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002046 RandomAccessFile out = null;
2047 try {
2048 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2049 out = new RandomAccessFile(mJournal, "rws");
2050 out.seek(out.length());
2051 out.writeUTF(str);
2052 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002053 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002054 mJournal = null;
2055 } finally {
2056 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002057 }
2058 }
2059
Christopher Tateee0e78a2009-07-02 11:17:03 -07002060 // Clear the given package's backup data from the current transport
2061 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002062 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002063 PackageInfo info;
2064 try {
2065 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2066 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002067 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002068 return;
2069 }
2070
2071 // If the caller does not hold the BACKUP permission, it can only request a
2072 // wipe of its own backed-up data.
2073 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002074 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002075 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2076 apps = mBackupParticipants.get(Binder.getCallingUid());
2077 } else {
2078 // a caller with full permission can ask to back up any participating app
2079 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002080 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002081 apps = new HashSet<ApplicationInfo>();
2082 int N = mBackupParticipants.size();
2083 for (int i = 0; i < N; i++) {
2084 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2085 if (s != null) {
2086 apps.addAll(s);
2087 }
2088 }
2089 }
2090
2091 // now find the given package in the set of candidate apps
2092 for (ApplicationInfo app : apps) {
2093 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002094 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002095 // found it; fire off the clear request
2096 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002097 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002098 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002099 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2100 new ClearParams(getTransport(mCurrentTransport), info));
2101 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002102 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002103 }
2104 break;
2105 }
2106 }
2107 }
2108
Christopher Tateace7f092009-06-15 18:07:25 -07002109 // Run a backup pass immediately for any applications that have declared
2110 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002111 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002112 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002113
Joe Onorato8a9b2202010-02-26 18:56:32 -08002114 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002115 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002116 // Because the alarms we are using can jitter, and we want an *immediate*
2117 // backup pass to happen, we restart the timer beginning with "next time,"
2118 // then manually fire the backup trigger intent ourselves.
2119 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002120 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002121 mRunBackupIntent.send();
2122 } catch (PendingIntent.CanceledException e) {
2123 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002124 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002125 }
Christopher Tate46758122009-05-06 11:22:00 -07002126 }
2127 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002128
Christopher Tate8031a3d2009-07-06 16:36:05 -07002129 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002130 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002131 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2132 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002133
Joe Onorato8a9b2202010-02-26 18:56:32 -08002134 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002135
Christopher Tate6ef58a12009-06-29 14:56:28 -07002136 boolean wasEnabled = mEnabled;
2137 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002138 Settings.Secure.putInt(mContext.getContentResolver(),
2139 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002140 mEnabled = enable;
2141 }
2142
Christopher Tate49401dd2009-07-01 12:34:29 -07002143 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002144 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002145 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002146 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002147 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002148 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002149 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002150
Christopher Tateb6787f22009-07-02 17:40:45 -07002151 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002152
2153 // This also constitutes an opt-out, so we wipe any data for
2154 // this device from the backend. We start that process with
2155 // an alarm in order to guarantee wakelock states.
2156 if (wasEnabled && mProvisioned) {
2157 // NOTE: we currently flush every registered transport, not just
2158 // the currently-active one.
2159 HashSet<String> allTransports;
2160 synchronized (mTransports) {
2161 allTransports = new HashSet<String>(mTransports.keySet());
2162 }
2163 // build the set of transports for which we are posting an init
2164 for (String transport : allTransports) {
2165 recordInitPendingLocked(true, transport);
2166 }
2167 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2168 mRunInitIntent);
2169 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002170 }
2171 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002172 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002173
Christopher Tatecce9da52010-02-03 15:11:15 -08002174 // Enable/disable automatic restore of app data at install time
2175 public void setAutoRestore(boolean doAutoRestore) {
2176 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2177 "setBackupEnabled");
2178
Joe Onorato8a9b2202010-02-26 18:56:32 -08002179 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002180
2181 synchronized (this) {
2182 Settings.Secure.putInt(mContext.getContentResolver(),
2183 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2184 mAutoRestore = doAutoRestore;
2185 }
2186 }
2187
Christopher Tate8031a3d2009-07-06 16:36:05 -07002188 // Mark the backup service as having been provisioned
2189 public void setBackupProvisioned(boolean available) {
2190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2191 "setBackupProvisioned");
2192
2193 boolean wasProvisioned = mProvisioned;
2194 synchronized (this) {
2195 Settings.Secure.putInt(mContext.getContentResolver(),
2196 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2197 mProvisioned = available;
2198 }
2199
2200 synchronized (mQueueLock) {
2201 if (available && !wasProvisioned && mEnabled) {
2202 // we're now good to go, so start the backup alarms
2203 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2204 } else if (!available) {
2205 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002206 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002207 mAlarmManager.cancel(mRunBackupIntent);
2208 }
2209 }
2210 }
2211
2212 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002213 // We used to use setInexactRepeating(), but that may be linked to
2214 // backups running at :00 more often than not, creating load spikes.
2215 // Schedule at an exact time for now, and also add a bit of "fuzz".
2216
2217 Random random = new Random();
2218 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2219 random.nextInt(FUZZ_MILLIS);
2220 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2221 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002222 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002223 }
2224
Christopher Tate6ef58a12009-06-29 14:56:28 -07002225 // Report whether the backup mechanism is currently enabled
2226 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002227 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002228 return mEnabled; // no need to synchronize just to read it
2229 }
2230
Christopher Tate91717492009-06-26 21:07:13 -07002231 // Report the name of the currently active transport
2232 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002233 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002234 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002235 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002236 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002237 }
2238
Christopher Tate91717492009-06-26 21:07:13 -07002239 // Report all known, available backup transports
2240 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002242
Christopher Tate91717492009-06-26 21:07:13 -07002243 String[] list = null;
2244 ArrayList<String> known = new ArrayList<String>();
2245 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2246 if (entry.getValue() != null) {
2247 known.add(entry.getKey());
2248 }
2249 }
2250
2251 if (known.size() > 0) {
2252 list = new String[known.size()];
2253 known.toArray(list);
2254 }
2255 return list;
2256 }
2257
2258 // Select which transport to use for the next backup operation. If the given
2259 // name is not one of the available transports, no action is taken and the method
2260 // returns null.
2261 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002262 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002263
2264 synchronized (mTransports) {
2265 String prevTransport = null;
2266 if (mTransports.get(transport) != null) {
2267 prevTransport = mCurrentTransport;
2268 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002269 Settings.Secure.putString(mContext.getContentResolver(),
2270 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002271 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002272 + " returning " + prevTransport);
2273 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002274 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002275 }
2276 return prevTransport;
2277 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002278 }
2279
2280 // Callback: a requested backup agent has been instantiated. This should only
2281 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002282 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002283 synchronized(mAgentConnectLock) {
2284 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002285 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002286 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2287 mConnectedAgent = agent;
2288 mConnecting = false;
2289 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002290 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002291 + " claiming agent connected");
2292 }
2293 mAgentConnectLock.notifyAll();
2294 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002295 }
2296
2297 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2298 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002299 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002300 public void agentDisconnected(String packageName) {
2301 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002302 synchronized(mAgentConnectLock) {
2303 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2304 mConnectedAgent = null;
2305 mConnecting = false;
2306 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002307 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002308 + " claiming agent disconnected");
2309 }
2310 mAgentConnectLock.notifyAll();
2311 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002312 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002313
Christopher Tate1bb69062010-02-19 17:02:12 -08002314 // An application being installed will need a restore pass, then the Package Manager
2315 // will need to be told when the restore is finished.
2316 public void restoreAtInstall(String packageName, int token) {
2317 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002318 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002319 + " attemping install-time restore");
2320 return;
2321 }
2322
2323 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002324 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002325 + " token=" + Integer.toHexString(token));
2326
Christopher Tatef0872722010-02-25 15:22:48 -08002327 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002328 // okay, we're going to attempt a restore of this package from this restore set.
2329 // The eventual message back into the Package Manager to run the post-install
2330 // steps for 'token' will be issued from the restore handling code.
2331
2332 // We can use a synthetic PackageInfo here because:
2333 // 1. We know it's valid, since the Package Manager supplied the name
2334 // 2. Only the packageName field will be used by the restore code
2335 PackageInfo pkg = new PackageInfo();
2336 pkg.packageName = packageName;
2337
2338 mWakelock.acquire();
2339 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2340 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2341 restoreSet, pkg, token);
2342 mBackupHandler.sendMessage(msg);
2343 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002344 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2345 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002346 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002347 try {
2348 mPackageManagerBinder.finishPackageInstall(token);
2349 } catch (RemoteException e) { /* can't happen */ }
2350 }
2351 }
2352
Christopher Tate8c850b72009-06-07 19:33:20 -07002353 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002354 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002355 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002356
2357 synchronized(this) {
2358 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002359 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002360 return null;
2361 }
Christopher Tate80202c82010-01-25 19:37:47 -08002362 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002363 }
2364 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002365 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002366
Christopher Tate44a27902010-01-27 17:15:49 -08002367 // Note that a currently-active backup agent has notified us that it has
2368 // completed the given outstanding asynchronous backup/restore operation.
2369 public void opComplete(int token) {
2370 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002371 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002372 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2373 mCurrentOpLock.notifyAll();
2374 }
2375 }
2376
Christopher Tate9b3905c2009-06-08 15:24:01 -07002377 // ----- Restore session -----
2378
Christopher Tate80202c82010-01-25 19:37:47 -08002379 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002380 private static final String TAG = "RestoreSession";
2381
Christopher Tate9b3905c2009-06-08 15:24:01 -07002382 private IBackupTransport mRestoreTransport = null;
2383 RestoreSet[] mRestoreSets = null;
2384
Christopher Tate80202c82010-01-25 19:37:47 -08002385 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002386 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002387 }
2388
2389 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002390 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002391 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002392 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002393 if (observer == null) {
2394 throw new IllegalArgumentException("Observer must not be null");
2395 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002396
Christopher Tate1bb69062010-02-19 17:02:12 -08002397 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002398 try {
Christopher Tate43383042009-07-13 15:17:13 -07002399 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002400 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002401 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002402 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002403 // spin off the transport request to our service thread
2404 mWakelock.acquire();
2405 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2406 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2407 mBackupHandler.sendMessage(msg);
2408 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002409 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002410 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002411 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002412 } finally {
2413 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002414 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002415 }
2416
Christopher Tate84725812010-02-04 15:52:40 -08002417 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002418 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2419 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002420
Joe Onorato8a9b2202010-02-26 18:56:32 -08002421 if (DEBUG) Slog.d(TAG, "performRestore token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002422 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002423
Dan Egnor0084da52009-07-29 12:57:16 -07002424 if (mRestoreTransport == null || mRestoreSets == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002425 Slog.e(TAG, "Ignoring performRestore() with no restore set");
Dan Egnor0084da52009-07-29 12:57:16 -07002426 return -1;
2427 }
2428
Christopher Tate21ab6a52009-09-24 18:01:46 -07002429 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002430 for (int i = 0; i < mRestoreSets.length; i++) {
2431 if (token == mRestoreSets[i].token) {
2432 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002433 mWakelock.acquire();
2434 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2435 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2436 mBackupHandler.sendMessage(msg);
2437 Binder.restoreCallingIdentity(oldId);
2438 return 0;
2439 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002440 }
2441 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002442
Joe Onorato8a9b2202010-02-26 18:56:32 -08002443 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002444 return -1;
2445 }
2446
Christopher Tate84725812010-02-04 15:52:40 -08002447 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002448 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002449
2450 PackageInfo app = null;
2451 try {
2452 app = mPackageManager.getPackageInfo(packageName, 0);
2453 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002454 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002455 return -1;
2456 }
2457
2458 // If the caller is not privileged and is not coming from the target
2459 // app's uid, throw a permission exception back to the caller.
2460 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2461 Binder.getCallingPid(), Binder.getCallingUid());
2462 if ((perm == PackageManager.PERMISSION_DENIED) &&
2463 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002464 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002465 + " or calling uid=" + Binder.getCallingUid());
2466 throw new SecurityException("No permission to restore other packages");
2467 }
2468
Christopher Tate7d411a32010-02-26 11:27:08 -08002469 // If the package has no backup agent, we obviously cannot proceed
2470 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002471 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002472 return -1;
2473 }
2474
Christopher Tate84725812010-02-04 15:52:40 -08002475 // So far so good; we're allowed to try to restore this package. Now
2476 // check whether there is data for it in the current dataset, falling back
2477 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002478 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002479
2480 // If we didn't come up with a place to look -- no ancestral dataset and
2481 // the app has never been backed up from this device -- there's nothing
2482 // to do but return failure.
2483 if (token == 0) {
2484 return -1;
2485 }
2486
2487 // Ready to go: enqueue the restore request and claim success
2488 long oldId = Binder.clearCallingIdentity();
2489 mWakelock.acquire();
2490 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002491 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002492 mBackupHandler.sendMessage(msg);
2493 Binder.restoreCallingIdentity(oldId);
2494 return 0;
2495 }
2496
Dan Egnor0084da52009-07-29 12:57:16 -07002497 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002499 "endRestoreSession");
2500
Joe Onorato8a9b2202010-02-26 18:56:32 -08002501 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002502
Dan Egnor0084da52009-07-29 12:57:16 -07002503 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002504 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002505 try {
2506 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2507 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002508 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002509 } finally {
2510 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002511 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002512 }
2513 }
2514
2515 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002516 if (BackupManagerService.this.mActiveRestoreSession == this) {
2517 BackupManagerService.this.mActiveRestoreSession = null;
2518 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002519 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002520 }
2521 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002522 }
2523 }
2524
Christopher Tate043dadc2009-06-02 16:11:00 -07002525
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002526 @Override
2527 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2528 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002529 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002530 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002531 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002532 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002533 pw.println("Last backup pass: " + mLastBackupPass
2534 + " (now = " + System.currentTimeMillis() + ')');
2535 pw.println(" next scheduled: " + mNextBackupPass);
2536
Christopher Tate91717492009-06-26 21:07:13 -07002537 pw.println("Available transports:");
2538 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002539 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2540 try {
2541 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2542 for (File f : dir.listFiles()) {
2543 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2544 }
2545 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002546 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002547 pw.println(" Error: " + e);
2548 }
Christopher Tate91717492009-06-26 21:07:13 -07002549 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002550
2551 pw.println("Pending init: " + mPendingInits.size());
2552 for (String s : mPendingInits) {
2553 pw.println(" " + s);
2554 }
2555
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002556 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002557 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002558 for (int i=0; i<N; i++) {
2559 int uid = mBackupParticipants.keyAt(i);
2560 pw.print(" uid: ");
2561 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002562 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2563 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002564 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002565 }
2566 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002567
Christopher Tateb49ceb32010-02-08 16:22:24 -08002568 pw.println("Ancestral packages: "
2569 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002570 if (mAncestralPackages != null) {
2571 for (String pkg : mAncestralPackages) {
2572 pw.println(" " + pkg);
2573 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002574 }
2575
Christopher Tate73e02522009-07-15 14:18:26 -07002576 pw.println("Ever backed up: " + mEverStoredApps.size());
2577 for (String pkg : mEverStoredApps) {
2578 pw.println(" " + pkg);
2579 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002580
2581 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002582 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002583 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002584 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002585 }
2586 }
Christopher Tate487529a2009-04-29 14:03:25 -07002587}