blob: 3db5dc11baec27853553a6f08a57a19ace46f6ec [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 Tateb6787f22009-07-02 17:40:45 -070020import android.app.AlarmManager;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070021import android.app.AppGlobals;
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();
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700402 mPackageManagerBinder = AppGlobals.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.
424 mBaseStateDir = new File(Environment.getSecureDataDirectory(), "backup");
425 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.
Christopher Tatea32504f2010-04-21 17:58:07 -0700482 ComponentName transportComponent = new ComponentName("com.google.android.backup",
483 "com.google.android.backup.BackupTransportService");
484 try {
485 // If there's something out there that is supposed to be the Google
486 // backup transport, make sure it's legitimately part of the OS build
487 // and not an app lying about its package name.
488 ApplicationInfo info = mPackageManager.getApplicationInfo(
489 transportComponent.getPackageName(), 0);
490 if ((info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
491 if (DEBUG) Slog.v(TAG, "Binding to Google transport");
492 Intent intent = new Intent().setComponent(transportComponent);
493 context.bindService(intent, mGoogleConnection, Context.BIND_AUTO_CREATE);
494 } else {
495 Slog.w(TAG, "Possible Google transport spoof: ignoring " + info);
496 }
497 } catch (PackageManager.NameNotFoundException nnf) {
498 // No such package? No binding.
499 if (DEBUG) Slog.v(TAG, "Google transport not present");
500 }
Christopher Tateaa088442009-06-16 18:25:46 -0700501
Christopher Tatecde87f42009-06-12 12:55:53 -0700502 // Now that we know about valid backup participants, parse any
Christopher Tate49401dd2009-07-01 12:34:29 -0700503 // leftover journal files into the pending backup set
Christopher Tatecde87f42009-06-12 12:55:53 -0700504 parseLeftoverJournals();
505
Christopher Tateb6787f22009-07-02 17:40:45 -0700506 // Power management
507 mWakelock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "backup");
508
509 // Start the backup passes going
510 setBackupEnabled(areEnabled);
511 }
512
513 private class RunBackupReceiver extends BroadcastReceiver {
514 public void onReceive(Context context, Intent intent) {
515 if (RUN_BACKUP_ACTION.equals(intent.getAction())) {
Christopher Tateb6787f22009-07-02 17:40:45 -0700516 synchronized (mQueueLock) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700517 if (mPendingInits.size() > 0) {
518 // If there are pending init operations, we process those
519 // and then settle into the usual periodic backup schedule.
Joe Onorato8a9b2202010-02-26 18:56:32 -0800520 if (DEBUG) Slog.v(TAG, "Init pending at scheduled backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700521 try {
522 mAlarmManager.cancel(mRunInitIntent);
523 mRunInitIntent.send();
524 } catch (PendingIntent.CanceledException ce) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800525 Slog.e(TAG, "Run init intent cancelled");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700526 // can't really do more than bail here
527 }
528 } else {
Christopher Tatec2af5d32010-02-02 15:18:58 -0800529 // Don't run backups now if we're disabled or not yet
530 // fully set up.
531 if (mEnabled && mProvisioned) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800532 if (DEBUG) Slog.v(TAG, "Running a backup pass");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700533
534 // Acquire the wakelock and pass it to the backup thread. it will
535 // be released once backup concludes.
536 mWakelock.acquire();
537
538 Message msg = mBackupHandler.obtainMessage(MSG_RUN_BACKUP);
539 mBackupHandler.sendMessage(msg);
540 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800541 Slog.w(TAG, "Backup pass but e=" + mEnabled + " p=" + mProvisioned);
Christopher Tate4cc86e12009-09-21 19:36:51 -0700542 }
543 }
544 }
545 }
546 }
547 }
548
549 private class RunInitializeReceiver extends BroadcastReceiver {
550 public void onReceive(Context context, Intent intent) {
551 if (RUN_INITIALIZE_ACTION.equals(intent.getAction())) {
552 synchronized (mQueueLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800553 if (DEBUG) Slog.v(TAG, "Running a device init");
Christopher Tate4cc86e12009-09-21 19:36:51 -0700554
555 // Acquire the wakelock and pass it to the init thread. it will
556 // be released once init concludes.
Christopher Tateb6787f22009-07-02 17:40:45 -0700557 mWakelock.acquire();
558
Christopher Tate4cc86e12009-09-21 19:36:51 -0700559 Message msg = mBackupHandler.obtainMessage(MSG_RUN_INITIALIZE);
Christopher Tateb6787f22009-07-02 17:40:45 -0700560 mBackupHandler.sendMessage(msg);
561 }
562 }
Christopher Tate49401dd2009-07-01 12:34:29 -0700563 }
Christopher Tateb6787f22009-07-02 17:40:45 -0700564 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700565
Christopher Tate73e02522009-07-15 14:18:26 -0700566 private void initPackageTracking() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800567 if (DEBUG) Slog.v(TAG, "Initializing package tracking");
Christopher Tate73e02522009-07-15 14:18:26 -0700568
Christopher Tate84725812010-02-04 15:52:40 -0800569 // Remember our ancestral dataset
570 mTokenFile = new File(mBaseStateDir, "ancestral");
571 try {
572 RandomAccessFile tf = new RandomAccessFile(mTokenFile, "r");
Christopher Tateb49ceb32010-02-08 16:22:24 -0800573 int version = tf.readInt();
574 if (version == CURRENT_ANCESTRAL_RECORD_VERSION) {
575 mAncestralToken = tf.readLong();
576 mCurrentToken = tf.readLong();
577
578 int numPackages = tf.readInt();
579 if (numPackages >= 0) {
580 mAncestralPackages = new HashSet<String>();
581 for (int i = 0; i < numPackages; i++) {
582 String pkgName = tf.readUTF();
583 mAncestralPackages.add(pkgName);
584 }
585 }
586 }
Christopher Tate1168baa2010-02-17 13:03:40 -0800587 } catch (FileNotFoundException fnf) {
588 // Probably innocuous
Joe Onorato8a9b2202010-02-26 18:56:32 -0800589 Slog.v(TAG, "No ancestral data");
Christopher Tate84725812010-02-04 15:52:40 -0800590 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800591 Slog.w(TAG, "Unable to read token file", e);
Christopher Tate84725812010-02-04 15:52:40 -0800592 }
593
Christopher Tatee97e8072009-07-15 16:45:50 -0700594 // Keep a log of what apps we've ever backed up. Because we might have
595 // rebooted in the middle of an operation that was removing something from
596 // this log, we sanity-check its contents here and reconstruct it.
Christopher Tate73e02522009-07-15 14:18:26 -0700597 mEverStored = new File(mBaseStateDir, "processed");
Christopher Tatee97e8072009-07-15 16:45:50 -0700598 File tempProcessedFile = new File(mBaseStateDir, "processed.new");
Christopher Tate73e02522009-07-15 14:18:26 -0700599
Christopher Tatee97e8072009-07-15 16:45:50 -0700600 // If we were in the middle of removing something from the ever-backed-up
601 // file, there might be a transient "processed.new" file still present.
Dan Egnor852f8e42009-09-30 11:20:45 -0700602 // Ignore it -- we'll validate "processed" against the current package set.
Christopher Tatee97e8072009-07-15 16:45:50 -0700603 if (tempProcessedFile.exists()) {
604 tempProcessedFile.delete();
605 }
606
Dan Egnor852f8e42009-09-30 11:20:45 -0700607 // If there are previous contents, parse them out then start a new
608 // file to continue the recordkeeping.
609 if (mEverStored.exists()) {
610 RandomAccessFile temp = null;
611 RandomAccessFile in = null;
612
613 try {
614 temp = new RandomAccessFile(tempProcessedFile, "rws");
615 in = new RandomAccessFile(mEverStored, "r");
616
617 while (true) {
618 PackageInfo info;
619 String pkg = in.readUTF();
620 try {
621 info = mPackageManager.getPackageInfo(pkg, 0);
622 mEverStoredApps.add(pkg);
623 temp.writeUTF(pkg);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800624 if (DEBUG) Slog.v(TAG, " + " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700625 } catch (NameNotFoundException e) {
626 // nope, this package was uninstalled; don't include it
Joe Onorato8a9b2202010-02-26 18:56:32 -0800627 if (DEBUG) Slog.v(TAG, " - " + pkg);
Dan Egnor852f8e42009-09-30 11:20:45 -0700628 }
629 }
630 } catch (EOFException e) {
631 // Once we've rewritten the backup history log, atomically replace the
632 // old one with the new one then reopen the file for continuing use.
633 if (!tempProcessedFile.renameTo(mEverStored)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800634 Slog.e(TAG, "Error renaming " + tempProcessedFile + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -0700635 }
636 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800637 Slog.e(TAG, "Error in processed file", e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700638 } finally {
639 try { if (temp != null) temp.close(); } catch (IOException e) {}
640 try { if (in != null) in.close(); } catch (IOException e) {}
641 }
642 }
643
Christopher Tate73e02522009-07-15 14:18:26 -0700644 // Register for broadcasts about package install, etc., so we can
645 // update the provider list.
646 IntentFilter filter = new IntentFilter();
647 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
648 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
649 filter.addDataScheme("package");
650 mContext.registerReceiver(mBroadcastReceiver, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800651 // Register for events related to sdcard installation.
652 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800653 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
654 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800655 mContext.registerReceiver(mBroadcastReceiver, sdFilter);
Christopher Tate73e02522009-07-15 14:18:26 -0700656 }
657
Christopher Tatecde87f42009-06-12 12:55:53 -0700658 private void parseLeftoverJournals() {
Dan Egnor852f8e42009-09-30 11:20:45 -0700659 for (File f : mJournalDir.listFiles()) {
660 if (mJournal == null || f.compareTo(mJournal) != 0) {
661 // This isn't the current journal, so it must be a leftover. Read
662 // out the package names mentioned there and schedule them for
663 // backup.
664 RandomAccessFile in = null;
665 try {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800666 Slog.i(TAG, "Found stale backup journal, scheduling:");
Dan Egnor852f8e42009-09-30 11:20:45 -0700667 in = new RandomAccessFile(f, "r");
668 while (true) {
669 String packageName = in.readUTF();
Joe Onorato8a9b2202010-02-26 18:56:32 -0800670 Slog.i(TAG, " + " + packageName);
Dan Egnor852f8e42009-09-30 11:20:45 -0700671 dataChanged(packageName);
Christopher Tatecde87f42009-06-12 12:55:53 -0700672 }
Dan Egnor852f8e42009-09-30 11:20:45 -0700673 } catch (EOFException e) {
674 // no more data; we're done
675 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800676 Slog.e(TAG, "Can't read " + f, e);
Dan Egnor852f8e42009-09-30 11:20:45 -0700677 } finally {
678 // close/delete the file
679 try { if (in != null) in.close(); } catch (IOException e) {}
680 f.delete();
Christopher Tatecde87f42009-06-12 12:55:53 -0700681 }
682 }
683 }
684 }
685
Christopher Tate4cc86e12009-09-21 19:36:51 -0700686 // Maintain persistent state around whether need to do an initialize operation.
687 // Must be called with the queue lock held.
688 void recordInitPendingLocked(boolean isPending, String transportName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800689 if (DEBUG) Slog.i(TAG, "recordInitPendingLocked: " + isPending
Christopher Tate4cc86e12009-09-21 19:36:51 -0700690 + " on transport " + transportName);
691 try {
692 IBackupTransport transport = getTransport(transportName);
693 String transportDirName = transport.transportDirName();
694 File stateDir = new File(mBaseStateDir, transportDirName);
695 File initPendingFile = new File(stateDir, INIT_SENTINEL_FILE_NAME);
696
697 if (isPending) {
698 // We need an init before we can proceed with sending backup data.
699 // Record that with an entry in our set of pending inits, as well as
700 // journaling it via creation of a sentinel file.
701 mPendingInits.add(transportName);
702 try {
703 (new FileOutputStream(initPendingFile)).close();
704 } catch (IOException ioe) {
705 // Something is badly wrong with our permissions; just try to move on
706 }
707 } else {
708 // No more initialization needed; wipe the journal and reset our state.
709 initPendingFile.delete();
710 mPendingInits.remove(transportName);
711 }
712 } catch (RemoteException e) {
713 // can't happen; the transport is local
714 }
715 }
716
Christopher Tated55e18a2009-09-21 10:12:59 -0700717 // Reset all of our bookkeeping, in response to having been told that
718 // the backend data has been wiped [due to idle expiry, for example],
719 // so we must re-upload all saved settings.
720 void resetBackupState(File stateFileDir) {
721 synchronized (mQueueLock) {
722 // Wipe the "what we've ever backed up" tracking
Christopher Tated55e18a2009-09-21 10:12:59 -0700723 mEverStoredApps.clear();
Dan Egnor852f8e42009-09-30 11:20:45 -0700724 mEverStored.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -0700725
Christopher Tate84725812010-02-04 15:52:40 -0800726 mCurrentToken = 0;
727 writeRestoreTokens();
728
Christopher Tated55e18a2009-09-21 10:12:59 -0700729 // Remove all the state files
730 for (File sf : stateFileDir.listFiles()) {
Christopher Tate4cc86e12009-09-21 19:36:51 -0700731 // ... but don't touch the needs-init sentinel
732 if (!sf.getName().equals(INIT_SENTINEL_FILE_NAME)) {
733 sf.delete();
734 }
Christopher Tated55e18a2009-09-21 10:12:59 -0700735 }
736
737 // Enqueue a new backup of every participant
738 int N = mBackupParticipants.size();
739 for (int i=0; i<N; i++) {
740 int uid = mBackupParticipants.keyAt(i);
741 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
742 for (ApplicationInfo app: participants) {
Dan Egnor852f8e42009-09-30 11:20:45 -0700743 dataChanged(app.packageName);
Christopher Tated55e18a2009-09-21 10:12:59 -0700744 }
745 }
746 }
747 }
748
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800749 // Add a transport to our set of available backends. If 'transport' is null, this
750 // is an unregistration, and the transport's entry is removed from our bookkeeping.
Christopher Tate91717492009-06-26 21:07:13 -0700751 private void registerTransport(String name, IBackupTransport transport) {
752 synchronized (mTransports) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800753 if (DEBUG) Slog.v(TAG, "Registering transport " + name + " = " + transport);
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800754 if (transport != null) {
755 mTransports.put(name, transport);
756 } else {
757 mTransports.remove(name);
Christopher Tateb0dcaaf2010-01-29 16:27:04 -0800758 if ((mCurrentTransport != null) && mCurrentTransport.equals(name)) {
Christopher Tatedfa47b56e2009-12-22 16:01:32 -0800759 mCurrentTransport = null;
760 }
761 // Nothing further to do in the unregistration case
762 return;
763 }
Christopher Tate91717492009-06-26 21:07:13 -0700764 }
Christopher Tate4cc86e12009-09-21 19:36:51 -0700765
766 // If the init sentinel file exists, we need to be sure to perform the init
767 // as soon as practical. We also create the state directory at registration
768 // time to ensure it's present from the outset.
769 try {
770 String transportName = transport.transportDirName();
771 File stateDir = new File(mBaseStateDir, transportName);
772 stateDir.mkdirs();
773
774 File initSentinel = new File(stateDir, INIT_SENTINEL_FILE_NAME);
775 if (initSentinel.exists()) {
776 synchronized (mQueueLock) {
777 mPendingInits.add(transportName);
778
779 // TODO: pick a better starting time than now + 1 minute
780 long delay = 1000 * 60; // one minute, in milliseconds
781 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
782 System.currentTimeMillis() + delay, mRunInitIntent);
783 }
784 }
785 } catch (RemoteException e) {
786 // can't happen, the transport is local
787 }
Christopher Tate91717492009-06-26 21:07:13 -0700788 }
789
Christopher Tate3799bc22009-05-06 16:13:56 -0700790 // ----- Track installation/removal of packages -----
791 BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
792 public void onReceive(Context context, Intent intent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800793 if (DEBUG) Slog.d(TAG, "Received broadcast " + intent);
Christopher Tate3799bc22009-05-06 16:13:56 -0700794
Christopher Tate3799bc22009-05-06 16:13:56 -0700795 String action = intent.getAction();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800796 boolean replacing = false;
797 boolean added = false;
798 Bundle extras = intent.getExtras();
799 String pkgList[] = null;
800 if (Intent.ACTION_PACKAGE_ADDED.equals(action) ||
801 Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
802 Uri uri = intent.getData();
803 if (uri == null) {
804 return;
805 }
806 String pkgName = uri.getSchemeSpecificPart();
807 if (pkgName != null) {
808 pkgList = new String[] { pkgName };
809 }
810 added = Intent.ACTION_PACKAGE_ADDED.equals(action);
811 replacing = extras.getBoolean(Intent.EXTRA_REPLACING, false);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800812 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800813 added = true;
814 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800815 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800816 added = false;
817 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
818 }
819 if (pkgList == null || pkgList.length == 0) {
820 return;
821 }
822 if (added) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700823 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800824 for (String pkgName : pkgList) {
825 if (replacing) {
826 // The package was just upgraded
827 updatePackageParticipantsLocked(pkgName);
828 } else {
829 // The package was just added
830 addPackageParticipantsLocked(pkgName);
831 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700832 }
833 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800834 } else {
835 if (replacing) {
Christopher Tate3799bc22009-05-06 16:13:56 -0700836 // The package is being updated. We'll receive a PACKAGE_ADDED shortly.
837 } else {
838 synchronized (mBackupParticipants) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800839 for (String pkgName : pkgList) {
840 removePackageParticipantsLocked(pkgName);
841 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700842 }
843 }
844 }
845 }
846 };
847
Dan Egnor87a02bc2009-06-17 02:30:10 -0700848 // ----- Track connection to GoogleBackupTransport service -----
849 ServiceConnection mGoogleConnection = new ServiceConnection() {
850 public void onServiceConnected(ComponentName name, IBinder service) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800851 if (DEBUG) Slog.v(TAG, "Connected to Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700852 mGoogleTransport = IBackupTransport.Stub.asInterface(service);
Christopher Tate91717492009-06-26 21:07:13 -0700853 registerTransport(name.flattenToShortString(), mGoogleTransport);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700854 }
855
856 public void onServiceDisconnected(ComponentName name) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800857 if (DEBUG) Slog.v(TAG, "Disconnected from Google transport");
Dan Egnor87a02bc2009-06-17 02:30:10 -0700858 mGoogleTransport = null;
Christopher Tate91717492009-06-26 21:07:13 -0700859 registerTransport(name.flattenToShortString(), null);
Dan Egnor87a02bc2009-06-17 02:30:10 -0700860 }
861 };
862
Christopher Tate181fafa2009-05-14 11:12:14 -0700863 // Add the backup agents in the given package to our set of known backup participants.
864 // If 'packageName' is null, adds all backup agents in the whole system.
Christopher Tate3799bc22009-05-06 16:13:56 -0700865 void addPackageParticipantsLocked(String packageName) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700866 // Look for apps that define the android:backupAgent attribute
Joe Onorato8a9b2202010-02-26 18:56:32 -0800867 if (DEBUG) Slog.v(TAG, "addPackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700868 List<PackageInfo> targetApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700869 addPackageParticipantsLockedInner(packageName, targetApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700870 }
871
Christopher Tate181fafa2009-05-14 11:12:14 -0700872 private void addPackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700873 List<PackageInfo> targetPkgs) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700874 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800875 Slog.v(TAG, "Adding " + targetPkgs.size() + " backup participants:");
Dan Egnorefe52642009-06-24 00:16:33 -0700876 for (PackageInfo p : targetPkgs) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 Slog.v(TAG, " " + p + " agent=" + p.applicationInfo.backupAgentName
Christopher Tate5e1ab332009-09-01 20:32:49 -0700878 + " uid=" + p.applicationInfo.uid
879 + " killAfterRestore="
880 + (((p.applicationInfo.flags & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) ? "true" : "false")
Christopher Tate5e1ab332009-09-01 20:32:49 -0700881 );
Christopher Tate181fafa2009-05-14 11:12:14 -0700882 }
883 }
884
Dan Egnorefe52642009-06-24 00:16:33 -0700885 for (PackageInfo pkg : targetPkgs) {
886 if (packageName == null || pkg.packageName.equals(packageName)) {
887 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700888 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700889 if (set == null) {
Christopher Tate181fafa2009-05-14 11:12:14 -0700890 set = new HashSet<ApplicationInfo>();
Christopher Tate3799bc22009-05-06 16:13:56 -0700891 mBackupParticipants.put(uid, set);
892 }
Dan Egnorefe52642009-06-24 00:16:33 -0700893 set.add(pkg.applicationInfo);
Christopher Tate73e02522009-07-15 14:18:26 -0700894
895 // If we've never seen this app before, schedule a backup for it
896 if (!mEverStoredApps.contains(pkg.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800897 if (DEBUG) Slog.i(TAG, "New app " + pkg.packageName
Christopher Tate73e02522009-07-15 14:18:26 -0700898 + " never backed up; scheduling");
Dan Egnor852f8e42009-09-30 11:20:45 -0700899 dataChanged(pkg.packageName);
Christopher Tate73e02522009-07-15 14:18:26 -0700900 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700901 }
Christopher Tate487529a2009-04-29 14:03:25 -0700902 }
903 }
904
Christopher Tate6785dd82009-06-18 15:58:25 -0700905 // Remove the given package's entry from our known active set. If
906 // 'packageName' is null, *all* participating apps will be removed.
Christopher Tate3799bc22009-05-06 16:13:56 -0700907 void removePackageParticipantsLocked(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 if (DEBUG) Slog.v(TAG, "removePackageParticipantsLocked: " + packageName);
Dan Egnorefe52642009-06-24 00:16:33 -0700909 List<PackageInfo> allApps = null;
Christopher Tate181fafa2009-05-14 11:12:14 -0700910 if (packageName != null) {
Dan Egnorefe52642009-06-24 00:16:33 -0700911 allApps = new ArrayList<PackageInfo>();
Christopher Tate181fafa2009-05-14 11:12:14 -0700912 try {
Dan Egnorefe52642009-06-24 00:16:33 -0700913 int flags = PackageManager.GET_SIGNATURES;
914 allApps.add(mPackageManager.getPackageInfo(packageName, flags));
Christopher Tate181fafa2009-05-14 11:12:14 -0700915 } catch (Exception e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700916 // just skip it (???)
Christopher Tate181fafa2009-05-14 11:12:14 -0700917 }
918 } else {
919 // all apps with agents
Dan Egnorefe52642009-06-24 00:16:33 -0700920 allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700921 }
922 removePackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700923 }
924
Joe Onorato8ad02812009-05-13 01:41:44 -0400925 private void removePackageParticipantsLockedInner(String packageName,
Dan Egnorefe52642009-06-24 00:16:33 -0700926 List<PackageInfo> agents) {
Christopher Tate043dadc2009-06-02 16:11:00 -0700927 if (DEBUG) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800928 Slog.v(TAG, "removePackageParticipantsLockedInner (" + packageName
Christopher Tate043dadc2009-06-02 16:11:00 -0700929 + ") removing " + agents.size() + " entries");
Dan Egnorefe52642009-06-24 00:16:33 -0700930 for (PackageInfo p : agents) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800931 Slog.v(TAG, " - " + p);
Christopher Tate043dadc2009-06-02 16:11:00 -0700932 }
933 }
Dan Egnorefe52642009-06-24 00:16:33 -0700934 for (PackageInfo pkg : agents) {
935 if (packageName == null || pkg.packageName.equals(packageName)) {
936 int uid = pkg.applicationInfo.uid;
Christopher Tate181fafa2009-05-14 11:12:14 -0700937 HashSet<ApplicationInfo> set = mBackupParticipants.get(uid);
Christopher Tate3799bc22009-05-06 16:13:56 -0700938 if (set != null) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700939 // Find the existing entry with the same package name, and remove it.
940 // We can't just remove(app) because the instances are different.
941 for (ApplicationInfo entry: set) {
Dan Egnorefe52642009-06-24 00:16:33 -0700942 if (entry.packageName.equals(pkg.packageName)) {
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700943 set.remove(entry);
Christopher Tatee97e8072009-07-15 16:45:50 -0700944 removeEverBackedUp(pkg.packageName);
Christopher Tatecd4ff2e2009-06-05 13:57:54 -0700945 break;
946 }
947 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700948 if (set.size() == 0) {
Dan Egnorefe52642009-06-24 00:16:33 -0700949 mBackupParticipants.delete(uid);
950 }
Christopher Tate3799bc22009-05-06 16:13:56 -0700951 }
952 }
953 }
954 }
955
Christopher Tate181fafa2009-05-14 11:12:14 -0700956 // Returns the set of all applications that define an android:backupAgent attribute
Christopher Tate73e02522009-07-15 14:18:26 -0700957 List<PackageInfo> allAgentPackages() {
Christopher Tate6785dd82009-06-18 15:58:25 -0700958 // !!! TODO: cache this and regenerate only when necessary
Dan Egnorefe52642009-06-24 00:16:33 -0700959 int flags = PackageManager.GET_SIGNATURES;
960 List<PackageInfo> packages = mPackageManager.getInstalledPackages(flags);
961 int N = packages.size();
962 for (int a = N-1; a >= 0; a--) {
Christopher Tate0749dcd2009-08-13 15:13:03 -0700963 PackageInfo pkg = packages.get(a);
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700964 try {
965 ApplicationInfo app = pkg.applicationInfo;
966 if (((app.flags&ApplicationInfo.FLAG_ALLOW_BACKUP) == 0)
Christopher Tatea87240c2010-02-12 14:12:34 -0800967 || app.backupAgentName == null) {
Christopher Tateb8eb1cb2009-09-16 10:57:21 -0700968 packages.remove(a);
969 }
970 else {
971 // we will need the shared library path, so look that up and store it here
972 app = mPackageManager.getApplicationInfo(pkg.packageName,
973 PackageManager.GET_SHARED_LIBRARY_FILES);
974 pkg.applicationInfo.sharedLibraryFiles = app.sharedLibraryFiles;
975 }
976 } catch (NameNotFoundException e) {
Dan Egnorefe52642009-06-24 00:16:33 -0700977 packages.remove(a);
Christopher Tate181fafa2009-05-14 11:12:14 -0700978 }
979 }
Dan Egnorefe52642009-06-24 00:16:33 -0700980 return packages;
Christopher Tate181fafa2009-05-14 11:12:14 -0700981 }
Christopher Tateaa088442009-06-16 18:25:46 -0700982
Christopher Tate3799bc22009-05-06 16:13:56 -0700983 // Reset the given package's known backup participants. Unlike add/remove, the update
984 // action cannot be passed a null package name.
985 void updatePackageParticipantsLocked(String packageName) {
986 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800987 Slog.e(TAG, "updatePackageParticipants called with null package name");
Christopher Tate3799bc22009-05-06 16:13:56 -0700988 return;
989 }
Joe Onorato8a9b2202010-02-26 18:56:32 -0800990 if (DEBUG) Slog.v(TAG, "updatePackageParticipantsLocked: " + packageName);
Christopher Tate3799bc22009-05-06 16:13:56 -0700991
992 // brute force but small code size
Dan Egnorefe52642009-06-24 00:16:33 -0700993 List<PackageInfo> allApps = allAgentPackages();
Christopher Tate181fafa2009-05-14 11:12:14 -0700994 removePackageParticipantsLockedInner(packageName, allApps);
995 addPackageParticipantsLockedInner(packageName, allApps);
Christopher Tate3799bc22009-05-06 16:13:56 -0700996 }
997
Christopher Tate84725812010-02-04 15:52:40 -0800998 // Called from the backup task: record that the given app has been successfully
Christopher Tate73e02522009-07-15 14:18:26 -0700999 // backed up at least once
1000 void logBackupComplete(String packageName) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001001 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) return;
1002
1003 synchronized (mEverStoredApps) {
1004 if (!mEverStoredApps.add(packageName)) return;
1005
1006 RandomAccessFile out = null;
1007 try {
1008 out = new RandomAccessFile(mEverStored, "rws");
1009 out.seek(out.length());
1010 out.writeUTF(packageName);
1011 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001012 Slog.e(TAG, "Can't log backup of " + packageName + " to " + mEverStored);
Dan Egnor852f8e42009-09-30 11:20:45 -07001013 } finally {
1014 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tate73e02522009-07-15 14:18:26 -07001015 }
1016 }
1017 }
1018
Christopher Tatee97e8072009-07-15 16:45:50 -07001019 // Remove our awareness of having ever backed up the given package
1020 void removeEverBackedUp(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001021 if (DEBUG) Slog.v(TAG, "Removing backed-up knowledge of " + packageName + ", new set:");
Christopher Tatee97e8072009-07-15 16:45:50 -07001022
Dan Egnor852f8e42009-09-30 11:20:45 -07001023 synchronized (mEverStoredApps) {
1024 // Rewrite the file and rename to overwrite. If we reboot in the middle,
1025 // we'll recognize on initialization time that the package no longer
1026 // exists and fix it up then.
1027 File tempKnownFile = new File(mBaseStateDir, "processed.new");
1028 RandomAccessFile known = null;
1029 try {
1030 known = new RandomAccessFile(tempKnownFile, "rws");
1031 mEverStoredApps.remove(packageName);
1032 for (String s : mEverStoredApps) {
1033 known.writeUTF(s);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001034 if (DEBUG) Slog.v(TAG, " " + s);
Christopher Tatee97e8072009-07-15 16:45:50 -07001035 }
Dan Egnor852f8e42009-09-30 11:20:45 -07001036 known.close();
1037 known = null;
1038 if (!tempKnownFile.renameTo(mEverStored)) {
1039 throw new IOException("Can't rename " + tempKnownFile + " to " + mEverStored);
1040 }
1041 } catch (IOException e) {
1042 // Bad: we couldn't create the new copy. For safety's sake we
1043 // abandon the whole process and remove all what's-backed-up
1044 // state entirely, meaning we'll force a backup pass for every
1045 // participant on the next boot or [re]install.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001046 Slog.w(TAG, "Error rewriting " + mEverStored, e);
Dan Egnor852f8e42009-09-30 11:20:45 -07001047 mEverStoredApps.clear();
1048 tempKnownFile.delete();
1049 mEverStored.delete();
1050 } finally {
1051 try { if (known != null) known.close(); } catch (IOException e) {}
Christopher Tatee97e8072009-07-15 16:45:50 -07001052 }
1053 }
1054 }
1055
Christopher Tateb49ceb32010-02-08 16:22:24 -08001056 // Persistently record the current and ancestral backup tokens as well
1057 // as the set of packages with data [supposedly] available in the
1058 // ancestral dataset.
Christopher Tate84725812010-02-04 15:52:40 -08001059 void writeRestoreTokens() {
1060 try {
1061 RandomAccessFile af = new RandomAccessFile(mTokenFile, "rwd");
Christopher Tateb49ceb32010-02-08 16:22:24 -08001062
1063 // First, the version number of this record, for futureproofing
1064 af.writeInt(CURRENT_ANCESTRAL_RECORD_VERSION);
1065
1066 // Write the ancestral and current tokens
Christopher Tate84725812010-02-04 15:52:40 -08001067 af.writeLong(mAncestralToken);
1068 af.writeLong(mCurrentToken);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001069
1070 // Now write the set of ancestral packages
1071 if (mAncestralPackages == null) {
1072 af.writeInt(-1);
1073 } else {
1074 af.writeInt(mAncestralPackages.size());
Joe Onorato8a9b2202010-02-26 18:56:32 -08001075 if (DEBUG) Slog.v(TAG, "Ancestral packages: " + mAncestralPackages.size());
Christopher Tateb49ceb32010-02-08 16:22:24 -08001076 for (String pkgName : mAncestralPackages) {
1077 af.writeUTF(pkgName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001078 if (DEBUG) Slog.v(TAG, " " + pkgName);
Christopher Tateb49ceb32010-02-08 16:22:24 -08001079 }
1080 }
Christopher Tate84725812010-02-04 15:52:40 -08001081 af.close();
1082 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001083 Slog.w(TAG, "Unable to write token file:", e);
Christopher Tate84725812010-02-04 15:52:40 -08001084 }
1085 }
1086
Dan Egnor87a02bc2009-06-17 02:30:10 -07001087 // Return the given transport
Christopher Tate91717492009-06-26 21:07:13 -07001088 private IBackupTransport getTransport(String transportName) {
1089 synchronized (mTransports) {
1090 IBackupTransport transport = mTransports.get(transportName);
1091 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001092 Slog.w(TAG, "Requested unavailable transport: " + transportName);
Christopher Tate91717492009-06-26 21:07:13 -07001093 }
1094 return transport;
Christopher Tate8c850b72009-06-07 19:33:20 -07001095 }
Christopher Tate8c850b72009-06-07 19:33:20 -07001096 }
1097
Christopher Tatedf01dea2009-06-09 20:45:02 -07001098 // fire off a backup agent, blocking until it attaches or times out
1099 IBackupAgent bindToAgentSynchronous(ApplicationInfo app, int mode) {
1100 IBackupAgent agent = null;
1101 synchronized(mAgentConnectLock) {
1102 mConnecting = true;
1103 mConnectedAgent = null;
1104 try {
1105 if (mActivityManager.bindBackupAgent(app, mode)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001106 Slog.d(TAG, "awaiting agent for " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001107
1108 // success; wait for the agent to arrive
Christopher Tatec7b31e32009-06-10 15:49:30 -07001109 // only wait 10 seconds for the clear data to happen
1110 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1111 while (mConnecting && mConnectedAgent == null
1112 && (System.currentTimeMillis() < timeoutMark)) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001113 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001114 mAgentConnectLock.wait(5000);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001115 } catch (InterruptedException e) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001116 // just bail
Christopher Tatedf01dea2009-06-09 20:45:02 -07001117 return null;
1118 }
1119 }
1120
1121 // if we timed out with no connect, abort and move on
1122 if (mConnecting == true) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001123 Slog.w(TAG, "Timeout waiting for agent " + app);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001124 return null;
1125 }
1126 agent = mConnectedAgent;
1127 }
1128 } catch (RemoteException e) {
1129 // can't happen
1130 }
1131 }
1132 return agent;
1133 }
1134
Christopher Tatec7b31e32009-06-10 15:49:30 -07001135 // clear an application's data, blocking until the operation completes or times out
1136 void clearApplicationDataSynchronous(String packageName) {
Christopher Tatef7c886b2009-06-26 15:34:09 -07001137 // Don't wipe packages marked allowClearUserData=false
1138 try {
1139 PackageInfo info = mPackageManager.getPackageInfo(packageName, 0);
1140 if ((info.applicationInfo.flags & ApplicationInfo.FLAG_ALLOW_CLEAR_USER_DATA) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001141 if (DEBUG) Slog.i(TAG, "allowClearUserData=false so not wiping "
Christopher Tatef7c886b2009-06-26 15:34:09 -07001142 + packageName);
1143 return;
1144 }
1145 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001146 Slog.w(TAG, "Tried to clear data for " + packageName + " but not found");
Christopher Tatef7c886b2009-06-26 15:34:09 -07001147 return;
1148 }
1149
Christopher Tatec7b31e32009-06-10 15:49:30 -07001150 ClearDataObserver observer = new ClearDataObserver();
1151
1152 synchronized(mClearDataLock) {
1153 mClearingData = true;
Christopher Tate9dfdac52009-08-06 14:57:53 -07001154 try {
1155 mActivityManager.clearApplicationUserData(packageName, observer);
1156 } catch (RemoteException e) {
1157 // can't happen because the activity manager is in this process
1158 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001159
1160 // only wait 10 seconds for the clear data to happen
1161 long timeoutMark = System.currentTimeMillis() + TIMEOUT_INTERVAL;
1162 while (mClearingData && (System.currentTimeMillis() < timeoutMark)) {
1163 try {
1164 mClearDataLock.wait(5000);
1165 } catch (InterruptedException e) {
1166 // won't happen, but still.
1167 mClearingData = false;
1168 }
1169 }
1170 }
1171 }
1172
1173 class ClearDataObserver extends IPackageDataObserver.Stub {
Dan Egnor852f8e42009-09-30 11:20:45 -07001174 public void onRemoveCompleted(String packageName, boolean succeeded) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001175 synchronized(mClearDataLock) {
1176 mClearingData = false;
Christopher Tatef68eb502009-06-16 11:02:01 -07001177 mClearDataLock.notifyAll();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001178 }
1179 }
1180 }
1181
Christopher Tate1bb69062010-02-19 17:02:12 -08001182 // Get the restore-set token for the best-available restore set for this package:
1183 // the active set if possible, else the ancestral one. Returns zero if none available.
1184 long getAvailableRestoreToken(String packageName) {
1185 long token = mAncestralToken;
1186 synchronized (mQueueLock) {
1187 if (mEverStoredApps.contains(packageName)) {
1188 token = mCurrentToken;
1189 }
1190 }
1191 return token;
1192 }
1193
Christopher Tate44a27902010-01-27 17:15:49 -08001194 // -----
1195 // Utility methods used by the asynchronous-with-timeout backup/restore operations
1196 boolean waitUntilOperationComplete(int token) {
1197 int finalState = OP_PENDING;
1198 synchronized (mCurrentOpLock) {
1199 try {
1200 while ((finalState = mCurrentOperations.get(token, OP_TIMEOUT)) == OP_PENDING) {
1201 try {
1202 mCurrentOpLock.wait();
1203 } catch (InterruptedException e) {}
1204 }
1205 } catch (IndexOutOfBoundsException e) {
1206 // the operation has been mysteriously cleared from our
1207 // bookkeeping -- consider this a success and ignore it.
1208 }
1209 }
1210 mBackupHandler.removeMessages(MSG_TIMEOUT);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001211 if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001212 + " complete: finalState=" + finalState);
Christopher Tate44a27902010-01-27 17:15:49 -08001213 return finalState == OP_ACKNOWLEDGED;
1214 }
1215
1216 void prepareOperationTimeout(int token, long interval) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001217 if (DEBUG) Slog.v(TAG, "starting timeout: token=" + Integer.toHexString(token)
Christopher Tate1bb69062010-02-19 17:02:12 -08001218 + " interval=" + interval);
Christopher Tate44a27902010-01-27 17:15:49 -08001219 mCurrentOperations.put(token, OP_PENDING);
1220 Message msg = mBackupHandler.obtainMessage(MSG_TIMEOUT, token, 0);
1221 mBackupHandler.sendMessageDelayed(msg, interval);
1222 }
1223
Christopher Tate043dadc2009-06-02 16:11:00 -07001224 // ----- Back up a set of applications via a worker thread -----
1225
Christopher Tate44a27902010-01-27 17:15:49 -08001226 class PerformBackupTask implements Runnable {
Christopher Tate043dadc2009-06-02 16:11:00 -07001227 private static final String TAG = "PerformBackupThread";
Christopher Tateaa088442009-06-16 18:25:46 -07001228 IBackupTransport mTransport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001229 ArrayList<BackupRequest> mQueue;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001230 File mStateDir;
Christopher Tatecde87f42009-06-12 12:55:53 -07001231 File mJournal;
Christopher Tate043dadc2009-06-02 16:11:00 -07001232
Christopher Tate44a27902010-01-27 17:15:49 -08001233 public PerformBackupTask(IBackupTransport transport, ArrayList<BackupRequest> queue,
Christopher Tatecde87f42009-06-12 12:55:53 -07001234 File journal) {
Christopher Tateaa088442009-06-16 18:25:46 -07001235 mTransport = transport;
Christopher Tate043dadc2009-06-02 16:11:00 -07001236 mQueue = queue;
Christopher Tatecde87f42009-06-12 12:55:53 -07001237 mJournal = journal;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001238
1239 try {
1240 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1241 } catch (RemoteException e) {
1242 // can't happen; the transport is local
1243 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001244 }
1245
Christopher Tate043dadc2009-06-02 16:11:00 -07001246 public void run() {
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001247 int status = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001248 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001249 if (DEBUG) Slog.v(TAG, "Beginning backup of " + mQueue.size() + " targets");
Christopher Tate043dadc2009-06-02 16:11:00 -07001250
Christopher Tate79588342009-06-30 16:11:49 -07001251 // Backups run at background priority
1252 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1253
Christopher Tate043dadc2009-06-02 16:11:00 -07001254 try {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001255 EventLog.writeEvent(EventLogTags.BACKUP_START, mTransport.transportDirName());
Dan Egnor01445162009-09-21 17:04:05 -07001256
Dan Egnor852f8e42009-09-30 11:20:45 -07001257 // If we haven't stored package manager metadata yet, we must init the transport.
1258 File pmState = new File(mStateDir, PACKAGE_MANAGER_SENTINEL);
1259 if (status == BackupConstants.TRANSPORT_OK && pmState.length() <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001260 Slog.i(TAG, "Initializing (wiping) backup state and transport storage");
Dan Egnor852f8e42009-09-30 11:20:45 -07001261 resetBackupState(mStateDir); // Just to make sure.
Dan Egnor01445162009-09-21 17:04:05 -07001262 status = mTransport.initializeDevice();
Dan Egnor726247c2009-09-29 19:12:31 -07001263 if (status == BackupConstants.TRANSPORT_OK) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001264 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001265 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001266 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001267 Slog.e(TAG, "Transport error in initializeDevice()");
Dan Egnor726247c2009-09-29 19:12:31 -07001268 }
Dan Egnor01445162009-09-21 17:04:05 -07001269 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001270
1271 // The package manager doesn't have a proper <application> etc, but since
1272 // it's running here in the system process we can just set up its agent
1273 // directly and use a synthetic BackupRequest. We always run this pass
1274 // because it's cheap and this way we guarantee that we don't get out of
1275 // step even if we're selecting among various transports at run time.
Dan Egnor01445162009-09-21 17:04:05 -07001276 if (status == BackupConstants.TRANSPORT_OK) {
1277 PackageManagerBackupAgent pmAgent = new PackageManagerBackupAgent(
1278 mPackageManager, allAgentPackages());
1279 BackupRequest pmRequest = new BackupRequest(new ApplicationInfo(), false);
1280 pmRequest.appInfo.packageName = PACKAGE_MANAGER_SENTINEL;
1281 status = processOneBackup(pmRequest,
1282 IBackupAgent.Stub.asInterface(pmAgent.onBind()), mTransport);
1283 }
Christopher Tate90967f42009-09-20 15:28:33 -07001284
Dan Egnor01445162009-09-21 17:04:05 -07001285 if (status == BackupConstants.TRANSPORT_OK) {
1286 // Now run all the backups in our queue
1287 status = doQueuedBackups(mTransport);
1288 }
1289
1290 if (status == BackupConstants.TRANSPORT_OK) {
1291 // Tell the transport to finish everything it has buffered
1292 status = mTransport.finishBackup();
1293 if (status == BackupConstants.TRANSPORT_OK) {
1294 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001295 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, mQueue.size(), millis);
Dan Egnor01445162009-09-21 17:04:05 -07001296 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001297 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(finish)");
Joe Onorato8a9b2202010-02-26 18:56:32 -08001298 Slog.e(TAG, "Transport error in finishBackup()");
Dan Egnor01445162009-09-21 17:04:05 -07001299 }
1300 }
1301
Dan Egnor01445162009-09-21 17:04:05 -07001302 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Christopher Tated55e18a2009-09-21 10:12:59 -07001303 // The backend reports that our dataset has been wiped. We need to
1304 // reset all of our bookkeeping and instead run a new backup pass for
Christopher Tatec2af5d32010-02-02 15:18:58 -08001305 // everything.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001306 EventLog.writeEvent(EventLogTags.BACKUP_RESET, mTransport.transportDirName());
Christopher Tated55e18a2009-09-21 10:12:59 -07001307 resetBackupState(mStateDir);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001308 }
1309 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001310 Slog.e(TAG, "Error in backup thread", e);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001311 status = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001312 } finally {
Christopher Tate84725812010-02-04 15:52:40 -08001313 // If everything actually went through and this is the first time we've
1314 // done a backup, we can now record what the current backup dataset token
1315 // is.
Christopher Tate29505552010-06-24 15:58:01 -07001316 if ((mCurrentToken == 0) && (status == BackupConstants.TRANSPORT_OK)) {
Christopher Tate84725812010-02-04 15:52:40 -08001317 try {
1318 mCurrentToken = mTransport.getCurrentRestoreSet();
1319 } catch (RemoteException e) { /* cannot happen */ }
1320 writeRestoreTokens();
1321 }
1322
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001323 // If things went wrong, we need to re-stage the apps we had expected
1324 // to be backing up in this pass. This journals the package names in
1325 // the current active pending-backup file, not in the we are holding
1326 // here in mJournal.
1327 if (status != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001328 Slog.w(TAG, "Backup pass unsuccessful, restaging");
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001329 for (BackupRequest req : mQueue) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001330 dataChanged(req.appInfo.packageName);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001331 }
Christopher Tate21ab6a52009-09-24 18:01:46 -07001332
1333 // We also want to reset the backup schedule based on whatever
1334 // the transport suggests by way of retry/backoff time.
1335 try {
1336 startBackupAlarmsLocked(mTransport.requestBackupTime());
1337 } catch (RemoteException e) { /* cannot happen */ }
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001338 }
1339
1340 // Either backup was successful, in which case we of course do not need
1341 // this pass's journal any more; or it failed, in which case we just
1342 // re-enqueued all of these packages in the current active journal.
1343 // Either way, we no longer need this pass's journal.
Dan Egnor852f8e42009-09-30 11:20:45 -07001344 if (mJournal != null && !mJournal.delete()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001345 Slog.e(TAG, "Unable to remove backup journal file " + mJournal);
Christopher Tateb03b3bb2009-09-22 11:14:17 -07001346 }
1347
Christopher Tatec2af5d32010-02-02 15:18:58 -08001348 // Only once we're entirely finished do we release the wakelock
Dan Egnor852f8e42009-09-30 11:20:45 -07001349 if (status == BackupConstants.TRANSPORT_NOT_INITIALIZED) {
Dan Egnor852f8e42009-09-30 11:20:45 -07001350 backupNow();
1351 }
1352
Dan Egnorbb9001c2009-07-27 12:20:13 -07001353 mWakelock.release();
Christopher Tatecde87f42009-06-12 12:55:53 -07001354 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001355 }
1356
Dan Egnor01445162009-09-21 17:04:05 -07001357 private int doQueuedBackups(IBackupTransport transport) {
Christopher Tate043dadc2009-06-02 16:11:00 -07001358 for (BackupRequest request : mQueue) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001359 Slog.d(TAG, "starting agent for backup of " + request);
Christopher Tate043dadc2009-06-02 16:11:00 -07001360
1361 IBackupAgent agent = null;
1362 int mode = (request.fullBackup)
1363 ? IApplicationThread.BACKUP_MODE_FULL
1364 : IApplicationThread.BACKUP_MODE_INCREMENTAL;
1365 try {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001366 agent = bindToAgentSynchronous(request.appInfo, mode);
1367 if (agent != null) {
Dan Egnor01445162009-09-21 17:04:05 -07001368 int result = processOneBackup(request, agent, transport);
1369 if (result != BackupConstants.TRANSPORT_OK) return result;
Christopher Tate043dadc2009-06-02 16:11:00 -07001370 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001371 } catch (SecurityException ex) {
1372 // Try for the next one.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001373 Slog.d(TAG, "error in bind/backup", ex);
Dan Egnor01445162009-09-21 17:04:05 -07001374 } finally {
1375 try { // unbind even on timeout, just in case
1376 mActivityManager.unbindBackupAgent(request.appInfo);
1377 } catch (RemoteException e) {}
Christopher Tate043dadc2009-06-02 16:11:00 -07001378 }
1379 }
Dan Egnor01445162009-09-21 17:04:05 -07001380
1381 return BackupConstants.TRANSPORT_OK;
Christopher Tate043dadc2009-06-02 16:11:00 -07001382 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001383
Dan Egnor01445162009-09-21 17:04:05 -07001384 private int processOneBackup(BackupRequest request, IBackupAgent agent,
1385 IBackupTransport transport) {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001386 final String packageName = request.appInfo.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001387 if (DEBUG) Slog.d(TAG, "processOneBackup doBackup() on " + packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001388
Dan Egnorbb9001c2009-07-27 12:20:13 -07001389 File savedStateName = new File(mStateDir, packageName);
1390 File backupDataName = new File(mDataDir, packageName + ".data");
1391 File newStateName = new File(mStateDir, packageName + ".new");
1392
1393 ParcelFileDescriptor savedState = null;
1394 ParcelFileDescriptor backupData = null;
1395 ParcelFileDescriptor newState = null;
1396
1397 PackageInfo packInfo;
Christopher Tate44a27902010-01-27 17:15:49 -08001398 int token = mTokenGenerator.nextInt();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001399 try {
1400 // Look up the package info & signatures. This is first so that if it
1401 // throws an exception, there's no file setup yet that would need to
1402 // be unraveled.
Christopher Tateabce4e82009-06-18 18:35:32 -07001403 if (packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
1404 // The metadata 'package' is synthetic
1405 packInfo = new PackageInfo();
1406 packInfo.packageName = packageName;
1407 } else {
1408 packInfo = mPackageManager.getPackageInfo(packageName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001409 PackageManager.GET_SIGNATURES);
Christopher Tateabce4e82009-06-18 18:35:32 -07001410 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001411
Christopher Tatec7b31e32009-06-10 15:49:30 -07001412 // In a full backup, we pass a null ParcelFileDescriptor as
1413 // the saved-state "file"
Dan Egnorbb9001c2009-07-27 12:20:13 -07001414 if (!request.fullBackup) {
1415 savedState = ParcelFileDescriptor.open(savedStateName,
Christopher Tatec7b31e32009-06-10 15:49:30 -07001416 ParcelFileDescriptor.MODE_READ_ONLY |
Dan Egnorbb9001c2009-07-27 12:20:13 -07001417 ParcelFileDescriptor.MODE_CREATE); // Make an empty file if necessary
1418 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001419
Dan Egnorbb9001c2009-07-27 12:20:13 -07001420 backupData = ParcelFileDescriptor.open(backupDataName,
1421 ParcelFileDescriptor.MODE_READ_WRITE |
1422 ParcelFileDescriptor.MODE_CREATE |
1423 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001424
Dan Egnorbb9001c2009-07-27 12:20:13 -07001425 newState = ParcelFileDescriptor.open(newStateName,
1426 ParcelFileDescriptor.MODE_READ_WRITE |
1427 ParcelFileDescriptor.MODE_CREATE |
1428 ParcelFileDescriptor.MODE_TRUNCATE);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001429
Christopher Tate44a27902010-01-27 17:15:49 -08001430 // Initiate the target's backup pass
1431 prepareOperationTimeout(token, TIMEOUT_BACKUP_INTERVAL);
1432 agent.doBackup(savedState, backupData, newState, token, mBackupManagerBinder);
1433 boolean success = waitUntilOperationComplete(token);
1434
1435 if (!success) {
1436 // timeout -- bail out into the failed-transaction logic
1437 throw new RuntimeException("Backup timeout");
1438 }
1439
Dan Egnorbb9001c2009-07-27 12:20:13 -07001440 logBackupComplete(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08001441 if (DEBUG) Slog.v(TAG, "doBackup() success");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001442 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001443 Slog.e(TAG, "Error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001444 EventLog.writeEvent(EventLogTags.BACKUP_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001445 backupDataName.delete();
1446 newStateName.delete();
Christopher Tated55e18a2009-09-21 10:12:59 -07001447 return BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001448 } finally {
1449 try { if (savedState != null) savedState.close(); } catch (IOException e) {}
1450 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1451 try { if (newState != null) newState.close(); } catch (IOException e) {}
1452 savedState = backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001453 synchronized (mCurrentOpLock) {
1454 mCurrentOperations.clear();
1455 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001456 }
1457
1458 // Now propagate the newly-backed-up data to the transport
Dan Egnor01445162009-09-21 17:04:05 -07001459 int result = BackupConstants.TRANSPORT_OK;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001460 try {
1461 int size = (int) backupDataName.length();
1462 if (size > 0) {
Dan Egnor01445162009-09-21 17:04:05 -07001463 if (result == BackupConstants.TRANSPORT_OK) {
1464 backupData = ParcelFileDescriptor.open(backupDataName,
1465 ParcelFileDescriptor.MODE_READ_ONLY);
1466 result = transport.performBackup(packInfo, backupData);
1467 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001468
Dan Egnor83861e72009-09-17 16:17:55 -07001469 // TODO - We call finishBackup() for each application backed up, because
1470 // we need to know now whether it succeeded or failed. Instead, we should
1471 // hold off on finishBackup() until the end, which implies holding off on
1472 // renaming *all* the output state files (see below) until that happens.
1473
Dan Egnor01445162009-09-21 17:04:05 -07001474 if (result == BackupConstants.TRANSPORT_OK) {
1475 result = transport.finishBackup();
Dan Egnor83861e72009-09-17 16:17:55 -07001476 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001477 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001478 if (DEBUG) Slog.i(TAG, "no backup data written; not calling transport");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001479 }
1480
1481 // After successful transport, delete the now-stale data
1482 // and juggle the files so that next time we supply the agent
1483 // with the new state file it just created.
Dan Egnor01445162009-09-21 17:04:05 -07001484 if (result == BackupConstants.TRANSPORT_OK) {
1485 backupDataName.delete();
1486 newStateName.renameTo(savedStateName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001487 EventLog.writeEvent(EventLogTags.BACKUP_PACKAGE, packageName, size);
Dan Egnor01445162009-09-21 17:04:05 -07001488 } else {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001489 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001490 }
Dan Egnorbb9001c2009-07-27 12:20:13 -07001491 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001492 Slog.e(TAG, "Transport error backing up " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001493 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, packageName);
Dan Egnor01445162009-09-21 17:04:05 -07001494 result = BackupConstants.TRANSPORT_ERROR;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001495 } finally {
1496 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
Christopher Tatec7b31e32009-06-10 15:49:30 -07001497 }
Christopher Tated55e18a2009-09-21 10:12:59 -07001498
Dan Egnor01445162009-09-21 17:04:05 -07001499 return result;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001500 }
Christopher Tate043dadc2009-06-02 16:11:00 -07001501 }
1502
Christopher Tatedf01dea2009-06-09 20:45:02 -07001503
1504 // ----- Restore handling -----
1505
Christopher Tate78dd4a72009-11-04 11:49:08 -08001506 private boolean signaturesMatch(Signature[] storedSigs, PackageInfo target) {
1507 // If the target resides on the system partition, we allow it to restore
1508 // data from the like-named package in a restore set even if the signatures
1509 // do not match. (Unlike general applications, those flashed to the system
1510 // partition will be signed with the device's platform certificate, so on
1511 // different phones the same system app will have different signatures.)
1512 if ((target.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001513 if (DEBUG) Slog.v(TAG, "System app " + target.packageName + " - skipping sig check");
Christopher Tate78dd4a72009-11-04 11:49:08 -08001514 return true;
1515 }
1516
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001517 // Allow unsigned apps, but not signed on one device and unsigned on the other
1518 // !!! TODO: is this the right policy?
Christopher Tate78dd4a72009-11-04 11:49:08 -08001519 Signature[] deviceSigs = target.signatures;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001520 if (DEBUG) Slog.v(TAG, "signaturesMatch(): stored=" + storedSigs
Christopher Tate6aa41f42009-06-19 14:14:22 -07001521 + " device=" + deviceSigs);
Christopher Tate20efdf6b2009-06-18 19:41:36 -07001522 if ((storedSigs == null || storedSigs.length == 0)
1523 && (deviceSigs == null || deviceSigs.length == 0)) {
1524 return true;
1525 }
1526 if (storedSigs == null || deviceSigs == null) {
1527 return false;
1528 }
1529
Christopher Tateabce4e82009-06-18 18:35:32 -07001530 // !!! TODO: this demands that every stored signature match one
1531 // that is present on device, and does not demand the converse.
1532 // Is this this right policy?
1533 int nStored = storedSigs.length;
1534 int nDevice = deviceSigs.length;
1535
1536 for (int i=0; i < nStored; i++) {
1537 boolean match = false;
1538 for (int j=0; j < nDevice; j++) {
1539 if (storedSigs[i].equals(deviceSigs[j])) {
1540 match = true;
1541 break;
1542 }
1543 }
1544 if (!match) {
1545 return false;
1546 }
1547 }
1548 return true;
1549 }
1550
Christopher Tate44a27902010-01-27 17:15:49 -08001551 class PerformRestoreTask implements Runnable {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001552 private IBackupTransport mTransport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001553 private IRestoreObserver mObserver;
Dan Egnor156411d2009-06-26 13:20:02 -07001554 private long mToken;
Christopher Tate84725812010-02-04 15:52:40 -08001555 private PackageInfo mTargetPackage;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001556 private File mStateDir;
Christopher Tate1bb69062010-02-19 17:02:12 -08001557 private int mPmToken;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001558
Christopher Tate5cbbf562009-06-22 16:44:51 -07001559 class RestoreRequest {
1560 public PackageInfo app;
1561 public int storedAppVersion;
1562
1563 RestoreRequest(PackageInfo _app, int _version) {
1564 app = _app;
1565 storedAppVersion = _version;
1566 }
1567 }
1568
Christopher Tate44a27902010-01-27 17:15:49 -08001569 PerformRestoreTask(IBackupTransport transport, IRestoreObserver observer,
Christopher Tate1bb69062010-02-19 17:02:12 -08001570 long restoreSetToken, PackageInfo targetPackage, int pmToken) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001571 mTransport = transport;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001572 mObserver = observer;
Christopher Tate9bbc21a2009-06-10 20:23:25 -07001573 mToken = restoreSetToken;
Christopher Tate84725812010-02-04 15:52:40 -08001574 mTargetPackage = targetPackage;
Christopher Tate1bb69062010-02-19 17:02:12 -08001575 mPmToken = pmToken;
Christopher Tate5cb400b2009-06-25 16:03:14 -07001576
1577 try {
1578 mStateDir = new File(mBaseStateDir, transport.transportDirName());
1579 } catch (RemoteException e) {
1580 // can't happen; the transport is local
1581 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001582 }
1583
Christopher Tatedf01dea2009-06-09 20:45:02 -07001584 public void run() {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001585 long startRealtime = SystemClock.elapsedRealtime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001586 if (DEBUG) Slog.v(TAG, "Beginning restore process mTransport=" + mTransport
Christopher Tate84725812010-02-04 15:52:40 -08001587 + " mObserver=" + mObserver + " mToken=" + Long.toHexString(mToken)
Christopher Tate1bb69062010-02-19 17:02:12 -08001588 + " mTargetPackage=" + mTargetPackage + " mPmToken=" + mPmToken);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001589
Christopher Tateb49ceb32010-02-08 16:22:24 -08001590 PackageManagerBackupAgent pmAgent = null;
Christopher Tate7d562ec2009-06-25 18:03:43 -07001591 int error = -1; // assume error
1592
Dan Egnorefe52642009-06-24 00:16:33 -07001593 // build the set of apps to restore
Christopher Tatedf01dea2009-06-09 20:45:02 -07001594 try {
Dan Egnorbb9001c2009-07-27 12:20:13 -07001595 // TODO: Log this before getAvailableRestoreSets, somehow
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001596 EventLog.writeEvent(EventLogTags.RESTORE_START, mTransport.transportDirName(), mToken);
Christopher Tateabce4e82009-06-18 18:35:32 -07001597
Dan Egnorefe52642009-06-24 00:16:33 -07001598 // Get the list of all packages which have backup enabled.
1599 // (Include the Package Manager metadata pseudo-package first.)
1600 ArrayList<PackageInfo> restorePackages = new ArrayList<PackageInfo>();
1601 PackageInfo omPackage = new PackageInfo();
1602 omPackage.packageName = PACKAGE_MANAGER_SENTINEL;
1603 restorePackages.add(omPackage);
Christopher Tatedf01dea2009-06-09 20:45:02 -07001604
Dan Egnorefe52642009-06-24 00:16:33 -07001605 List<PackageInfo> agentPackages = allAgentPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001606 if (mTargetPackage == null) {
1607 restorePackages.addAll(agentPackages);
1608 } else {
1609 // Just one package to attempt restore of
1610 restorePackages.add(mTargetPackage);
1611 }
Dan Egnorefe52642009-06-24 00:16:33 -07001612
Christopher Tate7d562ec2009-06-25 18:03:43 -07001613 // let the observer know that we're running
1614 if (mObserver != null) {
1615 try {
1616 // !!! TODO: get an actual count from the transport after
1617 // its startRestore() runs?
1618 mObserver.restoreStarting(restorePackages.size());
1619 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001620 Slog.d(TAG, "Restore observer died at restoreStarting");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001621 mObserver = null;
1622 }
1623 }
1624
Dan Egnor01445162009-09-21 17:04:05 -07001625 if (mTransport.startRestore(mToken, restorePackages.toArray(new PackageInfo[0])) !=
1626 BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001627 Slog.e(TAG, "Error starting restore operation");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001628 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001629 return;
1630 }
1631
1632 String packageName = mTransport.nextRestorePackage();
1633 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 Slog.e(TAG, "Error getting first restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001635 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001636 return;
1637 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 Slog.i(TAG, "No restore data available");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001639 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001640 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, 0, millis);
Dan Egnorefe52642009-06-24 00:16:33 -07001641 return;
1642 } else if (!packageName.equals(PACKAGE_MANAGER_SENTINEL)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001643 Slog.e(TAG, "Expected restore data for \"" + PACKAGE_MANAGER_SENTINEL
Dan Egnorefe52642009-06-24 00:16:33 -07001644 + "\", found only \"" + packageName + "\"");
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 data missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001647 return;
1648 }
1649
1650 // Pull the Package Manager metadata from the restore set first
Christopher Tateb49ceb32010-02-08 16:22:24 -08001651 pmAgent = new PackageManagerBackupAgent(
Dan Egnorefe52642009-06-24 00:16:33 -07001652 mPackageManager, agentPackages);
1653 processOneRestore(omPackage, 0, IBackupAgent.Stub.asInterface(pmAgent.onBind()));
1654
Christopher Tate8c032472009-07-02 14:28:47 -07001655 // Verify that the backup set includes metadata. If not, we can't do
1656 // signature/version verification etc, so we simply do not proceed with
1657 // the restore operation.
Christopher Tate3d7cd132009-07-07 14:23:07 -07001658 if (!pmAgent.hasMetadata()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001659 Slog.e(TAG, "No restore metadata available, so not restoring settings");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001660 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, PACKAGE_MANAGER_SENTINEL,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001661 "Package manager restore metadata missing");
Christopher Tate8c032472009-07-02 14:28:47 -07001662 return;
1663 }
1664
Christopher Tate7d562ec2009-06-25 18:03:43 -07001665 int count = 0;
Dan Egnorefe52642009-06-24 00:16:33 -07001666 for (;;) {
1667 packageName = mTransport.nextRestorePackage();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001668
Dan Egnorefe52642009-06-24 00:16:33 -07001669 if (packageName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001670 Slog.e(TAG, "Error getting next restore package");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001671 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorefe52642009-06-24 00:16:33 -07001672 return;
1673 } else if (packageName.equals("")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001674 if (DEBUG) Slog.v(TAG, "No next package, finishing restore");
Dan Egnorefe52642009-06-24 00:16:33 -07001675 break;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001676 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001677
Christopher Tate7d562ec2009-06-25 18:03:43 -07001678 if (mObserver != null) {
Christopher Tate7d562ec2009-06-25 18:03:43 -07001679 try {
Christopher Tate9c3cee92010-03-25 16:06:43 -07001680 mObserver.onUpdate(count, packageName);
Christopher Tate7d562ec2009-06-25 18:03:43 -07001681 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001682 Slog.d(TAG, "Restore observer died in onUpdate");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001683 mObserver = null;
1684 }
1685 }
1686
Dan Egnorefe52642009-06-24 00:16:33 -07001687 Metadata metaInfo = pmAgent.getRestoredMetadata(packageName);
1688 if (metaInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001689 Slog.e(TAG, "Missing metadata for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001690 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001691 "Package metadata missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001692 continue;
1693 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001694
Dan Egnorbb9001c2009-07-27 12:20:13 -07001695 PackageInfo packageInfo;
1696 try {
1697 int flags = PackageManager.GET_SIGNATURES;
1698 packageInfo = mPackageManager.getPackageInfo(packageName, flags);
1699 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001700 Slog.e(TAG, "Invalid package restoring data", e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001701 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001702 "Package missing on device");
1703 continue;
1704 }
1705
Dan Egnorefe52642009-06-24 00:16:33 -07001706 if (metaInfo.versionCode > packageInfo.versionCode) {
Christopher Tate3dda5182010-02-24 16:06:18 -08001707 // Data is from a "newer" version of the app than we have currently
1708 // installed. If the app has not declared that it is prepared to
1709 // handle this case, we do not attempt the restore.
1710 if ((packageInfo.applicationInfo.flags
1711 & ApplicationInfo.FLAG_RESTORE_ANY_VERSION) == 0) {
1712 String message = "Version " + metaInfo.versionCode
1713 + " > installed version " + packageInfo.versionCode;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001714 Slog.w(TAG, "Package " + packageName + ": " + message);
Christopher Tate3dda5182010-02-24 16:06:18 -08001715 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE,
1716 packageName, message);
1717 continue;
1718 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001719 if (DEBUG) Slog.v(TAG, "Version " + metaInfo.versionCode
Christopher Tate3dda5182010-02-24 16:06:18 -08001720 + " > installed " + packageInfo.versionCode
1721 + " but restoreAnyVersion");
1722 }
Dan Egnorefe52642009-06-24 00:16:33 -07001723 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001724
Christopher Tate78dd4a72009-11-04 11:49:08 -08001725 if (!signaturesMatch(metaInfo.signatures, packageInfo)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001726 Slog.w(TAG, "Signature mismatch restoring " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001727 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001728 "Signature mismatch");
Dan Egnorefe52642009-06-24 00:16:33 -07001729 continue;
1730 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001731
Joe Onorato8a9b2202010-02-26 18:56:32 -08001732 if (DEBUG) Slog.v(TAG, "Package " + packageName
Dan Egnorefe52642009-06-24 00:16:33 -07001733 + " restore version [" + metaInfo.versionCode
1734 + "] is compatible with installed version ["
1735 + packageInfo.versionCode + "]");
Christopher Tatec7b31e32009-06-10 15:49:30 -07001736
Christopher Tate3de55bc2010-03-12 17:28:08 -08001737 // Then set up and bind the agent
Dan Egnorefe52642009-06-24 00:16:33 -07001738 IBackupAgent agent = bindToAgentSynchronous(
1739 packageInfo.applicationInfo,
Christopher Tate3de55bc2010-03-12 17:28:08 -08001740 IApplicationThread.BACKUP_MODE_INCREMENTAL);
Dan Egnorefe52642009-06-24 00:16:33 -07001741 if (agent == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001742 Slog.w(TAG, "Can't find backup agent for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001743 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName,
Dan Egnorbb9001c2009-07-27 12:20:13 -07001744 "Restore agent missing");
Dan Egnorefe52642009-06-24 00:16:33 -07001745 continue;
Christopher Tatedf01dea2009-06-09 20:45:02 -07001746 }
1747
Christopher Tate5e1ab332009-09-01 20:32:49 -07001748 // And then finally run the restore on this agent
Dan Egnorefe52642009-06-24 00:16:33 -07001749 try {
1750 processOneRestore(packageInfo, metaInfo.versionCode, agent);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001751 ++count;
Dan Egnorefe52642009-06-24 00:16:33 -07001752 } finally {
Christopher Tate5e1ab332009-09-01 20:32:49 -07001753 // unbind and tidy up even on timeout or failure, just in case
Dan Egnorefe52642009-06-24 00:16:33 -07001754 mActivityManager.unbindBackupAgent(packageInfo.applicationInfo);
Christopher Tate5e1ab332009-09-01 20:32:49 -07001755
1756 // The agent was probably running with a stub Application object,
1757 // which isn't a valid run mode for the main app logic. Shut
1758 // down the app so that next time it's launched, it gets the
Christopher Tate3dda5182010-02-24 16:06:18 -08001759 // usual full initialization. Note that this is only done for
1760 // full-system restores: when a single app has requested a restore,
1761 // it is explicitly not killed following that operation.
1762 if (mTargetPackage == null && (packageInfo.applicationInfo.flags
Christopher Tate5e1ab332009-09-01 20:32:49 -07001763 & ApplicationInfo.FLAG_KILL_AFTER_RESTORE) != 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001764 if (DEBUG) Slog.d(TAG, "Restore complete, killing host process of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07001765 + packageInfo.applicationInfo.processName);
1766 mActivityManager.killApplicationProcess(
1767 packageInfo.applicationInfo.processName,
1768 packageInfo.applicationInfo.uid);
1769 }
Dan Egnorefe52642009-06-24 00:16:33 -07001770 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001771 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001772
1773 // if we get this far, report success to the observer
1774 error = 0;
Dan Egnorbb9001c2009-07-27 12:20:13 -07001775 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001776 EventLog.writeEvent(EventLogTags.RESTORE_SUCCESS, count, millis);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001777 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001778 Slog.e(TAG, "Error in restore thread", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001779 } finally {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001780 if (DEBUG) Slog.d(TAG, "finishing restore mObserver=" + mObserver);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001781
Dan Egnorefe52642009-06-24 00:16:33 -07001782 try {
1783 mTransport.finishRestore();
1784 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001785 Slog.e(TAG, "Error finishing restore", e);
Dan Egnorefe52642009-06-24 00:16:33 -07001786 }
Christopher Tate7d562ec2009-06-25 18:03:43 -07001787
1788 if (mObserver != null) {
1789 try {
1790 mObserver.restoreFinished(error);
1791 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001792 Slog.d(TAG, "Restore observer died at restoreFinished");
Christopher Tate7d562ec2009-06-25 18:03:43 -07001793 }
1794 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001795
Christopher Tate84725812010-02-04 15:52:40 -08001796 // If this was a restoreAll operation, record that this was our
Christopher Tateb49ceb32010-02-08 16:22:24 -08001797 // ancestral dataset, as well as the set of apps that are possibly
1798 // restoreable from the dataset
1799 if (mTargetPackage == null && pmAgent != null) {
1800 mAncestralPackages = pmAgent.getRestoredPackages();
Christopher Tate84725812010-02-04 15:52:40 -08001801 mAncestralToken = mToken;
1802 writeRestoreTokens();
1803 }
1804
Christopher Tate1bb69062010-02-19 17:02:12 -08001805 // We must under all circumstances tell the Package Manager to
1806 // proceed with install notifications if it's waiting for us.
1807 if (mPmToken > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001808 if (DEBUG) Slog.v(TAG, "finishing PM token " + mPmToken);
Christopher Tate1bb69062010-02-19 17:02:12 -08001809 try {
1810 mPackageManagerBinder.finishPackageInstall(mPmToken);
1811 } catch (RemoteException e) { /* can't happen */ }
1812 }
1813
Christopher Tateb6787f22009-07-02 17:40:45 -07001814 // done; we can finally release the wakelock
1815 mWakelock.release();
Christopher Tatedf01dea2009-06-09 20:45:02 -07001816 }
1817 }
1818
Dan Egnorefe52642009-06-24 00:16:33 -07001819 // Do the guts of a restore of one application, using mTransport.getRestoreData().
1820 void processOneRestore(PackageInfo app, int appVersionCode, IBackupAgent agent) {
Christopher Tatedf01dea2009-06-09 20:45:02 -07001821 // !!! TODO: actually run the restore through mTransport
Christopher Tatec7b31e32009-06-10 15:49:30 -07001822 final String packageName = app.packageName;
1823
Joe Onorato8a9b2202010-02-26 18:56:32 -08001824 if (DEBUG) Slog.d(TAG, "processOneRestore packageName=" + packageName);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04001825
Christopher Tatec7b31e32009-06-10 15:49:30 -07001826 // !!! TODO: get the dirs from the transport
1827 File backupDataName = new File(mDataDir, packageName + ".restore");
Dan Egnorbb9001c2009-07-27 12:20:13 -07001828 File newStateName = new File(mStateDir, packageName + ".new");
1829 File savedStateName = new File(mStateDir, packageName);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001830
Dan Egnorbb9001c2009-07-27 12:20:13 -07001831 ParcelFileDescriptor backupData = null;
1832 ParcelFileDescriptor newState = null;
1833
Christopher Tate44a27902010-01-27 17:15:49 -08001834 int token = mTokenGenerator.nextInt();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001835 try {
Christopher Tatec7b31e32009-06-10 15:49:30 -07001836 // Run the transport's restore pass
Dan Egnorbb9001c2009-07-27 12:20:13 -07001837 backupData = ParcelFileDescriptor.open(backupDataName,
1838 ParcelFileDescriptor.MODE_READ_WRITE |
1839 ParcelFileDescriptor.MODE_CREATE |
1840 ParcelFileDescriptor.MODE_TRUNCATE);
1841
Dan Egnor01445162009-09-21 17:04:05 -07001842 if (mTransport.getRestoreData(backupData) != BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001843 Slog.e(TAG, "Error getting restore data for " + packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001844 EventLog.writeEvent(EventLogTags.RESTORE_TRANSPORT_FAILURE);
Dan Egnorbb9001c2009-07-27 12:20:13 -07001845 return;
Christopher Tatec7b31e32009-06-10 15:49:30 -07001846 }
1847
1848 // Okay, we have the data. Now have the agent do the restore.
Dan Egnorbb9001c2009-07-27 12:20:13 -07001849 backupData.close();
Christopher Tatec7b31e32009-06-10 15:49:30 -07001850 backupData = ParcelFileDescriptor.open(backupDataName,
1851 ParcelFileDescriptor.MODE_READ_ONLY);
1852
Dan Egnorbb9001c2009-07-27 12:20:13 -07001853 newState = ParcelFileDescriptor.open(newStateName,
1854 ParcelFileDescriptor.MODE_READ_WRITE |
1855 ParcelFileDescriptor.MODE_CREATE |
1856 ParcelFileDescriptor.MODE_TRUNCATE);
1857
Christopher Tate44a27902010-01-27 17:15:49 -08001858 // Kick off the restore, checking for hung agents
1859 prepareOperationTimeout(token, TIMEOUT_RESTORE_INTERVAL);
1860 agent.doRestore(backupData, appVersionCode, newState, token, mBackupManagerBinder);
1861 boolean success = waitUntilOperationComplete(token);
1862
1863 if (!success) {
1864 throw new RuntimeException("restore timeout");
1865 }
Christopher Tatec7b31e32009-06-10 15:49:30 -07001866
1867 // if everything went okay, remember the recorded state now
Christopher Tate90967f42009-09-20 15:28:33 -07001868 //
1869 // !!! TODO: the restored data should be migrated on the server
1870 // side into the current dataset. In that case the new state file
1871 // we just created would reflect the data already extant in the
1872 // backend, so there'd be nothing more to do. Until that happens,
1873 // however, we need to make sure that we record the data to the
1874 // current backend dataset. (Yes, this means shipping the data over
1875 // the wire in both directions. That's bad, but consistency comes
1876 // first, then efficiency.) Once we introduce server-side data
1877 // migration to the newly-restored device's dataset, we will change
1878 // the following from a discard of the newly-written state to the
1879 // "correct" operation of renaming into the canonical state blob.
1880 newStateName.delete(); // TODO: remove; see above comment
1881 //newStateName.renameTo(savedStateName); // TODO: replace with this
1882
Dan Egnorbb9001c2009-07-27 12:20:13 -07001883 int size = (int) backupDataName.length();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001884 EventLog.writeEvent(EventLogTags.RESTORE_PACKAGE, packageName, size);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001885 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001886 Slog.e(TAG, "Error restoring data for " + packageName, e);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001887 EventLog.writeEvent(EventLogTags.RESTORE_AGENT_FAILURE, packageName, e.toString());
Dan Egnorbb9001c2009-07-27 12:20:13 -07001888
Christopher Tate96733042009-07-20 14:49:13 -07001889 // If the agent fails restore, it might have put the app's data
1890 // into an incoherent state. For consistency we wipe its data
1891 // again in this case before propagating the exception
Christopher Tate96733042009-07-20 14:49:13 -07001892 clearApplicationDataSynchronous(packageName);
Christopher Tate1531dc82009-07-24 16:37:43 -07001893 } finally {
1894 backupDataName.delete();
Dan Egnorbb9001c2009-07-27 12:20:13 -07001895 try { if (backupData != null) backupData.close(); } catch (IOException e) {}
1896 try { if (newState != null) newState.close(); } catch (IOException e) {}
1897 backupData = newState = null;
Christopher Tate44a27902010-01-27 17:15:49 -08001898 mCurrentOperations.delete(token);
Christopher Tatec7b31e32009-06-10 15:49:30 -07001899 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07001900 }
1901 }
1902
Christopher Tate44a27902010-01-27 17:15:49 -08001903 class PerformClearTask implements Runnable {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001904 IBackupTransport mTransport;
1905 PackageInfo mPackage;
1906
Christopher Tate44a27902010-01-27 17:15:49 -08001907 PerformClearTask(IBackupTransport transport, PackageInfo packageInfo) {
Christopher Tateee0e78a2009-07-02 11:17:03 -07001908 mTransport = transport;
1909 mPackage = packageInfo;
1910 }
1911
Christopher Tateee0e78a2009-07-02 11:17:03 -07001912 public void run() {
1913 try {
1914 // Clear the on-device backup state to ensure a full backup next time
1915 File stateDir = new File(mBaseStateDir, mTransport.transportDirName());
1916 File stateFile = new File(stateDir, mPackage.packageName);
1917 stateFile.delete();
1918
1919 // Tell the transport to remove all the persistent storage for the app
Christopher Tate13f4a642009-09-30 20:06:45 -07001920 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001921 mTransport.clearBackupData(mPackage);
1922 } catch (RemoteException e) {
1923 // can't happen; the transport is local
1924 } finally {
1925 try {
Christopher Tate13f4a642009-09-30 20:06:45 -07001926 // TODO - need to handle failures
Christopher Tateee0e78a2009-07-02 11:17:03 -07001927 mTransport.finishBackup();
1928 } catch (RemoteException e) {
1929 // can't happen; the transport is local
1930 }
Christopher Tateb6787f22009-07-02 17:40:45 -07001931
1932 // Last but not least, release the cpu
1933 mWakelock.release();
Christopher Tateee0e78a2009-07-02 11:17:03 -07001934 }
1935 }
1936 }
1937
Christopher Tate44a27902010-01-27 17:15:49 -08001938 class PerformInitializeTask implements Runnable {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001939 HashSet<String> mQueue;
1940
Christopher Tate44a27902010-01-27 17:15:49 -08001941 PerformInitializeTask(HashSet<String> transportNames) {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001942 mQueue = transportNames;
1943 }
1944
Christopher Tate4cc86e12009-09-21 19:36:51 -07001945 public void run() {
Christopher Tate4cc86e12009-09-21 19:36:51 -07001946 try {
1947 for (String transportName : mQueue) {
1948 IBackupTransport transport = getTransport(transportName);
1949 if (transport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001950 Slog.e(TAG, "Requested init for " + transportName + " but not found");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001951 continue;
1952 }
1953
Joe Onorato8a9b2202010-02-26 18:56:32 -08001954 Slog.i(TAG, "Initializing (wiping) backup transport storage: " + transportName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001955 EventLog.writeEvent(EventLogTags.BACKUP_START, transport.transportDirName());
Dan Egnor726247c2009-09-29 19:12:31 -07001956 long startRealtime = SystemClock.elapsedRealtime();
1957 int status = transport.initializeDevice();
Christopher Tate4cc86e12009-09-21 19:36:51 -07001958
Christopher Tate4cc86e12009-09-21 19:36:51 -07001959 if (status == BackupConstants.TRANSPORT_OK) {
1960 status = transport.finishBackup();
1961 }
1962
1963 // Okay, the wipe really happened. Clean up our local bookkeeping.
1964 if (status == BackupConstants.TRANSPORT_OK) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001965 Slog.i(TAG, "Device init successful");
Dan Egnor726247c2009-09-29 19:12:31 -07001966 int millis = (int) (SystemClock.elapsedRealtime() - startRealtime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001967 EventLog.writeEvent(EventLogTags.BACKUP_INITIALIZE);
Dan Egnor726247c2009-09-29 19:12:31 -07001968 resetBackupState(new File(mBaseStateDir, transport.transportDirName()));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001969 EventLog.writeEvent(EventLogTags.BACKUP_SUCCESS, 0, millis);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001970 synchronized (mQueueLock) {
1971 recordInitPendingLocked(false, transportName);
1972 }
Dan Egnor726247c2009-09-29 19:12:31 -07001973 } else {
1974 // If this didn't work, requeue this one and try again
1975 // after a suitable interval
Joe Onorato8a9b2202010-02-26 18:56:32 -08001976 Slog.e(TAG, "Transport error in initializeDevice()");
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001977 EventLog.writeEvent(EventLogTags.BACKUP_TRANSPORT_FAILURE, "(initialize)");
Christopher Tate4cc86e12009-09-21 19:36:51 -07001978 synchronized (mQueueLock) {
1979 recordInitPendingLocked(true, transportName);
1980 }
1981 // do this via another alarm to make sure of the wakelock states
1982 long delay = transport.requestBackupTime();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 if (DEBUG) Slog.w(TAG, "init failed on "
Christopher Tate4cc86e12009-09-21 19:36:51 -07001984 + transportName + " resched in " + delay);
1985 mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1986 System.currentTimeMillis() + delay, mRunInitIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001987 }
Christopher Tate4cc86e12009-09-21 19:36:51 -07001988 }
1989 } catch (RemoteException e) {
1990 // can't happen; the transports are local
1991 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001992 Slog.e(TAG, "Unexpected error performing init", e);
Christopher Tate4cc86e12009-09-21 19:36:51 -07001993 } finally {
Christopher Tatec2af5d32010-02-02 15:18:58 -08001994 // Done; release the wakelock
Christopher Tate4cc86e12009-09-21 19:36:51 -07001995 mWakelock.release();
1996 }
1997 }
1998 }
1999
Christopher Tatedf01dea2009-06-09 20:45:02 -07002000
Christopher Tate487529a2009-04-29 14:03:25 -07002001 // ----- IBackupManager binder interface -----
Christopher Tatedf01dea2009-06-09 20:45:02 -07002002
Dan Egnor852f8e42009-09-30 11:20:45 -07002003 public void dataChanged(String packageName) {
Christopher Tate487529a2009-04-29 14:03:25 -07002004 // Record that we need a backup pass for the caller. Since multiple callers
2005 // may share a uid, we need to note all candidates within that uid and schedule
2006 // a backup pass for each of them.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002007 EventLog.writeEvent(EventLogTags.BACKUP_DATA_CHANGED, packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002008
Christopher Tate63d27002009-06-16 17:16:42 -07002009 // If the caller does not hold the BACKUP permission, it can only request a
2010 // backup of its own data.
2011 HashSet<ApplicationInfo> targets;
Dianne Hackborncf098292009-07-01 19:55:20 -07002012 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tate63d27002009-06-16 17:16:42 -07002013 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2014 targets = mBackupParticipants.get(Binder.getCallingUid());
2015 } else {
2016 // a caller with full permission can ask to back up any participating app
2017 // !!! TODO: allow backup of ANY app?
Christopher Tate63d27002009-06-16 17:16:42 -07002018 targets = new HashSet<ApplicationInfo>();
2019 int N = mBackupParticipants.size();
2020 for (int i = 0; i < N; i++) {
2021 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2022 if (s != null) {
2023 targets.addAll(s);
2024 }
2025 }
2026 }
Christopher Tate487529a2009-04-29 14:03:25 -07002027 if (targets != null) {
2028 synchronized (mQueueLock) {
2029 // Note that this client has made data changes that need to be backed up
Christopher Tate181fafa2009-05-14 11:12:14 -07002030 for (ApplicationInfo app : targets) {
Christopher Tatea8bf8152009-04-30 11:36:21 -07002031 // validate the caller-supplied package name against the known set of
2032 // packages associated with this uid
Christopher Tate181fafa2009-05-14 11:12:14 -07002033 if (app.packageName.equals(packageName)) {
Joe Onorato8ad02812009-05-13 01:41:44 -04002034 // Add the caller to the set of pending backups. If there is
2035 // one already there, then overwrite it, but no harm done.
Christopher Tate181fafa2009-05-14 11:12:14 -07002036 BackupRequest req = new BackupRequest(app, false);
Christopher Tatea7de3842009-07-07 14:50:26 -07002037 if (mPendingBackups.put(app, req) == null) {
2038 // Journal this request in case of crash. The put()
2039 // operation returned null when this package was not already
2040 // in the set; we want to avoid touching the disk redundantly.
2041 writeToJournalLocked(packageName);
Christopher Tate487529a2009-04-29 14:03:25 -07002042
Christopher Tate22b60d82009-07-07 16:36:02 -07002043 if (DEBUG) {
2044 int numKeys = mPendingBackups.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002045 Slog.d(TAG, "Now awaiting backup for " + numKeys + " participants:");
Christopher Tate22b60d82009-07-07 16:36:02 -07002046 for (BackupRequest b : mPendingBackups.values()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002047 Slog.d(TAG, " + " + b + " agent=" + b.appInfo.backupAgentName);
Christopher Tate22b60d82009-07-07 16:36:02 -07002048 }
2049 }
2050 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002051 }
2052 }
Christopher Tate487529a2009-04-29 14:03:25 -07002053 }
Christopher Tatedf01dea2009-06-09 20:45:02 -07002054 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002055 Slog.w(TAG, "dataChanged but no participant pkg='" + packageName + "'"
Christopher Tate73e02522009-07-15 14:18:26 -07002056 + " uid=" + Binder.getCallingUid());
Christopher Tate487529a2009-04-29 14:03:25 -07002057 }
2058 }
Christopher Tate46758122009-05-06 11:22:00 -07002059
Christopher Tatecde87f42009-06-12 12:55:53 -07002060 private void writeToJournalLocked(String str) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002061 RandomAccessFile out = null;
2062 try {
2063 if (mJournal == null) mJournal = File.createTempFile("journal", null, mJournalDir);
2064 out = new RandomAccessFile(mJournal, "rws");
2065 out.seek(out.length());
2066 out.writeUTF(str);
2067 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002068 Slog.e(TAG, "Can't write " + str + " to backup journal", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002069 mJournal = null;
2070 } finally {
2071 try { if (out != null) out.close(); } catch (IOException e) {}
Christopher Tatecde87f42009-06-12 12:55:53 -07002072 }
2073 }
2074
Christopher Tateee0e78a2009-07-02 11:17:03 -07002075 // Clear the given package's backup data from the current transport
2076 public void clearBackupData(String packageName) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002077 if (DEBUG) Slog.v(TAG, "clearBackupData() of " + packageName);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002078 PackageInfo info;
2079 try {
2080 info = mPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
2081 } catch (NameNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002082 Slog.d(TAG, "No such package '" + packageName + "' - not clearing backup data");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002083 return;
2084 }
2085
2086 // If the caller does not hold the BACKUP permission, it can only request a
2087 // wipe of its own backed-up data.
2088 HashSet<ApplicationInfo> apps;
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002089 if ((mContext.checkPermission(android.Manifest.permission.BACKUP, Binder.getCallingPid(),
Christopher Tateee0e78a2009-07-02 11:17:03 -07002090 Binder.getCallingUid())) == PackageManager.PERMISSION_DENIED) {
2091 apps = mBackupParticipants.get(Binder.getCallingUid());
2092 } else {
2093 // a caller with full permission can ask to back up any participating app
2094 // !!! TODO: allow data-clear of ANY app?
Joe Onorato8a9b2202010-02-26 18:56:32 -08002095 if (DEBUG) Slog.v(TAG, "Privileged caller, allowing clear of other apps");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002096 apps = new HashSet<ApplicationInfo>();
2097 int N = mBackupParticipants.size();
2098 for (int i = 0; i < N; i++) {
2099 HashSet<ApplicationInfo> s = mBackupParticipants.valueAt(i);
2100 if (s != null) {
2101 apps.addAll(s);
2102 }
2103 }
2104 }
2105
2106 // now find the given package in the set of candidate apps
2107 for (ApplicationInfo app : apps) {
2108 if (app.packageName.equals(packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002109 if (DEBUG) Slog.v(TAG, "Found the app - running clear process");
Christopher Tateee0e78a2009-07-02 11:17:03 -07002110 // found it; fire off the clear request
2111 synchronized (mQueueLock) {
Christopher Tateaa93b042009-08-05 18:21:40 -07002112 long oldId = Binder.clearCallingIdentity();
Christopher Tateb6787f22009-07-02 17:40:45 -07002113 mWakelock.acquire();
Christopher Tateee0e78a2009-07-02 11:17:03 -07002114 Message msg = mBackupHandler.obtainMessage(MSG_RUN_CLEAR,
2115 new ClearParams(getTransport(mCurrentTransport), info));
2116 mBackupHandler.sendMessage(msg);
Christopher Tateaa93b042009-08-05 18:21:40 -07002117 Binder.restoreCallingIdentity(oldId);
Christopher Tateee0e78a2009-07-02 11:17:03 -07002118 }
2119 break;
2120 }
2121 }
2122 }
2123
Christopher Tateace7f092009-06-15 18:07:25 -07002124 // Run a backup pass immediately for any applications that have declared
2125 // that they have pending updates.
Dan Egnor852f8e42009-09-30 11:20:45 -07002126 public void backupNow() {
Joe Onorato5933a492009-07-23 18:24:08 -04002127 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "backupNow");
Christopher Tate043dadc2009-06-02 16:11:00 -07002128
Joe Onorato8a9b2202010-02-26 18:56:32 -08002129 if (DEBUG) Slog.v(TAG, "Scheduling immediate backup pass");
Christopher Tate46758122009-05-06 11:22:00 -07002130 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002131 // Because the alarms we are using can jitter, and we want an *immediate*
2132 // backup pass to happen, we restart the timer beginning with "next time,"
2133 // then manually fire the backup trigger intent ourselves.
2134 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tateb6787f22009-07-02 17:40:45 -07002135 try {
Christopher Tateb6787f22009-07-02 17:40:45 -07002136 mRunBackupIntent.send();
2137 } catch (PendingIntent.CanceledException e) {
2138 // should never happen
Joe Onorato8a9b2202010-02-26 18:56:32 -08002139 Slog.e(TAG, "run-backup intent cancelled!");
Christopher Tateb6787f22009-07-02 17:40:45 -07002140 }
Christopher Tate46758122009-05-06 11:22:00 -07002141 }
2142 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002143
Christopher Tate8031a3d2009-07-06 16:36:05 -07002144 // Enable/disable the backup service
Christopher Tate6ef58a12009-06-29 14:56:28 -07002145 public void setBackupEnabled(boolean enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002146 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2147 "setBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002148
Joe Onorato8a9b2202010-02-26 18:56:32 -08002149 Slog.i(TAG, "Backup enabled => " + enable);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002150
Christopher Tate6ef58a12009-06-29 14:56:28 -07002151 boolean wasEnabled = mEnabled;
2152 synchronized (this) {
Dianne Hackborncf098292009-07-01 19:55:20 -07002153 Settings.Secure.putInt(mContext.getContentResolver(),
2154 Settings.Secure.BACKUP_ENABLED, enable ? 1 : 0);
Christopher Tate6ef58a12009-06-29 14:56:28 -07002155 mEnabled = enable;
2156 }
2157
Christopher Tate49401dd2009-07-01 12:34:29 -07002158 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002159 if (enable && !wasEnabled && mProvisioned) {
Christopher Tate49401dd2009-07-01 12:34:29 -07002160 // if we've just been enabled, start scheduling backup passes
Christopher Tate8031a3d2009-07-06 16:36:05 -07002161 startBackupAlarmsLocked(BACKUP_INTERVAL);
Christopher Tate49401dd2009-07-01 12:34:29 -07002162 } else if (!enable) {
Christopher Tateb6787f22009-07-02 17:40:45 -07002163 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002164 if (DEBUG) Slog.i(TAG, "Opting out of backup");
Christopher Tate4cc86e12009-09-21 19:36:51 -07002165
Christopher Tateb6787f22009-07-02 17:40:45 -07002166 mAlarmManager.cancel(mRunBackupIntent);
Christopher Tate4cc86e12009-09-21 19:36:51 -07002167
2168 // This also constitutes an opt-out, so we wipe any data for
2169 // this device from the backend. We start that process with
2170 // an alarm in order to guarantee wakelock states.
2171 if (wasEnabled && mProvisioned) {
2172 // NOTE: we currently flush every registered transport, not just
2173 // the currently-active one.
2174 HashSet<String> allTransports;
2175 synchronized (mTransports) {
2176 allTransports = new HashSet<String>(mTransports.keySet());
2177 }
2178 // build the set of transports for which we are posting an init
2179 for (String transport : allTransports) {
2180 recordInitPendingLocked(true, transport);
2181 }
2182 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
2183 mRunInitIntent);
2184 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002185 }
2186 }
Christopher Tate49401dd2009-07-01 12:34:29 -07002187 }
Christopher Tate6ef58a12009-06-29 14:56:28 -07002188
Christopher Tatecce9da52010-02-03 15:11:15 -08002189 // Enable/disable automatic restore of app data at install time
2190 public void setAutoRestore(boolean doAutoRestore) {
2191 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2192 "setBackupEnabled");
2193
Joe Onorato8a9b2202010-02-26 18:56:32 -08002194 Slog.i(TAG, "Auto restore => " + doAutoRestore);
Christopher Tatecce9da52010-02-03 15:11:15 -08002195
2196 synchronized (this) {
2197 Settings.Secure.putInt(mContext.getContentResolver(),
2198 Settings.Secure.BACKUP_AUTO_RESTORE, doAutoRestore ? 1 : 0);
2199 mAutoRestore = doAutoRestore;
2200 }
2201 }
2202
Christopher Tate8031a3d2009-07-06 16:36:05 -07002203 // Mark the backup service as having been provisioned
2204 public void setBackupProvisioned(boolean available) {
2205 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2206 "setBackupProvisioned");
2207
2208 boolean wasProvisioned = mProvisioned;
2209 synchronized (this) {
2210 Settings.Secure.putInt(mContext.getContentResolver(),
2211 Settings.Secure.BACKUP_PROVISIONED, available ? 1 : 0);
2212 mProvisioned = available;
2213 }
2214
2215 synchronized (mQueueLock) {
2216 if (available && !wasProvisioned && mEnabled) {
2217 // we're now good to go, so start the backup alarms
2218 startBackupAlarmsLocked(FIRST_BACKUP_INTERVAL);
2219 } else if (!available) {
2220 // No longer enabled, so stop running backups
Joe Onorato8a9b2202010-02-26 18:56:32 -08002221 Slog.w(TAG, "Backup service no longer provisioned");
Christopher Tate8031a3d2009-07-06 16:36:05 -07002222 mAlarmManager.cancel(mRunBackupIntent);
2223 }
2224 }
2225 }
2226
2227 private void startBackupAlarmsLocked(long delayBeforeFirstBackup) {
Dan Egnorc1c49c02009-10-30 17:35:39 -07002228 // We used to use setInexactRepeating(), but that may be linked to
2229 // backups running at :00 more often than not, creating load spikes.
2230 // Schedule at an exact time for now, and also add a bit of "fuzz".
2231
2232 Random random = new Random();
2233 long when = System.currentTimeMillis() + delayBeforeFirstBackup +
2234 random.nextInt(FUZZ_MILLIS);
2235 mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, when,
2236 BACKUP_INTERVAL + random.nextInt(FUZZ_MILLIS), mRunBackupIntent);
Christopher Tate55f931a2009-09-29 17:17:34 -07002237 mNextBackupPass = when;
Christopher Tate8031a3d2009-07-06 16:36:05 -07002238 }
2239
Christopher Tate6ef58a12009-06-29 14:56:28 -07002240 // Report whether the backup mechanism is currently enabled
2241 public boolean isBackupEnabled() {
Joe Onorato5933a492009-07-23 18:24:08 -04002242 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "isBackupEnabled");
Christopher Tate6ef58a12009-06-29 14:56:28 -07002243 return mEnabled; // no need to synchronize just to read it
2244 }
2245
Christopher Tate91717492009-06-26 21:07:13 -07002246 // Report the name of the currently active transport
2247 public String getCurrentTransport() {
Joe Onorato5933a492009-07-23 18:24:08 -04002248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate4e3e50c2009-07-02 12:14:05 -07002249 "getCurrentTransport");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002250 if (DEBUG) Slog.v(TAG, "... getCurrentTransport() returning " + mCurrentTransport);
Christopher Tate91717492009-06-26 21:07:13 -07002251 return mCurrentTransport;
Christopher Tateace7f092009-06-15 18:07:25 -07002252 }
2253
Christopher Tate91717492009-06-26 21:07:13 -07002254 // Report all known, available backup transports
2255 public String[] listAllTransports() {
Christopher Tate34ebd0e2009-07-06 15:44:54 -07002256 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "listAllTransports");
Christopher Tate043dadc2009-06-02 16:11:00 -07002257
Christopher Tate91717492009-06-26 21:07:13 -07002258 String[] list = null;
2259 ArrayList<String> known = new ArrayList<String>();
2260 for (Map.Entry<String, IBackupTransport> entry : mTransports.entrySet()) {
2261 if (entry.getValue() != null) {
2262 known.add(entry.getKey());
2263 }
2264 }
2265
2266 if (known.size() > 0) {
2267 list = new String[known.size()];
2268 known.toArray(list);
2269 }
2270 return list;
2271 }
2272
2273 // Select which transport to use for the next backup operation. If the given
2274 // name is not one of the available transports, no action is taken and the method
2275 // returns null.
2276 public String selectBackupTransport(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002277 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "selectBackupTransport");
Christopher Tate91717492009-06-26 21:07:13 -07002278
2279 synchronized (mTransports) {
2280 String prevTransport = null;
2281 if (mTransports.get(transport) != null) {
2282 prevTransport = mCurrentTransport;
2283 mCurrentTransport = transport;
Dianne Hackborncf098292009-07-01 19:55:20 -07002284 Settings.Secure.putString(mContext.getContentResolver(),
2285 Settings.Secure.BACKUP_TRANSPORT, transport);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002286 Slog.v(TAG, "selectBackupTransport() set " + mCurrentTransport
Christopher Tate91717492009-06-26 21:07:13 -07002287 + " returning " + prevTransport);
2288 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002289 Slog.w(TAG, "Attempt to select unavailable transport " + transport);
Christopher Tate91717492009-06-26 21:07:13 -07002290 }
2291 return prevTransport;
2292 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002293 }
2294
2295 // Callback: a requested backup agent has been instantiated. This should only
2296 // be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002297 public void agentConnected(String packageName, IBinder agentBinder) {
Christopher Tate043dadc2009-06-02 16:11:00 -07002298 synchronized(mAgentConnectLock) {
2299 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002300 Slog.d(TAG, "agentConnected pkg=" + packageName + " agent=" + agentBinder);
Christopher Tate043dadc2009-06-02 16:11:00 -07002301 IBackupAgent agent = IBackupAgent.Stub.asInterface(agentBinder);
2302 mConnectedAgent = agent;
2303 mConnecting = false;
2304 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002305 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002306 + " claiming agent connected");
2307 }
2308 mAgentConnectLock.notifyAll();
2309 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002310 }
2311
2312 // Callback: a backup agent has failed to come up, or has unexpectedly quit.
2313 // If the agent failed to come up in the first place, the agentBinder argument
Christopher Tate043dadc2009-06-02 16:11:00 -07002314 // will be null. This should only be called from the Activity Manager.
Christopher Tate181fafa2009-05-14 11:12:14 -07002315 public void agentDisconnected(String packageName) {
2316 // TODO: handle backup being interrupted
Christopher Tate043dadc2009-06-02 16:11:00 -07002317 synchronized(mAgentConnectLock) {
2318 if (Binder.getCallingUid() == Process.SYSTEM_UID) {
2319 mConnectedAgent = null;
2320 mConnecting = false;
2321 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002322 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate043dadc2009-06-02 16:11:00 -07002323 + " claiming agent disconnected");
2324 }
2325 mAgentConnectLock.notifyAll();
2326 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002327 }
Christopher Tate181fafa2009-05-14 11:12:14 -07002328
Christopher Tate1bb69062010-02-19 17:02:12 -08002329 // An application being installed will need a restore pass, then the Package Manager
2330 // will need to be told when the restore is finished.
2331 public void restoreAtInstall(String packageName, int token) {
2332 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002333 Slog.w(TAG, "Non-system process uid=" + Binder.getCallingUid()
Christopher Tate1bb69062010-02-19 17:02:12 -08002334 + " attemping install-time restore");
2335 return;
2336 }
2337
2338 long restoreSet = getAvailableRestoreToken(packageName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002339 if (DEBUG) Slog.v(TAG, "restoreAtInstall pkg=" + packageName
Christopher Tate1bb69062010-02-19 17:02:12 -08002340 + " token=" + Integer.toHexString(token));
2341
Christopher Tatef0872722010-02-25 15:22:48 -08002342 if (mAutoRestore && mProvisioned && restoreSet != 0) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002343 // okay, we're going to attempt a restore of this package from this restore set.
2344 // The eventual message back into the Package Manager to run the post-install
2345 // steps for 'token' will be issued from the restore handling code.
2346
2347 // We can use a synthetic PackageInfo here because:
2348 // 1. We know it's valid, since the Package Manager supplied the name
2349 // 2. Only the packageName field will be used by the restore code
2350 PackageInfo pkg = new PackageInfo();
2351 pkg.packageName = packageName;
2352
2353 mWakelock.acquire();
2354 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2355 msg.obj = new RestoreParams(getTransport(mCurrentTransport), null,
2356 restoreSet, pkg, token);
2357 mBackupHandler.sendMessage(msg);
2358 } else {
Christopher Tatef0872722010-02-25 15:22:48 -08002359 // Auto-restore disabled or no way to attempt a restore; just tell the Package
2360 // Manager to proceed with the post-install handling for this package.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002361 if (DEBUG) Slog.v(TAG, "No restore set -- skipping restore");
Christopher Tate1bb69062010-02-19 17:02:12 -08002362 try {
2363 mPackageManagerBinder.finishPackageInstall(token);
2364 } catch (RemoteException e) { /* can't happen */ }
2365 }
2366 }
2367
Christopher Tate8c850b72009-06-07 19:33:20 -07002368 // Hand off a restore session
Christopher Tate91717492009-06-26 21:07:13 -07002369 public IRestoreSession beginRestoreSession(String transport) {
Joe Onorato5933a492009-07-23 18:24:08 -04002370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP, "beginRestoreSession");
Christopher Tatef68eb502009-06-16 11:02:01 -07002371
2372 synchronized(this) {
2373 if (mActiveRestoreSession != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002374 Slog.d(TAG, "Restore session requested but one already active");
Christopher Tatef68eb502009-06-16 11:02:01 -07002375 return null;
2376 }
Christopher Tate80202c82010-01-25 19:37:47 -08002377 mActiveRestoreSession = new ActiveRestoreSession(transport);
Christopher Tatef68eb502009-06-16 11:02:01 -07002378 }
2379 return mActiveRestoreSession;
Christopher Tate8c850b72009-06-07 19:33:20 -07002380 }
Christopher Tate043dadc2009-06-02 16:11:00 -07002381
Christopher Tate44a27902010-01-27 17:15:49 -08002382 // Note that a currently-active backup agent has notified us that it has
2383 // completed the given outstanding asynchronous backup/restore operation.
2384 public void opComplete(int token) {
2385 synchronized (mCurrentOpLock) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002386 if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));
Christopher Tate44a27902010-01-27 17:15:49 -08002387 mCurrentOperations.put(token, OP_ACKNOWLEDGED);
2388 mCurrentOpLock.notifyAll();
2389 }
2390 }
2391
Christopher Tate9b3905c2009-06-08 15:24:01 -07002392 // ----- Restore session -----
2393
Christopher Tate80202c82010-01-25 19:37:47 -08002394 class ActiveRestoreSession extends IRestoreSession.Stub {
Christopher Tatef68eb502009-06-16 11:02:01 -07002395 private static final String TAG = "RestoreSession";
2396
Christopher Tate9b3905c2009-06-08 15:24:01 -07002397 private IBackupTransport mRestoreTransport = null;
2398 RestoreSet[] mRestoreSets = null;
2399
Christopher Tate80202c82010-01-25 19:37:47 -08002400 ActiveRestoreSession(String transport) {
Christopher Tate91717492009-06-26 21:07:13 -07002401 mRestoreTransport = getTransport(transport);
Christopher Tate9b3905c2009-06-08 15:24:01 -07002402 }
2403
2404 // --- Binder interface ---
Christopher Tate2d449afe2010-03-29 19:14:24 -07002405 public synchronized int getAvailableRestoreSets(IRestoreObserver observer) {
Joe Onorato5933a492009-07-23 18:24:08 -04002406 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002407 "getAvailableRestoreSets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002408 if (observer == null) {
2409 throw new IllegalArgumentException("Observer must not be null");
2410 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002411
Christopher Tate1bb69062010-02-19 17:02:12 -08002412 long oldId = Binder.clearCallingIdentity();
Christopher Tatef68eb502009-06-16 11:02:01 -07002413 try {
Christopher Tate43383042009-07-13 15:17:13 -07002414 if (mRestoreTransport == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002415 Slog.w(TAG, "Null transport getting restore sets");
Christopher Tate2d449afe2010-03-29 19:14:24 -07002416 return -1;
Dan Egnor0084da52009-07-29 12:57:16 -07002417 }
Christopher Tate2d449afe2010-03-29 19:14:24 -07002418 // spin off the transport request to our service thread
2419 mWakelock.acquire();
2420 Message msg = mBackupHandler.obtainMessage(MSG_RUN_GET_RESTORE_SETS,
2421 new RestoreGetSetsParams(mRestoreTransport, this, observer));
2422 mBackupHandler.sendMessage(msg);
2423 return 0;
Dan Egnor0084da52009-07-29 12:57:16 -07002424 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002425 Slog.e(TAG, "Error in getAvailableRestoreSets", e);
Christopher Tate2d449afe2010-03-29 19:14:24 -07002426 return -1;
Christopher Tate1bb69062010-02-19 17:02:12 -08002427 } finally {
2428 Binder.restoreCallingIdentity(oldId);
Christopher Tatef68eb502009-06-16 11:02:01 -07002429 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002430 }
2431
Christopher Tate84725812010-02-04 15:52:40 -08002432 public synchronized int restoreAll(long token, IRestoreObserver observer) {
Dan Egnor0084da52009-07-29 12:57:16 -07002433 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
2434 "performRestore");
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002435
Joe Onorato8a9b2202010-02-26 18:56:32 -08002436 if (DEBUG) Slog.d(TAG, "performRestore token=" + Long.toHexString(token)
Christopher Tatef2c321a2009-08-10 15:43:36 -07002437 + " observer=" + observer);
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002438
Dan Egnor0084da52009-07-29 12:57:16 -07002439 if (mRestoreTransport == null || mRestoreSets == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002440 Slog.e(TAG, "Ignoring performRestore() with no restore set");
Dan Egnor0084da52009-07-29 12:57:16 -07002441 return -1;
2442 }
2443
Christopher Tate21ab6a52009-09-24 18:01:46 -07002444 synchronized (mQueueLock) {
Christopher Tate21ab6a52009-09-24 18:01:46 -07002445 for (int i = 0; i < mRestoreSets.length; i++) {
2446 if (token == mRestoreSets[i].token) {
2447 long oldId = Binder.clearCallingIdentity();
Christopher Tate21ab6a52009-09-24 18:01:46 -07002448 mWakelock.acquire();
2449 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
2450 msg.obj = new RestoreParams(mRestoreTransport, observer, token);
2451 mBackupHandler.sendMessage(msg);
2452 Binder.restoreCallingIdentity(oldId);
2453 return 0;
2454 }
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002455 }
2456 }
Christopher Tate0e0b4ae2009-08-10 16:13:47 -07002457
Joe Onorato8a9b2202010-02-26 18:56:32 -08002458 Slog.w(TAG, "Restore token " + Long.toHexString(token) + " not found");
Christopher Tate9b3905c2009-06-08 15:24:01 -07002459 return -1;
2460 }
2461
Christopher Tate84725812010-02-04 15:52:40 -08002462 public synchronized int restorePackage(String packageName, IRestoreObserver observer) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002463 if (DEBUG) Slog.v(TAG, "restorePackage pkg=" + packageName + " obs=" + observer);
Christopher Tate84725812010-02-04 15:52:40 -08002464
2465 PackageInfo app = null;
2466 try {
2467 app = mPackageManager.getPackageInfo(packageName, 0);
2468 } catch (NameNotFoundException nnf) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002469 Slog.w(TAG, "Asked to restore nonexistent pkg " + packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002470 return -1;
2471 }
2472
2473 // If the caller is not privileged and is not coming from the target
2474 // app's uid, throw a permission exception back to the caller.
2475 int perm = mContext.checkPermission(android.Manifest.permission.BACKUP,
2476 Binder.getCallingPid(), Binder.getCallingUid());
2477 if ((perm == PackageManager.PERMISSION_DENIED) &&
2478 (app.applicationInfo.uid != Binder.getCallingUid())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002479 Slog.w(TAG, "restorePackage: bad packageName=" + packageName
Christopher Tate84725812010-02-04 15:52:40 -08002480 + " or calling uid=" + Binder.getCallingUid());
2481 throw new SecurityException("No permission to restore other packages");
2482 }
2483
Christopher Tate7d411a32010-02-26 11:27:08 -08002484 // If the package has no backup agent, we obviously cannot proceed
2485 if (app.applicationInfo.backupAgentName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002486 Slog.w(TAG, "Asked to restore package " + packageName + " with no agent");
Christopher Tate7d411a32010-02-26 11:27:08 -08002487 return -1;
2488 }
2489
Christopher Tate84725812010-02-04 15:52:40 -08002490 // So far so good; we're allowed to try to restore this package. Now
2491 // check whether there is data for it in the current dataset, falling back
2492 // to the ancestral dataset if not.
Christopher Tate1bb69062010-02-19 17:02:12 -08002493 long token = getAvailableRestoreToken(packageName);
Christopher Tate84725812010-02-04 15:52:40 -08002494
2495 // If we didn't come up with a place to look -- no ancestral dataset and
2496 // the app has never been backed up from this device -- there's nothing
2497 // to do but return failure.
2498 if (token == 0) {
2499 return -1;
2500 }
2501
2502 // Ready to go: enqueue the restore request and claim success
2503 long oldId = Binder.clearCallingIdentity();
2504 mWakelock.acquire();
2505 Message msg = mBackupHandler.obtainMessage(MSG_RUN_RESTORE);
Christopher Tate1bb69062010-02-19 17:02:12 -08002506 msg.obj = new RestoreParams(mRestoreTransport, observer, token, app, 0);
Christopher Tate84725812010-02-04 15:52:40 -08002507 mBackupHandler.sendMessage(msg);
2508 Binder.restoreCallingIdentity(oldId);
2509 return 0;
2510 }
2511
Dan Egnor0084da52009-07-29 12:57:16 -07002512 public synchronized void endRestoreSession() {
Joe Onorato5933a492009-07-23 18:24:08 -04002513 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.BACKUP,
Christopher Tate9bbc21a2009-06-10 20:23:25 -07002514 "endRestoreSession");
2515
Joe Onorato8a9b2202010-02-26 18:56:32 -08002516 if (DEBUG) Slog.d(TAG, "endRestoreSession");
Joe Onorato9a5e3e12009-07-01 21:04:03 -04002517
Dan Egnor0084da52009-07-29 12:57:16 -07002518 synchronized (this) {
Christopher Tate1bb69062010-02-19 17:02:12 -08002519 long oldId = Binder.clearCallingIdentity();
Dan Egnor0084da52009-07-29 12:57:16 -07002520 try {
2521 if (mRestoreTransport != null) mRestoreTransport.finishRestore();
2522 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002523 Slog.e(TAG, "Error in finishRestore", e);
Dan Egnor0084da52009-07-29 12:57:16 -07002524 } finally {
2525 mRestoreTransport = null;
Christopher Tate1bb69062010-02-19 17:02:12 -08002526 Binder.restoreCallingIdentity(oldId);
Dan Egnor0084da52009-07-29 12:57:16 -07002527 }
2528 }
2529
2530 synchronized (BackupManagerService.this) {
Christopher Tatef68eb502009-06-16 11:02:01 -07002531 if (BackupManagerService.this.mActiveRestoreSession == this) {
2532 BackupManagerService.this.mActiveRestoreSession = null;
2533 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002534 Slog.e(TAG, "ending non-current restore session");
Christopher Tatef68eb502009-06-16 11:02:01 -07002535 }
2536 }
Christopher Tate9b3905c2009-06-08 15:24:01 -07002537 }
2538 }
2539
Christopher Tate043dadc2009-06-02 16:11:00 -07002540
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002541 @Override
2542 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2543 synchronized (mQueueLock) {
Christopher Tate8031a3d2009-07-06 16:36:05 -07002544 pw.println("Backup Manager is " + (mEnabled ? "enabled" : "disabled")
Christopher Tate55f931a2009-09-29 17:17:34 -07002545 + " / " + (!mProvisioned ? "not " : "") + "provisioned / "
Christopher Tatec2af5d32010-02-02 15:18:58 -08002546 + (this.mPendingInits.size() == 0 ? "not " : "") + "pending init");
Christopher Tateae06ed92010-02-25 17:13:28 -08002547 pw.println("Auto-restore is " + (mAutoRestore ? "enabled" : "disabled"));
Christopher Tate55f931a2009-09-29 17:17:34 -07002548 pw.println("Last backup pass: " + mLastBackupPass
2549 + " (now = " + System.currentTimeMillis() + ')');
2550 pw.println(" next scheduled: " + mNextBackupPass);
2551
Christopher Tate91717492009-06-26 21:07:13 -07002552 pw.println("Available transports:");
2553 for (String t : listAllTransports()) {
Dan Egnor852f8e42009-09-30 11:20:45 -07002554 pw.println((t.equals(mCurrentTransport) ? " * " : " ") + t);
2555 try {
2556 File dir = new File(mBaseStateDir, getTransport(t).transportDirName());
2557 for (File f : dir.listFiles()) {
2558 pw.println(" " + f.getName() + " - " + f.length() + " state bytes");
2559 }
2560 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002561 Slog.e(TAG, "Error in transportDirName()", e);
Dan Egnor852f8e42009-09-30 11:20:45 -07002562 pw.println(" Error: " + e);
2563 }
Christopher Tate91717492009-06-26 21:07:13 -07002564 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002565
2566 pw.println("Pending init: " + mPendingInits.size());
2567 for (String s : mPendingInits) {
2568 pw.println(" " + s);
2569 }
2570
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002571 int N = mBackupParticipants.size();
Christopher Tate55f931a2009-09-29 17:17:34 -07002572 pw.println("Participants:");
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002573 for (int i=0; i<N; i++) {
2574 int uid = mBackupParticipants.keyAt(i);
2575 pw.print(" uid: ");
2576 pw.println(uid);
Christopher Tate181fafa2009-05-14 11:12:14 -07002577 HashSet<ApplicationInfo> participants = mBackupParticipants.valueAt(i);
2578 for (ApplicationInfo app: participants) {
Christopher Tate55f931a2009-09-29 17:17:34 -07002579 pw.println(" " + app.packageName);
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002580 }
2581 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002582
Christopher Tateb49ceb32010-02-08 16:22:24 -08002583 pw.println("Ancestral packages: "
2584 + (mAncestralPackages == null ? "none" : mAncestralPackages.size()));
Christopher Tate5923c972010-04-04 17:45:35 -07002585 if (mAncestralPackages != null) {
2586 for (String pkg : mAncestralPackages) {
2587 pw.println(" " + pkg);
2588 }
Christopher Tateb49ceb32010-02-08 16:22:24 -08002589 }
2590
Christopher Tate73e02522009-07-15 14:18:26 -07002591 pw.println("Ever backed up: " + mEverStoredApps.size());
2592 for (String pkg : mEverStoredApps) {
2593 pw.println(" " + pkg);
2594 }
Christopher Tate55f931a2009-09-29 17:17:34 -07002595
2596 pw.println("Pending backup: " + mPendingBackups.size());
Christopher Tate6aa41f42009-06-19 14:14:22 -07002597 for (BackupRequest req : mPendingBackups.values()) {
Christopher Tate6ef58a12009-06-29 14:56:28 -07002598 pw.println(" " + req);
Christopher Tate181fafa2009-05-14 11:12:14 -07002599 }
Joe Onoratob1a7ffe2009-05-06 18:06:21 -07002600 }
2601 }
Christopher Tate487529a2009-04-29 14:03:25 -07002602}